blob: 11412cf1b76eb3e1ad630ab0be6956344d7c3fb0 [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>
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080060#include <statslog.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65#define INDENT4 " "
66#define INDENT5 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// --- Constants ---
73
74// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080075static constexpr size_t MAX_SLOTS = 32;
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Michael Wright842500e2015-03-13 17:32:02 -070077// Maximum amount of latency to add to touch events while waiting for data from an
78// external stylus.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080079static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070080
Michael Wright43fd19f2015-04-21 19:02:58 +010081// Maximum amount of time to wait on touch data before pushing out new pressure data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080082static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
Michael Wright43fd19f2015-04-21 19:02:58 +010083
84// Artificial latency on synthetic events created from stylus data without corresponding touch
85// data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080086static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
87
88// How often to report input event statistics
89static constexpr nsecs_t STATISTICS_REPORT_FREQUENCY = seconds_to_nanoseconds(5 * 60);
Michael Wright43fd19f2015-04-21 19:02:58 +010090
Michael Wrightd02c5b62014-02-10 15:10:22 -080091// --- Static Functions ---
92
Prabir Pradhan2b281812019-08-29 14:12:42 -070093template <typename T>
Michael Wrightd02c5b62014-02-10 15:10:22 -080094inline static T abs(const T& value) {
Prabir Pradhan2b281812019-08-29 14:12:42 -070095 return value < 0 ? -value : value;
Michael Wrightd02c5b62014-02-10 15:10:22 -080096}
97
Prabir Pradhan2b281812019-08-29 14:12:42 -070098template <typename T>
Michael Wrightd02c5b62014-02-10 15:10:22 -080099inline static T min(const T& a, const T& b) {
100 return a < b ? a : b;
101}
102
Prabir Pradhan2b281812019-08-29 14:12:42 -0700103template <typename T>
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104inline static void swap(T& a, T& b) {
105 T temp = a;
106 a = b;
107 b = temp;
108}
109
110inline static float avg(float x, float y) {
111 return (x + y) / 2;
112}
113
114inline static float distance(float x1, float y1, float x2, float y2) {
115 return hypotf(x1 - x2, y1 - y2);
116}
117
118inline static int32_t signExtendNybble(int32_t value) {
119 return value >= 8 ? value - 16 : value;
120}
121
122static inline const char* toString(bool value) {
123 return value ? "true" : "false";
124}
125
126static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700127 const int32_t map[][4], size_t mapSize) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128 if (orientation != DISPLAY_ORIENTATION_0) {
129 for (size_t i = 0; i < mapSize; i++) {
130 if (value == map[i][0]) {
131 return map[i][orientation];
132 }
133 }
134 }
135 return value;
136}
137
138static const int32_t keyCodeRotationMap[][4] = {
139 // key codes enumerated counter-clockwise with the original (unrotated) key first
140 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
Prabir Pradhan2b281812019-08-29 14:12:42 -0700141 {AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT},
142 {AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN},
143 {AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT},
144 {AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP},
145 {AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
146 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT},
147 {AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
148 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN},
149 {AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
150 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT},
151 {AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
152 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP},
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153};
154static const size_t keyCodeRotationMapSize =
155 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
156
Prabir Pradhan2b281812019-08-29 14:12:42 -0700157static int32_t rotateStemKey(int32_t value, int32_t orientation, const int32_t map[][2],
158 size_t mapSize) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000159 if (orientation == DISPLAY_ORIENTATION_180) {
160 for (size_t i = 0; i < mapSize; i++) {
161 if (value == map[i][0]) {
162 return map[i][1];
163 }
164 }
165 }
166 return value;
167}
168
169// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
170static int32_t stemKeyRotationMap[][2] = {
171 // key codes enumerated with the original (unrotated) key first
172 // no rotation, 180 degree rotation
Prabir Pradhan2b281812019-08-29 14:12:42 -0700173 {AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY},
174 {AKEYCODE_STEM_1, AKEYCODE_STEM_1},
175 {AKEYCODE_STEM_2, AKEYCODE_STEM_2},
176 {AKEYCODE_STEM_3, AKEYCODE_STEM_3},
Ivan Podogovb9afef32017-02-13 15:34:32 +0000177};
178static const size_t stemKeyRotationMapSize =
179 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
180
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700182 keyCode = rotateStemKey(keyCode, orientation, stemKeyRotationMap, stemKeyRotationMapSize);
183 return rotateValueUsingRotationMap(keyCode, orientation, keyCodeRotationMap,
184 keyCodeRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185}
186
187static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
188 float temp;
189 switch (orientation) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700190 case DISPLAY_ORIENTATION_90:
191 temp = *deltaX;
192 *deltaX = *deltaY;
193 *deltaY = -temp;
194 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195
Prabir Pradhan2b281812019-08-29 14:12:42 -0700196 case DISPLAY_ORIENTATION_180:
197 *deltaX = -*deltaX;
198 *deltaY = -*deltaY;
199 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200
Prabir Pradhan2b281812019-08-29 14:12:42 -0700201 case DISPLAY_ORIENTATION_270:
202 temp = *deltaX;
203 *deltaX = -*deltaY;
204 *deltaY = temp;
205 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 }
207}
208
209static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700210 return (sources & sourceMask & ~AINPUT_SOURCE_CLASS_MASK) != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211}
212
213// Returns true if the pointer should be reported as being down given the specified
214// button states. This determines whether the event is reported as a touch event.
215static bool isPointerDown(int32_t buttonState) {
216 return buttonState &
Prabir Pradhan2b281812019-08-29 14:12:42 -0700217 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY |
218 AMOTION_EVENT_BUTTON_TERTIARY);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219}
220
221static float calculateCommonVector(float a, float b) {
222 if (a > 0 && b > 0) {
223 return a < b ? a : b;
224 } else if (a < 0 && b < 0) {
225 return a > b ? a : b;
226 } else {
227 return 0;
228 }
229}
230
Prabir Pradhan2b281812019-08-29 14:12:42 -0700231static void synthesizeButtonKey(InputReaderContext* context, int32_t action, nsecs_t when,
232 int32_t deviceId, uint32_t source, int32_t displayId,
233 uint32_t policyFlags, int32_t lastButtonState,
234 int32_t currentButtonState, int32_t buttonState, int32_t keyCode) {
235 if ((action == AKEY_EVENT_ACTION_DOWN && !(lastButtonState & buttonState) &&
236 (currentButtonState & buttonState)) ||
237 (action == AKEY_EVENT_ACTION_UP && (lastButtonState & buttonState) &&
238 !(currentButtonState & buttonState))) {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800239 NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700240 policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 context->getListener()->notifyKey(&args);
242 }
243}
244
Prabir Pradhan2b281812019-08-29 14:12:42 -0700245static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, nsecs_t when,
246 int32_t deviceId, uint32_t source, int32_t displayId,
247 uint32_t policyFlags, int32_t lastButtonState,
248 int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100249 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700250 lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_BACK,
251 AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100252 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700253 lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_FORWARD,
254 AKEYCODE_FORWARD);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255}
256
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257// --- InputReader ---
258
259InputReader::InputReader(const sp<EventHubInterface>& eventHub,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700260 const sp<InputReaderPolicyInterface>& policy,
261 const sp<InputListenerInterface>& listener)
262 : mContext(this),
263 mEventHub(eventHub),
264 mPolicy(policy),
265 mNextSequenceNum(1),
266 mGlobalMetaState(0),
267 mGeneration(1),
268 mDisableVirtualKeysTimeout(LLONG_MIN),
269 mNextTimeout(LLONG_MAX),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800270 mConfigurationChangesToRefresh(0) {
271 mQueuedListener = new QueuedInputListener(listener);
272
273 { // acquire lock
274 AutoMutex _l(mLock);
275
276 refreshConfigurationLocked(0);
277 updateGlobalMetaStateLocked();
278 } // release lock
279}
280
281InputReader::~InputReader() {
282 for (size_t i = 0; i < mDevices.size(); i++) {
283 delete mDevices.valueAt(i);
284 }
285}
286
287void InputReader::loopOnce() {
288 int32_t oldGeneration;
289 int32_t timeoutMillis;
290 bool inputDevicesChanged = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800291 std::vector<InputDeviceInfo> inputDevices;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292 { // acquire lock
293 AutoMutex _l(mLock);
294
295 oldGeneration = mGeneration;
296 timeoutMillis = -1;
297
298 uint32_t changes = mConfigurationChangesToRefresh;
299 if (changes) {
300 mConfigurationChangesToRefresh = 0;
301 timeoutMillis = 0;
302 refreshConfigurationLocked(changes);
303 } else if (mNextTimeout != LLONG_MAX) {
304 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
305 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
306 }
307 } // release lock
308
309 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
310
311 { // acquire lock
312 AutoMutex _l(mLock);
313 mReaderIsAliveCondition.broadcast();
314
315 if (count) {
316 processEventsLocked(mEventBuffer, count);
317 }
318
319 if (mNextTimeout != LLONG_MAX) {
320 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
321 if (now >= mNextTimeout) {
322#if DEBUG_RAW_EVENTS
323 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
324#endif
325 mNextTimeout = LLONG_MAX;
326 timeoutExpiredLocked(now);
327 }
328 }
329
330 if (oldGeneration != mGeneration) {
331 inputDevicesChanged = true;
332 getInputDevicesLocked(inputDevices);
333 }
334 } // release lock
335
336 // Send out a message that the describes the changed input devices.
337 if (inputDevicesChanged) {
338 mPolicy->notifyInputDevicesChanged(inputDevices);
339 }
340
341 // Flush queued events out to the listener.
342 // This must happen outside of the lock because the listener could potentially call
343 // back into the InputReader's methods, such as getScanCodeState, or become blocked
344 // on another thread similarly waiting to acquire the InputReader lock thereby
345 // resulting in a deadlock. This situation is actually quite plausible because the
346 // listener is actually the input dispatcher, which calls into the window manager,
347 // which occasionally calls into the input reader.
348 mQueuedListener->flush();
349}
350
351void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
352 for (const RawEvent* rawEvent = rawEvents; count;) {
353 int32_t type = rawEvent->type;
354 size_t batchSize = 1;
355 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
356 int32_t deviceId = rawEvent->deviceId;
357 while (batchSize < count) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700358 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT ||
359 rawEvent[batchSize].deviceId != deviceId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360 break;
361 }
362 batchSize += 1;
363 }
364#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700365 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800366#endif
367 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
368 } else {
369 switch (rawEvent->type) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700370 case EventHubInterface::DEVICE_ADDED:
371 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
372 break;
373 case EventHubInterface::DEVICE_REMOVED:
374 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
375 break;
376 case EventHubInterface::FINISHED_DEVICE_SCAN:
377 handleConfigurationChangedLocked(rawEvent->when);
378 break;
379 default:
380 ALOG_ASSERT(false); // can't happen
381 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383 }
384 count -= batchSize;
385 rawEvent += batchSize;
386 }
387}
388
389void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
390 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
391 if (deviceIndex >= 0) {
392 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
393 return;
394 }
395
396 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
397 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
398 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
399
400 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
401 device->configure(when, &mConfig, 0);
402 device->reset(when);
403
404 if (device->isIgnored()) {
405 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700406 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407 } else {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700408 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, identifier.name.c_str(),
409 device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 }
411
412 mDevices.add(deviceId, device);
413 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700414
415 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
416 notifyExternalStylusPresenceChanged();
417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418}
419
420void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700421 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
423 if (deviceIndex < 0) {
424 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
425 return;
426 }
427
428 device = mDevices.valueAt(deviceIndex);
429 mDevices.removeItemsAt(deviceIndex, 1);
430 bumpGenerationLocked();
431
432 if (device->isIgnored()) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700433 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)", device->getId(),
434 device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435 } else {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700436 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x", device->getId(),
437 device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 }
439
Michael Wright842500e2015-03-13 17:32:02 -0700440 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
441 notifyExternalStylusPresenceChanged();
442 }
443
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 device->reset(when);
445 delete device;
446}
447
448InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700449 const InputDeviceIdentifier& identifier,
450 uint32_t classes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
Prabir Pradhan2b281812019-08-29 14:12:42 -0700452 controllerNumber, identifier, classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
454 // External devices.
455 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
456 device->setExternal(true);
457 }
458
Tim Kilbourn063ff532015-04-08 10:26:18 -0700459 // Devices with mics.
460 if (classes & INPUT_DEVICE_CLASS_MIC) {
461 device->setMic(true);
462 }
463
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 // Switch-like devices.
465 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
466 device->addMapper(new SwitchInputMapper(device));
467 }
468
Prashant Malani1941ff52015-08-11 18:29:28 -0700469 // Scroll wheel-like devices.
470 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
471 device->addMapper(new RotaryEncoderInputMapper(device));
472 }
473
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474 // Vibrator-like devices.
475 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
476 device->addMapper(new VibratorInputMapper(device));
477 }
478
479 // Keyboard-like devices.
480 uint32_t keyboardSource = 0;
481 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
482 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
483 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
484 }
485 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
486 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
487 }
488 if (classes & INPUT_DEVICE_CLASS_DPAD) {
489 keyboardSource |= AINPUT_SOURCE_DPAD;
490 }
491 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
492 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
493 }
494
495 if (keyboardSource != 0) {
496 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
497 }
498
499 // Cursor-like devices.
500 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
501 device->addMapper(new CursorInputMapper(device));
502 }
503
504 // Touchscreens and touchpad devices.
505 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
506 device->addMapper(new MultiTouchInputMapper(device));
507 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
508 device->addMapper(new SingleTouchInputMapper(device));
509 }
510
511 // Joystick-like devices.
512 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
513 device->addMapper(new JoystickInputMapper(device));
514 }
515
Michael Wright842500e2015-03-13 17:32:02 -0700516 // External stylus-like devices.
517 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
518 device->addMapper(new ExternalStylusInputMapper(device));
519 }
520
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 return device;
522}
523
Prabir Pradhan2b281812019-08-29 14:12:42 -0700524void InputReader::processEventsForDeviceLocked(int32_t deviceId, const RawEvent* rawEvents,
525 size_t count) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
527 if (deviceIndex < 0) {
528 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
529 return;
530 }
531
532 InputDevice* device = mDevices.valueAt(deviceIndex);
533 if (device->isIgnored()) {
Prabir Pradhan2b281812019-08-29 14:12:42 -0700534 // ALOGD("Discarding event for ignored deviceId %d.", deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535 return;
536 }
537
538 device->process(rawEvents, count);
539}
540
541void InputReader::timeoutExpiredLocked(nsecs_t when) {
542 for (size_t i = 0; i < mDevices.size(); i++) {
543 InputDevice* device = mDevices.valueAt(i);
544 if (!device->isIgnored()) {
545 device->timeoutExpired(when);
546 }
547 }
548}
549
550void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
551 // Reset global meta state because it depends on the list of all configured devices.
552 updateGlobalMetaStateLocked();
553
554 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800555 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 mQueuedListener->notifyConfigurationChanged(&args);
557}
558
559void InputReader::refreshConfigurationLocked(uint32_t changes) {
560 mPolicy->getReaderConfiguration(&mConfig);
561 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
562
563 if (changes) {
564 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
565 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
566
567 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
568 mEventHub->requestReopenDevices();
569 } else {
570 for (size_t i = 0; i < mDevices.size(); i++) {
571 InputDevice* device = mDevices.valueAt(i);
572 device->configure(now, &mConfig, changes);
573 }
574 }
575 }
576}
577
578void InputReader::updateGlobalMetaStateLocked() {
579 mGlobalMetaState = 0;
580
581 for (size_t i = 0; i < mDevices.size(); i++) {
582 InputDevice* device = mDevices.valueAt(i);
583 mGlobalMetaState |= device->getMetaState();
584 }
585}
586
587int32_t InputReader::getGlobalMetaStateLocked() {
588 return mGlobalMetaState;
589}
590
Michael Wright842500e2015-03-13 17:32:02 -0700591void InputReader::notifyExternalStylusPresenceChanged() {
592 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
593}
594
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800595void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700596 for (size_t i = 0; i < mDevices.size(); i++) {
597 InputDevice* device = mDevices.valueAt(i);
598 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800599 InputDeviceInfo info;
600 device->getDeviceInfo(&info);
601 outDevices.push_back(info);
Michael Wright842500e2015-03-13 17:32:02 -0700602 }
603 }
604}
605
606void InputReader::dispatchExternalStylusState(const StylusState& state) {
607 for (size_t i = 0; i < mDevices.size(); i++) {
608 InputDevice* device = mDevices.valueAt(i);
609 device->updateExternalStylusState(state);
610 }
611}
612
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
614 mDisableVirtualKeysTimeout = time;
615}
616
Prabir Pradhan2b281812019-08-29 14:12:42 -0700617bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now, InputDevice* device, int32_t keyCode,
618 int32_t scanCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619 if (now < mDisableVirtualKeysTimeout) {
620 ALOGI("Dropping virtual key from device %s because virtual keys are "
Prabir Pradhan2b281812019-08-29 14:12:42 -0700621 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
622 device->getName().c_str(), (mDisableVirtualKeysTimeout - now) * 0.000001, keyCode,
623 scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 return true;
625 } else {
626 return false;
627 }
628}
629
630void InputReader::fadePointerLocked() {
631 for (size_t i = 0; i < mDevices.size(); i++) {
632 InputDevice* device = mDevices.valueAt(i);
633 device->fadePointer();
634 }
635}
636
637void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
638 if (when < mNextTimeout) {
639 mNextTimeout = when;
640 mEventHub->wake();
641 }
642}
643
644int32_t InputReader::bumpGenerationLocked() {
645 return ++mGeneration;
646}
647
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800648void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 AutoMutex _l(mLock);
650 getInputDevicesLocked(outInputDevices);
651}
652
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800653void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 outInputDevices.clear();
655
656 size_t numDevices = mDevices.size();
657 for (size_t i = 0; i < numDevices; i++) {
658 InputDevice* device = mDevices.valueAt(i);
659 if (!device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800660 InputDeviceInfo info;
661 device->getDeviceInfo(&info);
662 outInputDevices.push_back(info);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 }
664 }
665}
666
Prabir Pradhan2b281812019-08-29 14:12:42 -0700667int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 AutoMutex _l(mLock);
669
670 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
671}
672
Prabir Pradhan2b281812019-08-29 14:12:42 -0700673int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 AutoMutex _l(mLock);
675
676 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
677}
678
679int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
680 AutoMutex _l(mLock);
681
682 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
683}
684
685int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700686 GetStateFunc getStateFunc) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800687 int32_t result = AKEY_STATE_UNKNOWN;
688 if (deviceId >= 0) {
689 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
690 if (deviceIndex >= 0) {
691 InputDevice* device = mDevices.valueAt(deviceIndex);
Prabir Pradhan2b281812019-08-29 14:12:42 -0700692 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 result = (device->*getStateFunc)(sourceMask, code);
694 }
695 }
696 } else {
697 size_t numDevices = mDevices.size();
698 for (size_t i = 0; i < numDevices; i++) {
699 InputDevice* device = mDevices.valueAt(i);
Prabir Pradhan2b281812019-08-29 14:12:42 -0700700 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
702 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
703 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
704 if (currentResult >= AKEY_STATE_DOWN) {
705 return currentResult;
706 } else if (currentResult == AKEY_STATE_UP) {
707 result = currentResult;
708 }
709 }
710 }
711 }
712 return result;
713}
714
Andrii Kulian763a3a42016-03-08 10:46:16 -0800715void InputReader::toggleCapsLockState(int32_t deviceId) {
716 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
717 if (deviceIndex < 0) {
718 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
719 return;
720 }
721
722 InputDevice* device = mDevices.valueAt(deviceIndex);
723 if (device->isIgnored()) {
724 return;
725 }
726
727 device->updateMetaState(AKEYCODE_CAPS_LOCK);
728}
729
Prabir Pradhan2b281812019-08-29 14:12:42 -0700730bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
731 const int32_t* keyCodes, uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 AutoMutex _l(mLock);
733
734 memset(outFlags, 0, numCodes);
735 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
736}
737
738bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700739 size_t numCodes, const int32_t* keyCodes,
740 uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 bool result = false;
742 if (deviceId >= 0) {
743 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
744 if (deviceIndex >= 0) {
745 InputDevice* device = mDevices.valueAt(deviceIndex);
Prabir Pradhan2b281812019-08-29 14:12:42 -0700746 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
747 result = device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 }
749 }
750 } else {
751 size_t numDevices = mDevices.size();
752 for (size_t i = 0; i < numDevices; i++) {
753 InputDevice* device = mDevices.valueAt(i);
Prabir Pradhan2b281812019-08-29 14:12:42 -0700754 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
755 result |= device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 }
757 }
758 }
759 return result;
760}
761
762void InputReader::requestRefreshConfiguration(uint32_t changes) {
763 AutoMutex _l(mLock);
764
765 if (changes) {
766 bool needWake = !mConfigurationChangesToRefresh;
767 mConfigurationChangesToRefresh |= changes;
768
769 if (needWake) {
770 mEventHub->wake();
771 }
772 }
773}
774
775void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700776 ssize_t repeat, int32_t token) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 AutoMutex _l(mLock);
778
779 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
780 if (deviceIndex >= 0) {
781 InputDevice* device = mDevices.valueAt(deviceIndex);
782 device->vibrate(pattern, patternSize, repeat, token);
783 }
784}
785
786void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
787 AutoMutex _l(mLock);
788
789 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
790 if (deviceIndex >= 0) {
791 InputDevice* device = mDevices.valueAt(deviceIndex);
792 device->cancelVibrate(token);
793 }
794}
795
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700796bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
797 AutoMutex _l(mLock);
798
799 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
800 if (deviceIndex >= 0) {
801 InputDevice* device = mDevices.valueAt(deviceIndex);
802 return device->isEnabled();
803 }
804 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
805 return false;
806}
807
Arthur Hungc23540e2018-11-29 20:42:11 +0800808bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
809 AutoMutex _l(mLock);
810
811 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
812 if (deviceIndex < 0) {
813 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
814 return false;
815 }
816
817 InputDevice* device = mDevices.valueAt(deviceIndex);
818 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplay();
819 // No associated display. By default, can dispatch to all displays.
820 if (!associatedDisplayId) {
821 return true;
822 }
823
824 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
825 ALOGW("Device has associated, but no associated display id.");
826 return true;
827 }
828
829 return *associatedDisplayId == displayId;
830}
831
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800832void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 AutoMutex _l(mLock);
834
835 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800836 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800838 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
840 for (size_t i = 0; i < mDevices.size(); i++) {
841 mDevices.valueAt(i)->dump(dump);
842 }
843
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800844 dump += INDENT "Configuration:\n";
845 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
847 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800848 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100850 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800852 dump += "]\n";
853 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700854 mConfig.virtualKeyQuietTime * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800856 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Prabir Pradhan2b281812019-08-29 14:12:42 -0700857 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
858 "acceleration=%0.3f\n",
859 mConfig.pointerVelocityControlParameters.scale,
860 mConfig.pointerVelocityControlParameters.lowThreshold,
861 mConfig.pointerVelocityControlParameters.highThreshold,
862 mConfig.pointerVelocityControlParameters.acceleration);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800864 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Prabir Pradhan2b281812019-08-29 14:12:42 -0700865 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
866 "acceleration=%0.3f\n",
867 mConfig.wheelVelocityControlParameters.scale,
868 mConfig.wheelVelocityControlParameters.lowThreshold,
869 mConfig.wheelVelocityControlParameters.highThreshold,
870 mConfig.wheelVelocityControlParameters.acceleration);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800872 dump += StringPrintf(INDENT2 "PointerGesture:\n");
Prabir Pradhan2b281812019-08-29 14:12:42 -0700873 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800874 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700875 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800876 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700877 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800878 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700879 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800880 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700881 mConfig.pointerGestureTapDragInterval * 0.000001f);
882 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n", mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800883 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700884 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800885 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700886 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800887 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700888 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800889 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700890 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -0700892 mConfig.pointerGestureMovementSpeedRatio);
893 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n", mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700894
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800895 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700896 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897}
898
899void InputReader::monitor() {
900 // Acquire and release the lock to ensure that the reader has not deadlocked.
901 mLock.lock();
902 mEventHub->wake();
903 mReaderIsAliveCondition.wait(mLock);
904 mLock.unlock();
905
906 // Check the EventHub
907 mEventHub->monitor();
908}
909
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910// --- InputReader::ContextImpl ---
911
Prabir Pradhan2b281812019-08-29 14:12:42 -0700912InputReader::ContextImpl::ContextImpl(InputReader* reader) : mReader(reader) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913
914void InputReader::ContextImpl::updateGlobalMetaState() {
915 // lock is already held by the input loop
916 mReader->updateGlobalMetaStateLocked();
917}
918
919int32_t InputReader::ContextImpl::getGlobalMetaState() {
920 // lock is already held by the input loop
921 return mReader->getGlobalMetaStateLocked();
922}
923
924void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
925 // lock is already held by the input loop
926 mReader->disableVirtualKeysUntilLocked(time);
927}
928
Prabir Pradhan2b281812019-08-29 14:12:42 -0700929bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now, InputDevice* device,
930 int32_t keyCode, int32_t scanCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 // lock is already held by the input loop
932 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
933}
934
935void InputReader::ContextImpl::fadePointer() {
936 // lock is already held by the input loop
937 mReader->fadePointerLocked();
938}
939
940void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
941 // lock is already held by the input loop
942 mReader->requestTimeoutAtTimeLocked(when);
943}
944
945int32_t InputReader::ContextImpl::bumpGeneration() {
946 // lock is already held by the input loop
947 return mReader->bumpGenerationLocked();
948}
949
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800950void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700951 // lock is already held by whatever called refreshConfigurationLocked
952 mReader->getExternalStylusDevicesLocked(outDevices);
953}
954
955void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
956 mReader->dispatchExternalStylusState(state);
957}
958
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
960 return mReader->mPolicy.get();
961}
962
963InputListenerInterface* InputReader::ContextImpl::getListener() {
964 return mReader->mQueuedListener.get();
965}
966
967EventHubInterface* InputReader::ContextImpl::getEventHub() {
968 return mReader->mEventHub.get();
969}
970
Prabir Pradhan42611e02018-11-27 14:04:02 -0800971uint32_t InputReader::ContextImpl::getNextSequenceNum() {
972 return (mReader->mNextSequenceNum)++;
973}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975// --- InputDevice ---
976
977InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
Prabir Pradhan2b281812019-08-29 14:12:42 -0700978 int32_t controllerNumber, const InputDeviceIdentifier& identifier,
979 uint32_t classes)
980 : mContext(context),
981 mId(id),
982 mGeneration(generation),
983 mControllerNumber(controllerNumber),
984 mIdentifier(identifier),
985 mClasses(classes),
986 mSources(0),
987 mIsExternal(false),
988 mHasMic(false),
989 mDropUntilNextSync(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990
991InputDevice::~InputDevice() {
992 size_t numMappers = mMappers.size();
993 for (size_t i = 0; i < numMappers; i++) {
994 delete mMappers[i];
995 }
996 mMappers.clear();
997}
998
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700999bool InputDevice::isEnabled() {
1000 return getEventHub()->isDeviceEnabled(mId);
1001}
1002
1003void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1004 if (isEnabled() == enabled) {
1005 return;
1006 }
1007
1008 if (enabled) {
1009 getEventHub()->enableDevice(mId);
1010 reset(when);
1011 } else {
1012 reset(when);
1013 getEventHub()->disableDevice(mId);
1014 }
1015 // Must change generation to flag this device as changed
1016 bumpGeneration();
1017}
1018
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001019void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001021 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001023 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Prabir Pradhan2b281812019-08-29 14:12:42 -07001024 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001025 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1026 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001027 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1028 if (mAssociatedDisplayPort) {
1029 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1030 } else {
1031 dump += "<none>\n";
1032 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001033 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1034 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1035 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001037 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1038 if (!ranges.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001039 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 for (size_t i = 0; i < ranges.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001041 const InputDeviceInfo::MotionRange& range = ranges[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 const char* label = getAxisLabel(range.axis);
1043 char name[32];
1044 if (label) {
1045 strncpy(name, label, sizeof(name));
1046 name[sizeof(name) - 1] = '\0';
1047 } else {
1048 snprintf(name, sizeof(name), "%d", range.axis);
1049 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07001050 dump += StringPrintf(INDENT3
1051 "%s: source=0x%08x, "
1052 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1053 name, range.source, range.min, range.max, range.flat, range.fuzz,
1054 range.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
1056 }
1057
1058 size_t numMappers = mMappers.size();
1059 for (size_t i = 0; i < numMappers; i++) {
1060 InputMapper* mapper = mMappers[i];
1061 mapper->dump(dump);
1062 }
1063}
1064
1065void InputDevice::addMapper(InputMapper* mapper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001066 mMappers.push_back(mapper);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067}
1068
Prabir Pradhan2b281812019-08-29 14:12:42 -07001069void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config,
1070 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 mSources = 0;
1072
1073 if (!isIgnored()) {
1074 if (!changes) { // first time only
1075 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1076 }
1077
1078 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1079 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1080 sp<KeyCharacterMap> keyboardLayout =
1081 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1082 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1083 bumpGeneration();
1084 }
1085 }
1086 }
1087
1088 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1089 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001090 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 if (mAlias != alias) {
1092 mAlias = alias;
1093 bumpGeneration();
1094 }
1095 }
1096 }
1097
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001098 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1099 ssize_t index = config->disabledDevices.indexOf(mId);
1100 bool enabled = index < 0;
1101 setEnabled(enabled, when);
1102 }
1103
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001104 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001105 // In most situations, no port will be specified.
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001106 mAssociatedDisplayPort = std::nullopt;
1107 // Find the display port that corresponds to the current input port.
1108 const std::string& inputPort = mIdentifier.location;
1109 if (!inputPort.empty()) {
1110 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1111 const auto& displayPort = ports.find(inputPort);
1112 if (displayPort != ports.end()) {
1113 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1114 }
1115 }
1116 }
1117
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001118 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 mapper->configure(when, config, changes);
1120 mSources |= mapper->getSources();
1121 }
1122 }
1123}
1124
1125void InputDevice::reset(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001126 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 mapper->reset(when);
1128 }
1129
1130 mContext->updateGlobalMetaState();
1131
1132 notifyReset(when);
1133}
1134
1135void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1136 // Process all of the events in order for each mapper.
1137 // We cannot simply ask each mapper to process them in bulk because mappers may
1138 // have side-effects that must be interleaved. For example, joystick movement events and
1139 // gamepad button presses are handled by different mappers but they should be dispatched
1140 // in the order received.
Ivan Lozano96f12992017-11-09 14:45:38 -08001141 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001143 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Prabir Pradhan2b281812019-08-29 14:12:42 -07001144 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value, rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145#endif
1146
1147 if (mDropUntilNextSync) {
1148 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1149 mDropUntilNextSync = false;
1150#if DEBUG_RAW_EVENTS
1151 ALOGD("Recovered from input event buffer overrun.");
1152#endif
1153 } else {
1154#if DEBUG_RAW_EVENTS
1155 ALOGD("Dropped input event while waiting for next input sync.");
1156#endif
1157 }
1158 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001159 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 mDropUntilNextSync = true;
1161 reset(rawEvent->when);
1162 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001163 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 mapper->process(rawEvent);
1165 }
1166 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001167 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
1169}
1170
1171void InputDevice::timeoutExpired(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001172 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 mapper->timeoutExpired(when);
1174 }
1175}
1176
Michael Wright842500e2015-03-13 17:32:02 -07001177void InputDevice::updateExternalStylusState(const StylusState& state) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001178 for (InputMapper* mapper : mMappers) {
Michael Wright842500e2015-03-13 17:32:02 -07001179 mapper->updateExternalStylusState(state);
1180 }
1181}
1182
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001184 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal,
1185 mHasMic);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001186 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 mapper->populateDeviceInfo(outDeviceInfo);
1188 }
1189}
1190
1191int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001192 return getState(sourceMask, keyCode, &InputMapper::getKeyCodeState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193}
1194
1195int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001196 return getState(sourceMask, scanCode, &InputMapper::getScanCodeState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197}
1198
1199int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001200 return getState(sourceMask, switchCode, &InputMapper::getSwitchState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201}
1202
1203int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1204 int32_t result = AKEY_STATE_UNKNOWN;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001205 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1207 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1208 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1209 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1210 if (currentResult >= AKEY_STATE_DOWN) {
1211 return currentResult;
1212 } else if (currentResult == AKEY_STATE_UP) {
1213 result = currentResult;
1214 }
1215 }
1216 }
1217 return result;
1218}
1219
1220bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
Prabir Pradhan2b281812019-08-29 14:12:42 -07001221 const int32_t* keyCodes, uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 bool result = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001223 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1225 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1226 }
1227 }
1228 return result;
1229}
1230
1231void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
Prabir Pradhan2b281812019-08-29 14:12:42 -07001232 int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001233 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 mapper->vibrate(pattern, patternSize, repeat, token);
1235 }
1236}
1237
1238void InputDevice::cancelVibrate(int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001239 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 mapper->cancelVibrate(token);
1241 }
1242}
1243
Jeff Brownc9aa6282015-02-11 19:03:28 -08001244void InputDevice::cancelTouch(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001245 for (InputMapper* mapper : mMappers) {
Jeff Brownc9aa6282015-02-11 19:03:28 -08001246 mapper->cancelTouch(when);
1247 }
1248}
1249
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250int32_t InputDevice::getMetaState() {
1251 int32_t result = 0;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001252 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 result |= mapper->getMetaState();
1254 }
1255 return result;
1256}
1257
Andrii Kulian763a3a42016-03-08 10:46:16 -08001258void InputDevice::updateMetaState(int32_t keyCode) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001259 for (InputMapper* mapper : mMappers) {
1260 mapper->updateMetaState(keyCode);
Andrii Kulian763a3a42016-03-08 10:46:16 -08001261 }
1262}
1263
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264void InputDevice::fadePointer() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001265 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 mapper->fadePointer();
1267 }
1268}
1269
1270void InputDevice::bumpGeneration() {
1271 mGeneration = mContext->bumpGeneration();
1272}
1273
1274void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001275 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 mContext->getListener()->notifyDeviceReset(&args);
1277}
1278
Arthur Hungc23540e2018-11-29 20:42:11 +08001279std::optional<int32_t> InputDevice::getAssociatedDisplay() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001280 for (InputMapper* mapper : mMappers) {
Arthur Hungc23540e2018-11-29 20:42:11 +08001281 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplay();
1282 if (associatedDisplayId) {
1283 return associatedDisplayId;
1284 }
1285 }
1286
1287 return std::nullopt;
1288}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289
1290// --- CursorButtonAccumulator ---
1291
1292CursorButtonAccumulator::CursorButtonAccumulator() {
1293 clearButtons();
1294}
1295
1296void CursorButtonAccumulator::reset(InputDevice* device) {
1297 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1298 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1299 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1300 mBtnBack = device->isKeyPressed(BTN_BACK);
1301 mBtnSide = device->isKeyPressed(BTN_SIDE);
1302 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1303 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1304 mBtnTask = device->isKeyPressed(BTN_TASK);
1305}
1306
1307void CursorButtonAccumulator::clearButtons() {
1308 mBtnLeft = 0;
1309 mBtnRight = 0;
1310 mBtnMiddle = 0;
1311 mBtnBack = 0;
1312 mBtnSide = 0;
1313 mBtnForward = 0;
1314 mBtnExtra = 0;
1315 mBtnTask = 0;
1316}
1317
1318void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1319 if (rawEvent->type == EV_KEY) {
1320 switch (rawEvent->code) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001321 case BTN_LEFT:
1322 mBtnLeft = rawEvent->value;
1323 break;
1324 case BTN_RIGHT:
1325 mBtnRight = rawEvent->value;
1326 break;
1327 case BTN_MIDDLE:
1328 mBtnMiddle = rawEvent->value;
1329 break;
1330 case BTN_BACK:
1331 mBtnBack = rawEvent->value;
1332 break;
1333 case BTN_SIDE:
1334 mBtnSide = rawEvent->value;
1335 break;
1336 case BTN_FORWARD:
1337 mBtnForward = rawEvent->value;
1338 break;
1339 case BTN_EXTRA:
1340 mBtnExtra = rawEvent->value;
1341 break;
1342 case BTN_TASK:
1343 mBtnTask = rawEvent->value;
1344 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 }
1346 }
1347}
1348
1349uint32_t CursorButtonAccumulator::getButtonState() const {
1350 uint32_t result = 0;
1351 if (mBtnLeft) {
1352 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1353 }
1354 if (mBtnRight) {
1355 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1356 }
1357 if (mBtnMiddle) {
1358 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1359 }
1360 if (mBtnBack || mBtnSide) {
1361 result |= AMOTION_EVENT_BUTTON_BACK;
1362 }
1363 if (mBtnForward || mBtnExtra) {
1364 result |= AMOTION_EVENT_BUTTON_FORWARD;
1365 }
1366 return result;
1367}
1368
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369// --- CursorMotionAccumulator ---
1370
1371CursorMotionAccumulator::CursorMotionAccumulator() {
1372 clearRelativeAxes();
1373}
1374
1375void CursorMotionAccumulator::reset(InputDevice* device) {
1376 clearRelativeAxes();
1377}
1378
1379void CursorMotionAccumulator::clearRelativeAxes() {
1380 mRelX = 0;
1381 mRelY = 0;
1382}
1383
1384void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1385 if (rawEvent->type == EV_REL) {
1386 switch (rawEvent->code) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001387 case REL_X:
1388 mRelX = rawEvent->value;
1389 break;
1390 case REL_Y:
1391 mRelY = rawEvent->value;
1392 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 }
1394 }
1395}
1396
1397void CursorMotionAccumulator::finishSync() {
1398 clearRelativeAxes();
1399}
1400
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401// --- CursorScrollAccumulator ---
1402
Prabir Pradhan2b281812019-08-29 14:12:42 -07001403CursorScrollAccumulator::CursorScrollAccumulator() : mHaveRelWheel(false), mHaveRelHWheel(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 clearRelativeAxes();
1405}
1406
1407void CursorScrollAccumulator::configure(InputDevice* device) {
1408 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1409 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1410}
1411
1412void CursorScrollAccumulator::reset(InputDevice* device) {
1413 clearRelativeAxes();
1414}
1415
1416void CursorScrollAccumulator::clearRelativeAxes() {
1417 mRelWheel = 0;
1418 mRelHWheel = 0;
1419}
1420
1421void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1422 if (rawEvent->type == EV_REL) {
1423 switch (rawEvent->code) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001424 case REL_WHEEL:
1425 mRelWheel = rawEvent->value;
1426 break;
1427 case REL_HWHEEL:
1428 mRelHWheel = rawEvent->value;
1429 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 }
1431 }
1432}
1433
1434void CursorScrollAccumulator::finishSync() {
1435 clearRelativeAxes();
1436}
1437
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438// --- TouchButtonAccumulator ---
1439
Prabir Pradhan2b281812019-08-29 14:12:42 -07001440TouchButtonAccumulator::TouchButtonAccumulator() : mHaveBtnTouch(false), mHaveStylus(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 clearButtons();
1442}
1443
1444void TouchButtonAccumulator::configure(InputDevice* device) {
1445 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
Prabir Pradhan2b281812019-08-29 14:12:42 -07001446 mHaveStylus = device->hasKey(BTN_TOOL_PEN) || device->hasKey(BTN_TOOL_RUBBER) ||
1447 device->hasKey(BTN_TOOL_BRUSH) || device->hasKey(BTN_TOOL_PENCIL) ||
1448 device->hasKey(BTN_TOOL_AIRBRUSH);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449}
1450
1451void TouchButtonAccumulator::reset(InputDevice* device) {
1452 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1453 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001454 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Prabir Pradhan2b281812019-08-29 14:12:42 -07001455 mBtnStylus2 = device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1457 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1458 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1459 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1460 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1461 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1462 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1463 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1464 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1465 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1466 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1467}
1468
1469void TouchButtonAccumulator::clearButtons() {
1470 mBtnTouch = 0;
1471 mBtnStylus = 0;
1472 mBtnStylus2 = 0;
1473 mBtnToolFinger = 0;
1474 mBtnToolPen = 0;
1475 mBtnToolRubber = 0;
1476 mBtnToolBrush = 0;
1477 mBtnToolPencil = 0;
1478 mBtnToolAirbrush = 0;
1479 mBtnToolMouse = 0;
1480 mBtnToolLens = 0;
1481 mBtnToolDoubleTap = 0;
1482 mBtnToolTripleTap = 0;
1483 mBtnToolQuadTap = 0;
1484}
1485
1486void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1487 if (rawEvent->type == EV_KEY) {
1488 switch (rawEvent->code) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001489 case BTN_TOUCH:
1490 mBtnTouch = rawEvent->value;
1491 break;
1492 case BTN_STYLUS:
1493 mBtnStylus = rawEvent->value;
1494 break;
1495 case BTN_STYLUS2:
1496 case BTN_0: // BTN_0 is what gets mapped for the HID usage
1497 // Digitizers.SecondaryBarrelSwitch
1498 mBtnStylus2 = rawEvent->value;
1499 break;
1500 case BTN_TOOL_FINGER:
1501 mBtnToolFinger = rawEvent->value;
1502 break;
1503 case BTN_TOOL_PEN:
1504 mBtnToolPen = rawEvent->value;
1505 break;
1506 case BTN_TOOL_RUBBER:
1507 mBtnToolRubber = rawEvent->value;
1508 break;
1509 case BTN_TOOL_BRUSH:
1510 mBtnToolBrush = rawEvent->value;
1511 break;
1512 case BTN_TOOL_PENCIL:
1513 mBtnToolPencil = rawEvent->value;
1514 break;
1515 case BTN_TOOL_AIRBRUSH:
1516 mBtnToolAirbrush = rawEvent->value;
1517 break;
1518 case BTN_TOOL_MOUSE:
1519 mBtnToolMouse = rawEvent->value;
1520 break;
1521 case BTN_TOOL_LENS:
1522 mBtnToolLens = rawEvent->value;
1523 break;
1524 case BTN_TOOL_DOUBLETAP:
1525 mBtnToolDoubleTap = rawEvent->value;
1526 break;
1527 case BTN_TOOL_TRIPLETAP:
1528 mBtnToolTripleTap = rawEvent->value;
1529 break;
1530 case BTN_TOOL_QUADTAP:
1531 mBtnToolQuadTap = rawEvent->value;
1532 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
1534 }
1535}
1536
1537uint32_t TouchButtonAccumulator::getButtonState() const {
1538 uint32_t result = 0;
1539 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001540 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 }
1542 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001543 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545 return result;
1546}
1547
1548int32_t TouchButtonAccumulator::getToolType() const {
1549 if (mBtnToolMouse || mBtnToolLens) {
1550 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1551 }
1552 if (mBtnToolRubber) {
1553 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1554 }
1555 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1556 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1557 }
1558 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1559 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1560 }
1561 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1562}
1563
1564bool TouchButtonAccumulator::isToolActive() const {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001565 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber || mBtnToolBrush ||
1566 mBtnToolPencil || mBtnToolAirbrush || mBtnToolMouse || mBtnToolLens ||
1567 mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568}
1569
1570bool TouchButtonAccumulator::isHovering() const {
1571 return mHaveBtnTouch && !mBtnTouch;
1572}
1573
1574bool TouchButtonAccumulator::hasStylus() const {
1575 return mHaveStylus;
1576}
1577
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578// --- RawPointerAxes ---
1579
1580RawPointerAxes::RawPointerAxes() {
1581 clear();
1582}
1583
1584void RawPointerAxes::clear() {
1585 x.clear();
1586 y.clear();
1587 pressure.clear();
1588 touchMajor.clear();
1589 touchMinor.clear();
1590 toolMajor.clear();
1591 toolMinor.clear();
1592 orientation.clear();
1593 distance.clear();
1594 tiltX.clear();
1595 tiltY.clear();
1596 trackingId.clear();
1597 slot.clear();
1598}
1599
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600// --- RawPointerData ---
1601
1602RawPointerData::RawPointerData() {
1603 clear();
1604}
1605
1606void RawPointerData::clear() {
1607 pointerCount = 0;
1608 clearIdBits();
1609}
1610
1611void RawPointerData::copyFrom(const RawPointerData& other) {
1612 pointerCount = other.pointerCount;
1613 hoveringIdBits = other.hoveringIdBits;
1614 touchingIdBits = other.touchingIdBits;
1615
1616 for (uint32_t i = 0; i < pointerCount; i++) {
1617 pointers[i] = other.pointers[i];
1618
1619 int id = pointers[i].id;
1620 idToIndex[id] = other.idToIndex[id];
1621 }
1622}
1623
1624void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1625 float x = 0, y = 0;
1626 uint32_t count = touchingIdBits.count();
1627 if (count) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001628 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 uint32_t id = idBits.clearFirstMarkedBit();
1630 const Pointer& pointer = pointerForId(id);
1631 x += pointer.x;
1632 y += pointer.y;
1633 }
1634 x /= count;
1635 y /= count;
1636 }
1637 *outX = x;
1638 *outY = y;
1639}
1640
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641// --- CookedPointerData ---
1642
1643CookedPointerData::CookedPointerData() {
1644 clear();
1645}
1646
1647void CookedPointerData::clear() {
1648 pointerCount = 0;
1649 hoveringIdBits.clear();
1650 touchingIdBits.clear();
1651}
1652
1653void CookedPointerData::copyFrom(const CookedPointerData& other) {
1654 pointerCount = other.pointerCount;
1655 hoveringIdBits = other.hoveringIdBits;
1656 touchingIdBits = other.touchingIdBits;
1657
1658 for (uint32_t i = 0; i < pointerCount; i++) {
1659 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1660 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1661
1662 int id = pointerProperties[i].id;
1663 idToIndex[id] = other.idToIndex[id];
1664 }
1665}
1666
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667// --- SingleTouchMotionAccumulator ---
1668
1669SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1670 clearAbsoluteAxes();
1671}
1672
1673void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1674 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1675 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1676 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1677 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1678 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1679 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1680 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1681}
1682
1683void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1684 mAbsX = 0;
1685 mAbsY = 0;
1686 mAbsPressure = 0;
1687 mAbsToolWidth = 0;
1688 mAbsDistance = 0;
1689 mAbsTiltX = 0;
1690 mAbsTiltY = 0;
1691}
1692
1693void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1694 if (rawEvent->type == EV_ABS) {
1695 switch (rawEvent->code) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001696 case ABS_X:
1697 mAbsX = rawEvent->value;
1698 break;
1699 case ABS_Y:
1700 mAbsY = rawEvent->value;
1701 break;
1702 case ABS_PRESSURE:
1703 mAbsPressure = rawEvent->value;
1704 break;
1705 case ABS_TOOL_WIDTH:
1706 mAbsToolWidth = rawEvent->value;
1707 break;
1708 case ABS_DISTANCE:
1709 mAbsDistance = rawEvent->value;
1710 break;
1711 case ABS_TILT_X:
1712 mAbsTiltX = rawEvent->value;
1713 break;
1714 case ABS_TILT_Y:
1715 mAbsTiltY = rawEvent->value;
1716 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
1718 }
1719}
1720
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721// --- MultiTouchMotionAccumulator ---
1722
Prabir Pradhan2b281812019-08-29 14:12:42 -07001723MultiTouchMotionAccumulator::MultiTouchMotionAccumulator()
1724 : mCurrentSlot(-1),
1725 mSlots(nullptr),
1726 mSlotCount(0),
1727 mUsingSlotsProtocol(false),
1728 mHaveStylus(false),
1729 mDeviceTimestamp(0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730
1731MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1732 delete[] mSlots;
1733}
1734
Prabir Pradhan2b281812019-08-29 14:12:42 -07001735void MultiTouchMotionAccumulator::configure(InputDevice* device, size_t slotCount,
1736 bool usingSlotsProtocol) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 mSlotCount = slotCount;
1738 mUsingSlotsProtocol = usingSlotsProtocol;
1739 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1740
1741 delete[] mSlots;
1742 mSlots = new Slot[slotCount];
1743}
1744
1745void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1746 // Unfortunately there is no way to read the initial contents of the slots.
1747 // So when we reset the accumulator, we must assume they are all zeroes.
1748 if (mUsingSlotsProtocol) {
1749 // Query the driver for the current slot index and use it as the initial slot
1750 // before we start reading events from the device. It is possible that the
1751 // current slot index will not be the same as it was when the first event was
1752 // written into the evdev buffer, which means the input mapper could start
1753 // out of sync with the initial state of the events in the evdev buffer.
1754 // In the extremely unlikely case that this happens, the data from
1755 // two slots will be confused until the next ABS_MT_SLOT event is received.
1756 // This can cause the touch point to "jump", but at least there will be
1757 // no stuck touches.
1758 int32_t initialSlot;
Prabir Pradhan2b281812019-08-29 14:12:42 -07001759 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(), ABS_MT_SLOT,
1760 &initialSlot);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 if (status) {
1762 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1763 initialSlot = -1;
1764 }
1765 clearSlots(initialSlot);
1766 } else {
1767 clearSlots(-1);
1768 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001769 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770}
1771
1772void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1773 if (mSlots) {
1774 for (size_t i = 0; i < mSlotCount; i++) {
1775 mSlots[i].clear();
1776 }
1777 }
1778 mCurrentSlot = initialSlot;
1779}
1780
1781void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1782 if (rawEvent->type == EV_ABS) {
1783 bool newSlot = false;
1784 if (mUsingSlotsProtocol) {
1785 if (rawEvent->code == ABS_MT_SLOT) {
1786 mCurrentSlot = rawEvent->value;
1787 newSlot = true;
1788 }
1789 } else if (mCurrentSlot < 0) {
1790 mCurrentSlot = 0;
1791 }
1792
1793 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1794#if DEBUG_POINTERS
1795 if (newSlot) {
1796 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Prabir Pradhan2b281812019-08-29 14:12:42 -07001797 "should be between 0 and %zd; ignoring this slot.",
1798 mCurrentSlot, mSlotCount - 1);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
1800#endif
1801 } else {
1802 Slot* slot = &mSlots[mCurrentSlot];
1803
1804 switch (rawEvent->code) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001805 case ABS_MT_POSITION_X:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 slot->mInUse = true;
Prabir Pradhan2b281812019-08-29 14:12:42 -07001807 slot->mAbsMTPositionX = rawEvent->value;
1808 break;
1809 case ABS_MT_POSITION_Y:
1810 slot->mInUse = true;
1811 slot->mAbsMTPositionY = rawEvent->value;
1812 break;
1813 case ABS_MT_TOUCH_MAJOR:
1814 slot->mInUse = true;
1815 slot->mAbsMTTouchMajor = rawEvent->value;
1816 break;
1817 case ABS_MT_TOUCH_MINOR:
1818 slot->mInUse = true;
1819 slot->mAbsMTTouchMinor = rawEvent->value;
1820 slot->mHaveAbsMTTouchMinor = true;
1821 break;
1822 case ABS_MT_WIDTH_MAJOR:
1823 slot->mInUse = true;
1824 slot->mAbsMTWidthMajor = rawEvent->value;
1825 break;
1826 case ABS_MT_WIDTH_MINOR:
1827 slot->mInUse = true;
1828 slot->mAbsMTWidthMinor = rawEvent->value;
1829 slot->mHaveAbsMTWidthMinor = true;
1830 break;
1831 case ABS_MT_ORIENTATION:
1832 slot->mInUse = true;
1833 slot->mAbsMTOrientation = rawEvent->value;
1834 break;
1835 case ABS_MT_TRACKING_ID:
1836 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1837 // The slot is no longer in use but it retains its previous contents,
1838 // which may be reused for subsequent touches.
1839 slot->mInUse = false;
1840 } else {
1841 slot->mInUse = true;
1842 slot->mAbsMTTrackingId = rawEvent->value;
1843 }
1844 break;
1845 case ABS_MT_PRESSURE:
1846 slot->mInUse = true;
1847 slot->mAbsMTPressure = rawEvent->value;
1848 break;
1849 case ABS_MT_DISTANCE:
1850 slot->mInUse = true;
1851 slot->mAbsMTDistance = rawEvent->value;
1852 break;
1853 case ABS_MT_TOOL_TYPE:
1854 slot->mInUse = true;
1855 slot->mAbsMTToolType = rawEvent->value;
1856 slot->mHaveAbsMTToolType = true;
1857 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 }
1859 }
1860 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1861 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1862 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001863 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1864 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 }
1866}
1867
1868void MultiTouchMotionAccumulator::finishSync() {
1869 if (!mUsingSlotsProtocol) {
1870 clearSlots(-1);
1871 }
1872}
1873
1874bool MultiTouchMotionAccumulator::hasStylus() const {
1875 return mHaveStylus;
1876}
1877
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878// --- MultiTouchMotionAccumulator::Slot ---
1879
1880MultiTouchMotionAccumulator::Slot::Slot() {
1881 clear();
1882}
1883
1884void MultiTouchMotionAccumulator::Slot::clear() {
1885 mInUse = false;
1886 mHaveAbsMTTouchMinor = false;
1887 mHaveAbsMTWidthMinor = false;
1888 mHaveAbsMTToolType = false;
1889 mAbsMTPositionX = 0;
1890 mAbsMTPositionY = 0;
1891 mAbsMTTouchMajor = 0;
1892 mAbsMTTouchMinor = 0;
1893 mAbsMTWidthMajor = 0;
1894 mAbsMTWidthMinor = 0;
1895 mAbsMTOrientation = 0;
1896 mAbsMTTrackingId = -1;
1897 mAbsMTPressure = 0;
1898 mAbsMTDistance = 0;
1899 mAbsMTToolType = 0;
1900}
1901
1902int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1903 if (mHaveAbsMTToolType) {
1904 switch (mAbsMTToolType) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001905 case MT_TOOL_FINGER:
1906 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1907 case MT_TOOL_PEN:
1908 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 }
1910 }
1911 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1912}
1913
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914// --- InputMapper ---
1915
Prabir Pradhan2b281812019-08-29 14:12:42 -07001916InputMapper::InputMapper(InputDevice* device) : mDevice(device), mContext(device->getContext()) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917
Prabir Pradhan2b281812019-08-29 14:12:42 -07001918InputMapper::~InputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919
1920void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1921 info->addSource(getSources());
1922}
1923
Prabir Pradhan2b281812019-08-29 14:12:42 -07001924void InputMapper::dump(std::string& dump) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925
Prabir Pradhan2b281812019-08-29 14:12:42 -07001926void InputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
1927 uint32_t changes) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928
Prabir Pradhan2b281812019-08-29 14:12:42 -07001929void InputMapper::reset(nsecs_t when) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930
Prabir Pradhan2b281812019-08-29 14:12:42 -07001931void InputMapper::timeoutExpired(nsecs_t when) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
1933int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1934 return AKEY_STATE_UNKNOWN;
1935}
1936
1937int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1938 return AKEY_STATE_UNKNOWN;
1939}
1940
1941int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1942 return AKEY_STATE_UNKNOWN;
1943}
1944
1945bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
Prabir Pradhan2b281812019-08-29 14:12:42 -07001946 const int32_t* keyCodes, uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 return false;
1948}
1949
1950void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
Prabir Pradhan2b281812019-08-29 14:12:42 -07001951 int32_t token) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952
Prabir Pradhan2b281812019-08-29 14:12:42 -07001953void InputMapper::cancelVibrate(int32_t token) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954
Prabir Pradhan2b281812019-08-29 14:12:42 -07001955void InputMapper::cancelTouch(nsecs_t when) {}
Jeff Brownc9aa6282015-02-11 19:03:28 -08001956
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957int32_t InputMapper::getMetaState() {
1958 return 0;
1959}
1960
Prabir Pradhan2b281812019-08-29 14:12:42 -07001961void InputMapper::updateMetaState(int32_t keyCode) {}
Andrii Kulian763a3a42016-03-08 10:46:16 -08001962
Prabir Pradhan2b281812019-08-29 14:12:42 -07001963void InputMapper::updateExternalStylusState(const StylusState& state) {}
Michael Wright842500e2015-03-13 17:32:02 -07001964
Prabir Pradhan2b281812019-08-29 14:12:42 -07001965void InputMapper::fadePointer() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966
1967status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1968 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1969}
1970
1971void InputMapper::bumpGeneration() {
1972 mDevice->bumpGeneration();
1973}
1974
Prabir Pradhan2b281812019-08-29 14:12:42 -07001975void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump, const RawAbsoluteAxisInfo& axis,
1976 const char* name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 if (axis.valid) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07001978 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n", name,
1979 axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001981 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
1983}
1984
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001985void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
1986 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
1987 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
1988 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
1989 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07001990}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991
1992// --- SwitchInputMapper ---
1993
Prabir Pradhan2b281812019-08-29 14:12:42 -07001994SwitchInputMapper::SwitchInputMapper(InputDevice* device)
1995 : InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996
Prabir Pradhan2b281812019-08-29 14:12:42 -07001997SwitchInputMapper::~SwitchInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998
1999uint32_t SwitchInputMapper::getSources() {
2000 return AINPUT_SOURCE_SWITCH;
2001}
2002
2003void SwitchInputMapper::process(const RawEvent* rawEvent) {
2004 switch (rawEvent->type) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07002005 case EV_SW:
2006 processSwitch(rawEvent->code, rawEvent->value);
2007 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008
Prabir Pradhan2b281812019-08-29 14:12:42 -07002009 case EV_SYN:
2010 if (rawEvent->code == SYN_REPORT) {
2011 sync(rawEvent->when);
2012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 }
2014}
2015
2016void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2017 if (switchCode >= 0 && switchCode < 32) {
2018 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002019 mSwitchValues |= 1 << switchCode;
2020 } else {
2021 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 }
2023 mUpdatedSwitchMask |= 1 << switchCode;
2024 }
2025}
2026
2027void SwitchInputMapper::sync(nsecs_t when) {
2028 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002029 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002030 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
Prabir Pradhan2b281812019-08-29 14:12:42 -07002031 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 getListener()->notifySwitch(&args);
2033
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 mUpdatedSwitchMask = 0;
2035 }
2036}
2037
2038int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2039 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2040}
2041
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002042void SwitchInputMapper::dump(std::string& dump) {
2043 dump += INDENT2 "Switch Input Mapper:\n";
2044 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002045}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046
2047// --- VibratorInputMapper ---
2048
Prabir Pradhan2b281812019-08-29 14:12:42 -07002049VibratorInputMapper::VibratorInputMapper(InputDevice* device)
2050 : InputMapper(device), mVibrating(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051
Prabir Pradhan2b281812019-08-29 14:12:42 -07002052VibratorInputMapper::~VibratorInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053
2054uint32_t VibratorInputMapper::getSources() {
2055 return 0;
2056}
2057
2058void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2059 InputMapper::populateDeviceInfo(info);
2060
2061 info->setVibrator(true);
2062}
2063
2064void VibratorInputMapper::process(const RawEvent* rawEvent) {
2065 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2066}
2067
2068void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
Prabir Pradhan2b281812019-08-29 14:12:42 -07002069 int32_t token) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002071 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 for (size_t i = 0; i < patternSize; i++) {
2073 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002074 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002076 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07002078 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d", getDeviceId(),
2079 patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080#endif
2081
2082 mVibrating = true;
2083 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2084 mPatternSize = patternSize;
2085 mRepeat = repeat;
2086 mToken = token;
2087 mIndex = -1;
2088
2089 nextStep();
2090}
2091
2092void VibratorInputMapper::cancelVibrate(int32_t token) {
2093#if DEBUG_VIBRATOR
2094 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2095#endif
2096
2097 if (mVibrating && mToken == token) {
2098 stopVibrating();
2099 }
2100}
2101
2102void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2103 if (mVibrating) {
2104 if (when >= mNextStepTime) {
2105 nextStep();
2106 } else {
2107 getContext()->requestTimeoutAtTime(mNextStepTime);
2108 }
2109 }
2110}
2111
2112void VibratorInputMapper::nextStep() {
2113 mIndex += 1;
2114 if (size_t(mIndex) >= mPatternSize) {
2115 if (mRepeat < 0) {
2116 // We are done.
2117 stopVibrating();
2118 return;
2119 }
2120 mIndex = mRepeat;
2121 }
2122
2123 bool vibratorOn = mIndex & 1;
2124 nsecs_t duration = mPattern[mIndex];
2125 if (vibratorOn) {
2126#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002127 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128#endif
2129 getEventHub()->vibrate(getDeviceId(), duration);
2130 } else {
2131#if DEBUG_VIBRATOR
2132 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2133#endif
2134 getEventHub()->cancelVibrate(getDeviceId());
2135 }
2136 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2137 mNextStepTime = now + duration;
2138 getContext()->requestTimeoutAtTime(mNextStepTime);
2139#if DEBUG_VIBRATOR
2140 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2141#endif
2142}
2143
2144void VibratorInputMapper::stopVibrating() {
2145 mVibrating = false;
2146#if DEBUG_VIBRATOR
2147 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2148#endif
2149 getEventHub()->cancelVibrate(getDeviceId());
2150}
2151
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002152void VibratorInputMapper::dump(std::string& dump) {
2153 dump += INDENT2 "Vibrator Input Mapper:\n";
2154 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155}
2156
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157// --- KeyboardInputMapper ---
2158
Prabir Pradhan2b281812019-08-29 14:12:42 -07002159KeyboardInputMapper::KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType)
2160 : InputMapper(device), mSource(source), mKeyboardType(keyboardType) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161
Prabir Pradhan2b281812019-08-29 14:12:42 -07002162KeyboardInputMapper::~KeyboardInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163
2164uint32_t KeyboardInputMapper::getSources() {
2165 return mSource;
2166}
2167
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002168int32_t KeyboardInputMapper::getOrientation() {
2169 if (mViewport) {
2170 return mViewport->orientation;
2171 }
2172 return DISPLAY_ORIENTATION_0;
2173}
2174
2175int32_t KeyboardInputMapper::getDisplayId() {
2176 if (mViewport) {
2177 return mViewport->displayId;
2178 }
2179 return ADISPLAY_ID_NONE;
2180}
2181
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2183 InputMapper::populateDeviceInfo(info);
2184
2185 info->setKeyboardType(mKeyboardType);
2186 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2187}
2188
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002189void KeyboardInputMapper::dump(std::string& dump) {
2190 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002192 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002193 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002194 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2195 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2196 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197}
2198
Prabir Pradhan2b281812019-08-29 14:12:42 -07002199void KeyboardInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
2200 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 InputMapper::configure(when, config, changes);
2202
2203 if (!changes) { // first time only
2204 // Configure basic parameters.
2205 configureParameters();
2206 }
2207
2208 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002209 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002210 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
2212 }
2213}
2214
Prabir Pradhan2b281812019-08-29 14:12:42 -07002215static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const* property) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002216 int32_t mapped = 0;
2217 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2218 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2219 if (stemKeyRotationMap[i][0] == keyCode) {
2220 stemKeyRotationMap[i][1] = mapped;
2221 return;
2222 }
2223 }
2224 }
2225}
2226
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227void KeyboardInputMapper::configureParameters() {
2228 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002229 const PropertyMap& config = getDevice()->getConfiguration();
Prabir Pradhan2b281812019-08-29 14:12:42 -07002230 config.tryGetProperty(String8("keyboard.orientationAware"), mParameters.orientationAware);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002233 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2234 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2235 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2236 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002238
2239 mParameters.handlesKeyRepeat = false;
Prabir Pradhan2b281812019-08-29 14:12:42 -07002240 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"), mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241}
2242
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002243void KeyboardInputMapper::dumpParameters(std::string& dump) {
2244 dump += INDENT3 "Parameters:\n";
Prabir Pradhan2b281812019-08-29 14:12:42 -07002245 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
2246 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n", toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247}
2248
2249void KeyboardInputMapper::reset(nsecs_t when) {
2250 mMetaState = AMETA_NONE;
2251 mDownTime = 0;
2252 mKeyDowns.clear();
2253 mCurrentHidUsage = 0;
2254
2255 resetLedState();
2256
2257 InputMapper::reset(when);
2258}
2259
2260void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2261 switch (rawEvent->type) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07002262 case EV_KEY: {
2263 int32_t scanCode = rawEvent->code;
2264 int32_t usageCode = mCurrentHidUsage;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 mCurrentHidUsage = 0;
Prabir Pradhan2b281812019-08-29 14:12:42 -07002266
2267 if (isKeyboardOrGamepadKey(scanCode)) {
2268 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
2269 }
2270 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07002272 case EV_MSC: {
2273 if (rawEvent->code == MSC_SCAN) {
2274 mCurrentHidUsage = rawEvent->value;
2275 }
2276 break;
2277 }
2278 case EV_SYN: {
2279 if (rawEvent->code == SYN_REPORT) {
2280 mCurrentHidUsage = 0;
2281 }
2282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284}
2285
2286bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07002287 return scanCode < BTN_MOUSE || scanCode >= KEY_OK ||
2288 (scanCode >= BTN_MISC && scanCode < BTN_MOUSE) ||
2289 (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290}
2291
Michael Wright58ba9882017-07-26 16:19:11 +01002292bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2293 switch (keyCode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07002294 case AKEYCODE_MEDIA_PLAY:
2295 case AKEYCODE_MEDIA_PAUSE:
2296 case AKEYCODE_MEDIA_PLAY_PAUSE:
2297 case AKEYCODE_MUTE:
2298 case AKEYCODE_HEADSETHOOK:
2299 case AKEYCODE_MEDIA_STOP:
2300 case AKEYCODE_MEDIA_NEXT:
2301 case AKEYCODE_MEDIA_PREVIOUS:
2302 case AKEYCODE_MEDIA_REWIND:
2303 case AKEYCODE_MEDIA_RECORD:
2304 case AKEYCODE_MEDIA_FAST_FORWARD:
2305 case AKEYCODE_MEDIA_SKIP_FORWARD:
2306 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2307 case AKEYCODE_MEDIA_STEP_FORWARD:
2308 case AKEYCODE_MEDIA_STEP_BACKWARD:
2309 case AKEYCODE_MEDIA_AUDIO_TRACK:
2310 case AKEYCODE_VOLUME_UP:
2311 case AKEYCODE_VOLUME_DOWN:
2312 case AKEYCODE_VOLUME_MUTE:
2313 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2314 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2315 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2316 return true;
Michael Wright58ba9882017-07-26 16:19:11 +01002317 }
2318 return false;
2319}
2320
Prabir Pradhan2b281812019-08-29 14:12:42 -07002321void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, int32_t usageCode) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002322 int32_t keyCode;
2323 int32_t keyMetaState;
2324 uint32_t policyFlags;
2325
Prabir Pradhan2b281812019-08-29 14:12:42 -07002326 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState, &keyCode,
2327 &keyMetaState, &policyFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002328 keyCode = AKEYCODE_UNKNOWN;
2329 keyMetaState = mMetaState;
2330 policyFlags = 0;
2331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332
2333 if (down) {
2334 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002335 if (mParameters.orientationAware) {
2336 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 }
2338
2339 // Add key down.
2340 ssize_t keyDownIndex = findKeyDown(scanCode);
2341 if (keyDownIndex >= 0) {
2342 // key repeat, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002343 keyCode = mKeyDowns[keyDownIndex].keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 } else {
2345 // key down
Prabir Pradhan2b281812019-08-29 14:12:42 -07002346 if ((policyFlags & POLICY_FLAG_VIRTUAL) &&
2347 mContext->shouldDropVirtualKey(when, getDevice(), keyCode, scanCode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 return;
2349 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002350 if (policyFlags & POLICY_FLAG_GESTURE) {
2351 mDevice->cancelTouch(when);
2352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002354 KeyDown keyDown;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 keyDown.keyCode = keyCode;
2356 keyDown.scanCode = scanCode;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002357 mKeyDowns.push_back(keyDown);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 }
2359
2360 mDownTime = when;
2361 } else {
2362 // Remove key down.
2363 ssize_t keyDownIndex = findKeyDown(scanCode);
2364 if (keyDownIndex >= 0) {
2365 // key up, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002366 keyCode = mKeyDowns[keyDownIndex].keyCode;
2367 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 } else {
2369 // key was not actually down
2370 ALOGI("Dropping key up from device %s because the key was not down. "
Prabir Pradhan2b281812019-08-29 14:12:42 -07002371 "keyCode=%d, scanCode=%d",
2372 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 return;
2374 }
2375 }
2376
Andrii Kulian763a3a42016-03-08 10:46:16 -08002377 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002378 // If global meta state changed send it along with the key.
2379 // If it has not changed then we'll use what keymap gave us,
2380 // since key replacement logic might temporarily reset a few
2381 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002382 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 }
2384
2385 nsecs_t downTime = mDownTime;
2386
2387 // Key down on external an keyboard should wake the device.
2388 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2389 // For internal keyboards, the key layout file should specify the policy flags for
2390 // each wake key individually.
2391 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002392 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002393 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
2395
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002396 if (mParameters.handlesKeyRepeat) {
2397 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2398 }
2399
Prabir Pradhan2b281812019-08-29 14:12:42 -07002400 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, getDisplayId(),
2401 policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
2402 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 getListener()->notifyKey(&args);
2404}
2405
2406ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2407 size_t n = mKeyDowns.size();
2408 for (size_t i = 0; i < n; i++) {
2409 if (mKeyDowns[i].scanCode == scanCode) {
2410 return i;
2411 }
2412 }
2413 return -1;
2414}
2415
2416int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2417 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2418}
2419
2420int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2421 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2422}
2423
2424bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
Prabir Pradhan2b281812019-08-29 14:12:42 -07002425 const int32_t* keyCodes, uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2427}
2428
2429int32_t KeyboardInputMapper::getMetaState() {
2430 return mMetaState;
2431}
2432
Andrii Kulian763a3a42016-03-08 10:46:16 -08002433void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2434 updateMetaStateIfNeeded(keyCode, false);
2435}
2436
2437bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2438 int32_t oldMetaState = mMetaState;
2439 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2440 bool metaStateChanged = oldMetaState != newMetaState;
2441 if (metaStateChanged) {
2442 mMetaState = newMetaState;
2443 updateLedState(false);
2444
2445 getContext()->updateGlobalMetaState();
2446 }
2447
2448 return metaStateChanged;
2449}
2450
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451void KeyboardInputMapper::resetLedState() {
2452 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2453 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2454 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2455
2456 updateLedState(true);
2457}
2458
2459void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2460 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2461 ledState.on = false;
2462}
2463
2464void KeyboardInputMapper::updateLedState(bool reset) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07002465 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK, AMETA_CAPS_LOCK_ON, reset);
2466 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK, AMETA_NUM_LOCK_ON, reset);
2467 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK, AMETA_SCROLL_LOCK_ON, reset);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468}
2469
Prabir Pradhan2b281812019-08-29 14:12:42 -07002470void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState, int32_t led,
2471 int32_t modifier, bool reset) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 if (ledState.avail) {
2473 bool desiredState = (mMetaState & modifier) != 0;
2474 if (reset || ledState.on != desiredState) {
2475 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2476 ledState.on = desiredState;
2477 }
2478 }
2479}
2480
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481// --- CursorInputMapper ---
2482
Prabir Pradhan2b281812019-08-29 14:12:42 -07002483CursorInputMapper::CursorInputMapper(InputDevice* device) : InputMapper(device) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484
Prabir Pradhan2b281812019-08-29 14:12:42 -07002485CursorInputMapper::~CursorInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486
2487uint32_t CursorInputMapper::getSources() {
2488 return mSource;
2489}
2490
2491void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2492 InputMapper::populateDeviceInfo(info);
2493
2494 if (mParameters.mode == Parameters::MODE_POINTER) {
2495 float minX, minY, maxX, maxY;
2496 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2497 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2498 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2499 }
2500 } else {
2501 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2502 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2503 }
2504 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2505
2506 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2507 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2508 }
2509 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2510 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2511 }
2512}
2513
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002514void CursorInputMapper::dump(std::string& dump) {
2515 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002517 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2518 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2519 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2520 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2521 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07002522 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002523 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07002524 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002525 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2526 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2527 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2528 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2529 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2530 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531}
2532
Prabir Pradhan2b281812019-08-29 14:12:42 -07002533void CursorInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
2534 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 InputMapper::configure(when, config, changes);
2536
2537 if (!changes) { // first time only
2538 mCursorScrollAccumulator.configure(getDevice());
2539
2540 // Configure basic parameters.
2541 configureParameters();
2542
2543 // Configure device mode.
2544 switch (mParameters.mode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07002545 case Parameters::MODE_POINTER_RELATIVE:
2546 // Should not happen during first time configuration.
2547 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2548 mParameters.mode = Parameters::MODE_POINTER;
2549 [[fallthrough]];
2550 case Parameters::MODE_POINTER:
2551 mSource = AINPUT_SOURCE_MOUSE;
2552 mXPrecision = 1.0f;
2553 mYPrecision = 1.0f;
2554 mXScale = 1.0f;
2555 mYScale = 1.0f;
2556 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2557 break;
2558 case Parameters::MODE_NAVIGATION:
2559 mSource = AINPUT_SOURCE_TRACKBALL;
2560 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2561 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2562 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2563 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2564 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 }
2566
2567 mVWheelScale = 1.0f;
2568 mHWheelScale = 1.0f;
2569 }
2570
Prabir Pradhan2b281812019-08-29 14:12:42 -07002571 if ((!changes && config->pointerCapture) ||
2572 (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002573 if (config->pointerCapture) {
2574 if (mParameters.mode == Parameters::MODE_POINTER) {
2575 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2576 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2577 // Keep PointerController around in order to preserve the pointer position.
2578 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2579 } else {
2580 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2581 }
2582 } else {
2583 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2584 mParameters.mode = Parameters::MODE_POINTER;
2585 mSource = AINPUT_SOURCE_MOUSE;
2586 } else {
2587 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2588 }
2589 }
2590 bumpGeneration();
2591 if (changes) {
2592 getDevice()->notifyReset(when);
2593 }
2594 }
2595
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2597 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2598 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2599 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2600 }
2601
2602 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002603 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002605 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002606 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002607 if (internalViewport) {
2608 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002611
2612 // Update the PointerController if viewports changed.
Arthur Hungc23540e2018-11-29 20:42:11 +08002613 if (mParameters.mode == Parameters::MODE_POINTER) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002614 getPolicy()->obtainPointerController(getDeviceId());
2615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 bumpGeneration();
2617 }
2618}
2619
2620void CursorInputMapper::configureParameters() {
2621 mParameters.mode = Parameters::MODE_POINTER;
2622 String8 cursorModeString;
2623 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2624 if (cursorModeString == "navigation") {
2625 mParameters.mode = Parameters::MODE_NAVIGATION;
2626 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2627 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2628 }
2629 }
2630
2631 mParameters.orientationAware = false;
2632 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
Prabir Pradhan2b281812019-08-29 14:12:42 -07002633 mParameters.orientationAware);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634
2635 mParameters.hasAssociatedDisplay = false;
2636 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2637 mParameters.hasAssociatedDisplay = true;
2638 }
2639}
2640
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002641void CursorInputMapper::dumpParameters(std::string& dump) {
2642 dump += INDENT3 "Parameters:\n";
2643 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07002644 toString(mParameters.hasAssociatedDisplay));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645
2646 switch (mParameters.mode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07002647 case Parameters::MODE_POINTER:
2648 dump += INDENT4 "Mode: pointer\n";
2649 break;
2650 case Parameters::MODE_POINTER_RELATIVE:
2651 dump += INDENT4 "Mode: relative pointer\n";
2652 break;
2653 case Parameters::MODE_NAVIGATION:
2654 dump += INDENT4 "Mode: navigation\n";
2655 break;
2656 default:
2657 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658 }
2659
Prabir Pradhan2b281812019-08-29 14:12:42 -07002660 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661}
2662
2663void CursorInputMapper::reset(nsecs_t when) {
2664 mButtonState = 0;
2665 mDownTime = 0;
2666
2667 mPointerVelocityControl.reset();
2668 mWheelXVelocityControl.reset();
2669 mWheelYVelocityControl.reset();
2670
2671 mCursorButtonAccumulator.reset(getDevice());
2672 mCursorMotionAccumulator.reset(getDevice());
2673 mCursorScrollAccumulator.reset(getDevice());
2674
2675 InputMapper::reset(when);
2676}
2677
2678void CursorInputMapper::process(const RawEvent* rawEvent) {
2679 mCursorButtonAccumulator.process(rawEvent);
2680 mCursorMotionAccumulator.process(rawEvent);
2681 mCursorScrollAccumulator.process(rawEvent);
2682
2683 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2684 sync(rawEvent->when);
2685 }
2686}
2687
2688void CursorInputMapper::sync(nsecs_t when) {
2689 int32_t lastButtonState = mButtonState;
2690 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2691 mButtonState = currentButtonState;
2692
2693 bool wasDown = isPointerDown(lastButtonState);
2694 bool down = isPointerDown(currentButtonState);
2695 bool downChanged;
2696 if (!wasDown && down) {
2697 mDownTime = when;
2698 downChanged = true;
2699 } else if (wasDown && !down) {
2700 downChanged = true;
2701 } else {
2702 downChanged = false;
2703 }
2704 nsecs_t downTime = mDownTime;
2705 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002706 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2707 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708
2709 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2710 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2711 bool moved = deltaX != 0 || deltaY != 0;
2712
2713 // Rotate delta according to orientation if needed.
Prabir Pradhan2b281812019-08-29 14:12:42 -07002714 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay &&
2715 (deltaX != 0.0f || deltaY != 0.0f)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716 rotateDelta(mOrientation, &deltaX, &deltaY);
2717 }
2718
2719 // Move the pointer.
2720 PointerProperties pointerProperties;
2721 pointerProperties.clear();
2722 pointerProperties.id = 0;
2723 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2724
2725 PointerCoords pointerCoords;
2726 pointerCoords.clear();
2727
2728 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2729 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2730 bool scrolled = vscroll != 0 || hscroll != 0;
2731
Yi Kong9b14ac62018-07-17 13:48:38 -07002732 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2733 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
2735 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2736
2737 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002738 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 if (moved || scrolled || buttonsChanged) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07002740 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741
2742 if (moved) {
2743 mPointerController->move(deltaX, deltaY);
2744 }
2745
2746 if (buttonsChanged) {
2747 mPointerController->setButtonState(currentButtonState);
2748 }
2749
2750 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2751 }
2752
2753 float x, y;
2754 mPointerController->getPosition(&x, &y);
2755 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2756 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002757 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2758 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002759 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760 } else {
2761 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2762 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2763 displayId = ADISPLAY_ID_NONE;
2764 }
2765
2766 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2767
2768 // Moving an external trackball or mouse should wake the device.
2769 // We don't do this for internal cursor devices to prevent them from waking up
2770 // the device in your pocket.
2771 // TODO: Use the input device configuration to control this behavior more finely.
2772 uint32_t policyFlags = 0;
2773 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002774 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 }
2776
2777 // Synthesize key down from buttons if needed.
2778 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Prabir Pradhan2b281812019-08-29 14:12:42 -07002779 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780
2781 // Send motion event.
2782 if (downChanged || moved || scrolled || buttonsChanged) {
2783 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002784 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 int32_t motionEventAction;
2786 if (downChanged) {
2787 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002788 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2790 } else {
2791 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2792 }
2793
Michael Wright7b159c92015-05-14 14:48:03 +01002794 if (buttonsReleased) {
2795 BitSet32 released(buttonsReleased);
2796 while (!released.isEmpty()) {
2797 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2798 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002799 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Prabir Pradhan2b281812019-08-29 14:12:42 -07002800 mSource, displayId, policyFlags,
2801 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2802 metaState, buttonState, MotionClassification::NONE,
2803 AMOTION_EVENT_EDGE_FLAG_NONE,
2804 /* deviceTimestamp */ 0, 1, &pointerProperties,
2805 &pointerCoords, mXPrecision, mYPrecision, downTime,
2806 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002807 getListener()->notifyMotion(&releaseArgs);
2808 }
2809 }
2810
Prabir Pradhan42611e02018-11-27 14:04:02 -08002811 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
Prabir Pradhan2b281812019-08-29 14:12:42 -07002812 displayId, policyFlags, motionEventAction, 0, 0, metaState,
2813 currentButtonState, MotionClassification::NONE,
2814 AMOTION_EVENT_EDGE_FLAG_NONE,
2815 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
2816 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 getListener()->notifyMotion(&args);
2818
Michael Wright7b159c92015-05-14 14:48:03 +01002819 if (buttonsPressed) {
2820 BitSet32 pressed(buttonsPressed);
2821 while (!pressed.isEmpty()) {
2822 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2823 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002824 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Prabir Pradhan2b281812019-08-29 14:12:42 -07002825 mSource, displayId, policyFlags,
2826 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2827 metaState, buttonState, MotionClassification::NONE,
2828 AMOTION_EVENT_EDGE_FLAG_NONE,
2829 /* deviceTimestamp */ 0, 1, &pointerProperties,
2830 &pointerCoords, mXPrecision, mYPrecision, downTime,
2831 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002832 getListener()->notifyMotion(&pressArgs);
2833 }
2834 }
2835
2836 ALOG_ASSERT(buttonState == currentButtonState);
2837
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 // Send hover move after UP to tell the application that the mouse is hovering now.
Prabir Pradhan2b281812019-08-29 14:12:42 -07002839 if (motionEventAction == AMOTION_EVENT_ACTION_UP && (mSource == AINPUT_SOURCE_MOUSE)) {
2840 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2841 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2842 0, metaState, currentButtonState, MotionClassification::NONE,
2843 AMOTION_EVENT_EDGE_FLAG_NONE,
2844 /* deviceTimestamp */ 0, 1, &pointerProperties,
2845 &pointerCoords, mXPrecision, mYPrecision, downTime,
2846 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 getListener()->notifyMotion(&hoverArgs);
2848 }
2849
2850 // Send scroll events.
2851 if (scrolled) {
2852 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2853 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2854
Prabir Pradhan42611e02018-11-27 14:04:02 -08002855 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Prabir Pradhan2b281812019-08-29 14:12:42 -07002856 mSource, displayId, policyFlags,
2857 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
2858 currentButtonState, MotionClassification::NONE,
2859 AMOTION_EVENT_EDGE_FLAG_NONE,
2860 /* deviceTimestamp */ 0, 1, &pointerProperties,
2861 &pointerCoords, mXPrecision, mYPrecision, downTime,
2862 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 getListener()->notifyMotion(&scrollArgs);
2864 }
2865 }
2866
2867 // Synthesize key up from buttons if needed.
2868 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Prabir Pradhan2b281812019-08-29 14:12:42 -07002869 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870
2871 mCursorMotionAccumulator.finishSync();
2872 mCursorScrollAccumulator.finishSync();
2873}
2874
2875int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2876 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2877 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2878 } else {
2879 return AKEY_STATE_UNKNOWN;
2880 }
2881}
2882
2883void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002884 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2886 }
2887}
2888
Arthur Hungc23540e2018-11-29 20:42:11 +08002889std::optional<int32_t> CursorInputMapper::getAssociatedDisplay() {
2890 if (mParameters.hasAssociatedDisplay) {
2891 if (mParameters.mode == Parameters::MODE_POINTER) {
2892 return std::make_optional(mPointerController->getDisplayId());
2893 } else {
2894 // If the device is orientationAware and not a mouse,
2895 // it expects to dispatch events to any display
2896 return std::make_optional(ADISPLAY_ID_NONE);
2897 }
2898 }
2899 return std::nullopt;
2900}
2901
Prashant Malani1941ff52015-08-11 18:29:28 -07002902// --- RotaryEncoderInputMapper ---
2903
Prabir Pradhan2b281812019-08-29 14:12:42 -07002904RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device)
2905 : InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002906 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2907}
2908
Prabir Pradhan2b281812019-08-29 14:12:42 -07002909RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {}
Prashant Malani1941ff52015-08-11 18:29:28 -07002910
2911uint32_t RotaryEncoderInputMapper::getSources() {
2912 return mSource;
2913}
2914
2915void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2916 InputMapper::populateDeviceInfo(info);
2917
2918 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002919 float res = 0.0f;
2920 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2921 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2922 }
2923 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
Prabir Pradhan2b281812019-08-29 14:12:42 -07002924 mScalingFactor)) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002925 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
Prabir Pradhan2b281812019-08-29 14:12:42 -07002926 "default to 1.0!\n");
Prashant Malanidae627a2016-01-11 17:08:18 -08002927 mScalingFactor = 1.0f;
2928 }
2929 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
Prabir Pradhan2b281812019-08-29 14:12:42 -07002930 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002931 }
2932}
2933
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002934void RotaryEncoderInputMapper::dump(std::string& dump) {
2935 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2936 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07002937 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
Prashant Malani1941ff52015-08-11 18:29:28 -07002938}
2939
Prabir Pradhan2b281812019-08-29 14:12:42 -07002940void RotaryEncoderInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
2941 uint32_t changes) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002942 InputMapper::configure(when, config, changes);
2943 if (!changes) {
2944 mRotaryEncoderScrollAccumulator.configure(getDevice());
2945 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002946 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002947 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002948 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002949 if (internalViewport) {
2950 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002951 } else {
2952 mOrientation = DISPLAY_ORIENTATION_0;
2953 }
2954 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002955}
2956
2957void RotaryEncoderInputMapper::reset(nsecs_t when) {
2958 mRotaryEncoderScrollAccumulator.reset(getDevice());
2959
2960 InputMapper::reset(when);
2961}
2962
2963void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2964 mRotaryEncoderScrollAccumulator.process(rawEvent);
2965
2966 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2967 sync(rawEvent->when);
2968 }
2969}
2970
2971void RotaryEncoderInputMapper::sync(nsecs_t when) {
2972 PointerCoords pointerCoords;
2973 pointerCoords.clear();
2974
2975 PointerProperties pointerProperties;
2976 pointerProperties.clear();
2977 pointerProperties.id = 0;
2978 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2979
2980 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2981 bool scrolled = scroll != 0;
2982
2983 // This is not a pointer, so it's not associated with a display.
2984 int32_t displayId = ADISPLAY_ID_NONE;
2985
2986 // Moving the rotary encoder should wake the device (if specified).
2987 uint32_t policyFlags = 0;
2988 if (scrolled && getDevice()->isExternal()) {
2989 policyFlags |= POLICY_FLAG_WAKE;
2990 }
2991
Ivan Podogovad437252016-09-29 16:29:55 +01002992 if (mOrientation == DISPLAY_ORIENTATION_180) {
2993 scroll = -scroll;
2994 }
2995
Prashant Malani1941ff52015-08-11 18:29:28 -07002996 // Send motion event.
2997 if (scrolled) {
2998 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08002999 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003000
Prabir Pradhan2b281812019-08-29 14:12:42 -07003001 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
3002 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0,
3003 metaState, /* buttonState */ 0, MotionClassification::NONE,
3004 AMOTION_EVENT_EDGE_FLAG_NONE,
3005 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
3006 0, 0, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003007 getListener()->notifyMotion(&scrollArgs);
3008 }
3009
3010 mRotaryEncoderScrollAccumulator.finishSync();
3011}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012
3013// --- TouchInputMapper ---
3014
Prabir Pradhan2b281812019-08-29 14:12:42 -07003015TouchInputMapper::TouchInputMapper(InputDevice* device)
3016 : InputMapper(device),
3017 mSource(0),
3018 mDeviceMode(DEVICE_MODE_DISABLED),
3019 mSurfaceWidth(-1),
3020 mSurfaceHeight(-1),
3021 mSurfaceLeft(0),
3022 mSurfaceTop(0),
3023 mPhysicalWidth(-1),
3024 mPhysicalHeight(-1),
3025 mPhysicalLeft(0),
3026 mPhysicalTop(0),
3027 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028
Prabir Pradhan2b281812019-08-29 14:12:42 -07003029TouchInputMapper::~TouchInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030
3031uint32_t TouchInputMapper::getSources() {
3032 return mSource;
3033}
3034
3035void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3036 InputMapper::populateDeviceInfo(info);
3037
3038 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3039 info->addMotionRange(mOrientedRanges.x);
3040 info->addMotionRange(mOrientedRanges.y);
3041 info->addMotionRange(mOrientedRanges.pressure);
3042
3043 if (mOrientedRanges.haveSize) {
3044 info->addMotionRange(mOrientedRanges.size);
3045 }
3046
3047 if (mOrientedRanges.haveTouchSize) {
3048 info->addMotionRange(mOrientedRanges.touchMajor);
3049 info->addMotionRange(mOrientedRanges.touchMinor);
3050 }
3051
3052 if (mOrientedRanges.haveToolSize) {
3053 info->addMotionRange(mOrientedRanges.toolMajor);
3054 info->addMotionRange(mOrientedRanges.toolMinor);
3055 }
3056
3057 if (mOrientedRanges.haveOrientation) {
3058 info->addMotionRange(mOrientedRanges.orientation);
3059 }
3060
3061 if (mOrientedRanges.haveDistance) {
3062 info->addMotionRange(mOrientedRanges.distance);
3063 }
3064
3065 if (mOrientedRanges.haveTilt) {
3066 info->addMotionRange(mOrientedRanges.tilt);
3067 }
3068
3069 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3070 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
Prabir Pradhan2b281812019-08-29 14:12:42 -07003071 0.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072 }
3073 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3074 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
Prabir Pradhan2b281812019-08-29 14:12:42 -07003075 0.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076 }
3077 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3078 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3079 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3080 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
Prabir Pradhan2b281812019-08-29 14:12:42 -07003081 x.fuzz, x.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
Prabir Pradhan2b281812019-08-29 14:12:42 -07003083 y.fuzz, y.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
Prabir Pradhan2b281812019-08-29 14:12:42 -07003085 x.fuzz, x.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
Prabir Pradhan2b281812019-08-29 14:12:42 -07003087 y.fuzz, y.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 }
3089 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3090 }
3091}
3092
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003093void TouchInputMapper::dump(std::string& dump) {
3094 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 dumpParameters(dump);
3096 dumpVirtualKeys(dump);
3097 dumpRawPointerAxes(dump);
3098 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003099 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 dumpSurface(dump);
3101
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003102 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3103 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3104 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3105 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3106 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3107 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3108 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3109 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3110 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3111 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3112 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3113 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3114 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3115 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3116 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3117 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3118 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003120 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3121 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07003122 mLastRawState.rawPointerData.pointerCount);
Michael Wright842500e2015-03-13 17:32:02 -07003123 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3124 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003125 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07003126 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3127 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3128 "toolType=%d, isHovering=%s\n",
3129 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
3130 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
3131 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
3132 pointer.distance, pointer.toolType, toString(pointer.isHovering));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133 }
3134
Prabir Pradhan2b281812019-08-29 14:12:42 -07003135 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
3136 mLastCookedState.buttonState);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003137 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07003138 mLastCookedState.cookedPointerData.pointerCount);
Michael Wright842500e2015-03-13 17:32:02 -07003139 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3140 const PointerProperties& pointerProperties =
3141 mLastCookedState.cookedPointerData.pointerProperties[i];
3142 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003143 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07003144 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, "
3145 "toolMinor=%0.3f, "
3146 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3147 "toolType=%d, isHovering=%s\n",
3148 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
3149 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3150 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3151 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3152 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3153 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3154 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3155 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3156 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3157 pointerProperties.toolType,
3158 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003161 dump += INDENT3 "Stylus Fusion:\n";
3162 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07003163 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003164 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3165 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07003166 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003167 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003168 dumpStylusState(dump, mExternalStylusState);
3169
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003171 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
Prabir Pradhan2b281812019-08-29 14:12:42 -07003172 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
3173 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
3174 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
3175 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
3176 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
3178}
3179
Santos Cordonfa5cf462017-04-05 10:37:00 -07003180const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3181 switch (deviceMode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07003182 case DEVICE_MODE_DISABLED:
3183 return "disabled";
3184 case DEVICE_MODE_DIRECT:
3185 return "direct";
3186 case DEVICE_MODE_UNSCALED:
3187 return "unscaled";
3188 case DEVICE_MODE_NAVIGATION:
3189 return "navigation";
3190 case DEVICE_MODE_POINTER:
3191 return "pointer";
Santos Cordonfa5cf462017-04-05 10:37:00 -07003192 }
3193 return "unknown";
3194}
3195
Prabir Pradhan2b281812019-08-29 14:12:42 -07003196void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
3197 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 InputMapper::configure(when, config, changes);
3199
3200 mConfig = *config;
3201
3202 if (!changes) { // first time only
3203 // Configure basic parameters.
3204 configureParameters();
3205
3206 // Configure common accumulators.
3207 mCursorScrollAccumulator.configure(getDevice());
3208 mTouchButtonAccumulator.configure(getDevice());
3209
3210 // Configure absolute axis information.
3211 configureRawPointerAxes();
3212
3213 // Prepare input device calibration.
3214 parseCalibration();
3215 resolveCalibration();
3216 }
3217
Michael Wright842500e2015-03-13 17:32:02 -07003218 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003219 // Update location calibration to reflect current settings
3220 updateAffineTransformation();
3221 }
3222
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3224 // Update pointer speed.
3225 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3226 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3227 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3228 }
3229
3230 bool resetNeeded = false;
Prabir Pradhan2b281812019-08-29 14:12:42 -07003231 if (!changes ||
3232 (changes &
3233 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
3234 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
3235 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
3236 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 // Configure device sources, surface dimensions, orientation and
3238 // scaling factors.
3239 configureSurface(when, &resetNeeded);
3240 }
3241
3242 if (changes && resetNeeded) {
3243 // Send reset, unless this is the first time the device has been configured,
3244 // in which case the reader will call reset itself after all mappers are ready.
3245 getDevice()->notifyReset(when);
3246 }
3247}
3248
Michael Wright842500e2015-03-13 17:32:02 -07003249void TouchInputMapper::resolveExternalStylusPresence() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003250 std::vector<InputDeviceInfo> devices;
Michael Wright842500e2015-03-13 17:32:02 -07003251 mContext->getExternalStylusDevices(devices);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003252 mExternalStylusConnected = !devices.empty();
Michael Wright842500e2015-03-13 17:32:02 -07003253
3254 if (!mExternalStylusConnected) {
3255 resetExternalStylus();
3256 }
3257}
3258
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259void TouchInputMapper::configureParameters() {
3260 // Use the pointer presentation mode for devices that do not support distinct
3261 // multitouch. The spot-based presentation relies on being able to accurately
3262 // locate two or more fingers on the touch pad.
3263 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Prabir Pradhan2b281812019-08-29 14:12:42 -07003264 ? Parameters::GESTURE_MODE_SINGLE_TOUCH
3265 : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266
3267 String8 gestureModeString;
3268 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
Prabir Pradhan2b281812019-08-29 14:12:42 -07003269 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003270 if (gestureModeString == "single-touch") {
3271 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3272 } else if (gestureModeString == "multi-touch") {
3273 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 } else if (gestureModeString != "default") {
3275 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3276 }
3277 }
3278
3279 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3280 // The device is a touch screen.
3281 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3282 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3283 // The device is a pointing device like a track pad.
3284 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Prabir Pradhan2b281812019-08-29 14:12:42 -07003285 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X) ||
3286 getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287 // The device is a cursor device with a touch pad attached.
3288 // By default don't use the touch pad to move the pointer.
3289 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3290 } else {
3291 // The device is a touch pad of unknown purpose.
3292 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3293 }
3294
Prabir Pradhan2b281812019-08-29 14:12:42 -07003295 mParameters.hasButtonUnderPad =
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3297
3298 String8 deviceTypeString;
3299 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
Prabir Pradhan2b281812019-08-29 14:12:42 -07003300 deviceTypeString)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 if (deviceTypeString == "touchScreen") {
3302 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3303 } else if (deviceTypeString == "touchPad") {
3304 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3305 } else if (deviceTypeString == "touchNavigation") {
3306 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3307 } else if (deviceTypeString == "pointer") {
3308 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3309 } else if (deviceTypeString != "default") {
3310 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3311 }
3312 }
3313
3314 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3315 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
Prabir Pradhan2b281812019-08-29 14:12:42 -07003316 mParameters.orientationAware);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
3318 mParameters.hasAssociatedDisplay = false;
3319 mParameters.associatedDisplayIsExternal = false;
Prabir Pradhan2b281812019-08-29 14:12:42 -07003320 if (mParameters.orientationAware ||
3321 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN ||
3322 mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003324 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3325 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003326 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003327 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Prabir Pradhan2b281812019-08-29 14:12:42 -07003328 uniqueDisplayId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003329 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003332 if (getDevice()->getAssociatedDisplayPort()) {
3333 mParameters.hasAssociatedDisplay = true;
3334 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003335
3336 // Initial downs on external touch devices should wake the device.
3337 // Normally we don't do this for internal touch screens to prevent them from waking
3338 // up in your pocket but you can enable it using the input device configuration.
3339 mParameters.wake = getDevice()->isExternal();
Prabir Pradhan2b281812019-08-29 14:12:42 -07003340 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341}
3342
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003343void TouchInputMapper::dumpParameters(std::string& dump) {
3344 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345
3346 switch (mParameters.gestureMode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07003347 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3348 dump += INDENT4 "GestureMode: single-touch\n";
3349 break;
3350 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3351 dump += INDENT4 "GestureMode: multi-touch\n";
3352 break;
3353 default:
3354 assert(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 }
3356
3357 switch (mParameters.deviceType) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07003358 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3359 dump += INDENT4 "DeviceType: touchScreen\n";
3360 break;
3361 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3362 dump += INDENT4 "DeviceType: touchPad\n";
3363 break;
3364 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3365 dump += INDENT4 "DeviceType: touchNavigation\n";
3366 break;
3367 case Parameters::DEVICE_TYPE_POINTER:
3368 dump += INDENT4 "DeviceType: pointer\n";
3369 break;
3370 default:
3371 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 }
3373
Prabir Pradhan2b281812019-08-29 14:12:42 -07003374 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
3375 "displayId='%s'\n",
3376 toString(mParameters.hasAssociatedDisplay),
3377 toString(mParameters.associatedDisplayIsExternal),
3378 mParameters.uniqueDisplayId.c_str());
3379 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380}
3381
3382void TouchInputMapper::configureRawPointerAxes() {
3383 mRawPointerAxes.clear();
3384}
3385
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003386void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3387 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3389 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3390 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3391 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3392 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3393 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3394 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3395 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3396 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3397 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3398 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3399 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3400 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3401}
3402
Michael Wright842500e2015-03-13 17:32:02 -07003403bool TouchInputMapper::hasExternalStylus() const {
3404 return mExternalStylusConnected;
3405}
3406
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003407/**
3408 * Determine which DisplayViewport to use.
3409 * 1. If display port is specified, return the matching viewport. If matching viewport not
3410 * found, then return.
3411 * 2. If a device has associated display, get the matching viewport by either unique id or by
3412 * the display type (internal or external).
3413 * 3. Otherwise, use a non-display viewport.
3414 */
3415std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3416 if (mParameters.hasAssociatedDisplay) {
3417 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3418 if (displayPort) {
3419 // Find the viewport that contains the same port
3420 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3421 if (!v) {
3422 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
Prabir Pradhan2b281812019-08-29 14:12:42 -07003423 "but the corresponding viewport is not found.",
3424 getDeviceName().c_str(), *displayPort);
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003425 }
3426 return v;
3427 }
3428
3429 if (!mParameters.uniqueDisplayId.empty()) {
3430 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3431 }
3432
3433 ViewportType viewportTypeToUse;
3434 if (mParameters.associatedDisplayIsExternal) {
3435 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3436 } else {
3437 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3438 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003439
3440 std::optional<DisplayViewport> viewport =
3441 mConfig.getDisplayViewportByType(viewportTypeToUse);
3442 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3443 ALOGW("Input device %s should be associated with external display, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07003444 "fallback to internal one for the external viewport is not found.",
3445 getDeviceName().c_str());
Arthur Hung41a712e2018-11-22 19:41:03 +08003446 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3447 }
3448
3449 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003450 }
3451
3452 DisplayViewport newViewport;
3453 // Raw width and height in the natural orientation.
3454 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3455 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3456 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3457 return std::make_optional(newViewport);
3458}
3459
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3461 int32_t oldDeviceMode = mDeviceMode;
3462
Michael Wright842500e2015-03-13 17:32:02 -07003463 resolveExternalStylusPresence();
3464
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 // Determine device mode.
Prabir Pradhan2b281812019-08-29 14:12:42 -07003466 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER &&
3467 mConfig.pointerGesturesEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 mSource = AINPUT_SOURCE_MOUSE;
3469 mDeviceMode = DEVICE_MODE_POINTER;
3470 if (hasStylus()) {
3471 mSource |= AINPUT_SOURCE_STYLUS;
3472 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07003473 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN &&
3474 mParameters.hasAssociatedDisplay) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3476 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003477 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 mSource |= AINPUT_SOURCE_STYLUS;
3479 }
Michael Wright2f78b682015-06-12 15:25:08 +01003480 if (hasExternalStylus()) {
3481 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3484 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3485 mDeviceMode = DEVICE_MODE_NAVIGATION;
3486 } else {
3487 mSource = AINPUT_SOURCE_TOUCHPAD;
3488 mDeviceMode = DEVICE_MODE_UNSCALED;
3489 }
3490
3491 // Ensure we have valid X and Y axes.
3492 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003493 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Prabir Pradhan2b281812019-08-29 14:12:42 -07003494 "The device will be inoperable.",
3495 getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 mDeviceMode = DEVICE_MODE_DISABLED;
3497 return;
3498 }
3499
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003500 // Get associated display dimensions.
3501 std::optional<DisplayViewport> newViewport = findViewport();
3502 if (!newViewport) {
3503 ALOGI("Touch device '%s' could not query the properties of its associated "
Prabir Pradhan2b281812019-08-29 14:12:42 -07003504 "display. The device will be inoperable until the display size "
3505 "becomes available.",
3506 getDeviceName().c_str());
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003507 mDeviceMode = DEVICE_MODE_DISABLED;
3508 return;
3509 }
3510
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003512 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3513 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003515 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003517 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518
3519 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3520 // Convert rotated viewport to natural surface coordinates.
3521 int32_t naturalLogicalWidth, naturalLogicalHeight;
3522 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3523 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3524 int32_t naturalDeviceWidth, naturalDeviceHeight;
3525 switch (mViewport.orientation) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07003526 case DISPLAY_ORIENTATION_90:
3527 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3528 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3529 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3530 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3531 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3532 naturalPhysicalTop = mViewport.physicalLeft;
3533 naturalDeviceWidth = mViewport.deviceHeight;
3534 naturalDeviceHeight = mViewport.deviceWidth;
3535 break;
3536 case DISPLAY_ORIENTATION_180:
3537 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3538 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3539 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3540 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3541 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3542 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3543 naturalDeviceWidth = mViewport.deviceWidth;
3544 naturalDeviceHeight = mViewport.deviceHeight;
3545 break;
3546 case DISPLAY_ORIENTATION_270:
3547 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3548 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3549 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3550 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3551 naturalPhysicalLeft = mViewport.physicalTop;
3552 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3553 naturalDeviceWidth = mViewport.deviceHeight;
3554 naturalDeviceHeight = mViewport.deviceWidth;
3555 break;
3556 case DISPLAY_ORIENTATION_0:
3557 default:
3558 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3559 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3560 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3561 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3562 naturalPhysicalLeft = mViewport.physicalLeft;
3563 naturalPhysicalTop = mViewport.physicalTop;
3564 naturalDeviceWidth = mViewport.deviceWidth;
3565 naturalDeviceHeight = mViewport.deviceHeight;
3566 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 }
3568
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003569 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3570 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3571 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3572 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3573 }
3574
Michael Wright358bcc72018-08-21 04:01:07 +01003575 mPhysicalWidth = naturalPhysicalWidth;
3576 mPhysicalHeight = naturalPhysicalHeight;
3577 mPhysicalLeft = naturalPhysicalLeft;
3578 mPhysicalTop = naturalPhysicalTop;
3579
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3581 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3582 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3583 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3584
Prabir Pradhan2b281812019-08-29 14:12:42 -07003585 mSurfaceOrientation =
3586 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003588 mPhysicalWidth = rawWidth;
3589 mPhysicalHeight = rawHeight;
3590 mPhysicalLeft = 0;
3591 mPhysicalTop = 0;
3592
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 mSurfaceWidth = rawWidth;
3594 mSurfaceHeight = rawHeight;
3595 mSurfaceLeft = 0;
3596 mSurfaceTop = 0;
3597 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3598 }
3599 }
3600
3601 // If moving between pointer modes, need to reset some state.
3602 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3603 if (deviceModeChanged) {
3604 mOrientedRanges.clear();
3605 }
3606
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003607 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 if (mDeviceMode == DEVICE_MODE_POINTER ||
Prabir Pradhan2b281812019-08-29 14:12:42 -07003609 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003610 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3612 }
3613 } else {
3614 mPointerController.clear();
3615 }
3616
3617 if (viewportChanged || deviceModeChanged) {
3618 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07003619 "display id %d",
3620 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
3621 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622
3623 // Configure X and Y factors.
3624 mXScale = float(mSurfaceWidth) / rawWidth;
3625 mYScale = float(mSurfaceHeight) / rawHeight;
3626 mXTranslate = -mSurfaceLeft;
3627 mYTranslate = -mSurfaceTop;
3628 mXPrecision = 1.0f / mXScale;
3629 mYPrecision = 1.0f / mYScale;
3630
3631 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3632 mOrientedRanges.x.source = mSource;
3633 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3634 mOrientedRanges.y.source = mSource;
3635
3636 configureVirtualKeys();
3637
3638 // Scale factor for terms that are not oriented in a particular axis.
3639 // If the pixels are square then xScale == yScale otherwise we fake it
3640 // by choosing an average.
3641 mGeometricScale = avg(mXScale, mYScale);
3642
3643 // Size of diagonal axis.
3644 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3645
3646 // Size factors.
3647 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07003648 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
Prabir Pradhan2b281812019-08-29 14:12:42 -07003650 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3652 } else {
3653 mSizeScale = 0.0f;
3654 }
3655
3656 mOrientedRanges.haveTouchSize = true;
3657 mOrientedRanges.haveToolSize = true;
3658 mOrientedRanges.haveSize = true;
3659
3660 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3661 mOrientedRanges.touchMajor.source = mSource;
3662 mOrientedRanges.touchMajor.min = 0;
3663 mOrientedRanges.touchMajor.max = diagonalSize;
3664 mOrientedRanges.touchMajor.flat = 0;
3665 mOrientedRanges.touchMajor.fuzz = 0;
3666 mOrientedRanges.touchMajor.resolution = 0;
3667
3668 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3669 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3670
3671 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3672 mOrientedRanges.toolMajor.source = mSource;
3673 mOrientedRanges.toolMajor.min = 0;
3674 mOrientedRanges.toolMajor.max = diagonalSize;
3675 mOrientedRanges.toolMajor.flat = 0;
3676 mOrientedRanges.toolMajor.fuzz = 0;
3677 mOrientedRanges.toolMajor.resolution = 0;
3678
3679 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3680 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3681
3682 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3683 mOrientedRanges.size.source = mSource;
3684 mOrientedRanges.size.min = 0;
3685 mOrientedRanges.size.max = 1.0;
3686 mOrientedRanges.size.flat = 0;
3687 mOrientedRanges.size.fuzz = 0;
3688 mOrientedRanges.size.resolution = 0;
3689 } else {
3690 mSizeScale = 0.0f;
3691 }
3692
3693 // Pressure factors.
3694 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003695 float pressureMax = 1.0;
Prabir Pradhan2b281812019-08-29 14:12:42 -07003696 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL ||
3697 mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 if (mCalibration.havePressureScale) {
3699 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003700 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Prabir Pradhan2b281812019-08-29 14:12:42 -07003701 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3703 }
3704 }
3705
3706 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3707 mOrientedRanges.pressure.source = mSource;
3708 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003709 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 mOrientedRanges.pressure.flat = 0;
3711 mOrientedRanges.pressure.fuzz = 0;
3712 mOrientedRanges.pressure.resolution = 0;
3713
3714 // Tilt
3715 mTiltXCenter = 0;
3716 mTiltXScale = 0;
3717 mTiltYCenter = 0;
3718 mTiltYScale = 0;
3719 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3720 if (mHaveTilt) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07003721 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
3722 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 mTiltXScale = M_PI / 180;
3724 mTiltYScale = M_PI / 180;
3725
3726 mOrientedRanges.haveTilt = true;
3727
3728 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3729 mOrientedRanges.tilt.source = mSource;
3730 mOrientedRanges.tilt.min = 0;
3731 mOrientedRanges.tilt.max = M_PI_2;
3732 mOrientedRanges.tilt.flat = 0;
3733 mOrientedRanges.tilt.fuzz = 0;
3734 mOrientedRanges.tilt.resolution = 0;
3735 }
3736
3737 // Orientation
3738 mOrientationScale = 0;
3739 if (mHaveTilt) {
3740 mOrientedRanges.haveOrientation = true;
3741
3742 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3743 mOrientedRanges.orientation.source = mSource;
3744 mOrientedRanges.orientation.min = -M_PI;
3745 mOrientedRanges.orientation.max = M_PI;
3746 mOrientedRanges.orientation.flat = 0;
3747 mOrientedRanges.orientation.fuzz = 0;
3748 mOrientedRanges.orientation.resolution = 0;
3749 } else if (mCalibration.orientationCalibration !=
Prabir Pradhan2b281812019-08-29 14:12:42 -07003750 Calibration::ORIENTATION_CALIBRATION_NONE) {
3751 if (mCalibration.orientationCalibration ==
3752 Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 if (mRawPointerAxes.orientation.valid) {
3754 if (mRawPointerAxes.orientation.maxValue > 0) {
3755 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3756 } else if (mRawPointerAxes.orientation.minValue < 0) {
3757 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3758 } else {
3759 mOrientationScale = 0;
3760 }
3761 }
3762 }
3763
3764 mOrientedRanges.haveOrientation = true;
3765
3766 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3767 mOrientedRanges.orientation.source = mSource;
3768 mOrientedRanges.orientation.min = -M_PI_2;
3769 mOrientedRanges.orientation.max = M_PI_2;
3770 mOrientedRanges.orientation.flat = 0;
3771 mOrientedRanges.orientation.fuzz = 0;
3772 mOrientedRanges.orientation.resolution = 0;
3773 }
3774
3775 // Distance
3776 mDistanceScale = 0;
3777 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07003778 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_SCALED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 if (mCalibration.haveDistanceScale) {
3780 mDistanceScale = mCalibration.distanceScale;
3781 } else {
3782 mDistanceScale = 1.0f;
3783 }
3784 }
3785
3786 mOrientedRanges.haveDistance = true;
3787
3788 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3789 mOrientedRanges.distance.source = mSource;
Prabir Pradhan2b281812019-08-29 14:12:42 -07003790 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
3791 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 mOrientedRanges.distance.flat = 0;
Prabir Pradhan2b281812019-08-29 14:12:42 -07003793 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 mOrientedRanges.distance.resolution = 0;
3795 }
3796
3797 // Compute oriented precision, scales and ranges.
3798 // Note that the maximum value reported is an inclusive maximum value so it is one
3799 // unit less than the total width or height of surface.
3800 switch (mSurfaceOrientation) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07003801 case DISPLAY_ORIENTATION_90:
3802 case DISPLAY_ORIENTATION_270:
3803 mOrientedXPrecision = mYPrecision;
3804 mOrientedYPrecision = mXPrecision;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805
Prabir Pradhan2b281812019-08-29 14:12:42 -07003806 mOrientedRanges.x.min = mYTranslate;
3807 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3808 mOrientedRanges.x.flat = 0;
3809 mOrientedRanges.x.fuzz = 0;
3810 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811
Prabir Pradhan2b281812019-08-29 14:12:42 -07003812 mOrientedRanges.y.min = mXTranslate;
3813 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3814 mOrientedRanges.y.flat = 0;
3815 mOrientedRanges.y.fuzz = 0;
3816 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3817 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818
Prabir Pradhan2b281812019-08-29 14:12:42 -07003819 default:
3820 mOrientedXPrecision = mXPrecision;
3821 mOrientedYPrecision = mYPrecision;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822
Prabir Pradhan2b281812019-08-29 14:12:42 -07003823 mOrientedRanges.x.min = mXTranslate;
3824 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3825 mOrientedRanges.x.flat = 0;
3826 mOrientedRanges.x.fuzz = 0;
3827 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828
Prabir Pradhan2b281812019-08-29 14:12:42 -07003829 mOrientedRanges.y.min = mYTranslate;
3830 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3831 mOrientedRanges.y.flat = 0;
3832 mOrientedRanges.y.fuzz = 0;
3833 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3834 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836
Jason Gerecke71b16e82014-03-10 09:47:59 -07003837 // Location
3838 updateAffineTransformation();
3839
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 if (mDeviceMode == DEVICE_MODE_POINTER) {
3841 // Compute pointer gesture detection parameters.
3842 float rawDiagonal = hypotf(rawWidth, rawHeight);
3843 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3844
3845 // Scale movements such that one whole swipe of the touch pad covers a
3846 // given area relative to the diagonal size of the display when no acceleration
3847 // is applied.
3848 // Assume that the touch pad has a square aspect ratio such that movements in
3849 // X and Y of the same number of raw units cover the same physical distance.
Prabir Pradhan2b281812019-08-29 14:12:42 -07003850 mPointerXMovementScale =
3851 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 mPointerYMovementScale = mPointerXMovementScale;
3853
3854 // Scale zooms to cover a smaller range of the display than movements do.
3855 // This value determines the area around the pointer that is affected by freeform
3856 // pointer gestures.
Prabir Pradhan2b281812019-08-29 14:12:42 -07003857 mPointerXZoomScale =
3858 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 mPointerYZoomScale = mPointerXZoomScale;
3860
3861 // Max width between pointers to detect a swipe gesture is more than some fraction
3862 // of the diagonal axis of the touch pad. Touches that are wider than this are
3863 // translated into freeform gestures.
Prabir Pradhan2b281812019-08-29 14:12:42 -07003864 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865
3866 // Abort current pointer usages because the state has changed.
3867 abortPointerUsage(when, 0 /*policyFlags*/);
3868 }
3869
3870 // Inform the dispatcher about the changes.
3871 *outResetNeeded = true;
3872 bumpGeneration();
3873 }
3874}
3875
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003876void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003877 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003878 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3879 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3880 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3881 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003882 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3883 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3884 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3885 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003886 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887}
3888
3889void TouchInputMapper::configureVirtualKeys() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003890 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3892
3893 mVirtualKeys.clear();
3894
3895 if (virtualKeyDefinitions.size() == 0) {
3896 return;
3897 }
3898
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3900 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003901 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3902 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003904 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
3905 VirtualKey virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906
3907 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3908 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003909 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 uint32_t flags;
Prabir Pradhan2b281812019-08-29 14:12:42 -07003911 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0, &keyCode,
3912 &dummyKeyMetaState, &flags)) {
3913 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003914 continue; // drop the key
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 }
3916
3917 virtualKey.keyCode = keyCode;
3918 virtualKey.flags = flags;
3919
3920 // convert the key definition's display coordinates into touch coordinates for a hit box
3921 int32_t halfWidth = virtualKeyDefinition.width / 2;
3922 int32_t halfHeight = virtualKeyDefinition.height / 2;
3923
Prabir Pradhan2b281812019-08-29 14:12:42 -07003924 virtualKey.hitLeft =
3925 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mSurfaceWidth +
3926 touchScreenLeft;
3927 virtualKey.hitRight =
3928 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mSurfaceWidth +
3929 touchScreenLeft;
3930 virtualKey.hitTop =
3931 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mSurfaceHeight +
3932 touchScreenTop;
3933 virtualKey.hitBottom =
3934 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mSurfaceHeight +
3935 touchScreenTop;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003936 mVirtualKeys.push_back(virtualKey);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 }
3938}
3939
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003940void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003941 if (!mVirtualKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003942 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943
3944 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003945 const VirtualKey& virtualKey = mVirtualKeys[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003946 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07003947 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3948 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
3949 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 }
3951 }
3952}
3953
3954void TouchInputMapper::parseCalibration() {
3955 const PropertyMap& in = getDevice()->getConfiguration();
3956 Calibration& out = mCalibration;
3957
3958 // Size
3959 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3960 String8 sizeCalibrationString;
3961 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3962 if (sizeCalibrationString == "none") {
3963 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3964 } else if (sizeCalibrationString == "geometric") {
3965 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3966 } else if (sizeCalibrationString == "diameter") {
3967 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3968 } else if (sizeCalibrationString == "box") {
3969 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3970 } else if (sizeCalibrationString == "area") {
3971 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3972 } else if (sizeCalibrationString != "default") {
Prabir Pradhan2b281812019-08-29 14:12:42 -07003973 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 }
3975 }
3976
Prabir Pradhan2b281812019-08-29 14:12:42 -07003977 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
3978 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
3979 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
3981 // Pressure
3982 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3983 String8 pressureCalibrationString;
3984 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3985 if (pressureCalibrationString == "none") {
3986 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3987 } else if (pressureCalibrationString == "physical") {
3988 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3989 } else if (pressureCalibrationString == "amplitude") {
3990 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3991 } else if (pressureCalibrationString != "default") {
3992 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Prabir Pradhan2b281812019-08-29 14:12:42 -07003993 pressureCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 }
3995 }
3996
Prabir Pradhan2b281812019-08-29 14:12:42 -07003997 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998
3999 // Orientation
4000 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4001 String8 orientationCalibrationString;
4002 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4003 if (orientationCalibrationString == "none") {
4004 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4005 } else if (orientationCalibrationString == "interpolated") {
4006 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4007 } else if (orientationCalibrationString == "vector") {
4008 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4009 } else if (orientationCalibrationString != "default") {
4010 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Prabir Pradhan2b281812019-08-29 14:12:42 -07004011 orientationCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 }
4013 }
4014
4015 // Distance
4016 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4017 String8 distanceCalibrationString;
4018 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4019 if (distanceCalibrationString == "none") {
4020 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4021 } else if (distanceCalibrationString == "scaled") {
4022 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4023 } else if (distanceCalibrationString != "default") {
4024 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Prabir Pradhan2b281812019-08-29 14:12:42 -07004025 distanceCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026 }
4027 }
4028
Prabir Pradhan2b281812019-08-29 14:12:42 -07004029 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030
4031 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4032 String8 coverageCalibrationString;
4033 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4034 if (coverageCalibrationString == "none") {
4035 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4036 } else if (coverageCalibrationString == "box") {
4037 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4038 } else if (coverageCalibrationString != "default") {
4039 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Prabir Pradhan2b281812019-08-29 14:12:42 -07004040 coverageCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041 }
4042 }
4043}
4044
4045void TouchInputMapper::resolveCalibration() {
4046 // Size
4047 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4048 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4049 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4050 }
4051 } else {
4052 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4053 }
4054
4055 // Pressure
4056 if (mRawPointerAxes.pressure.valid) {
4057 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4058 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4059 }
4060 } else {
4061 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4062 }
4063
4064 // Orientation
4065 if (mRawPointerAxes.orientation.valid) {
4066 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4067 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4068 }
4069 } else {
4070 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4071 }
4072
4073 // Distance
4074 if (mRawPointerAxes.distance.valid) {
4075 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4076 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4077 }
4078 } else {
4079 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4080 }
4081
4082 // Coverage
4083 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4084 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4085 }
4086}
4087
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004088void TouchInputMapper::dumpCalibration(std::string& dump) {
4089 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090
4091 // Size
4092 switch (mCalibration.sizeCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004093 case Calibration::SIZE_CALIBRATION_NONE:
4094 dump += INDENT4 "touch.size.calibration: none\n";
4095 break;
4096 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4097 dump += INDENT4 "touch.size.calibration: geometric\n";
4098 break;
4099 case Calibration::SIZE_CALIBRATION_DIAMETER:
4100 dump += INDENT4 "touch.size.calibration: diameter\n";
4101 break;
4102 case Calibration::SIZE_CALIBRATION_BOX:
4103 dump += INDENT4 "touch.size.calibration: box\n";
4104 break;
4105 case Calibration::SIZE_CALIBRATION_AREA:
4106 dump += INDENT4 "touch.size.calibration: area\n";
4107 break;
4108 default:
4109 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 }
4111
4112 if (mCalibration.haveSizeScale) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004113 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 }
4115
4116 if (mCalibration.haveSizeBias) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004117 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 }
4119
4120 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004121 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07004122 toString(mCalibration.sizeIsSummed));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 }
4124
4125 // Pressure
4126 switch (mCalibration.pressureCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004127 case Calibration::PRESSURE_CALIBRATION_NONE:
4128 dump += INDENT4 "touch.pressure.calibration: none\n";
4129 break;
4130 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4131 dump += INDENT4 "touch.pressure.calibration: physical\n";
4132 break;
4133 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4134 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
4135 break;
4136 default:
4137 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 }
4139
4140 if (mCalibration.havePressureScale) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004141 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143
4144 // Orientation
4145 switch (mCalibration.orientationCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004146 case Calibration::ORIENTATION_CALIBRATION_NONE:
4147 dump += INDENT4 "touch.orientation.calibration: none\n";
4148 break;
4149 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4150 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
4151 break;
4152 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4153 dump += INDENT4 "touch.orientation.calibration: vector\n";
4154 break;
4155 default:
4156 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 }
4158
4159 // Distance
4160 switch (mCalibration.distanceCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004161 case Calibration::DISTANCE_CALIBRATION_NONE:
4162 dump += INDENT4 "touch.distance.calibration: none\n";
4163 break;
4164 case Calibration::DISTANCE_CALIBRATION_SCALED:
4165 dump += INDENT4 "touch.distance.calibration: scaled\n";
4166 break;
4167 default:
4168 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 }
4170
4171 if (mCalibration.haveDistanceScale) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004172 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 }
4174
4175 switch (mCalibration.coverageCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004176 case Calibration::COVERAGE_CALIBRATION_NONE:
4177 dump += INDENT4 "touch.coverage.calibration: none\n";
4178 break;
4179 case Calibration::COVERAGE_CALIBRATION_BOX:
4180 dump += INDENT4 "touch.coverage.calibration: box\n";
4181 break;
4182 default:
4183 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 }
4185}
4186
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004187void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4188 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004189
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004190 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4191 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4192 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4193 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4194 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4195 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004196}
4197
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004198void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004199 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
Prabir Pradhan2b281812019-08-29 14:12:42 -07004200 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004201}
4202
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203void TouchInputMapper::reset(nsecs_t when) {
4204 mCursorButtonAccumulator.reset(getDevice());
4205 mCursorScrollAccumulator.reset(getDevice());
4206 mTouchButtonAccumulator.reset(getDevice());
4207
4208 mPointerVelocityControl.reset();
4209 mWheelXVelocityControl.reset();
4210 mWheelYVelocityControl.reset();
4211
Michael Wright842500e2015-03-13 17:32:02 -07004212 mRawStatesPending.clear();
4213 mCurrentRawState.clear();
4214 mCurrentCookedState.clear();
4215 mLastRawState.clear();
4216 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 mPointerUsage = POINTER_USAGE_NONE;
4218 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004219 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004220 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 mDownTime = 0;
4222
4223 mCurrentVirtualKey.down = false;
4224
4225 mPointerGesture.reset();
4226 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004227 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228
Yi Kong9b14ac62018-07-17 13:48:38 -07004229 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4231 mPointerController->clearSpots();
4232 }
4233
4234 InputMapper::reset(when);
4235}
4236
Michael Wright842500e2015-03-13 17:32:02 -07004237void TouchInputMapper::resetExternalStylus() {
4238 mExternalStylusState.clear();
4239 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004240 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004241 mExternalStylusDataPending = false;
4242}
4243
Michael Wright43fd19f2015-04-21 19:02:58 +01004244void TouchInputMapper::clearStylusDataPendingFlags() {
4245 mExternalStylusDataPending = false;
4246 mExternalStylusFusionTimeout = LLONG_MAX;
4247}
4248
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004249void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4250 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4251 nsecs_t latency = now - evdevTime;
4252 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4253 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4254 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004255 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mStatistics.min,
4256 mStatistics.max, mStatistics.mean(), mStatistics.stdev(),
4257 mStatistics.count);
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004258 mStatistics.reset(now);
4259 }
4260}
4261
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262void TouchInputMapper::process(const RawEvent* rawEvent) {
4263 mCursorButtonAccumulator.process(rawEvent);
4264 mCursorScrollAccumulator.process(rawEvent);
4265 mTouchButtonAccumulator.process(rawEvent);
4266
4267 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004268 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 sync(rawEvent->when);
4270 }
4271}
4272
4273void TouchInputMapper::sync(nsecs_t when) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004274 const RawState* last =
4275 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004276
4277 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004278 mRawStatesPending.emplace_back();
4279
4280 RawState* next = &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004281 next->clear();
4282 next->when = when;
4283
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 // Sync button state.
Prabir Pradhan2b281812019-08-29 14:12:42 -07004285 next->buttonState =
4286 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287
Michael Wright842500e2015-03-13 17:32:02 -07004288 // Sync scroll
4289 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4290 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 mCursorScrollAccumulator.finishSync();
4292
Michael Wright842500e2015-03-13 17:32:02 -07004293 // Sync touch
4294 syncTouch(when, next);
4295
4296 // Assign pointer ids.
4297 if (!mHavePointerIds) {
4298 assignPointerIds(last, next);
4299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300
4301#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004302 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07004303 "hovering ids 0x%08x -> 0x%08x",
4304 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
4305 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
4306 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307#endif
4308
Michael Wright842500e2015-03-13 17:32:02 -07004309 processRawTouches(false /*timeout*/);
4310}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311
Michael Wright842500e2015-03-13 17:32:02 -07004312void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4314 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004315 mCurrentRawState.clear();
4316 mRawStatesPending.clear();
4317 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 }
4319
Michael Wright842500e2015-03-13 17:32:02 -07004320 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4321 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4322 // touching the current state will only observe the events that have been dispatched to the
4323 // rest of the pipeline.
4324 const size_t N = mRawStatesPending.size();
4325 size_t count;
Prabir Pradhan2b281812019-08-29 14:12:42 -07004326 for (count = 0; count < N; count++) {
Michael Wright842500e2015-03-13 17:32:02 -07004327 const RawState& next = mRawStatesPending[count];
4328
4329 // A failure to assign the stylus id means that we're waiting on stylus data
4330 // and so should defer the rest of the pipeline.
4331 if (assignExternalStylusId(next, timeout)) {
4332 break;
4333 }
4334
4335 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004336 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004337 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004338 if (mCurrentRawState.when < mLastRawState.when) {
4339 mCurrentRawState.when = mLastRawState.when;
4340 }
Michael Wright842500e2015-03-13 17:32:02 -07004341 cookAndDispatch(mCurrentRawState.when);
4342 }
4343 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004344 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004345 }
4346
Michael Wright842500e2015-03-13 17:32:02 -07004347 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004348 if (timeout) {
4349 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4350 clearStylusDataPendingFlags();
4351 mCurrentRawState.copyFrom(mLastRawState);
4352#if DEBUG_STYLUS_FUSION
4353 ALOGD("Timeout expired, synthesizing event with new stylus data");
4354#endif
4355 cookAndDispatch(when);
4356 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4357 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4358 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4359 }
Michael Wright842500e2015-03-13 17:32:02 -07004360 }
4361}
4362
4363void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4364 // Always start with a clean state.
4365 mCurrentCookedState.clear();
4366
4367 // Apply stylus buttons to current raw state.
4368 applyExternalStylusButtonState(when);
4369
4370 // Handle policy on initial down or hover events.
Prabir Pradhan2b281812019-08-29 14:12:42 -07004371 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
4372 mCurrentRawState.rawPointerData.pointerCount != 0;
Michael Wright842500e2015-03-13 17:32:02 -07004373
4374 uint32_t policyFlags = 0;
4375 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4376 if (initialDown || buttonsPressed) {
4377 // If this is a touch screen, hide the pointer on an initial down.
4378 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4379 getContext()->fadePointer();
4380 }
4381
4382 if (mParameters.wake) {
4383 policyFlags |= POLICY_FLAG_WAKE;
4384 }
4385 }
4386
4387 // Consume raw off-screen touches before cooking pointer data.
4388 // If touches are consumed, subsequent code will not receive any pointer data.
4389 if (consumeRawTouches(when, policyFlags)) {
4390 mCurrentRawState.rawPointerData.clear();
4391 }
4392
4393 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4394 // with cooked pointer data that has the same ids and indices as the raw data.
4395 // The following code can use either the raw or cooked data, as needed.
4396 cookPointerData();
4397
4398 // Apply stylus pressure to current cooked state.
4399 applyExternalStylusTouchState(when);
4400
4401 // Synthesize key down from raw buttons if needed.
4402 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Prabir Pradhan2b281812019-08-29 14:12:42 -07004403 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
4404 mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004405
4406 // Dispatch the touches either directly or by translation through a pointer on screen.
4407 if (mDeviceMode == DEVICE_MODE_POINTER) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004408 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
Michael Wright842500e2015-03-13 17:32:02 -07004409 uint32_t id = idBits.clearFirstMarkedBit();
4410 const RawPointerData::Pointer& pointer =
4411 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan2b281812019-08-29 14:12:42 -07004412 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
4413 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
Michael Wright842500e2015-03-13 17:32:02 -07004414 mCurrentCookedState.stylusIdBits.markBit(id);
Prabir Pradhan2b281812019-08-29 14:12:42 -07004415 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
4416 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Michael Wright842500e2015-03-13 17:32:02 -07004417 mCurrentCookedState.fingerIdBits.markBit(id);
4418 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4419 mCurrentCookedState.mouseIdBits.markBit(id);
4420 }
4421 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07004422 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
Michael Wright842500e2015-03-13 17:32:02 -07004423 uint32_t id = idBits.clearFirstMarkedBit();
4424 const RawPointerData::Pointer& pointer =
4425 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan2b281812019-08-29 14:12:42 -07004426 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
4427 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
Michael Wright842500e2015-03-13 17:32:02 -07004428 mCurrentCookedState.stylusIdBits.markBit(id);
4429 }
4430 }
4431
4432 // Stylus takes precedence over all tools, then mouse, then finger.
4433 PointerUsage pointerUsage = mPointerUsage;
4434 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4435 mCurrentCookedState.mouseIdBits.clear();
4436 mCurrentCookedState.fingerIdBits.clear();
4437 pointerUsage = POINTER_USAGE_STYLUS;
4438 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4439 mCurrentCookedState.fingerIdBits.clear();
4440 pointerUsage = POINTER_USAGE_MOUSE;
4441 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
Prabir Pradhan2b281812019-08-29 14:12:42 -07004442 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright842500e2015-03-13 17:32:02 -07004443 pointerUsage = POINTER_USAGE_GESTURES;
4444 }
4445
4446 dispatchPointerUsage(when, policyFlags, pointerUsage);
4447 } else {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004448 if (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches &&
4449 mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004450 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4451 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4452
4453 mPointerController->setButtonState(mCurrentRawState.buttonState);
4454 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
Prabir Pradhan2b281812019-08-29 14:12:42 -07004455 mCurrentCookedState.cookedPointerData.idToIndex,
4456 mCurrentCookedState.cookedPointerData.touchingIdBits,
4457 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004458 }
4459
Michael Wright8e812822015-06-22 16:18:21 +01004460 if (!mCurrentMotionAborted) {
4461 dispatchButtonRelease(when, policyFlags);
4462 dispatchHoverExit(when, policyFlags);
4463 dispatchTouches(when, policyFlags);
4464 dispatchHoverEnterAndMove(when, policyFlags);
4465 dispatchButtonPress(when, policyFlags);
4466 }
4467
4468 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4469 mCurrentMotionAborted = false;
4470 }
Michael Wright842500e2015-03-13 17:32:02 -07004471 }
4472
4473 // Synthesize key up from raw buttons if needed.
4474 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Prabir Pradhan2b281812019-08-29 14:12:42 -07004475 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
4476 mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477
4478 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004479 mCurrentRawState.rawVScroll = 0;
4480 mCurrentRawState.rawHScroll = 0;
4481
4482 // Copy current touch to last touch in preparation for the next cycle.
4483 mLastRawState.copyFrom(mCurrentRawState);
4484 mLastCookedState.copyFrom(mCurrentCookedState);
4485}
4486
4487void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004488 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004489 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4490 }
4491}
4492
4493void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004494 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4495 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004496
Michael Wright53dca3a2015-04-23 17:39:53 +01004497 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4498 float pressure = mExternalStylusState.pressure;
4499 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4500 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4501 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4502 }
4503 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4504 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4505
4506 PointerProperties& properties =
4507 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004508 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4509 properties.toolType = mExternalStylusState.toolType;
4510 }
4511 }
4512}
4513
4514bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4515 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4516 return false;
4517 }
4518
Prabir Pradhan2b281812019-08-29 14:12:42 -07004519 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
4520 state.rawPointerData.pointerCount != 0;
Michael Wright842500e2015-03-13 17:32:02 -07004521 if (initialDown) {
4522 if (mExternalStylusState.pressure != 0.0f) {
4523#if DEBUG_STYLUS_FUSION
4524 ALOGD("Have both stylus and touch data, beginning fusion");
4525#endif
4526 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4527 } else if (timeout) {
4528#if DEBUG_STYLUS_FUSION
4529 ALOGD("Timeout expired, assuming touch is not a stylus.");
4530#endif
4531 resetExternalStylus();
4532 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004533 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4534 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004535 }
4536#if DEBUG_STYLUS_FUSION
4537 ALOGD("No stylus data but stylus is connected, requesting timeout "
Prabir Pradhan2b281812019-08-29 14:12:42 -07004538 "(%" PRId64 "ms)",
4539 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004540#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004541 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004542 return true;
4543 }
4544 }
4545
4546 // Check if the stylus pointer has gone up.
Prabir Pradhan2b281812019-08-29 14:12:42 -07004547 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Michael Wright842500e2015-03-13 17:32:02 -07004548#if DEBUG_STYLUS_FUSION
Prabir Pradhan2b281812019-08-29 14:12:42 -07004549 ALOGD("Stylus pointer is going up");
Michael Wright842500e2015-03-13 17:32:02 -07004550#endif
4551 mExternalStylusId = -1;
4552 }
4553
4554 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555}
4556
4557void TouchInputMapper::timeoutExpired(nsecs_t when) {
4558 if (mDeviceMode == DEVICE_MODE_POINTER) {
4559 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4560 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4561 }
Michael Wright842500e2015-03-13 17:32:02 -07004562 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004563 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004564 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004565 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4566 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004567 }
4568 }
4569}
4570
4571void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004572 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004573 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004574 // We're either in the middle of a fused stream of data or we're waiting on data before
4575 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4576 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004577 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004578 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579 }
4580}
4581
4582bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4583 // Check for release of a virtual key.
4584 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004585 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 // Pointer went up while virtual key was down.
4587 mCurrentVirtualKey.down = false;
4588 if (!mCurrentVirtualKey.ignored) {
4589#if DEBUG_VIRTUAL_KEYS
4590 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Prabir Pradhan2b281812019-08-29 14:12:42 -07004591 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592#endif
Prabir Pradhan2b281812019-08-29 14:12:42 -07004593 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
4594 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 }
4596 return true;
4597 }
4598
Michael Wright842500e2015-03-13 17:32:02 -07004599 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4600 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4601 const RawPointerData::Pointer& pointer =
4602 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4604 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4605 // Pointer is still within the space of the virtual key.
4606 return true;
4607 }
4608 }
4609
4610 // Pointer left virtual key area or another pointer also went down.
4611 // Send key cancellation but do not consume the touch yet.
4612 // This is useful when the user swipes through from the virtual key area
4613 // into the main display surface.
4614 mCurrentVirtualKey.down = false;
4615 if (!mCurrentVirtualKey.ignored) {
4616#if DEBUG_VIRTUAL_KEYS
Prabir Pradhan2b281812019-08-29 14:12:42 -07004617 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
4618 mCurrentVirtualKey.scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619#endif
Prabir Pradhan2b281812019-08-29 14:12:42 -07004620 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
4621 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
4622 AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 }
4624 }
4625
Prabir Pradhan2b281812019-08-29 14:12:42 -07004626 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
4627 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004629 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4630 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4632 // If exactly one pointer went down, check for virtual key hit.
4633 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004634 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4636 if (virtualKey) {
4637 mCurrentVirtualKey.down = true;
4638 mCurrentVirtualKey.downTime = when;
4639 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4640 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
Prabir Pradhan2b281812019-08-29 14:12:42 -07004641 mCurrentVirtualKey.ignored =
4642 mContext->shouldDropVirtualKey(when, getDevice(), virtualKey->keyCode,
4643 virtualKey->scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644
4645 if (!mCurrentVirtualKey.ignored) {
4646#if DEBUG_VIRTUAL_KEYS
4647 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Prabir Pradhan2b281812019-08-29 14:12:42 -07004648 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649#endif
Prabir Pradhan2b281812019-08-29 14:12:42 -07004650 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
4651 AKEY_EVENT_FLAG_FROM_SYSTEM |
4652 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 }
4654 }
4655 }
4656 return true;
4657 }
4658 }
4659
4660 // Disable all virtual key touches that happen within a short time interval of the
4661 // most recent touch within the screen area. The idea is to filter out stray
4662 // virtual key presses when interacting with the touch screen.
4663 //
4664 // Problems we're trying to solve:
4665 //
4666 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4667 // virtual key area that is implemented by a separate touch panel and accidentally
4668 // triggers a virtual key.
4669 //
4670 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4671 // area and accidentally triggers a virtual key. This often happens when virtual keys
4672 // are layed out below the screen near to where the on screen keyboard's space bar
4673 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004674 if (mConfig.virtualKeyQuietTime > 0 &&
Prabir Pradhan2b281812019-08-29 14:12:42 -07004675 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4677 }
4678 return false;
4679}
4680
4681void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
Prabir Pradhan2b281812019-08-29 14:12:42 -07004682 int32_t keyEventAction, int32_t keyEventFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683 int32_t keyCode = mCurrentVirtualKey.keyCode;
4684 int32_t scanCode = mCurrentVirtualKey.scanCode;
4685 nsecs_t downTime = mCurrentVirtualKey.downTime;
4686 int32_t metaState = mContext->getGlobalMetaState();
4687 policyFlags |= POLICY_FLAG_VIRTUAL;
4688
Prabir Pradhan42611e02018-11-27 14:04:02 -08004689 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
Prabir Pradhan2b281812019-08-29 14:12:42 -07004690 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
4691 scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 getListener()->notifyKey(&args);
4693}
4694
Michael Wright8e812822015-06-22 16:18:21 +01004695void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4696 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4697 if (!currentIdBits.isEmpty()) {
4698 int32_t metaState = getContext()->getGlobalMetaState();
4699 int32_t buttonState = mCurrentCookedState.buttonState;
Prabir Pradhan2b281812019-08-29 14:12:42 -07004700 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
4701 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4702 mCurrentCookedState.deviceTimestamp,
4703 mCurrentCookedState.cookedPointerData.pointerProperties,
4704 mCurrentCookedState.cookedPointerData.pointerCoords,
4705 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
4706 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wright8e812822015-06-22 16:18:21 +01004707 mCurrentMotionAborted = true;
4708 }
4709}
4710
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004712 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4713 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004715 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716
4717 if (currentIdBits == lastIdBits) {
4718 if (!currentIdBits.isEmpty()) {
4719 // No pointer id changes so this is a move event.
4720 // The listener takes care of batching moves so we don't have to deal with that here.
Prabir Pradhan2b281812019-08-29 14:12:42 -07004721 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
4722 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4723 mCurrentCookedState.deviceTimestamp,
4724 mCurrentCookedState.cookedPointerData.pointerProperties,
4725 mCurrentCookedState.cookedPointerData.pointerCoords,
4726 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
4727 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 }
4729 } else {
4730 // There may be pointers going up and pointers going down and pointers moving
4731 // all at the same time.
4732 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4733 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4734 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4735 BitSet32 dispatchedIdBits(lastIdBits.value);
4736
4737 // Update last coordinates of pointers that have moved so that we observe the new
4738 // pointer positions at the same time as other pointers that have just gone up.
Prabir Pradhan2b281812019-08-29 14:12:42 -07004739 bool moveNeeded =
4740 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
4741 mCurrentCookedState.cookedPointerData.pointerCoords,
4742 mCurrentCookedState.cookedPointerData.idToIndex,
4743 mLastCookedState.cookedPointerData.pointerProperties,
4744 mLastCookedState.cookedPointerData.pointerCoords,
4745 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004746 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 moveNeeded = true;
4748 }
4749
4750 // Dispatch pointer up events.
4751 while (!upIdBits.isEmpty()) {
4752 uint32_t upId = upIdBits.clearFirstMarkedBit();
4753
Prabir Pradhan2b281812019-08-29 14:12:42 -07004754 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
4755 metaState, buttonState, 0, mCurrentCookedState.deviceTimestamp,
4756 mLastCookedState.cookedPointerData.pointerProperties,
4757 mLastCookedState.cookedPointerData.pointerCoords,
4758 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
4759 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 dispatchedIdBits.clearBit(upId);
4761 }
4762
4763 // Dispatch move events if any of the remaining pointers moved from their old locations.
4764 // Although applications receive new locations as part of individual pointer up
4765 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004766 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Prabir Pradhan2b281812019-08-29 14:12:42 -07004768 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
4769 buttonState, 0, mCurrentCookedState.deviceTimestamp,
4770 mCurrentCookedState.cookedPointerData.pointerProperties,
4771 mCurrentCookedState.cookedPointerData.pointerCoords,
4772 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
4773 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774 }
4775
4776 // Dispatch pointer down events using the new pointer locations.
4777 while (!downIdBits.isEmpty()) {
4778 uint32_t downId = downIdBits.clearFirstMarkedBit();
4779 dispatchedIdBits.markBit(downId);
4780
4781 if (dispatchedIdBits.count() == 1) {
4782 // First pointer is going down. Set down time.
4783 mDownTime = when;
4784 }
4785
Prabir Pradhan2b281812019-08-29 14:12:42 -07004786 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
4787 metaState, buttonState, 0, mCurrentCookedState.deviceTimestamp,
4788 mCurrentCookedState.cookedPointerData.pointerProperties,
4789 mCurrentCookedState.cookedPointerData.pointerCoords,
4790 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
4791 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792 }
4793 }
4794}
4795
4796void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4797 if (mSentHoverEnter &&
Prabir Pradhan2b281812019-08-29 14:12:42 -07004798 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
4799 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan2b281812019-08-29 14:12:42 -07004801 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
4802 mLastCookedState.buttonState, 0, mLastCookedState.deviceTimestamp,
4803 mLastCookedState.cookedPointerData.pointerProperties,
4804 mLastCookedState.cookedPointerData.pointerCoords,
4805 mLastCookedState.cookedPointerData.idToIndex,
4806 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
4807 mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 mSentHoverEnter = false;
4809 }
4810}
4811
4812void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004813 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
4814 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 int32_t metaState = getContext()->getGlobalMetaState();
4816 if (!mSentHoverEnter) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004817 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
4818 metaState, mCurrentRawState.buttonState, 0,
4819 mCurrentCookedState.deviceTimestamp,
4820 mCurrentCookedState.cookedPointerData.pointerProperties,
4821 mCurrentCookedState.cookedPointerData.pointerCoords,
4822 mCurrentCookedState.cookedPointerData.idToIndex,
4823 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
4824 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 mSentHoverEnter = true;
4826 }
4827
Prabir Pradhan2b281812019-08-29 14:12:42 -07004828 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
4829 mCurrentRawState.buttonState, 0, mCurrentCookedState.deviceTimestamp,
4830 mCurrentCookedState.cookedPointerData.pointerProperties,
4831 mCurrentCookedState.cookedPointerData.pointerCoords,
4832 mCurrentCookedState.cookedPointerData.idToIndex,
4833 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
4834 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 }
4836}
4837
Michael Wright7b159c92015-05-14 14:48:03 +01004838void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4839 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4840 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4841 const int32_t metaState = getContext()->getGlobalMetaState();
4842 int32_t buttonState = mLastCookedState.buttonState;
4843 while (!releasedButtons.isEmpty()) {
4844 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4845 buttonState &= ~actionButton;
Prabir Pradhan2b281812019-08-29 14:12:42 -07004846 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
4847 actionButton, 0, metaState, buttonState, 0,
4848 mCurrentCookedState.deviceTimestamp,
4849 mCurrentCookedState.cookedPointerData.pointerProperties,
4850 mCurrentCookedState.cookedPointerData.pointerCoords,
4851 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4852 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wright7b159c92015-05-14 14:48:03 +01004853 }
4854}
4855
4856void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4857 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4858 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4859 const int32_t metaState = getContext()->getGlobalMetaState();
4860 int32_t buttonState = mLastCookedState.buttonState;
4861 while (!pressedButtons.isEmpty()) {
4862 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4863 buttonState |= actionButton;
4864 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
Prabir Pradhan2b281812019-08-29 14:12:42 -07004865 0, metaState, buttonState, 0, mCurrentCookedState.deviceTimestamp,
4866 mCurrentCookedState.cookedPointerData.pointerProperties,
4867 mCurrentCookedState.cookedPointerData.pointerCoords,
4868 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4869 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wright7b159c92015-05-14 14:48:03 +01004870 }
4871}
4872
4873const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4874 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4875 return cookedPointerData.touchingIdBits;
4876 }
4877 return cookedPointerData.hoveringIdBits;
4878}
4879
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004881 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882
Michael Wright842500e2015-03-13 17:32:02 -07004883 mCurrentCookedState.cookedPointerData.clear();
Prabir Pradhan2b281812019-08-29 14:12:42 -07004884 mCurrentCookedState.deviceTimestamp = mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004885 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4886 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4887 mCurrentRawState.rawPointerData.hoveringIdBits;
4888 mCurrentCookedState.cookedPointerData.touchingIdBits =
4889 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890
Michael Wright7b159c92015-05-14 14:48:03 +01004891 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4892 mCurrentCookedState.buttonState = 0;
4893 } else {
4894 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4895 }
4896
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 // Walk through the the active pointers and map device coordinates onto
4898 // surface coordinates and adjust for display orientation.
4899 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004900 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901
4902 // Size
4903 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4904 switch (mCalibration.sizeCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004905 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4906 case Calibration::SIZE_CALIBRATION_DIAMETER:
4907 case Calibration::SIZE_CALIBRATION_BOX:
4908 case Calibration::SIZE_CALIBRATION_AREA:
4909 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4910 touchMajor = in.touchMajor;
4911 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4912 toolMajor = in.toolMajor;
4913 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4914 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
4915 : in.touchMajor;
4916 } else if (mRawPointerAxes.touchMajor.valid) {
4917 toolMajor = touchMajor = in.touchMajor;
4918 toolMinor = touchMinor =
4919 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4920 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
4921 : in.touchMajor;
4922 } else if (mRawPointerAxes.toolMajor.valid) {
4923 touchMajor = toolMajor = in.toolMajor;
4924 touchMinor = toolMinor =
4925 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4926 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
4927 : in.toolMajor;
4928 } else {
4929 ALOG_ASSERT(false,
4930 "No touch or tool axes. "
4931 "Size calibration should have been resolved to NONE.");
4932 touchMajor = 0;
4933 touchMinor = 0;
4934 toolMajor = 0;
4935 toolMinor = 0;
4936 size = 0;
4937 }
4938
4939 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
4940 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
4941 if (touchingCount > 1) {
4942 touchMajor /= touchingCount;
4943 touchMinor /= touchingCount;
4944 toolMajor /= touchingCount;
4945 toolMinor /= touchingCount;
4946 size /= touchingCount;
4947 }
4948 }
4949
4950 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4951 touchMajor *= mGeometricScale;
4952 touchMinor *= mGeometricScale;
4953 toolMajor *= mGeometricScale;
4954 toolMinor *= mGeometricScale;
4955 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4956 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4957 touchMinor = touchMajor;
4958 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4959 toolMinor = toolMajor;
4960 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4961 touchMinor = touchMajor;
4962 toolMinor = toolMajor;
4963 }
4964
4965 mCalibration.applySizeScaleAndBias(&touchMajor);
4966 mCalibration.applySizeScaleAndBias(&touchMinor);
4967 mCalibration.applySizeScaleAndBias(&toolMajor);
4968 mCalibration.applySizeScaleAndBias(&toolMinor);
4969 size *= mSizeScale;
4970 break;
4971 default:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972 touchMajor = 0;
4973 touchMinor = 0;
4974 toolMajor = 0;
4975 toolMinor = 0;
4976 size = 0;
Prabir Pradhan2b281812019-08-29 14:12:42 -07004977 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978 }
4979
4980 // Pressure
4981 float pressure;
4982 switch (mCalibration.pressureCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07004983 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4984 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4985 pressure = in.pressure * mPressureScale;
4986 break;
4987 default:
4988 pressure = in.isHovering ? 0 : 1;
4989 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 }
4991
4992 // Tilt and Orientation
4993 float tilt;
4994 float orientation;
4995 if (mHaveTilt) {
4996 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4997 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4998 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4999 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5000 } else {
5001 tilt = 0;
5002
5003 switch (mCalibration.orientationCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005004 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5005 orientation = in.orientation * mOrientationScale;
5006 break;
5007 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5008 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5009 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5010 if (c1 != 0 || c2 != 0) {
5011 orientation = atan2f(c1, c2) * 0.5f;
5012 float confidence = hypotf(c1, c2);
5013 float scale = 1.0f + confidence / 16.0f;
5014 touchMajor *= scale;
5015 touchMinor /= scale;
5016 toolMajor *= scale;
5017 toolMinor /= scale;
5018 } else {
5019 orientation = 0;
5020 }
5021 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07005023 default:
5024 orientation = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025 }
5026 }
5027
5028 // Distance
5029 float distance;
5030 switch (mCalibration.distanceCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005031 case Calibration::DISTANCE_CALIBRATION_SCALED:
5032 distance = in.distance * mDistanceScale;
5033 break;
5034 default:
5035 distance = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 }
5037
5038 // Coverage
5039 int32_t rawLeft, rawTop, rawRight, rawBottom;
5040 switch (mCalibration.coverageCalibration) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005041 case Calibration::COVERAGE_CALIBRATION_BOX:
5042 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5043 rawRight = in.toolMinor & 0x0000ffff;
5044 rawBottom = in.toolMajor & 0x0000ffff;
5045 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5046 break;
5047 default:
5048 rawLeft = rawTop = rawRight = rawBottom = 0;
5049 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050 }
5051
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005052 // Adjust X,Y coords for device calibration
5053 // TODO: Adjust coverage coords?
5054 float xTransformed = in.x, yTransformed = in.y;
5055 mAffineTransform.applyTo(xTransformed, yTransformed);
5056
5057 // Adjust X, Y, and coverage coords for surface orientation.
5058 float x, y;
5059 float left, top, right, bottom;
5060
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 switch (mSurfaceOrientation) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005062 case DISPLAY_ORIENTATION_90:
5063 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5064 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5065 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5066 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5067 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5068 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5069 orientation -= M_PI_2;
5070 if (mOrientedRanges.haveOrientation &&
5071 orientation < mOrientedRanges.orientation.min) {
5072 orientation +=
5073 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5074 }
5075 break;
5076 case DISPLAY_ORIENTATION_180:
5077 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
5078 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5079 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5080 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
5081 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5082 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5083 orientation -= M_PI;
5084 if (mOrientedRanges.haveOrientation &&
5085 orientation < mOrientedRanges.orientation.min) {
5086 orientation +=
5087 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5088 }
5089 break;
5090 case DISPLAY_ORIENTATION_270:
5091 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
5092 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5093 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5094 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
5095 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5096 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5097 orientation += M_PI_2;
5098 if (mOrientedRanges.haveOrientation &&
5099 orientation > mOrientedRanges.orientation.max) {
5100 orientation -=
5101 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5102 }
5103 break;
5104 default:
5105 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5106 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5107 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5108 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5109 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5110 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5111 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005112 }
5113
5114 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005115 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 out.clear();
5117 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5118 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5119 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5120 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5121 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5122 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5123 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5124 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5125 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5126 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5127 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5128 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5129 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5130 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5131 } else {
5132 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5133 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5134 }
5135
5136 // Write output properties.
Prabir Pradhan2b281812019-08-29 14:12:42 -07005137 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 uint32_t id = in.id;
5139 properties.clear();
5140 properties.id = id;
5141 properties.toolType = in.toolType;
5142
5143 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005144 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
5146}
5147
5148void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
Prabir Pradhan2b281812019-08-29 14:12:42 -07005149 PointerUsage pointerUsage) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 if (pointerUsage != mPointerUsage) {
5151 abortPointerUsage(when, policyFlags);
5152 mPointerUsage = pointerUsage;
5153 }
5154
5155 switch (mPointerUsage) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005156 case POINTER_USAGE_GESTURES:
5157 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5158 break;
5159 case POINTER_USAGE_STYLUS:
5160 dispatchPointerStylus(when, policyFlags);
5161 break;
5162 case POINTER_USAGE_MOUSE:
5163 dispatchPointerMouse(when, policyFlags);
5164 break;
5165 default:
5166 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 }
5168}
5169
5170void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5171 switch (mPointerUsage) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005172 case POINTER_USAGE_GESTURES:
5173 abortPointerGestures(when, policyFlags);
5174 break;
5175 case POINTER_USAGE_STYLUS:
5176 abortPointerStylus(when, policyFlags);
5177 break;
5178 case POINTER_USAGE_MOUSE:
5179 abortPointerMouse(when, policyFlags);
5180 break;
5181 default:
5182 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 }
5184
5185 mPointerUsage = POINTER_USAGE_NONE;
5186}
5187
Prabir Pradhan2b281812019-08-29 14:12:42 -07005188void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189 // Update current gesture coordinates.
5190 bool cancelPreviousGesture, finishPreviousGesture;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005191 bool sendEvents =
5192 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 if (!sendEvents) {
5194 return;
5195 }
5196 if (finishPreviousGesture) {
5197 cancelPreviousGesture = false;
5198 }
5199
5200 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005201 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5202 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 if (finishPreviousGesture || cancelPreviousGesture) {
5204 mPointerController->clearSpots();
5205 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005206
5207 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5208 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
Prabir Pradhan2b281812019-08-29 14:12:42 -07005209 mPointerGesture.currentGestureIdToIndex,
5210 mPointerGesture.currentGestureIdBits,
5211 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005213 } else {
5214 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5215 }
5216
5217 // Show or hide the pointer if needed.
5218 switch (mPointerGesture.currentGestureMode) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005219 case PointerGesture::NEUTRAL:
5220 case PointerGesture::QUIET:
5221 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH &&
5222 mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
5223 // Remind the user of where the pointer is after finishing a gesture with spots.
5224 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5225 }
5226 break;
5227 case PointerGesture::TAP:
5228 case PointerGesture::TAP_DRAG:
5229 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5230 case PointerGesture::HOVER:
5231 case PointerGesture::PRESS:
5232 case PointerGesture::SWIPE:
5233 // Unfade the pointer when the current gesture manipulates the
5234 // area directly under the pointer.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
Prabir Pradhan2b281812019-08-29 14:12:42 -07005236 break;
5237 case PointerGesture::FREEFORM:
5238 // Fade the pointer when the current gesture manipulates a different
5239 // area and there are spots to guide the user experience.
5240 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5241 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5242 } else {
5243 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5244 }
5245 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 }
5247
5248 // Send events!
5249 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005250 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251
5252 // Update last coordinates of pointers that have moved so that we observe the new
5253 // pointer positions at the same time as other pointers that have just gone up.
Prabir Pradhan2b281812019-08-29 14:12:42 -07005254 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP ||
5255 mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG ||
5256 mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG ||
5257 mPointerGesture.currentGestureMode == PointerGesture::PRESS ||
5258 mPointerGesture.currentGestureMode == PointerGesture::SWIPE ||
5259 mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 bool moveNeeded = false;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005261 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
5262 !mPointerGesture.lastGestureIdBits.isEmpty() &&
5263 !mPointerGesture.currentGestureIdBits.isEmpty()) {
5264 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
5265 mPointerGesture.lastGestureIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
Prabir Pradhan2b281812019-08-29 14:12:42 -07005267 mPointerGesture.currentGestureCoords,
5268 mPointerGesture.currentGestureIdToIndex,
5269 mPointerGesture.lastGestureProperties,
5270 mPointerGesture.lastGestureCoords,
5271 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005272 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 moveNeeded = true;
5274 }
5275 }
5276
5277 // Send motion events for all pointers that went up or were canceled.
5278 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5279 if (!dispatchedGestureIdBits.isEmpty()) {
5280 if (cancelPreviousGesture) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005281 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5282 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
5283 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5284 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5285 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286
5287 dispatchedGestureIdBits.clear();
5288 } else {
5289 BitSet32 upGestureIdBits;
5290 if (finishPreviousGesture) {
5291 upGestureIdBits = dispatchedGestureIdBits;
5292 } else {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005293 upGestureIdBits.value =
5294 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295 }
5296 while (!upGestureIdBits.isEmpty()) {
5297 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5298
Prabir Pradhan2b281812019-08-29 14:12:42 -07005299 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
5300 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5301 /* deviceTimestamp */ 0, mPointerGesture.lastGestureProperties,
5302 mPointerGesture.lastGestureCoords,
5303 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
5304 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305
5306 dispatchedGestureIdBits.clearBit(id);
5307 }
5308 }
5309 }
5310
5311 // Send motion events for all pointers that moved.
5312 if (moveNeeded) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005313 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
5314 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
5315 mPointerGesture.currentGestureProperties,
5316 mPointerGesture.currentGestureCoords,
5317 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5318 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 }
5320
5321 // Send motion events for all pointers that went down.
5322 if (down) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005323 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
5324 ~dispatchedGestureIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 while (!downGestureIdBits.isEmpty()) {
5326 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5327 dispatchedGestureIdBits.markBit(id);
5328
5329 if (dispatchedGestureIdBits.count() == 1) {
5330 mPointerGesture.downTime = when;
5331 }
5332
Prabir Pradhan2b281812019-08-29 14:12:42 -07005333 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
5334 metaState, buttonState, 0,
5335 /* deviceTimestamp */ 0, mPointerGesture.currentGestureProperties,
5336 mPointerGesture.currentGestureCoords,
5337 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
5338 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 }
5340 }
5341
5342 // Send motion events for hover.
5343 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005344 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
5345 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
5346 mPointerGesture.currentGestureProperties,
5347 mPointerGesture.currentGestureCoords,
5348 mPointerGesture.currentGestureIdToIndex,
5349 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
5350 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 // Synthesize a hover move event after all pointers go up to indicate that
5352 // the pointer is hovering again even if the user is not currently touching
5353 // the touch pad. This ensures that a view will receive a fresh hover enter
5354 // event after a tap.
5355 float x, y;
5356 mPointerController->getPosition(&x, &y);
5357
5358 PointerProperties pointerProperties;
5359 pointerProperties.clear();
5360 pointerProperties.id = 0;
5361 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5362
5363 PointerCoords pointerCoords;
5364 pointerCoords.clear();
5365 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5366 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5367
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005368 const int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhan2b281812019-08-29 14:12:42 -07005369 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
5370 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5371 metaState, buttonState, MotionClassification::NONE,
5372 AMOTION_EVENT_EDGE_FLAG_NONE,
5373 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0,
5374 mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 getListener()->notifyMotion(&args);
5376 }
5377
5378 // Update state.
5379 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5380 if (!down) {
5381 mPointerGesture.lastGestureIdBits.clear();
5382 } else {
5383 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005384 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 uint32_t id = idBits.clearFirstMarkedBit();
5386 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5387 mPointerGesture.lastGestureProperties[index].copyFrom(
5388 mPointerGesture.currentGestureProperties[index]);
5389 mPointerGesture.lastGestureCoords[index].copyFrom(
5390 mPointerGesture.currentGestureCoords[index]);
5391 mPointerGesture.lastGestureIdToIndex[id] = index;
5392 }
5393 }
5394}
5395
5396void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5397 // Cancel previously dispatches pointers.
5398 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5399 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005400 int32_t buttonState = mCurrentRawState.buttonState;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005401 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5402 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
5403 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5404 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
5405 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406 }
5407
5408 // Reset the current pointer gesture.
5409 mPointerGesture.reset();
5410 mPointerVelocityControl.reset();
5411
5412 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005413 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5415 mPointerController->clearSpots();
5416 }
5417}
5418
Prabir Pradhan2b281812019-08-29 14:12:42 -07005419bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
5420 bool* outFinishPreviousGesture, bool isTimeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421 *outCancelPreviousGesture = false;
5422 *outFinishPreviousGesture = false;
5423
5424 // Handle TAP timeout.
5425 if (isTimeout) {
5426#if DEBUG_GESTURES
5427 ALOGD("Gestures: Processing timeout");
5428#endif
5429
5430 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5431 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5432 // The tap/drag timeout has not yet expired.
Prabir Pradhan2b281812019-08-29 14:12:42 -07005433 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
5434 mConfig.pointerGestureTapDragInterval);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435 } else {
5436 // The tap is finished.
5437#if DEBUG_GESTURES
5438 ALOGD("Gestures: TAP finished");
5439#endif
5440 *outFinishPreviousGesture = true;
5441
5442 mPointerGesture.activeGestureId = -1;
5443 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5444 mPointerGesture.currentGestureIdBits.clear();
5445
5446 mPointerVelocityControl.reset();
5447 return true;
5448 }
5449 }
5450
5451 // We did not handle this timeout.
5452 return false;
5453 }
5454
Michael Wright842500e2015-03-13 17:32:02 -07005455 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5456 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005457
5458 // Update the velocity tracker.
5459 {
5460 VelocityTracker::Position positions[MAX_POINTERS];
5461 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005462 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005464 const RawPointerData::Pointer& pointer =
5465 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 positions[count].x = pointer.x * mPointerXMovementScale;
5467 positions[count].y = pointer.y * mPointerYMovementScale;
5468 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07005469 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
5470 positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 }
5472
5473 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5474 // to NEUTRAL, then we should not generate tap event.
Prabir Pradhan2b281812019-08-29 14:12:42 -07005475 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER &&
5476 mPointerGesture.lastGestureMode != PointerGesture::TAP &&
5477 mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 mPointerGesture.resetTap();
5479 }
5480
5481 // Pick a new active touch id if needed.
5482 // Choose an arbitrary pointer that just went down, if there is one.
5483 // Otherwise choose an arbitrary remaining pointer.
5484 // This guarantees we always have an active touch id when there is at least one pointer.
5485 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5487 int32_t activeTouchId = lastActiveTouchId;
5488 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005489 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005491 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492 mPointerGesture.firstTouchTime = when;
5493 }
Michael Wright842500e2015-03-13 17:32:02 -07005494 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005495 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005497 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 } else {
5499 activeTouchId = mPointerGesture.activeTouchId = -1;
5500 }
5501 }
5502
5503 // Determine whether we are in quiet time.
5504 bool isQuietTime = false;
5505 if (activeTouchId < 0) {
5506 mPointerGesture.resetQuietTime();
5507 } else {
5508 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5509 if (!isQuietTime) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07005510 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS ||
5511 mPointerGesture.lastGestureMode == PointerGesture::SWIPE ||
5512 mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) &&
5513 currentFingerCount < 2) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514 // Enter quiet time when exiting swipe or freeform state.
5515 // This is to prevent accidentally entering the hover state and flinging the
5516 // pointer when finishing a swipe and there is still one pointer left onscreen.
5517 isQuietTime = true;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005518 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG &&
5519 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 // Enter quiet time when releasing the button and there are still two or more
5521 // fingers down. This may indicate that one finger was used to press the button
5522 // but it has not gone up yet.
5523 isQuietTime = true;
5524 }
5525 if (isQuietTime) {
5526 mPointerGesture.quietTime = when;
5527 }
5528 }
5529 }
5530
5531 // Switch states based on button and pointer state.
5532 if (isQuietTime) {
5533 // Case 1: Quiet time. (QUIET)
5534#if DEBUG_GESTURES
Prabir Pradhan2b281812019-08-29 14:12:42 -07005535 ALOGD("Gestures: QUIET for next %0.3fms",
5536 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537#endif
5538 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5539 *outFinishPreviousGesture = true;
5540 }
5541
5542 mPointerGesture.activeGestureId = -1;
5543 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5544 mPointerGesture.currentGestureIdBits.clear();
5545
5546 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005547 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5549 // The pointer follows the active touch point.
5550 // Emit DOWN, MOVE, UP events at the pointer location.
5551 //
5552 // Only the active touch matters; other fingers are ignored. This policy helps
5553 // to handle the case where the user places a second finger on the touch pad
5554 // to apply the necessary force to depress an integrated button below the surface.
5555 // We don't want the second finger to be delivered to applications.
5556 //
5557 // For this to work well, we need to make sure to track the pointer that is really
5558 // active. If the user first puts one finger down to click then adds another
5559 // finger to drag then the active pointer should switch to the finger that is
5560 // being dragged.
5561#if DEBUG_GESTURES
5562 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07005563 "currentFingerCount=%d",
5564 activeTouchId, currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565#endif
5566 // Reset state when just starting.
5567 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5568 *outFinishPreviousGesture = true;
5569 mPointerGesture.activeGestureId = 0;
5570 }
5571
5572 // Switch pointers if needed.
5573 // Find the fastest pointer and follow it.
5574 if (activeTouchId >= 0 && currentFingerCount > 1) {
5575 int32_t bestId = -1;
5576 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005577 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 uint32_t id = idBits.clearFirstMarkedBit();
5579 float vx, vy;
5580 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5581 float speed = hypotf(vx, vy);
5582 if (speed > bestSpeed) {
5583 bestId = id;
5584 bestSpeed = speed;
5585 }
5586 }
5587 }
5588 if (bestId >= 0 && bestId != activeTouchId) {
5589 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590#if DEBUG_GESTURES
5591 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07005592 "bestId=%d, bestSpeed=%0.3f",
5593 bestId, bestSpeed);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594#endif
5595 }
5596 }
5597
Jun Mukaifa1706a2015-12-03 01:14:46 -08005598 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005599 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005601 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005603 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005604 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5605 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606
5607 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5608 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5609
5610 // Move the pointer using a relative motion.
5611 // When using spots, the click will occur at the position of the anchor
5612 // spot and all other spots will move there.
5613 mPointerController->move(deltaX, deltaY);
5614 } else {
5615 mPointerVelocityControl.reset();
5616 }
5617
5618 float x, y;
5619 mPointerController->getPosition(&x, &y);
5620
5621 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5622 mPointerGesture.currentGestureIdBits.clear();
5623 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5624 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5625 mPointerGesture.currentGestureProperties[0].clear();
5626 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5627 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5628 mPointerGesture.currentGestureCoords[0].clear();
5629 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5630 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5631 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5632 } else if (currentFingerCount == 0) {
5633 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5634 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5635 *outFinishPreviousGesture = true;
5636 }
5637
5638 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5639 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5640 bool tapped = false;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005641 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER ||
5642 mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) &&
5643 lastFingerCount == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5645 float x, y;
5646 mPointerController->getPosition(&x, &y);
Prabir Pradhan2b281812019-08-29 14:12:42 -07005647 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
5648 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649#if DEBUG_GESTURES
5650 ALOGD("Gestures: TAP");
5651#endif
5652
5653 mPointerGesture.tapUpTime = when;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005654 getContext()->requestTimeoutAtTime(when +
5655 mConfig.pointerGestureTapDragInterval);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656
5657 mPointerGesture.activeGestureId = 0;
5658 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5659 mPointerGesture.currentGestureIdBits.clear();
Prabir Pradhan2b281812019-08-29 14:12:42 -07005660 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5661 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662 mPointerGesture.currentGestureProperties[0].clear();
5663 mPointerGesture.currentGestureProperties[0].id =
5664 mPointerGesture.activeGestureId;
5665 mPointerGesture.currentGestureProperties[0].toolType =
5666 AMOTION_EVENT_TOOL_TYPE_FINGER;
5667 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhan2b281812019-08-29 14:12:42 -07005668 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5669 mPointerGesture.tapX);
5670 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5671 mPointerGesture.tapY);
5672 mPointerGesture.currentGestureCoords[0]
5673 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005674
5675 tapped = true;
5676 } else {
5677#if DEBUG_GESTURES
Prabir Pradhan2b281812019-08-29 14:12:42 -07005678 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
5679 y - mPointerGesture.tapY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680#endif
5681 }
5682 } else {
5683#if DEBUG_GESTURES
5684 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5685 ALOGD("Gestures: Not a TAP, %0.3fms since down",
Prabir Pradhan2b281812019-08-29 14:12:42 -07005686 (when - mPointerGesture.tapDownTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 } else {
5688 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5689 }
5690#endif
5691 }
5692 }
5693
5694 mPointerVelocityControl.reset();
5695
5696 if (!tapped) {
5697#if DEBUG_GESTURES
5698 ALOGD("Gestures: NEUTRAL");
5699#endif
5700 mPointerGesture.activeGestureId = -1;
5701 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5702 mPointerGesture.currentGestureIdBits.clear();
5703 }
5704 } else if (currentFingerCount == 1) {
5705 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5706 // The pointer follows the active touch point.
5707 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5708 // When in TAP_DRAG, emit MOVE events at the pointer location.
5709 ALOG_ASSERT(activeTouchId >= 0);
5710
5711 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5712 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5713 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5714 float x, y;
5715 mPointerController->getPosition(&x, &y);
Prabir Pradhan2b281812019-08-29 14:12:42 -07005716 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
5717 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5719 } else {
5720#if DEBUG_GESTURES
5721 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
Prabir Pradhan2b281812019-08-29 14:12:42 -07005722 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723#endif
5724 }
5725 } else {
5726#if DEBUG_GESTURES
5727 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
Prabir Pradhan2b281812019-08-29 14:12:42 -07005728 (when - mPointerGesture.tapUpTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729#endif
5730 }
5731 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5732 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5733 }
5734
Jun Mukaifa1706a2015-12-03 01:14:46 -08005735 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005736 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005738 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005740 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005741 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5742 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743
5744 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5745 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5746
5747 // Move the pointer using a relative motion.
5748 // When using spots, the hover or drag will occur at the position of the anchor spot.
5749 mPointerController->move(deltaX, deltaY);
5750 } else {
5751 mPointerVelocityControl.reset();
5752 }
5753
5754 bool down;
5755 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5756#if DEBUG_GESTURES
5757 ALOGD("Gestures: TAP_DRAG");
5758#endif
5759 down = true;
5760 } else {
5761#if DEBUG_GESTURES
5762 ALOGD("Gestures: HOVER");
5763#endif
5764 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5765 *outFinishPreviousGesture = true;
5766 }
5767 mPointerGesture.activeGestureId = 0;
5768 down = false;
5769 }
5770
5771 float x, y;
5772 mPointerController->getPosition(&x, &y);
5773
5774 mPointerGesture.currentGestureIdBits.clear();
5775 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5776 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5777 mPointerGesture.currentGestureProperties[0].clear();
5778 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005779 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 mPointerGesture.currentGestureCoords[0].clear();
5781 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5782 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5783 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
Prabir Pradhan2b281812019-08-29 14:12:42 -07005784 down ? 1.0f : 0.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785
5786 if (lastFingerCount == 0 && currentFingerCount != 0) {
5787 mPointerGesture.resetTap();
5788 mPointerGesture.tapDownTime = when;
5789 mPointerGesture.tapX = x;
5790 mPointerGesture.tapY = y;
5791 }
5792 } else {
5793 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5794 // We need to provide feedback for each finger that goes down so we cannot wait
5795 // for the fingers to move before deciding what to do.
5796 //
5797 // The ambiguous case is deciding what to do when there are two fingers down but they
5798 // have not moved enough to determine whether they are part of a drag or part of a
5799 // freeform gesture, or just a press or long-press at the pointer location.
5800 //
5801 // When there are two fingers we start with the PRESS hypothesis and we generate a
5802 // down at the pointer location.
5803 //
5804 // When the two fingers move enough or when additional fingers are added, we make
5805 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5806 ALOG_ASSERT(activeTouchId >= 0);
5807
Prabir Pradhan2b281812019-08-29 14:12:42 -07005808 bool settled = when >=
5809 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
5810 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS &&
5811 mPointerGesture.lastGestureMode != PointerGesture::SWIPE &&
5812 mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813 *outFinishPreviousGesture = true;
5814 } else if (!settled && currentFingerCount > lastFingerCount) {
5815 // Additional pointers have gone down but not yet settled.
5816 // Reset the gesture.
5817#if DEBUG_GESTURES
5818 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07005819 "settle time remaining %0.3fms",
5820 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
5821 when) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822#endif
5823 *outCancelPreviousGesture = true;
5824 } else {
5825 // Continue previous gesture.
5826 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5827 }
5828
5829 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5830 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5831 mPointerGesture.activeGestureId = 0;
5832 mPointerGesture.referenceIdBits.clear();
5833 mPointerVelocityControl.reset();
5834
5835 // Use the centroid and pointer location as the reference points for the gesture.
5836#if DEBUG_GESTURES
5837 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07005838 "settle time remaining %0.3fms",
5839 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
5840 when) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005841#endif
Prabir Pradhan2b281812019-08-29 14:12:42 -07005842 mCurrentRawState.rawPointerData
5843 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
5844 &mPointerGesture.referenceTouchY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
Prabir Pradhan2b281812019-08-29 14:12:42 -07005846 &mPointerGesture.referenceGestureY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 }
5848
5849 // Clear the reference deltas for fingers not yet included in the reference calculation.
Prabir Pradhan2b281812019-08-29 14:12:42 -07005850 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
5851 ~mPointerGesture.referenceIdBits.value);
5852 !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853 uint32_t id = idBits.clearFirstMarkedBit();
5854 mPointerGesture.referenceDeltas[id].dx = 0;
5855 mPointerGesture.referenceDeltas[id].dy = 0;
5856 }
Michael Wright842500e2015-03-13 17:32:02 -07005857 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858
5859 // Add delta for all fingers and calculate a common movement delta.
5860 float commonDeltaX = 0, commonDeltaY = 0;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005861 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
5862 mCurrentCookedState.fingerIdBits.value);
5863 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005864 bool first = (idBits == commonIdBits);
5865 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005866 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5867 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5869 delta.dx += cpd.x - lpd.x;
5870 delta.dy += cpd.y - lpd.y;
5871
5872 if (first) {
5873 commonDeltaX = delta.dx;
5874 commonDeltaY = delta.dy;
5875 } else {
5876 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5877 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5878 }
5879 }
5880
5881 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5882 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5883 float dist[MAX_POINTER_ID + 1];
5884 int32_t distOverThreshold = 0;
Prabir Pradhan2b281812019-08-29 14:12:42 -07005885 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 uint32_t id = idBits.clearFirstMarkedBit();
5887 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
Prabir Pradhan2b281812019-08-29 14:12:42 -07005888 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005889 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5890 distOverThreshold += 1;
5891 }
5892 }
5893
5894 // Only transition when at least two pointers have moved further than
5895 // the minimum distance threshold.
5896 if (distOverThreshold >= 2) {
5897 if (currentFingerCount > 2) {
5898 // There are more than two pointers, switch to FREEFORM.
5899#if DEBUG_GESTURES
5900 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
Prabir Pradhan2b281812019-08-29 14:12:42 -07005901 currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902#endif
5903 *outCancelPreviousGesture = true;
5904 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5905 } else {
5906 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005907 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 uint32_t id1 = idBits.clearFirstMarkedBit();
5909 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005910 const RawPointerData::Pointer& p1 =
5911 mCurrentRawState.rawPointerData.pointerForId(id1);
5912 const RawPointerData::Pointer& p2 =
5913 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005914 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5915 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5916 // There are two pointers but they are too far apart for a SWIPE,
5917 // switch to FREEFORM.
5918#if DEBUG_GESTURES
5919 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
Prabir Pradhan2b281812019-08-29 14:12:42 -07005920 mutualDistance, mPointerGestureMaxSwipeWidth);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921#endif
5922 *outCancelPreviousGesture = true;
5923 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5924 } else {
5925 // There are two pointers. Wait for both pointers to start moving
5926 // before deciding whether this is a SWIPE or FREEFORM gesture.
5927 float dist1 = dist[id1];
5928 float dist2 = dist[id2];
Prabir Pradhan2b281812019-08-29 14:12:42 -07005929 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
5930 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931 // Calculate the dot product of the displacement vectors.
5932 // When the vectors are oriented in approximately the same direction,
5933 // the angle betweeen them is near zero and the cosine of the angle
Prabir Pradhan2b281812019-08-29 14:12:42 -07005934 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
5935 // mag(v2).
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5937 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5938 float dx1 = delta1.dx * mPointerXZoomScale;
5939 float dy1 = delta1.dy * mPointerYZoomScale;
5940 float dx2 = delta2.dx * mPointerXZoomScale;
5941 float dy2 = delta2.dy * mPointerYZoomScale;
5942 float dot = dx1 * dx2 + dy1 * dy2;
5943 float cosine = dot / (dist1 * dist2); // denominator always > 0
5944 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5945 // Pointers are moving in the same direction. Switch to SWIPE.
5946#if DEBUG_GESTURES
5947 ALOGD("Gestures: PRESS transitioned to SWIPE, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07005948 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5949 "cosine %0.3f >= %0.3f",
5950 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
5951 mConfig.pointerGestureMultitouchMinDistance, cosine,
5952 mConfig.pointerGestureSwipeTransitionAngleCosine);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953#endif
5954 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5955 } else {
5956 // Pointers are moving in different directions. Switch to FREEFORM.
5957#if DEBUG_GESTURES
5958 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07005959 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5960 "cosine %0.3f < %0.3f",
5961 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
5962 mConfig.pointerGestureMultitouchMinDistance, cosine,
5963 mConfig.pointerGestureSwipeTransitionAngleCosine);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964#endif
5965 *outCancelPreviousGesture = true;
5966 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5967 }
5968 }
5969 }
5970 }
5971 }
5972 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5973 // Switch from SWIPE to FREEFORM if additional pointers go down.
5974 // Cancel previous gesture.
5975 if (currentFingerCount > 2) {
5976#if DEBUG_GESTURES
5977 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
Prabir Pradhan2b281812019-08-29 14:12:42 -07005978 currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979#endif
5980 *outCancelPreviousGesture = true;
5981 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5982 }
5983 }
5984
5985 // Move the reference points based on the overall group motion of the fingers
5986 // except in PRESS mode while waiting for a transition to occur.
Prabir Pradhan2b281812019-08-29 14:12:42 -07005987 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS &&
5988 (commonDeltaX || commonDeltaY)) {
5989 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005990 uint32_t id = idBits.clearFirstMarkedBit();
5991 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5992 delta.dx = 0;
5993 delta.dy = 0;
5994 }
5995
5996 mPointerGesture.referenceTouchX += commonDeltaX;
5997 mPointerGesture.referenceTouchY += commonDeltaY;
5998
5999 commonDeltaX *= mPointerXMovementScale;
6000 commonDeltaY *= mPointerYMovementScale;
6001
6002 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6003 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6004
6005 mPointerGesture.referenceGestureX += commonDeltaX;
6006 mPointerGesture.referenceGestureY += commonDeltaY;
6007 }
6008
6009 // Report gestures.
Prabir Pradhan2b281812019-08-29 14:12:42 -07006010 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS ||
6011 mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012 // PRESS or SWIPE mode.
6013#if DEBUG_GESTURES
6014 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
Prabir Pradhan2b281812019-08-29 14:12:42 -07006015 "activeGestureId=%d, currentTouchPointerCount=%d",
6016 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006017#endif
6018 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6019
6020 mPointerGesture.currentGestureIdBits.clear();
6021 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6022 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6023 mPointerGesture.currentGestureProperties[0].clear();
6024 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Prabir Pradhan2b281812019-08-29 14:12:42 -07006025 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006026 mPointerGesture.currentGestureCoords[0].clear();
6027 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan2b281812019-08-29 14:12:42 -07006028 mPointerGesture.referenceGestureX);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan2b281812019-08-29 14:12:42 -07006030 mPointerGesture.referenceGestureY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006031 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6032 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6033 // FREEFORM mode.
6034#if DEBUG_GESTURES
6035 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
Prabir Pradhan2b281812019-08-29 14:12:42 -07006036 "activeGestureId=%d, currentTouchPointerCount=%d",
6037 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038#endif
6039 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6040
6041 mPointerGesture.currentGestureIdBits.clear();
6042
6043 BitSet32 mappedTouchIdBits;
6044 BitSet32 usedGestureIdBits;
6045 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6046 // Initially, assign the active gesture id to the active touch point
6047 // if there is one. No other touch id bits are mapped yet.
6048 if (!*outCancelPreviousGesture) {
6049 mappedTouchIdBits.markBit(activeTouchId);
6050 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6051 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6052 mPointerGesture.activeGestureId;
6053 } else {
6054 mPointerGesture.activeGestureId = -1;
6055 }
6056 } else {
6057 // Otherwise, assume we mapped all touches from the previous frame.
6058 // Reuse all mappings that are still applicable.
Prabir Pradhan2b281812019-08-29 14:12:42 -07006059 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
6060 mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006061 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6062
6063 // Check whether we need to choose a new active gesture id because the
6064 // current went went up.
Prabir Pradhan2b281812019-08-29 14:12:42 -07006065 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
6066 ~mCurrentCookedState.fingerIdBits.value);
6067 !upTouchIdBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6069 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6070 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6071 mPointerGesture.activeGestureId = -1;
6072 break;
6073 }
6074 }
6075 }
6076
6077#if DEBUG_GESTURES
6078 ALOGD("Gestures: FREEFORM follow up "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006079 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6080 "activeGestureId=%d",
6081 mappedTouchIdBits.value, usedGestureIdBits.value,
6082 mPointerGesture.activeGestureId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083#endif
6084
Michael Wright842500e2015-03-13 17:32:02 -07006085 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 for (uint32_t i = 0; i < currentFingerCount; i++) {
6087 uint32_t touchId = idBits.clearFirstMarkedBit();
6088 uint32_t gestureId;
6089 if (!mappedTouchIdBits.hasBit(touchId)) {
6090 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6091 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6092#if DEBUG_GESTURES
6093 ALOGD("Gestures: FREEFORM "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006094 "new mapping for touch id %d -> gesture id %d",
6095 touchId, gestureId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096#endif
6097 } else {
6098 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6099#if DEBUG_GESTURES
6100 ALOGD("Gestures: FREEFORM "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006101 "existing mapping for touch id %d -> gesture id %d",
6102 touchId, gestureId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103#endif
6104 }
6105 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6106 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6107
6108 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006109 mCurrentRawState.rawPointerData.pointerForId(touchId);
Prabir Pradhan2b281812019-08-29 14:12:42 -07006110 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
6111 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6113
6114 mPointerGesture.currentGestureProperties[i].clear();
6115 mPointerGesture.currentGestureProperties[i].id = gestureId;
6116 mPointerGesture.currentGestureProperties[i].toolType =
6117 AMOTION_EVENT_TOOL_TYPE_FINGER;
6118 mPointerGesture.currentGestureCoords[i].clear();
Prabir Pradhan2b281812019-08-29 14:12:42 -07006119 mPointerGesture.currentGestureCoords[i]
6120 .setAxisValue(AMOTION_EVENT_AXIS_X,
6121 mPointerGesture.referenceGestureX + deltaX);
6122 mPointerGesture.currentGestureCoords[i]
6123 .setAxisValue(AMOTION_EVENT_AXIS_Y,
6124 mPointerGesture.referenceGestureY + deltaY);
6125 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6126 1.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006127 }
6128
6129 if (mPointerGesture.activeGestureId < 0) {
6130 mPointerGesture.activeGestureId =
6131 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6132#if DEBUG_GESTURES
6133 ALOGD("Gestures: FREEFORM new "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006134 "activeGestureId=%d",
6135 mPointerGesture.activeGestureId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136#endif
6137 }
6138 }
6139 }
6140
Michael Wright842500e2015-03-13 17:32:02 -07006141 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006142
6143#if DEBUG_GESTURES
6144 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006145 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6146 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6147 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6148 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6149 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6150 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006151 uint32_t id = idBits.clearFirstMarkedBit();
6152 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6153 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6154 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6155 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006156 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6157 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6158 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6159 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006160 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07006161 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006162 uint32_t id = idBits.clearFirstMarkedBit();
6163 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6164 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6165 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6166 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006167 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6168 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6169 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6170 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171 }
6172#endif
6173 return true;
6174}
6175
6176void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6177 mPointerSimple.currentCoords.clear();
6178 mPointerSimple.currentProperties.clear();
6179
6180 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006181 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6182 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6183 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6184 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6185 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006186 mPointerController->setPosition(x, y);
6187
Michael Wright842500e2015-03-13 17:32:02 -07006188 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189 down = !hovering;
6190
6191 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006192 mPointerSimple.currentCoords.copyFrom(
6193 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006194 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6195 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6196 mPointerSimple.currentProperties.id = 0;
6197 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006198 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006199 } else {
6200 down = false;
6201 hovering = false;
6202 }
6203
6204 dispatchPointerSimple(when, policyFlags, down, hovering);
6205}
6206
6207void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6208 abortPointerSimple(when, policyFlags);
6209}
6210
6211void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6212 mPointerSimple.currentCoords.clear();
6213 mPointerSimple.currentProperties.clear();
6214
6215 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006216 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6217 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6218 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006219 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006220 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6221 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhan2b281812019-08-29 14:12:42 -07006222 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
6223 mLastRawState.rawPointerData.pointers[lastIndex].x) *
6224 mPointerXMovementScale;
6225 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
6226 mLastRawState.rawPointerData.pointers[lastIndex].y) *
6227 mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228
6229 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6230 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6231
6232 mPointerController->move(deltaX, deltaY);
6233 } else {
6234 mPointerVelocityControl.reset();
6235 }
6236
Michael Wright842500e2015-03-13 17:32:02 -07006237 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 hovering = !down;
6239
6240 float x, y;
6241 mPointerController->getPosition(&x, &y);
6242 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006243 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006244 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6245 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6246 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
Prabir Pradhan2b281812019-08-29 14:12:42 -07006247 hovering ? 0.0f : 1.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 mPointerSimple.currentProperties.id = 0;
6249 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006250 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 } else {
6252 mPointerVelocityControl.reset();
6253
6254 down = false;
6255 hovering = false;
6256 }
6257
6258 dispatchPointerSimple(when, policyFlags, down, hovering);
6259}
6260
6261void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6262 abortPointerSimple(when, policyFlags);
6263
6264 mPointerVelocityControl.reset();
6265}
6266
Prabir Pradhan2b281812019-08-29 14:12:42 -07006267void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
6268 bool hovering) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006270 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006271
Yi Kong9b14ac62018-07-17 13:48:38 -07006272 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006273 if (down || hovering) {
6274 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6275 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006276 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006277 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6278 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6279 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6280 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006281 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 }
6283
6284 if (mPointerSimple.down && !down) {
6285 mPointerSimple.down = false;
6286
6287 // Send up.
Prabir Pradhan2b281812019-08-29 14:12:42 -07006288 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6289 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
6290 mLastRawState.buttonState, MotionClassification::NONE,
6291 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6292 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6293 mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime,
6294 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 getListener()->notifyMotion(&args);
6296 }
6297
6298 if (mPointerSimple.hovering && !hovering) {
6299 mPointerSimple.hovering = false;
6300
6301 // Send hover exit.
Prabir Pradhan2b281812019-08-29 14:12:42 -07006302 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6303 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
6304 metaState, mLastRawState.buttonState, MotionClassification::NONE,
6305 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6306 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6307 mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime,
6308 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 getListener()->notifyMotion(&args);
6310 }
6311
6312 if (down) {
6313 if (!mPointerSimple.down) {
6314 mPointerSimple.down = true;
6315 mPointerSimple.downTime = when;
6316
6317 // Send down.
Prabir Pradhan2b281812019-08-29 14:12:42 -07006318 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6319 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
6320 metaState, mCurrentRawState.buttonState,
6321 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
6322 /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties,
6323 &mPointerSimple.currentCoords, mOrientedXPrecision,
6324 mOrientedYPrecision, mPointerSimple.downTime,
6325 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006326 getListener()->notifyMotion(&args);
6327 }
6328
6329 // Send move.
Prabir Pradhan2b281812019-08-29 14:12:42 -07006330 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6331 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
6332 mCurrentRawState.buttonState, MotionClassification::NONE,
6333 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6334 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6335 mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime,
6336 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006337 getListener()->notifyMotion(&args);
6338 }
6339
6340 if (hovering) {
6341 if (!mPointerSimple.hovering) {
6342 mPointerSimple.hovering = true;
6343
6344 // Send hover enter.
Prabir Pradhan2b281812019-08-29 14:12:42 -07006345 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6346 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
6347 metaState, mCurrentRawState.buttonState,
6348 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
6349 /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties,
6350 &mPointerSimple.currentCoords, mOrientedXPrecision,
6351 mOrientedYPrecision, mPointerSimple.downTime,
6352 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353 getListener()->notifyMotion(&args);
6354 }
6355
6356 // Send hover move.
Prabir Pradhan2b281812019-08-29 14:12:42 -07006357 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6358 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
6359 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
6360 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6361 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6362 mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime,
6363 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364 getListener()->notifyMotion(&args);
6365 }
6366
Michael Wright842500e2015-03-13 17:32:02 -07006367 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6368 float vscroll = mCurrentRawState.rawVScroll;
6369 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006370 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6371 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372
6373 // Send scroll.
6374 PointerCoords pointerCoords;
6375 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6376 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6377 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6378
Prabir Pradhan2b281812019-08-29 14:12:42 -07006379 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6380 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
6381 mCurrentRawState.buttonState, MotionClassification::NONE,
6382 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6383 &mPointerSimple.currentProperties, &pointerCoords,
6384 mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime,
6385 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386 getListener()->notifyMotion(&args);
6387 }
6388
6389 // Save state.
6390 if (down || hovering) {
6391 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6392 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6393 } else {
6394 mPointerSimple.reset();
6395 }
6396}
6397
6398void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6399 mPointerSimple.currentCoords.clear();
6400 mPointerSimple.currentProperties.clear();
6401
6402 dispatchPointerSimple(when, policyFlags, false, false);
6403}
6404
6405void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Prabir Pradhan2b281812019-08-29 14:12:42 -07006406 int32_t action, int32_t actionButton, int32_t flags,
6407 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
6408 uint32_t deviceTimestamp, const PointerProperties* properties,
6409 const PointerCoords* coords, const uint32_t* idToIndex,
6410 BitSet32 idBits, int32_t changedId, float xPrecision,
6411 float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412 PointerCoords pointerCoords[MAX_POINTERS];
6413 PointerProperties pointerProperties[MAX_POINTERS];
6414 uint32_t pointerCount = 0;
6415 while (!idBits.isEmpty()) {
6416 uint32_t id = idBits.clearFirstMarkedBit();
6417 uint32_t index = idToIndex[id];
6418 pointerProperties[pointerCount].copyFrom(properties[index]);
6419 pointerCoords[pointerCount].copyFrom(coords[index]);
6420
6421 if (changedId >= 0 && id == uint32_t(changedId)) {
6422 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6423 }
6424
6425 pointerCount += 1;
6426 }
6427
6428 ALOG_ASSERT(pointerCount != 0);
6429
6430 if (changedId >= 0 && pointerCount == 1) {
6431 // Replace initial down and final up action.
6432 // We can compare the action without masking off the changed pointer index
6433 // because we know the index is 0.
6434 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6435 action = AMOTION_EVENT_ACTION_DOWN;
6436 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6437 action = AMOTION_EVENT_ACTION_UP;
6438 } else {
6439 // Can't happen.
6440 ALOG_ASSERT(false);
6441 }
6442 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006443 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006444 const int32_t deviceId = getDeviceId();
6445 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006446 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan2b281812019-08-29 14:12:42 -07006447 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
6448 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId,
6449 policyFlags, action, actionButton, flags, metaState, buttonState,
6450 MotionClassification::NONE, edgeFlags, deviceTimestamp, pointerCount,
6451 pointerProperties, pointerCoords, xPrecision, yPrecision, downTime,
6452 std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006453 getListener()->notifyMotion(&args);
6454}
6455
6456bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
Prabir Pradhan2b281812019-08-29 14:12:42 -07006457 const PointerCoords* inCoords,
6458 const uint32_t* inIdToIndex,
6459 PointerProperties* outProperties,
6460 PointerCoords* outCoords, const uint32_t* outIdToIndex,
6461 BitSet32 idBits) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006462 bool changed = false;
6463 while (!idBits.isEmpty()) {
6464 uint32_t id = idBits.clearFirstMarkedBit();
6465 uint32_t inIndex = inIdToIndex[id];
6466 uint32_t outIndex = outIdToIndex[id];
6467
6468 const PointerProperties& curInProperties = inProperties[inIndex];
6469 const PointerCoords& curInCoords = inCoords[inIndex];
6470 PointerProperties& curOutProperties = outProperties[outIndex];
6471 PointerCoords& curOutCoords = outCoords[outIndex];
6472
6473 if (curInProperties != curOutProperties) {
6474 curOutProperties.copyFrom(curInProperties);
6475 changed = true;
6476 }
6477
6478 if (curInCoords != curOutCoords) {
6479 curOutCoords.copyFrom(curInCoords);
6480 changed = true;
6481 }
6482 }
6483 return changed;
6484}
6485
6486void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006487 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006488 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6489 }
6490}
6491
Jeff Brownc9aa6282015-02-11 19:03:28 -08006492void TouchInputMapper::cancelTouch(nsecs_t when) {
6493 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006494 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006495}
6496
Michael Wrightd02c5b62014-02-10 15:10:22 -08006497bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006498 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006499 const float scaledY = y * mYScale;
Prabir Pradhan2b281812019-08-29 14:12:42 -07006500 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
6501 scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth &&
6502 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
6503 scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006504}
6505
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006506const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07006507 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006508#if DEBUG_VIRTUAL_KEYS
6509 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006510 "left=%d, top=%d, right=%d, bottom=%d",
6511 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
6512 virtualKey.hitRight, virtualKey.hitBottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006513#endif
6514
6515 if (virtualKey.isHit(x, y)) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07006516 return &virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006517 }
6518 }
6519
Yi Kong9b14ac62018-07-17 13:48:38 -07006520 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006521}
6522
Michael Wright842500e2015-03-13 17:32:02 -07006523void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6524 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6525 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006526
Michael Wright842500e2015-03-13 17:32:02 -07006527 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006528
6529 if (currentPointerCount == 0) {
6530 // No pointers to assign.
6531 return;
6532 }
6533
6534 if (lastPointerCount == 0) {
6535 // All pointers are new.
6536 for (uint32_t i = 0; i < currentPointerCount; i++) {
6537 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006538 current->rawPointerData.pointers[i].id = id;
6539 current->rawPointerData.idToIndex[id] = i;
6540 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541 }
6542 return;
6543 }
6544
Prabir Pradhan2b281812019-08-29 14:12:42 -07006545 if (currentPointerCount == 1 && lastPointerCount == 1 &&
6546 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006547 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006548 uint32_t id = last->rawPointerData.pointers[0].id;
6549 current->rawPointerData.pointers[0].id = id;
6550 current->rawPointerData.idToIndex[id] = 0;
6551 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552 return;
6553 }
6554
6555 // General case.
6556 // We build a heap of squared euclidean distances between current and last pointers
6557 // associated with the current and last pointer indices. Then, we find the best
6558 // match (by distance) for each current pointer.
6559 // The pointers must have the same tool type but it is possible for them to
6560 // transition from hovering to touching or vice-versa while retaining the same id.
6561 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6562
6563 uint32_t heapSize = 0;
6564 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
Prabir Pradhan2b281812019-08-29 14:12:42 -07006565 currentPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
Prabir Pradhan2b281812019-08-29 14:12:42 -07006567 lastPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006568 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006569 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006570 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006571 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006572 if (currentPointer.toolType == lastPointer.toolType) {
6573 int64_t deltaX = currentPointer.x - lastPointer.x;
6574 int64_t deltaY = currentPointer.y - lastPointer.y;
6575
6576 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6577
6578 // Insert new element into the heap (sift up).
6579 heap[heapSize].currentPointerIndex = currentPointerIndex;
6580 heap[heapSize].lastPointerIndex = lastPointerIndex;
6581 heap[heapSize].distance = distance;
6582 heapSize += 1;
6583 }
6584 }
6585 }
6586
6587 // Heapify
Prabir Pradhan2b281812019-08-29 14:12:42 -07006588 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006589 startIndex -= 1;
Prabir Pradhan2b281812019-08-29 14:12:42 -07006590 for (uint32_t parentIndex = startIndex;;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006591 uint32_t childIndex = parentIndex * 2 + 1;
6592 if (childIndex >= heapSize) {
6593 break;
6594 }
6595
Prabir Pradhan2b281812019-08-29 14:12:42 -07006596 if (childIndex + 1 < heapSize &&
6597 heap[childIndex + 1].distance < heap[childIndex].distance) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006598 childIndex += 1;
6599 }
6600
6601 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6602 break;
6603 }
6604
6605 swap(heap[parentIndex], heap[childIndex]);
6606 parentIndex = childIndex;
6607 }
6608 }
6609
6610#if DEBUG_POINTER_ASSIGNMENT
6611 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6612 for (size_t i = 0; i < heapSize; i++) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07006613 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
6614 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615 }
6616#endif
6617
6618 // Pull matches out by increasing order of distance.
6619 // To avoid reassigning pointers that have already been matched, the loop keeps track
6620 // of which last and current pointers have been matched using the matchedXXXBits variables.
6621 // It also tracks the used pointer id bits.
6622 BitSet32 matchedLastBits(0);
6623 BitSet32 matchedCurrentBits(0);
6624 BitSet32 usedIdBits(0);
6625 bool first = true;
6626 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6627 while (heapSize > 0) {
6628 if (first) {
6629 // The first time through the loop, we just consume the root element of
6630 // the heap (the one with smallest distance).
6631 first = false;
6632 } else {
6633 // Previous iterations consumed the root element of the heap.
6634 // Pop root element off of the heap (sift down).
6635 heap[0] = heap[heapSize];
Prabir Pradhan2b281812019-08-29 14:12:42 -07006636 for (uint32_t parentIndex = 0;;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006637 uint32_t childIndex = parentIndex * 2 + 1;
6638 if (childIndex >= heapSize) {
6639 break;
6640 }
6641
Prabir Pradhan2b281812019-08-29 14:12:42 -07006642 if (childIndex + 1 < heapSize &&
6643 heap[childIndex + 1].distance < heap[childIndex].distance) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006644 childIndex += 1;
6645 }
6646
6647 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6648 break;
6649 }
6650
6651 swap(heap[parentIndex], heap[childIndex]);
6652 parentIndex = childIndex;
6653 }
6654
6655#if DEBUG_POINTER_ASSIGNMENT
6656 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6657 for (size_t i = 0; i < heapSize; i++) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07006658 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
6659 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006660 }
6661#endif
6662 }
6663
6664 heapSize -= 1;
6665
6666 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6667 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6668
6669 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6670 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6671
6672 matchedCurrentBits.markBit(currentPointerIndex);
6673 matchedLastBits.markBit(lastPointerIndex);
6674
Michael Wright842500e2015-03-13 17:32:02 -07006675 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6676 current->rawPointerData.pointers[currentPointerIndex].id = id;
6677 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6678 current->rawPointerData.markIdBit(id,
Prabir Pradhan2b281812019-08-29 14:12:42 -07006679 current->rawPointerData.isHovering(
6680 currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006681 usedIdBits.markBit(id);
6682
6683#if DEBUG_POINTER_ASSIGNMENT
Prabir Pradhan2b281812019-08-29 14:12:42 -07006684 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
6685 ", distance=%" PRIu64,
6686 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006687#endif
6688 break;
6689 }
6690 }
6691
6692 // Assign fresh ids to pointers that were not matched in the process.
6693 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6694 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6695 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6696
Michael Wright842500e2015-03-13 17:32:02 -07006697 current->rawPointerData.pointers[currentPointerIndex].id = id;
6698 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6699 current->rawPointerData.markIdBit(id,
Prabir Pradhan2b281812019-08-29 14:12:42 -07006700 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006701
6702#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006703 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006704#endif
6705 }
6706}
6707
6708int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6709 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6710 return AKEY_STATE_VIRTUAL;
6711 }
6712
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006713 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006714 if (virtualKey.keyCode == keyCode) {
6715 return AKEY_STATE_UP;
6716 }
6717 }
6718
6719 return AKEY_STATE_UNKNOWN;
6720}
6721
6722int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6723 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6724 return AKEY_STATE_VIRTUAL;
6725 }
6726
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006727 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006728 if (virtualKey.scanCode == scanCode) {
6729 return AKEY_STATE_UP;
6730 }
6731 }
6732
6733 return AKEY_STATE_UNKNOWN;
6734}
6735
6736bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
Prabir Pradhan2b281812019-08-29 14:12:42 -07006737 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006738 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006739 for (size_t i = 0; i < numCodes; i++) {
6740 if (virtualKey.keyCode == keyCodes[i]) {
6741 outFlags[i] = 1;
6742 }
6743 }
6744 }
6745
6746 return true;
6747}
6748
Arthur Hungc23540e2018-11-29 20:42:11 +08006749std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6750 if (mParameters.hasAssociatedDisplay) {
6751 if (mDeviceMode == DEVICE_MODE_POINTER) {
6752 return std::make_optional(mPointerController->getDisplayId());
6753 } else {
6754 return std::make_optional(mViewport.displayId);
6755 }
6756 }
6757 return std::nullopt;
6758}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006759
6760// --- SingleTouchInputMapper ---
6761
Prabir Pradhan2b281812019-08-29 14:12:42 -07006762SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) : TouchInputMapper(device) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006763
Prabir Pradhan2b281812019-08-29 14:12:42 -07006764SingleTouchInputMapper::~SingleTouchInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006765
6766void SingleTouchInputMapper::reset(nsecs_t when) {
6767 mSingleTouchMotionAccumulator.reset(getDevice());
6768
6769 TouchInputMapper::reset(when);
6770}
6771
6772void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6773 TouchInputMapper::process(rawEvent);
6774
6775 mSingleTouchMotionAccumulator.process(rawEvent);
6776}
6777
Michael Wright842500e2015-03-13 17:32:02 -07006778void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006779 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006780 outState->rawPointerData.pointerCount = 1;
6781 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006782
Prabir Pradhan2b281812019-08-29 14:12:42 -07006783 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE &&
6784 (mTouchButtonAccumulator.isHovering() ||
6785 (mRawPointerAxes.pressure.valid &&
6786 mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006787 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006788
Michael Wright842500e2015-03-13 17:32:02 -07006789 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006790 outPointer.id = 0;
6791 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6792 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6793 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6794 outPointer.touchMajor = 0;
6795 outPointer.touchMinor = 0;
6796 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6797 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6798 outPointer.orientation = 0;
6799 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6800 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6801 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6802 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6803 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6804 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6805 }
6806 outPointer.isHovering = isHovering;
6807 }
6808}
6809
6810void SingleTouchInputMapper::configureRawPointerAxes() {
6811 TouchInputMapper::configureRawPointerAxes();
6812
6813 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6814 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6815 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6816 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6817 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6818 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6819 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6820}
6821
6822bool SingleTouchInputMapper::hasStylus() const {
6823 return mTouchButtonAccumulator.hasStylus();
6824}
6825
Michael Wrightd02c5b62014-02-10 15:10:22 -08006826// --- MultiTouchInputMapper ---
6827
Prabir Pradhan2b281812019-08-29 14:12:42 -07006828MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) : TouchInputMapper(device) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006829
Prabir Pradhan2b281812019-08-29 14:12:42 -07006830MultiTouchInputMapper::~MultiTouchInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006831
6832void MultiTouchInputMapper::reset(nsecs_t when) {
6833 mMultiTouchMotionAccumulator.reset(getDevice());
6834
6835 mPointerIdBits.clear();
6836
6837 TouchInputMapper::reset(when);
6838}
6839
6840void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6841 TouchInputMapper::process(rawEvent);
6842
6843 mMultiTouchMotionAccumulator.process(rawEvent);
6844}
6845
Michael Wright842500e2015-03-13 17:32:02 -07006846void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006847 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6848 size_t outCount = 0;
6849 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006850 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006851
6852 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6853 const MultiTouchMotionAccumulator::Slot* inSlot =
6854 mMultiTouchMotionAccumulator.getSlot(inIndex);
6855 if (!inSlot->isInUse()) {
6856 continue;
6857 }
6858
6859 if (outCount >= MAX_POINTERS) {
6860#if DEBUG_POINTERS
6861 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006862 "ignoring the rest.",
6863 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006864#endif
6865 break; // too many fingers!
6866 }
6867
Michael Wright842500e2015-03-13 17:32:02 -07006868 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006869 outPointer.x = inSlot->getX();
6870 outPointer.y = inSlot->getY();
6871 outPointer.pressure = inSlot->getPressure();
6872 outPointer.touchMajor = inSlot->getTouchMajor();
6873 outPointer.touchMinor = inSlot->getTouchMinor();
6874 outPointer.toolMajor = inSlot->getToolMajor();
6875 outPointer.toolMinor = inSlot->getToolMinor();
6876 outPointer.orientation = inSlot->getOrientation();
6877 outPointer.distance = inSlot->getDistance();
6878 outPointer.tiltX = 0;
6879 outPointer.tiltY = 0;
6880
6881 outPointer.toolType = inSlot->getToolType();
6882 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6883 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6884 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6885 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6886 }
6887 }
6888
Prabir Pradhan2b281812019-08-29 14:12:42 -07006889 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE &&
6890 (mTouchButtonAccumulator.isHovering() ||
6891 (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006892 outPointer.isHovering = isHovering;
6893
6894 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006895 if (mHavePointerIds) {
6896 int32_t trackingId = inSlot->getTrackingId();
6897 int32_t id = -1;
6898 if (trackingId >= 0) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07006899 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty();) {
gaoshang1a632de2016-08-24 10:23:50 +08006900 uint32_t n = idBits.clearFirstMarkedBit();
6901 if (mPointerTrackingIdMap[n] == trackingId) {
6902 id = n;
6903 }
6904 }
6905
6906 if (id < 0 && !mPointerIdBits.isFull()) {
6907 id = mPointerIdBits.markFirstUnmarkedBit();
6908 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006909 }
Michael Wright842500e2015-03-13 17:32:02 -07006910 }
gaoshang1a632de2016-08-24 10:23:50 +08006911 if (id < 0) {
6912 mHavePointerIds = false;
6913 outState->rawPointerData.clearIdBits();
6914 newPointerIdBits.clear();
6915 } else {
6916 outPointer.id = id;
6917 outState->rawPointerData.idToIndex[id] = outCount;
6918 outState->rawPointerData.markIdBit(id, isHovering);
6919 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006920 }
Michael Wright842500e2015-03-13 17:32:02 -07006921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006922 outCount += 1;
6923 }
6924
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006925 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006926 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006927 mPointerIdBits = newPointerIdBits;
6928
6929 mMultiTouchMotionAccumulator.finishSync();
6930}
6931
6932void MultiTouchInputMapper::configureRawPointerAxes() {
6933 TouchInputMapper::configureRawPointerAxes();
6934
6935 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6936 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6937 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6938 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6939 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6940 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6941 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6942 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6943 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6944 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6945 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6946
Prabir Pradhan2b281812019-08-29 14:12:42 -07006947 if (mRawPointerAxes.trackingId.valid && mRawPointerAxes.slot.valid &&
6948 mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006949 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6950 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006951 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
Prabir Pradhan2b281812019-08-29 14:12:42 -07006952 "only supports a maximum of %zu slots at this time.",
6953 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006954 slotCount = MAX_SLOTS;
6955 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07006956 mMultiTouchMotionAccumulator.configure(getDevice(), slotCount, true /*usingSlotsProtocol*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006957 } else {
Prabir Pradhan2b281812019-08-29 14:12:42 -07006958 mMultiTouchMotionAccumulator.configure(getDevice(), MAX_POINTERS,
6959 false /*usingSlotsProtocol*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006960 }
6961}
6962
6963bool MultiTouchInputMapper::hasStylus() const {
Prabir Pradhan2b281812019-08-29 14:12:42 -07006964 return mMultiTouchMotionAccumulator.hasStylus() || mTouchButtonAccumulator.hasStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006965}
6966
Michael Wright842500e2015-03-13 17:32:02 -07006967// --- ExternalStylusInputMapper
6968
Prabir Pradhan2b281812019-08-29 14:12:42 -07006969ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) : InputMapper(device) {}
Michael Wright842500e2015-03-13 17:32:02 -07006970
6971uint32_t ExternalStylusInputMapper::getSources() {
6972 return AINPUT_SOURCE_STYLUS;
6973}
6974
6975void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6976 InputMapper::populateDeviceInfo(info);
Prabir Pradhan2b281812019-08-29 14:12:42 -07006977 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS, 0.0f, 1.0f, 0.0f, 0.0f,
6978 0.0f);
Michael Wright842500e2015-03-13 17:32:02 -07006979}
6980
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006981void ExternalStylusInputMapper::dump(std::string& dump) {
6982 dump += INDENT2 "External Stylus Input Mapper:\n";
6983 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07006984 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006985 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07006986 dumpStylusState(dump, mStylusState);
6987}
6988
Prabir Pradhan2b281812019-08-29 14:12:42 -07006989void ExternalStylusInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
6990 uint32_t changes) {
Michael Wright842500e2015-03-13 17:32:02 -07006991 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6992 mTouchButtonAccumulator.configure(getDevice());
6993}
6994
6995void ExternalStylusInputMapper::reset(nsecs_t when) {
6996 InputDevice* device = getDevice();
6997 mSingleTouchMotionAccumulator.reset(device);
6998 mTouchButtonAccumulator.reset(device);
6999 InputMapper::reset(when);
7000}
7001
7002void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7003 mSingleTouchMotionAccumulator.process(rawEvent);
7004 mTouchButtonAccumulator.process(rawEvent);
7005
7006 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7007 sync(rawEvent->when);
7008 }
7009}
7010
7011void ExternalStylusInputMapper::sync(nsecs_t when) {
7012 mStylusState.clear();
7013
7014 mStylusState.when = when;
7015
Michael Wright45ccacf2015-04-21 19:01:58 +01007016 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7017 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7018 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7019 }
7020
Michael Wright842500e2015-03-13 17:32:02 -07007021 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7022 if (mRawPressureAxis.valid) {
7023 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7024 } else if (mTouchButtonAccumulator.isToolActive()) {
7025 mStylusState.pressure = 1.0f;
7026 } else {
7027 mStylusState.pressure = 0.0f;
7028 }
7029
7030 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007031
7032 mContext->dispatchExternalStylusState(mStylusState);
7033}
7034
Michael Wrightd02c5b62014-02-10 15:10:22 -08007035// --- JoystickInputMapper ---
7036
Prabir Pradhan2b281812019-08-29 14:12:42 -07007037JoystickInputMapper::JoystickInputMapper(InputDevice* device) : InputMapper(device) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08007038
Prabir Pradhan2b281812019-08-29 14:12:42 -07007039JoystickInputMapper::~JoystickInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08007040
7041uint32_t JoystickInputMapper::getSources() {
7042 return AINPUT_SOURCE_JOYSTICK;
7043}
7044
7045void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7046 InputMapper::populateDeviceInfo(info);
7047
7048 for (size_t i = 0; i < mAxes.size(); i++) {
7049 const Axis& axis = mAxes.valueAt(i);
7050 addMotionRange(axis.axisInfo.axis, axis, info);
7051
7052 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7053 addMotionRange(axis.axisInfo.highAxis, axis, info);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007054 }
7055 }
7056}
7057
Prabir Pradhan2b281812019-08-29 14:12:42 -07007058void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info) {
7059 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat, axis.fuzz,
7060 axis.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007061 /* In order to ease the transition for developers from using the old axes
7062 * to the newer, more semantically correct axes, we'll continue to register
7063 * the old axes as duplicates of their corresponding new ones. */
7064 int32_t compatAxis = getCompatAxis(axisId);
7065 if (compatAxis >= 0) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07007066 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat,
7067 axis.fuzz, axis.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007068 }
7069}
7070
7071/* A mapping from axes the joystick actually has to the axes that should be
7072 * artificially created for compatibility purposes.
7073 * Returns -1 if no compatibility axis is needed. */
7074int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07007075 switch (axis) {
7076 case AMOTION_EVENT_AXIS_LTRIGGER:
7077 return AMOTION_EVENT_AXIS_BRAKE;
7078 case AMOTION_EVENT_AXIS_RTRIGGER:
7079 return AMOTION_EVENT_AXIS_GAS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007080 }
7081 return -1;
7082}
7083
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007084void JoystickInputMapper::dump(std::string& dump) {
7085 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007086
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007087 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007088 size_t numAxes = mAxes.size();
7089 for (size_t i = 0; i < numAxes; i++) {
7090 const Axis& axis = mAxes.valueAt(i);
7091 const char* label = getAxisLabel(axis.axisInfo.axis);
7092 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007093 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007094 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007095 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007096 }
7097 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7098 label = getAxisLabel(axis.axisInfo.highAxis);
7099 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007100 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007101 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007102 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Prabir Pradhan2b281812019-08-29 14:12:42 -07007103 axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007104 }
7105 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007106 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007107 }
7108
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007109 dump += StringPrintf(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
Prabir Pradhan2b281812019-08-29 14:12:42 -07007110 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007111 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07007112 "highScale=%0.5f, highOffset=%0.5f\n",
7113 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007114 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Prabir Pradhan2b281812019-08-29 14:12:42 -07007115 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7116 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7117 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz,
7118 axis.rawAxisInfo.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007119 }
7120}
7121
Prabir Pradhan2b281812019-08-29 14:12:42 -07007122void JoystickInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
7123 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007124 InputMapper::configure(when, config, changes);
7125
7126 if (!changes) { // first time only
7127 // Collect all axes.
7128 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07007129 if (!(getAbsAxisUsage(abs, getDevice()->getClasses()) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007130 continue; // axis must be claimed by a different device
7131 }
7132
7133 RawAbsoluteAxisInfo rawAxisInfo;
7134 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7135 if (rawAxisInfo.valid) {
7136 // Map axis.
7137 AxisInfo axisInfo;
7138 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7139 if (!explicitlyMapped) {
7140 // Axis is not explicitly mapped, will choose a generic axis later.
7141 axisInfo.mode = AxisInfo::MODE_NORMAL;
7142 axisInfo.axis = -1;
7143 }
7144
7145 // Apply flat override.
Prabir Pradhan2b281812019-08-29 14:12:42 -07007146 int32_t rawFlat =
7147 axisInfo.flatOverride < 0 ? rawAxisInfo.flat : axisInfo.flatOverride;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007148
7149 // Calculate scaling factors and limits.
7150 Axis axis;
7151 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7152 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7153 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
Prabir Pradhan2b281812019-08-29 14:12:42 -07007154 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, highScale,
7155 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7156 rawAxisInfo.resolution * scale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007157 } else if (isCenteredAxis(axisInfo.axis)) {
7158 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7159 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
Prabir Pradhan2b281812019-08-29 14:12:42 -07007160 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, offset, scale,
7161 offset, -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7162 rawAxisInfo.resolution * scale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007163 } else {
7164 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
Prabir Pradhan2b281812019-08-29 14:12:42 -07007165 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, scale,
7166 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7167 rawAxisInfo.resolution * scale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007168 }
7169
7170 // To eliminate noise while the joystick is at rest, filter out small variations
7171 // in axis values up front.
7172 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7173
7174 mAxes.add(abs, axis);
7175 }
7176 }
7177
7178 // If there are too many axes, start dropping them.
7179 // Prefer to keep explicitly mapped axes.
7180 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007181 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Prabir Pradhan2b281812019-08-29 14:12:42 -07007182 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007183 pruneAxes(true);
7184 pruneAxes(false);
7185 }
7186
7187 // Assign generic axis ids to remaining axes.
7188 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7189 size_t numAxes = mAxes.size();
7190 for (size_t i = 0; i < numAxes; i++) {
7191 Axis& axis = mAxes.editValueAt(i);
7192 if (axis.axisInfo.axis < 0) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07007193 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16 &&
7194 haveAxis(nextGenericAxisId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007195 nextGenericAxisId += 1;
7196 }
7197
7198 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7199 axis.axisInfo.axis = nextGenericAxisId;
7200 nextGenericAxisId += 1;
7201 } else {
7202 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
Prabir Pradhan2b281812019-08-29 14:12:42 -07007203 "have already been assigned to other axes.",
7204 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007205 mAxes.removeItemsAt(i--);
7206 numAxes -= 1;
7207 }
7208 }
7209 }
7210 }
7211}
7212
7213bool JoystickInputMapper::haveAxis(int32_t axisId) {
7214 size_t numAxes = mAxes.size();
7215 for (size_t i = 0; i < numAxes; i++) {
7216 const Axis& axis = mAxes.valueAt(i);
Prabir Pradhan2b281812019-08-29 14:12:42 -07007217 if (axis.axisInfo.axis == axisId ||
7218 (axis.axisInfo.mode == AxisInfo::MODE_SPLIT && axis.axisInfo.highAxis == axisId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007219 return true;
7220 }
7221 }
7222 return false;
7223}
7224
7225void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7226 size_t i = mAxes.size();
7227 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7228 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7229 continue;
7230 }
7231 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Prabir Pradhan2b281812019-08-29 14:12:42 -07007232 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007233 mAxes.removeItemsAt(i);
7234 }
7235}
7236
7237bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7238 switch (axis) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07007239 case AMOTION_EVENT_AXIS_X:
7240 case AMOTION_EVENT_AXIS_Y:
7241 case AMOTION_EVENT_AXIS_Z:
7242 case AMOTION_EVENT_AXIS_RX:
7243 case AMOTION_EVENT_AXIS_RY:
7244 case AMOTION_EVENT_AXIS_RZ:
7245 case AMOTION_EVENT_AXIS_HAT_X:
7246 case AMOTION_EVENT_AXIS_HAT_Y:
7247 case AMOTION_EVENT_AXIS_ORIENTATION:
7248 case AMOTION_EVENT_AXIS_RUDDER:
7249 case AMOTION_EVENT_AXIS_WHEEL:
7250 return true;
7251 default:
7252 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007253 }
7254}
7255
7256void JoystickInputMapper::reset(nsecs_t when) {
7257 // Recenter all axes.
7258 size_t numAxes = mAxes.size();
7259 for (size_t i = 0; i < numAxes; i++) {
7260 Axis& axis = mAxes.editValueAt(i);
7261 axis.resetValue();
7262 }
7263
7264 InputMapper::reset(when);
7265}
7266
7267void JoystickInputMapper::process(const RawEvent* rawEvent) {
7268 switch (rawEvent->type) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07007269 case EV_ABS: {
7270 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7271 if (index >= 0) {
7272 Axis& axis = mAxes.editValueAt(index);
7273 float newValue, highNewValue;
7274 switch (axis.axisInfo.mode) {
7275 case AxisInfo::MODE_INVERT:
7276 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value) * axis.scale +
7277 axis.offset;
7278 highNewValue = 0.0f;
7279 break;
7280 case AxisInfo::MODE_SPLIT:
7281 if (rawEvent->value < axis.axisInfo.splitValue) {
7282 newValue = (axis.axisInfo.splitValue - rawEvent->value) * axis.scale +
7283 axis.offset;
7284 highNewValue = 0.0f;
7285 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7286 newValue = 0.0f;
7287 highNewValue =
7288 (rawEvent->value - axis.axisInfo.splitValue) * axis.highScale +
7289 axis.highOffset;
7290 } else {
7291 newValue = 0.0f;
7292 highNewValue = 0.0f;
7293 }
7294 break;
7295 default:
7296 newValue = rawEvent->value * axis.scale + axis.offset;
7297 highNewValue = 0.0f;
7298 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007299 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07007300 axis.newValue = newValue;
7301 axis.highNewValue = highNewValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007303 break;
7304 }
Prabir Pradhan2b281812019-08-29 14:12:42 -07007305
7306 case EV_SYN:
7307 switch (rawEvent->code) {
7308 case SYN_REPORT:
7309 sync(rawEvent->when, false /*force*/);
7310 break;
7311 }
7312 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007313 }
7314}
7315
7316void JoystickInputMapper::sync(nsecs_t when, bool force) {
7317 if (!filterAxes(force)) {
7318 return;
7319 }
7320
7321 int32_t metaState = mContext->getGlobalMetaState();
7322 int32_t buttonState = 0;
7323
7324 PointerProperties pointerProperties;
7325 pointerProperties.clear();
7326 pointerProperties.id = 0;
7327 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7328
7329 PointerCoords pointerCoords;
7330 pointerCoords.clear();
7331
7332 size_t numAxes = mAxes.size();
7333 for (size_t i = 0; i < numAxes; i++) {
7334 const Axis& axis = mAxes.valueAt(i);
7335 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7336 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7337 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
Prabir Pradhan2b281812019-08-29 14:12:42 -07007338 axis.highCurrentValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007339 }
7340 }
7341
7342 // Moving a joystick axis should not wake the device because joysticks can
7343 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7344 // button will likely wake the device.
7345 // TODO: Use the input device configuration to control this behavior more finely.
7346 uint32_t policyFlags = 0;
7347
Prabir Pradhan42611e02018-11-27 14:04:02 -08007348 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Prabir Pradhan2b281812019-08-29 14:12:42 -07007349 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
7350 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
7351 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
7352 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0, 0,
7353 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007354 getListener()->notifyMotion(&args);
7355}
7356
Prabir Pradhan2b281812019-08-29 14:12:42 -07007357void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis,
7358 float value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007359 pointerCoords->setAxisValue(axis, value);
7360 /* In order to ease the transition for developers from using the old axes
7361 * to the newer, more semantically correct axes, we'll continue to produce
7362 * values for the old axes as mirrors of the value of their corresponding
7363 * new axes. */
7364 int32_t compatAxis = getCompatAxis(axis);
7365 if (compatAxis >= 0) {
7366 pointerCoords->setAxisValue(compatAxis, value);
7367 }
7368}
7369
7370bool JoystickInputMapper::filterAxes(bool force) {
7371 bool atLeastOneSignificantChange = force;
7372 size_t numAxes = mAxes.size();
7373 for (size_t i = 0; i < numAxes; i++) {
7374 Axis& axis = mAxes.editValueAt(i);
Prabir Pradhan2b281812019-08-29 14:12:42 -07007375 if (force ||
7376 hasValueChangedSignificantly(axis.filter, axis.newValue, axis.currentValue, axis.min,
7377 axis.max)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007378 axis.currentValue = axis.newValue;
7379 atLeastOneSignificantChange = true;
7380 }
7381 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Prabir Pradhan2b281812019-08-29 14:12:42 -07007382 if (force ||
7383 hasValueChangedSignificantly(axis.filter, axis.highNewValue, axis.highCurrentValue,
7384 axis.min, axis.max)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007385 axis.highCurrentValue = axis.highNewValue;
7386 atLeastOneSignificantChange = true;
7387 }
7388 }
7389 }
7390 return atLeastOneSignificantChange;
7391}
7392
Prabir Pradhan2b281812019-08-29 14:12:42 -07007393bool JoystickInputMapper::hasValueChangedSignificantly(float filter, float newValue,
7394 float currentValue, float min, float max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007395 if (newValue != currentValue) {
7396 // Filter out small changes in value unless the value is converging on the axis
7397 // bounds or center point. This is intended to reduce the amount of information
7398 // sent to applications by particularly noisy joysticks (such as PS3).
Prabir Pradhan2b281812019-08-29 14:12:42 -07007399 if (fabs(newValue - currentValue) > filter ||
7400 hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min) ||
7401 hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max) ||
7402 hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007403 return true;
7404 }
7405 }
7406 return false;
7407}
7408
Prabir Pradhan2b281812019-08-29 14:12:42 -07007409bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(float filter, float newValue,
7410 float currentValue,
7411 float thresholdValue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007412 float newDistance = fabs(newValue - thresholdValue);
7413 if (newDistance < filter) {
7414 float oldDistance = fabs(currentValue - thresholdValue);
7415 if (newDistance < oldDistance) {
7416 return true;
7417 }
7418 }
7419 return false;
7420}
7421
7422} // namespace android