blob: e85e6efe5dd6ac889905857644188072a4ea6ba4 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
25#define DEBUG_HACKS 0
26
27// Log debug messages about virtual key processing.
28#define DEBUG_VIRTUAL_KEYS 0
29
30// Log debug messages about pointers.
31#define DEBUG_POINTERS 0
32
33// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
36// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
39// Log debug messages about the vibrator.
40#define DEBUG_VIBRATOR 0
41
Michael Wright842500e2015-03-13 17:32:02 -070042// Log debug messages about fusing stylus data.
43#define DEBUG_STYLUS_FUSION 0
44
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include "InputReader.h"
46
Mark Salyzyna5e161b2016-09-29 08:08:05 -070047#include <errno.h>
Michael Wright842500e2015-03-13 17:32:02 -070048#include <inttypes.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070049#include <limits.h>
50#include <math.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <stddef.h>
52#include <stdlib.h>
53#include <unistd.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054
Mark Salyzyn7823e122016-09-29 08:08:05 -070055#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <input/Keyboard.h>
59#include <input/VirtualKeyMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61#define INDENT " "
62#define INDENT2 " "
63#define INDENT3 " "
64#define INDENT4 " "
65#define INDENT5 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// --- Constants ---
72
73// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
74static const size_t MAX_SLOTS = 32;
75
Michael Wright842500e2015-03-13 17:32:02 -070076// Maximum amount of latency to add to touch events while waiting for data from an
77// external stylus.
Michael Wright5e17a5d2015-04-21 22:45:13 +010078static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070079
Michael Wright43fd19f2015-04-21 19:02:58 +010080// Maximum amount of time to wait on touch data before pushing out new pressure data.
81static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
82
83// Artificial latency on synthetic events created from stylus data without corresponding touch
84// data.
85static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087// --- Static Functions ---
88
89template<typename T>
90inline static T abs(const T& value) {
91 return value < 0 ? - value : value;
92}
93
94template<typename T>
95inline static T min(const T& a, const T& b) {
96 return a < b ? a : b;
97}
98
99template<typename T>
100inline static void swap(T& a, T& b) {
101 T temp = a;
102 a = b;
103 b = temp;
104}
105
106inline static float avg(float x, float y) {
107 return (x + y) / 2;
108}
109
110inline static float distance(float x1, float y1, float x2, float y2) {
111 return hypotf(x1 - x2, y1 - y2);
112}
113
114inline static int32_t signExtendNybble(int32_t value) {
115 return value >= 8 ? value - 16 : value;
116}
117
118static inline const char* toString(bool value) {
119 return value ? "true" : "false";
120}
121
122static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
123 const int32_t map[][4], size_t mapSize) {
124 if (orientation != DISPLAY_ORIENTATION_0) {
125 for (size_t i = 0; i < mapSize; i++) {
126 if (value == map[i][0]) {
127 return map[i][orientation];
128 }
129 }
130 }
131 return value;
132}
133
134static const int32_t keyCodeRotationMap[][4] = {
135 // key codes enumerated counter-clockwise with the original (unrotated) key first
136 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
137 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
138 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
139 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
140 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700141 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
142 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
143 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
144 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
145 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
146 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
147 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
148 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149};
150static const size_t keyCodeRotationMapSize =
151 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
152
Ivan Podogovb9afef32017-02-13 15:34:32 +0000153static int32_t rotateStemKey(int32_t value, int32_t orientation,
154 const int32_t map[][2], size_t mapSize) {
155 if (orientation == DISPLAY_ORIENTATION_180) {
156 for (size_t i = 0; i < mapSize; i++) {
157 if (value == map[i][0]) {
158 return map[i][1];
159 }
160 }
161 }
162 return value;
163}
164
165// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
166static int32_t stemKeyRotationMap[][2] = {
167 // key codes enumerated with the original (unrotated) key first
168 // no rotation, 180 degree rotation
169 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
170 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
171 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
172 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
173};
174static const size_t stemKeyRotationMapSize =
175 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
176
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000178 keyCode = rotateStemKey(keyCode, orientation,
179 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return rotateValueUsingRotationMap(keyCode, orientation,
181 keyCodeRotationMap, keyCodeRotationMapSize);
182}
183
184static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
185 float temp;
186 switch (orientation) {
187 case DISPLAY_ORIENTATION_90:
188 temp = *deltaX;
189 *deltaX = *deltaY;
190 *deltaY = -temp;
191 break;
192
193 case DISPLAY_ORIENTATION_180:
194 *deltaX = -*deltaX;
195 *deltaY = -*deltaY;
196 break;
197
198 case DISPLAY_ORIENTATION_270:
199 temp = *deltaX;
200 *deltaX = -*deltaY;
201 *deltaY = temp;
202 break;
203 }
204}
205
206static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
207 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
208}
209
210// Returns true if the pointer should be reported as being down given the specified
211// button states. This determines whether the event is reported as a touch event.
212static bool isPointerDown(int32_t buttonState) {
213 return buttonState &
214 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
215 | AMOTION_EVENT_BUTTON_TERTIARY);
216}
217
218static float calculateCommonVector(float a, float b) {
219 if (a > 0 && b > 0) {
220 return a < b ? a : b;
221 } else if (a < 0 && b < 0) {
222 return a > b ? a : b;
223 } else {
224 return 0;
225 }
226}
227
228static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100229 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
231 int32_t buttonState, int32_t keyCode) {
232 if (
233 (action == AKEY_EVENT_ACTION_DOWN
234 && !(lastButtonState & buttonState)
235 && (currentButtonState & buttonState))
236 || (action == AKEY_EVENT_ACTION_UP
237 && (lastButtonState & buttonState)
238 && !(currentButtonState & buttonState))) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100239 NotifyKeyArgs args(when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
241 context->getListener()->notifyKey(&args);
242 }
243}
244
245static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100246 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100248 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 lastButtonState, currentButtonState,
250 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100251 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 lastButtonState, currentButtonState,
253 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
254}
255
256
257// --- InputReaderConfiguration ---
258
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -0700259std::optional<DisplayViewport> InputReaderConfiguration::getDisplayViewport(
260 ViewportType viewportType, const std::string& uniqueDisplayId) const {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +0100261 for (const DisplayViewport& currentViewport : mDisplays) {
Siarhei Vishniakou2d0867f2018-08-08 17:57:57 -0700262 if (currentViewport.type == viewportType) {
263 if (uniqueDisplayId.empty() ||
264 (!uniqueDisplayId.empty() && uniqueDisplayId == currentViewport.uniqueId)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -0700265 return std::make_optional(currentViewport);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700266 }
267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 }
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -0700269 return std::nullopt;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800270}
271
Siarhei Vishniakoud6343922018-07-06 23:33:37 +0100272void InputReaderConfiguration::setDisplayViewports(const std::vector<DisplayViewport>& viewports) {
273 mDisplays = viewports;
Santos Cordonfa5cf462017-04-05 10:37:00 -0700274}
275
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800276void InputReaderConfiguration::dump(std::string& dump) const {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +0100277 for (const DisplayViewport& viewport : mDisplays) {
Santos Cordonfa5cf462017-04-05 10:37:00 -0700278 dumpViewport(dump, viewport);
279 }
280}
281
Siarhei Vishniakoud6343922018-07-06 23:33:37 +0100282void InputReaderConfiguration::dumpViewport(std::string& dump, const DisplayViewport& viewport)
283 const {
284 dump += StringPrintf(INDENT4 "%s\n", viewport.toString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285}
286
287
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700288// -- TouchAffineTransformation --
289void TouchAffineTransformation::applyTo(float& x, float& y) const {
290 float newX, newY;
291 newX = x * x_scale + y * x_ymix + x_offset;
292 newY = x * y_xmix + y * y_scale + y_offset;
293
294 x = newX;
295 y = newY;
296}
297
298
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299// --- InputReader ---
300
301InputReader::InputReader(const sp<EventHubInterface>& eventHub,
302 const sp<InputReaderPolicyInterface>& policy,
303 const sp<InputListenerInterface>& listener) :
304 mContext(this), mEventHub(eventHub), mPolicy(policy),
305 mGlobalMetaState(0), mGeneration(1),
306 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
307 mConfigurationChangesToRefresh(0) {
308 mQueuedListener = new QueuedInputListener(listener);
309
310 { // acquire lock
311 AutoMutex _l(mLock);
312
313 refreshConfigurationLocked(0);
314 updateGlobalMetaStateLocked();
315 } // release lock
316}
317
318InputReader::~InputReader() {
319 for (size_t i = 0; i < mDevices.size(); i++) {
320 delete mDevices.valueAt(i);
321 }
322}
323
324void InputReader::loopOnce() {
325 int32_t oldGeneration;
326 int32_t timeoutMillis;
327 bool inputDevicesChanged = false;
328 Vector<InputDeviceInfo> inputDevices;
329 { // acquire lock
330 AutoMutex _l(mLock);
331
332 oldGeneration = mGeneration;
333 timeoutMillis = -1;
334
335 uint32_t changes = mConfigurationChangesToRefresh;
336 if (changes) {
337 mConfigurationChangesToRefresh = 0;
338 timeoutMillis = 0;
339 refreshConfigurationLocked(changes);
340 } else if (mNextTimeout != LLONG_MAX) {
341 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
342 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
343 }
344 } // release lock
345
346 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
347
348 { // acquire lock
349 AutoMutex _l(mLock);
350 mReaderIsAliveCondition.broadcast();
351
352 if (count) {
353 processEventsLocked(mEventBuffer, count);
354 }
355
356 if (mNextTimeout != LLONG_MAX) {
357 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
358 if (now >= mNextTimeout) {
359#if DEBUG_RAW_EVENTS
360 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
361#endif
362 mNextTimeout = LLONG_MAX;
363 timeoutExpiredLocked(now);
364 }
365 }
366
367 if (oldGeneration != mGeneration) {
368 inputDevicesChanged = true;
369 getInputDevicesLocked(inputDevices);
370 }
371 } // release lock
372
373 // Send out a message that the describes the changed input devices.
374 if (inputDevicesChanged) {
375 mPolicy->notifyInputDevicesChanged(inputDevices);
376 }
377
378 // Flush queued events out to the listener.
379 // This must happen outside of the lock because the listener could potentially call
380 // back into the InputReader's methods, such as getScanCodeState, or become blocked
381 // on another thread similarly waiting to acquire the InputReader lock thereby
382 // resulting in a deadlock. This situation is actually quite plausible because the
383 // listener is actually the input dispatcher, which calls into the window manager,
384 // which occasionally calls into the input reader.
385 mQueuedListener->flush();
386}
387
388void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
389 for (const RawEvent* rawEvent = rawEvents; count;) {
390 int32_t type = rawEvent->type;
391 size_t batchSize = 1;
392 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
393 int32_t deviceId = rawEvent->deviceId;
394 while (batchSize < count) {
395 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
396 || rawEvent[batchSize].deviceId != deviceId) {
397 break;
398 }
399 batchSize += 1;
400 }
401#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700402 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403#endif
404 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
405 } else {
406 switch (rawEvent->type) {
407 case EventHubInterface::DEVICE_ADDED:
408 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
409 break;
410 case EventHubInterface::DEVICE_REMOVED:
411 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
412 break;
413 case EventHubInterface::FINISHED_DEVICE_SCAN:
414 handleConfigurationChangedLocked(rawEvent->when);
415 break;
416 default:
417 ALOG_ASSERT(false); // can't happen
418 break;
419 }
420 }
421 count -= batchSize;
422 rawEvent += batchSize;
423 }
424}
425
426void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
427 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
428 if (deviceIndex >= 0) {
429 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
430 return;
431 }
432
433 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
434 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
435 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
436
437 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
438 device->configure(when, &mConfig, 0);
439 device->reset(when);
440
441 if (device->isIgnored()) {
442 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100443 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 } else {
445 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100446 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447 }
448
449 mDevices.add(deviceId, device);
450 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700451
452 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
453 notifyExternalStylusPresenceChanged();
454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455}
456
457void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700458 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
460 if (deviceIndex < 0) {
461 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
462 return;
463 }
464
465 device = mDevices.valueAt(deviceIndex);
466 mDevices.removeItemsAt(deviceIndex, 1);
467 bumpGenerationLocked();
468
469 if (device->isIgnored()) {
470 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100471 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 } else {
473 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100474 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 }
476
Michael Wright842500e2015-03-13 17:32:02 -0700477 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
478 notifyExternalStylusPresenceChanged();
479 }
480
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481 device->reset(when);
482 delete device;
483}
484
485InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
486 const InputDeviceIdentifier& identifier, uint32_t classes) {
487 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
488 controllerNumber, identifier, classes);
489
490 // External devices.
491 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
492 device->setExternal(true);
493 }
494
Tim Kilbourn063ff532015-04-08 10:26:18 -0700495 // Devices with mics.
496 if (classes & INPUT_DEVICE_CLASS_MIC) {
497 device->setMic(true);
498 }
499
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 // Switch-like devices.
501 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
502 device->addMapper(new SwitchInputMapper(device));
503 }
504
Prashant Malani1941ff52015-08-11 18:29:28 -0700505 // Scroll wheel-like devices.
506 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
507 device->addMapper(new RotaryEncoderInputMapper(device));
508 }
509
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 // Vibrator-like devices.
511 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
512 device->addMapper(new VibratorInputMapper(device));
513 }
514
515 // Keyboard-like devices.
516 uint32_t keyboardSource = 0;
517 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
518 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
519 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
520 }
521 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
522 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
523 }
524 if (classes & INPUT_DEVICE_CLASS_DPAD) {
525 keyboardSource |= AINPUT_SOURCE_DPAD;
526 }
527 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
528 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
529 }
530
531 if (keyboardSource != 0) {
532 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
533 }
534
535 // Cursor-like devices.
536 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
537 device->addMapper(new CursorInputMapper(device));
538 }
539
540 // Touchscreens and touchpad devices.
541 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
542 device->addMapper(new MultiTouchInputMapper(device));
543 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
544 device->addMapper(new SingleTouchInputMapper(device));
545 }
546
547 // Joystick-like devices.
548 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
549 device->addMapper(new JoystickInputMapper(device));
550 }
551
Michael Wright842500e2015-03-13 17:32:02 -0700552 // External stylus-like devices.
553 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
554 device->addMapper(new ExternalStylusInputMapper(device));
555 }
556
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 return device;
558}
559
560void InputReader::processEventsForDeviceLocked(int32_t deviceId,
561 const RawEvent* rawEvents, size_t count) {
562 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
563 if (deviceIndex < 0) {
564 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
565 return;
566 }
567
568 InputDevice* device = mDevices.valueAt(deviceIndex);
569 if (device->isIgnored()) {
570 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
571 return;
572 }
573
574 device->process(rawEvents, count);
575}
576
577void InputReader::timeoutExpiredLocked(nsecs_t when) {
578 for (size_t i = 0; i < mDevices.size(); i++) {
579 InputDevice* device = mDevices.valueAt(i);
580 if (!device->isIgnored()) {
581 device->timeoutExpired(when);
582 }
583 }
584}
585
586void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
587 // Reset global meta state because it depends on the list of all configured devices.
588 updateGlobalMetaStateLocked();
589
590 // Enqueue configuration changed.
591 NotifyConfigurationChangedArgs args(when);
592 mQueuedListener->notifyConfigurationChanged(&args);
593}
594
595void InputReader::refreshConfigurationLocked(uint32_t changes) {
596 mPolicy->getReaderConfiguration(&mConfig);
597 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
598
599 if (changes) {
600 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
601 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
602
603 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
604 mEventHub->requestReopenDevices();
605 } else {
606 for (size_t i = 0; i < mDevices.size(); i++) {
607 InputDevice* device = mDevices.valueAt(i);
608 device->configure(now, &mConfig, changes);
609 }
610 }
611 }
612}
613
614void InputReader::updateGlobalMetaStateLocked() {
615 mGlobalMetaState = 0;
616
617 for (size_t i = 0; i < mDevices.size(); i++) {
618 InputDevice* device = mDevices.valueAt(i);
619 mGlobalMetaState |= device->getMetaState();
620 }
621}
622
623int32_t InputReader::getGlobalMetaStateLocked() {
624 return mGlobalMetaState;
625}
626
Michael Wright842500e2015-03-13 17:32:02 -0700627void InputReader::notifyExternalStylusPresenceChanged() {
628 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
629}
630
631void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
632 for (size_t i = 0; i < mDevices.size(); i++) {
633 InputDevice* device = mDevices.valueAt(i);
634 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
635 outDevices.push();
636 device->getDeviceInfo(&outDevices.editTop());
637 }
638 }
639}
640
641void InputReader::dispatchExternalStylusState(const StylusState& state) {
642 for (size_t i = 0; i < mDevices.size(); i++) {
643 InputDevice* device = mDevices.valueAt(i);
644 device->updateExternalStylusState(state);
645 }
646}
647
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
649 mDisableVirtualKeysTimeout = time;
650}
651
652bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
653 InputDevice* device, int32_t keyCode, int32_t scanCode) {
654 if (now < mDisableVirtualKeysTimeout) {
655 ALOGI("Dropping virtual key from device %s because virtual keys are "
656 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100657 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 (mDisableVirtualKeysTimeout - now) * 0.000001,
659 keyCode, scanCode);
660 return true;
661 } else {
662 return false;
663 }
664}
665
666void InputReader::fadePointerLocked() {
667 for (size_t i = 0; i < mDevices.size(); i++) {
668 InputDevice* device = mDevices.valueAt(i);
669 device->fadePointer();
670 }
671}
672
673void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
674 if (when < mNextTimeout) {
675 mNextTimeout = when;
676 mEventHub->wake();
677 }
678}
679
680int32_t InputReader::bumpGenerationLocked() {
681 return ++mGeneration;
682}
683
684void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
685 AutoMutex _l(mLock);
686 getInputDevicesLocked(outInputDevices);
687}
688
689void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
690 outInputDevices.clear();
691
692 size_t numDevices = mDevices.size();
693 for (size_t i = 0; i < numDevices; i++) {
694 InputDevice* device = mDevices.valueAt(i);
695 if (!device->isIgnored()) {
696 outInputDevices.push();
697 device->getDeviceInfo(&outInputDevices.editTop());
698 }
699 }
700}
701
702int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
703 int32_t keyCode) {
704 AutoMutex _l(mLock);
705
706 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
707}
708
709int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
710 int32_t scanCode) {
711 AutoMutex _l(mLock);
712
713 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
714}
715
716int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
717 AutoMutex _l(mLock);
718
719 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
720}
721
722int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
723 GetStateFunc getStateFunc) {
724 int32_t result = AKEY_STATE_UNKNOWN;
725 if (deviceId >= 0) {
726 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
727 if (deviceIndex >= 0) {
728 InputDevice* device = mDevices.valueAt(deviceIndex);
729 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
730 result = (device->*getStateFunc)(sourceMask, code);
731 }
732 }
733 } else {
734 size_t numDevices = mDevices.size();
735 for (size_t i = 0; i < numDevices; i++) {
736 InputDevice* device = mDevices.valueAt(i);
737 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
738 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
739 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
740 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
741 if (currentResult >= AKEY_STATE_DOWN) {
742 return currentResult;
743 } else if (currentResult == AKEY_STATE_UP) {
744 result = currentResult;
745 }
746 }
747 }
748 }
749 return result;
750}
751
Andrii Kulian763a3a42016-03-08 10:46:16 -0800752void InputReader::toggleCapsLockState(int32_t deviceId) {
753 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
754 if (deviceIndex < 0) {
755 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
756 return;
757 }
758
759 InputDevice* device = mDevices.valueAt(deviceIndex);
760 if (device->isIgnored()) {
761 return;
762 }
763
764 device->updateMetaState(AKEYCODE_CAPS_LOCK);
765}
766
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
768 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
769 AutoMutex _l(mLock);
770
771 memset(outFlags, 0, numCodes);
772 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
773}
774
775bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
776 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
777 bool result = false;
778 if (deviceId >= 0) {
779 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
780 if (deviceIndex >= 0) {
781 InputDevice* device = mDevices.valueAt(deviceIndex);
782 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
783 result = device->markSupportedKeyCodes(sourceMask,
784 numCodes, keyCodes, outFlags);
785 }
786 }
787 } else {
788 size_t numDevices = mDevices.size();
789 for (size_t i = 0; i < numDevices; i++) {
790 InputDevice* device = mDevices.valueAt(i);
791 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
792 result |= device->markSupportedKeyCodes(sourceMask,
793 numCodes, keyCodes, outFlags);
794 }
795 }
796 }
797 return result;
798}
799
800void InputReader::requestRefreshConfiguration(uint32_t changes) {
801 AutoMutex _l(mLock);
802
803 if (changes) {
804 bool needWake = !mConfigurationChangesToRefresh;
805 mConfigurationChangesToRefresh |= changes;
806
807 if (needWake) {
808 mEventHub->wake();
809 }
810 }
811}
812
813void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
814 ssize_t repeat, int32_t token) {
815 AutoMutex _l(mLock);
816
817 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
818 if (deviceIndex >= 0) {
819 InputDevice* device = mDevices.valueAt(deviceIndex);
820 device->vibrate(pattern, patternSize, repeat, token);
821 }
822}
823
824void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
825 AutoMutex _l(mLock);
826
827 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
828 if (deviceIndex >= 0) {
829 InputDevice* device = mDevices.valueAt(deviceIndex);
830 device->cancelVibrate(token);
831 }
832}
833
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700834bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
835 AutoMutex _l(mLock);
836
837 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
838 if (deviceIndex >= 0) {
839 InputDevice* device = mDevices.valueAt(deviceIndex);
840 return device->isEnabled();
841 }
842 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
843 return false;
844}
845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 AutoMutex _l(mLock);
848
849 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800850 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800852 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853
854 for (size_t i = 0; i < mDevices.size(); i++) {
855 mDevices.valueAt(i)->dump(dump);
856 }
857
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800858 dump += INDENT "Configuration:\n";
859 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
861 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800862 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100864 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800866 dump += "]\n";
867 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 mConfig.virtualKeyQuietTime * 0.000001f);
869
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800870 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
872 mConfig.pointerVelocityControlParameters.scale,
873 mConfig.pointerVelocityControlParameters.lowThreshold,
874 mConfig.pointerVelocityControlParameters.highThreshold,
875 mConfig.pointerVelocityControlParameters.acceleration);
876
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800877 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
879 mConfig.wheelVelocityControlParameters.scale,
880 mConfig.wheelVelocityControlParameters.lowThreshold,
881 mConfig.wheelVelocityControlParameters.highThreshold,
882 mConfig.wheelVelocityControlParameters.acceleration);
883
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800884 dump += StringPrintf(INDENT2 "PointerGesture:\n");
885 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800887 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800889 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800893 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800895 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800897 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800899 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800901 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800903 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800905 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800907 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700909
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800910 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700911 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912}
913
914void InputReader::monitor() {
915 // Acquire and release the lock to ensure that the reader has not deadlocked.
916 mLock.lock();
917 mEventHub->wake();
918 mReaderIsAliveCondition.wait(mLock);
919 mLock.unlock();
920
921 // Check the EventHub
922 mEventHub->monitor();
923}
924
925
926// --- InputReader::ContextImpl ---
927
928InputReader::ContextImpl::ContextImpl(InputReader* reader) :
929 mReader(reader) {
930}
931
932void InputReader::ContextImpl::updateGlobalMetaState() {
933 // lock is already held by the input loop
934 mReader->updateGlobalMetaStateLocked();
935}
936
937int32_t InputReader::ContextImpl::getGlobalMetaState() {
938 // lock is already held by the input loop
939 return mReader->getGlobalMetaStateLocked();
940}
941
942void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
943 // lock is already held by the input loop
944 mReader->disableVirtualKeysUntilLocked(time);
945}
946
947bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
948 InputDevice* device, int32_t keyCode, int32_t scanCode) {
949 // lock is already held by the input loop
950 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
951}
952
953void InputReader::ContextImpl::fadePointer() {
954 // lock is already held by the input loop
955 mReader->fadePointerLocked();
956}
957
958void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
959 // lock is already held by the input loop
960 mReader->requestTimeoutAtTimeLocked(when);
961}
962
963int32_t InputReader::ContextImpl::bumpGeneration() {
964 // lock is already held by the input loop
965 return mReader->bumpGenerationLocked();
966}
967
Michael Wright842500e2015-03-13 17:32:02 -0700968void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
969 // lock is already held by whatever called refreshConfigurationLocked
970 mReader->getExternalStylusDevicesLocked(outDevices);
971}
972
973void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
974 mReader->dispatchExternalStylusState(state);
975}
976
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
978 return mReader->mPolicy.get();
979}
980
981InputListenerInterface* InputReader::ContextImpl::getListener() {
982 return mReader->mQueuedListener.get();
983}
984
985EventHubInterface* InputReader::ContextImpl::getEventHub() {
986 return mReader->mEventHub.get();
987}
988
989
990// --- InputReaderThread ---
991
992InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
993 Thread(/*canCallJava*/ true), mReader(reader) {
994}
995
996InputReaderThread::~InputReaderThread() {
997}
998
999bool InputReaderThread::threadLoop() {
1000 mReader->loopOnce();
1001 return true;
1002}
1003
1004
1005// --- InputDevice ---
1006
1007InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
1008 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
1009 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
1010 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -07001011 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012}
1013
1014InputDevice::~InputDevice() {
1015 size_t numMappers = mMappers.size();
1016 for (size_t i = 0; i < numMappers; i++) {
1017 delete mMappers[i];
1018 }
1019 mMappers.clear();
1020}
1021
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001022bool InputDevice::isEnabled() {
1023 return getEventHub()->isDeviceEnabled(mId);
1024}
1025
1026void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1027 if (isEnabled() == enabled) {
1028 return;
1029 }
1030
1031 if (enabled) {
1032 getEventHub()->enableDevice(mId);
1033 reset(when);
1034 } else {
1035 reset(when);
1036 getEventHub()->disableDevice(mId);
1037 }
1038 // Must change generation to flag this device as changed
1039 bumpGeneration();
1040}
1041
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001042void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001044 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001046 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001047 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001048 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1049 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
1050 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1051 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1052 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053
1054 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1055 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001056 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 for (size_t i = 0; i < ranges.size(); i++) {
1058 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1059 const char* label = getAxisLabel(range.axis);
1060 char name[32];
1061 if (label) {
1062 strncpy(name, label, sizeof(name));
1063 name[sizeof(name) - 1] = '\0';
1064 } else {
1065 snprintf(name, sizeof(name), "%d", range.axis);
1066 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001067 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1069 name, range.source, range.min, range.max, range.flat, range.fuzz,
1070 range.resolution);
1071 }
1072 }
1073
1074 size_t numMappers = mMappers.size();
1075 for (size_t i = 0; i < numMappers; i++) {
1076 InputMapper* mapper = mMappers[i];
1077 mapper->dump(dump);
1078 }
1079}
1080
1081void InputDevice::addMapper(InputMapper* mapper) {
1082 mMappers.add(mapper);
1083}
1084
1085void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1086 mSources = 0;
1087
1088 if (!isIgnored()) {
1089 if (!changes) { // first time only
1090 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1091 }
1092
1093 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1094 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1095 sp<KeyCharacterMap> keyboardLayout =
1096 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1097 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1098 bumpGeneration();
1099 }
1100 }
1101 }
1102
1103 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1104 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001105 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 if (mAlias != alias) {
1107 mAlias = alias;
1108 bumpGeneration();
1109 }
1110 }
1111 }
1112
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001113 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1114 ssize_t index = config->disabledDevices.indexOf(mId);
1115 bool enabled = index < 0;
1116 setEnabled(enabled, when);
1117 }
1118
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 size_t numMappers = mMappers.size();
1120 for (size_t i = 0; i < numMappers; i++) {
1121 InputMapper* mapper = mMappers[i];
1122 mapper->configure(when, config, changes);
1123 mSources |= mapper->getSources();
1124 }
1125 }
1126}
1127
1128void InputDevice::reset(nsecs_t when) {
1129 size_t numMappers = mMappers.size();
1130 for (size_t i = 0; i < numMappers; i++) {
1131 InputMapper* mapper = mMappers[i];
1132 mapper->reset(when);
1133 }
1134
1135 mContext->updateGlobalMetaState();
1136
1137 notifyReset(when);
1138}
1139
1140void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1141 // Process all of the events in order for each mapper.
1142 // We cannot simply ask each mapper to process them in bulk because mappers may
1143 // have side-effects that must be interleaved. For example, joystick movement events and
1144 // gamepad button presses are handled by different mappers but they should be dispatched
1145 // in the order received.
1146 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001147 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001149 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1151 rawEvent->when);
1152#endif
1153
1154 if (mDropUntilNextSync) {
1155 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1156 mDropUntilNextSync = false;
1157#if DEBUG_RAW_EVENTS
1158 ALOGD("Recovered from input event buffer overrun.");
1159#endif
1160 } else {
1161#if DEBUG_RAW_EVENTS
1162 ALOGD("Dropped input event while waiting for next input sync.");
1163#endif
1164 }
1165 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001166 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 mDropUntilNextSync = true;
1168 reset(rawEvent->when);
1169 } else {
1170 for (size_t i = 0; i < numMappers; i++) {
1171 InputMapper* mapper = mMappers[i];
1172 mapper->process(rawEvent);
1173 }
1174 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001175 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 }
1177}
1178
1179void InputDevice::timeoutExpired(nsecs_t when) {
1180 size_t numMappers = mMappers.size();
1181 for (size_t i = 0; i < numMappers; i++) {
1182 InputMapper* mapper = mMappers[i];
1183 mapper->timeoutExpired(when);
1184 }
1185}
1186
Michael Wright842500e2015-03-13 17:32:02 -07001187void InputDevice::updateExternalStylusState(const StylusState& state) {
1188 size_t numMappers = mMappers.size();
1189 for (size_t i = 0; i < numMappers; i++) {
1190 InputMapper* mapper = mMappers[i];
1191 mapper->updateExternalStylusState(state);
1192 }
1193}
1194
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1196 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001197 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 size_t numMappers = mMappers.size();
1199 for (size_t i = 0; i < numMappers; i++) {
1200 InputMapper* mapper = mMappers[i];
1201 mapper->populateDeviceInfo(outDeviceInfo);
1202 }
1203}
1204
1205int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1206 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1207}
1208
1209int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1210 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1211}
1212
1213int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1214 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1215}
1216
1217int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1218 int32_t result = AKEY_STATE_UNKNOWN;
1219 size_t numMappers = mMappers.size();
1220 for (size_t i = 0; i < numMappers; i++) {
1221 InputMapper* mapper = mMappers[i];
1222 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1223 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1224 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1225 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1226 if (currentResult >= AKEY_STATE_DOWN) {
1227 return currentResult;
1228 } else if (currentResult == AKEY_STATE_UP) {
1229 result = currentResult;
1230 }
1231 }
1232 }
1233 return result;
1234}
1235
1236bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1237 const int32_t* keyCodes, uint8_t* outFlags) {
1238 bool result = false;
1239 size_t numMappers = mMappers.size();
1240 for (size_t i = 0; i < numMappers; i++) {
1241 InputMapper* mapper = mMappers[i];
1242 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1243 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1244 }
1245 }
1246 return result;
1247}
1248
1249void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1250 int32_t token) {
1251 size_t numMappers = mMappers.size();
1252 for (size_t i = 0; i < numMappers; i++) {
1253 InputMapper* mapper = mMappers[i];
1254 mapper->vibrate(pattern, patternSize, repeat, token);
1255 }
1256}
1257
1258void InputDevice::cancelVibrate(int32_t token) {
1259 size_t numMappers = mMappers.size();
1260 for (size_t i = 0; i < numMappers; i++) {
1261 InputMapper* mapper = mMappers[i];
1262 mapper->cancelVibrate(token);
1263 }
1264}
1265
Jeff Brownc9aa6282015-02-11 19:03:28 -08001266void InputDevice::cancelTouch(nsecs_t when) {
1267 size_t numMappers = mMappers.size();
1268 for (size_t i = 0; i < numMappers; i++) {
1269 InputMapper* mapper = mMappers[i];
1270 mapper->cancelTouch(when);
1271 }
1272}
1273
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274int32_t InputDevice::getMetaState() {
1275 int32_t result = 0;
1276 size_t numMappers = mMappers.size();
1277 for (size_t i = 0; i < numMappers; i++) {
1278 InputMapper* mapper = mMappers[i];
1279 result |= mapper->getMetaState();
1280 }
1281 return result;
1282}
1283
Andrii Kulian763a3a42016-03-08 10:46:16 -08001284void InputDevice::updateMetaState(int32_t keyCode) {
1285 size_t numMappers = mMappers.size();
1286 for (size_t i = 0; i < numMappers; i++) {
1287 mMappers[i]->updateMetaState(keyCode);
1288 }
1289}
1290
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291void InputDevice::fadePointer() {
1292 size_t numMappers = mMappers.size();
1293 for (size_t i = 0; i < numMappers; i++) {
1294 InputMapper* mapper = mMappers[i];
1295 mapper->fadePointer();
1296 }
1297}
1298
1299void InputDevice::bumpGeneration() {
1300 mGeneration = mContext->bumpGeneration();
1301}
1302
1303void InputDevice::notifyReset(nsecs_t when) {
1304 NotifyDeviceResetArgs args(when, mId);
1305 mContext->getListener()->notifyDeviceReset(&args);
1306}
1307
1308
1309// --- CursorButtonAccumulator ---
1310
1311CursorButtonAccumulator::CursorButtonAccumulator() {
1312 clearButtons();
1313}
1314
1315void CursorButtonAccumulator::reset(InputDevice* device) {
1316 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1317 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1318 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1319 mBtnBack = device->isKeyPressed(BTN_BACK);
1320 mBtnSide = device->isKeyPressed(BTN_SIDE);
1321 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1322 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1323 mBtnTask = device->isKeyPressed(BTN_TASK);
1324}
1325
1326void CursorButtonAccumulator::clearButtons() {
1327 mBtnLeft = 0;
1328 mBtnRight = 0;
1329 mBtnMiddle = 0;
1330 mBtnBack = 0;
1331 mBtnSide = 0;
1332 mBtnForward = 0;
1333 mBtnExtra = 0;
1334 mBtnTask = 0;
1335}
1336
1337void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1338 if (rawEvent->type == EV_KEY) {
1339 switch (rawEvent->code) {
1340 case BTN_LEFT:
1341 mBtnLeft = rawEvent->value;
1342 break;
1343 case BTN_RIGHT:
1344 mBtnRight = rawEvent->value;
1345 break;
1346 case BTN_MIDDLE:
1347 mBtnMiddle = rawEvent->value;
1348 break;
1349 case BTN_BACK:
1350 mBtnBack = rawEvent->value;
1351 break;
1352 case BTN_SIDE:
1353 mBtnSide = rawEvent->value;
1354 break;
1355 case BTN_FORWARD:
1356 mBtnForward = rawEvent->value;
1357 break;
1358 case BTN_EXTRA:
1359 mBtnExtra = rawEvent->value;
1360 break;
1361 case BTN_TASK:
1362 mBtnTask = rawEvent->value;
1363 break;
1364 }
1365 }
1366}
1367
1368uint32_t CursorButtonAccumulator::getButtonState() const {
1369 uint32_t result = 0;
1370 if (mBtnLeft) {
1371 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1372 }
1373 if (mBtnRight) {
1374 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1375 }
1376 if (mBtnMiddle) {
1377 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1378 }
1379 if (mBtnBack || mBtnSide) {
1380 result |= AMOTION_EVENT_BUTTON_BACK;
1381 }
1382 if (mBtnForward || mBtnExtra) {
1383 result |= AMOTION_EVENT_BUTTON_FORWARD;
1384 }
1385 return result;
1386}
1387
1388
1389// --- CursorMotionAccumulator ---
1390
1391CursorMotionAccumulator::CursorMotionAccumulator() {
1392 clearRelativeAxes();
1393}
1394
1395void CursorMotionAccumulator::reset(InputDevice* device) {
1396 clearRelativeAxes();
1397}
1398
1399void CursorMotionAccumulator::clearRelativeAxes() {
1400 mRelX = 0;
1401 mRelY = 0;
1402}
1403
1404void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1405 if (rawEvent->type == EV_REL) {
1406 switch (rawEvent->code) {
1407 case REL_X:
1408 mRelX = rawEvent->value;
1409 break;
1410 case REL_Y:
1411 mRelY = rawEvent->value;
1412 break;
1413 }
1414 }
1415}
1416
1417void CursorMotionAccumulator::finishSync() {
1418 clearRelativeAxes();
1419}
1420
1421
1422// --- CursorScrollAccumulator ---
1423
1424CursorScrollAccumulator::CursorScrollAccumulator() :
1425 mHaveRelWheel(false), mHaveRelHWheel(false) {
1426 clearRelativeAxes();
1427}
1428
1429void CursorScrollAccumulator::configure(InputDevice* device) {
1430 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1431 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1432}
1433
1434void CursorScrollAccumulator::reset(InputDevice* device) {
1435 clearRelativeAxes();
1436}
1437
1438void CursorScrollAccumulator::clearRelativeAxes() {
1439 mRelWheel = 0;
1440 mRelHWheel = 0;
1441}
1442
1443void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1444 if (rawEvent->type == EV_REL) {
1445 switch (rawEvent->code) {
1446 case REL_WHEEL:
1447 mRelWheel = rawEvent->value;
1448 break;
1449 case REL_HWHEEL:
1450 mRelHWheel = rawEvent->value;
1451 break;
1452 }
1453 }
1454}
1455
1456void CursorScrollAccumulator::finishSync() {
1457 clearRelativeAxes();
1458}
1459
1460
1461// --- TouchButtonAccumulator ---
1462
1463TouchButtonAccumulator::TouchButtonAccumulator() :
1464 mHaveBtnTouch(false), mHaveStylus(false) {
1465 clearButtons();
1466}
1467
1468void TouchButtonAccumulator::configure(InputDevice* device) {
1469 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1470 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1471 || device->hasKey(BTN_TOOL_RUBBER)
1472 || device->hasKey(BTN_TOOL_BRUSH)
1473 || device->hasKey(BTN_TOOL_PENCIL)
1474 || device->hasKey(BTN_TOOL_AIRBRUSH);
1475}
1476
1477void TouchButtonAccumulator::reset(InputDevice* device) {
1478 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1479 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001480 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1481 mBtnStylus2 =
1482 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1484 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1485 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1486 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1487 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1488 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1489 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1490 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1491 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1492 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1493 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1494}
1495
1496void TouchButtonAccumulator::clearButtons() {
1497 mBtnTouch = 0;
1498 mBtnStylus = 0;
1499 mBtnStylus2 = 0;
1500 mBtnToolFinger = 0;
1501 mBtnToolPen = 0;
1502 mBtnToolRubber = 0;
1503 mBtnToolBrush = 0;
1504 mBtnToolPencil = 0;
1505 mBtnToolAirbrush = 0;
1506 mBtnToolMouse = 0;
1507 mBtnToolLens = 0;
1508 mBtnToolDoubleTap = 0;
1509 mBtnToolTripleTap = 0;
1510 mBtnToolQuadTap = 0;
1511}
1512
1513void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1514 if (rawEvent->type == EV_KEY) {
1515 switch (rawEvent->code) {
1516 case BTN_TOUCH:
1517 mBtnTouch = rawEvent->value;
1518 break;
1519 case BTN_STYLUS:
1520 mBtnStylus = rawEvent->value;
1521 break;
1522 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001523 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 mBtnStylus2 = rawEvent->value;
1525 break;
1526 case BTN_TOOL_FINGER:
1527 mBtnToolFinger = rawEvent->value;
1528 break;
1529 case BTN_TOOL_PEN:
1530 mBtnToolPen = rawEvent->value;
1531 break;
1532 case BTN_TOOL_RUBBER:
1533 mBtnToolRubber = rawEvent->value;
1534 break;
1535 case BTN_TOOL_BRUSH:
1536 mBtnToolBrush = rawEvent->value;
1537 break;
1538 case BTN_TOOL_PENCIL:
1539 mBtnToolPencil = rawEvent->value;
1540 break;
1541 case BTN_TOOL_AIRBRUSH:
1542 mBtnToolAirbrush = rawEvent->value;
1543 break;
1544 case BTN_TOOL_MOUSE:
1545 mBtnToolMouse = rawEvent->value;
1546 break;
1547 case BTN_TOOL_LENS:
1548 mBtnToolLens = rawEvent->value;
1549 break;
1550 case BTN_TOOL_DOUBLETAP:
1551 mBtnToolDoubleTap = rawEvent->value;
1552 break;
1553 case BTN_TOOL_TRIPLETAP:
1554 mBtnToolTripleTap = rawEvent->value;
1555 break;
1556 case BTN_TOOL_QUADTAP:
1557 mBtnToolQuadTap = rawEvent->value;
1558 break;
1559 }
1560 }
1561}
1562
1563uint32_t TouchButtonAccumulator::getButtonState() const {
1564 uint32_t result = 0;
1565 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001566 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 }
1568 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001569 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571 return result;
1572}
1573
1574int32_t TouchButtonAccumulator::getToolType() const {
1575 if (mBtnToolMouse || mBtnToolLens) {
1576 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1577 }
1578 if (mBtnToolRubber) {
1579 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1580 }
1581 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1582 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1583 }
1584 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1585 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1586 }
1587 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1588}
1589
1590bool TouchButtonAccumulator::isToolActive() const {
1591 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1592 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1593 || mBtnToolMouse || mBtnToolLens
1594 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1595}
1596
1597bool TouchButtonAccumulator::isHovering() const {
1598 return mHaveBtnTouch && !mBtnTouch;
1599}
1600
1601bool TouchButtonAccumulator::hasStylus() const {
1602 return mHaveStylus;
1603}
1604
1605
1606// --- RawPointerAxes ---
1607
1608RawPointerAxes::RawPointerAxes() {
1609 clear();
1610}
1611
1612void RawPointerAxes::clear() {
1613 x.clear();
1614 y.clear();
1615 pressure.clear();
1616 touchMajor.clear();
1617 touchMinor.clear();
1618 toolMajor.clear();
1619 toolMinor.clear();
1620 orientation.clear();
1621 distance.clear();
1622 tiltX.clear();
1623 tiltY.clear();
1624 trackingId.clear();
1625 slot.clear();
1626}
1627
1628
1629// --- RawPointerData ---
1630
1631RawPointerData::RawPointerData() {
1632 clear();
1633}
1634
1635void RawPointerData::clear() {
1636 pointerCount = 0;
1637 clearIdBits();
1638}
1639
1640void RawPointerData::copyFrom(const RawPointerData& other) {
1641 pointerCount = other.pointerCount;
1642 hoveringIdBits = other.hoveringIdBits;
1643 touchingIdBits = other.touchingIdBits;
1644
1645 for (uint32_t i = 0; i < pointerCount; i++) {
1646 pointers[i] = other.pointers[i];
1647
1648 int id = pointers[i].id;
1649 idToIndex[id] = other.idToIndex[id];
1650 }
1651}
1652
1653void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1654 float x = 0, y = 0;
1655 uint32_t count = touchingIdBits.count();
1656 if (count) {
1657 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1658 uint32_t id = idBits.clearFirstMarkedBit();
1659 const Pointer& pointer = pointerForId(id);
1660 x += pointer.x;
1661 y += pointer.y;
1662 }
1663 x /= count;
1664 y /= count;
1665 }
1666 *outX = x;
1667 *outY = y;
1668}
1669
1670
1671// --- CookedPointerData ---
1672
1673CookedPointerData::CookedPointerData() {
1674 clear();
1675}
1676
1677void CookedPointerData::clear() {
1678 pointerCount = 0;
1679 hoveringIdBits.clear();
1680 touchingIdBits.clear();
1681}
1682
1683void CookedPointerData::copyFrom(const CookedPointerData& other) {
1684 pointerCount = other.pointerCount;
1685 hoveringIdBits = other.hoveringIdBits;
1686 touchingIdBits = other.touchingIdBits;
1687
1688 for (uint32_t i = 0; i < pointerCount; i++) {
1689 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1690 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1691
1692 int id = pointerProperties[i].id;
1693 idToIndex[id] = other.idToIndex[id];
1694 }
1695}
1696
1697
1698// --- SingleTouchMotionAccumulator ---
1699
1700SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1701 clearAbsoluteAxes();
1702}
1703
1704void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1705 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1706 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1707 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1708 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1709 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1710 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1711 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1712}
1713
1714void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1715 mAbsX = 0;
1716 mAbsY = 0;
1717 mAbsPressure = 0;
1718 mAbsToolWidth = 0;
1719 mAbsDistance = 0;
1720 mAbsTiltX = 0;
1721 mAbsTiltY = 0;
1722}
1723
1724void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1725 if (rawEvent->type == EV_ABS) {
1726 switch (rawEvent->code) {
1727 case ABS_X:
1728 mAbsX = rawEvent->value;
1729 break;
1730 case ABS_Y:
1731 mAbsY = rawEvent->value;
1732 break;
1733 case ABS_PRESSURE:
1734 mAbsPressure = rawEvent->value;
1735 break;
1736 case ABS_TOOL_WIDTH:
1737 mAbsToolWidth = rawEvent->value;
1738 break;
1739 case ABS_DISTANCE:
1740 mAbsDistance = rawEvent->value;
1741 break;
1742 case ABS_TILT_X:
1743 mAbsTiltX = rawEvent->value;
1744 break;
1745 case ABS_TILT_Y:
1746 mAbsTiltY = rawEvent->value;
1747 break;
1748 }
1749 }
1750}
1751
1752
1753// --- MultiTouchMotionAccumulator ---
1754
1755MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001756 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001757 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758}
1759
1760MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1761 delete[] mSlots;
1762}
1763
1764void MultiTouchMotionAccumulator::configure(InputDevice* device,
1765 size_t slotCount, bool usingSlotsProtocol) {
1766 mSlotCount = slotCount;
1767 mUsingSlotsProtocol = usingSlotsProtocol;
1768 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1769
1770 delete[] mSlots;
1771 mSlots = new Slot[slotCount];
1772}
1773
1774void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1775 // Unfortunately there is no way to read the initial contents of the slots.
1776 // So when we reset the accumulator, we must assume they are all zeroes.
1777 if (mUsingSlotsProtocol) {
1778 // Query the driver for the current slot index and use it as the initial slot
1779 // before we start reading events from the device. It is possible that the
1780 // current slot index will not be the same as it was when the first event was
1781 // written into the evdev buffer, which means the input mapper could start
1782 // out of sync with the initial state of the events in the evdev buffer.
1783 // In the extremely unlikely case that this happens, the data from
1784 // two slots will be confused until the next ABS_MT_SLOT event is received.
1785 // This can cause the touch point to "jump", but at least there will be
1786 // no stuck touches.
1787 int32_t initialSlot;
1788 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1789 ABS_MT_SLOT, &initialSlot);
1790 if (status) {
1791 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1792 initialSlot = -1;
1793 }
1794 clearSlots(initialSlot);
1795 } else {
1796 clearSlots(-1);
1797 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001798 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799}
1800
1801void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1802 if (mSlots) {
1803 for (size_t i = 0; i < mSlotCount; i++) {
1804 mSlots[i].clear();
1805 }
1806 }
1807 mCurrentSlot = initialSlot;
1808}
1809
1810void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1811 if (rawEvent->type == EV_ABS) {
1812 bool newSlot = false;
1813 if (mUsingSlotsProtocol) {
1814 if (rawEvent->code == ABS_MT_SLOT) {
1815 mCurrentSlot = rawEvent->value;
1816 newSlot = true;
1817 }
1818 } else if (mCurrentSlot < 0) {
1819 mCurrentSlot = 0;
1820 }
1821
1822 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1823#if DEBUG_POINTERS
1824 if (newSlot) {
1825 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001826 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 mCurrentSlot, mSlotCount - 1);
1828 }
1829#endif
1830 } else {
1831 Slot* slot = &mSlots[mCurrentSlot];
1832
1833 switch (rawEvent->code) {
1834 case ABS_MT_POSITION_X:
1835 slot->mInUse = true;
1836 slot->mAbsMTPositionX = rawEvent->value;
1837 break;
1838 case ABS_MT_POSITION_Y:
1839 slot->mInUse = true;
1840 slot->mAbsMTPositionY = rawEvent->value;
1841 break;
1842 case ABS_MT_TOUCH_MAJOR:
1843 slot->mInUse = true;
1844 slot->mAbsMTTouchMajor = rawEvent->value;
1845 break;
1846 case ABS_MT_TOUCH_MINOR:
1847 slot->mInUse = true;
1848 slot->mAbsMTTouchMinor = rawEvent->value;
1849 slot->mHaveAbsMTTouchMinor = true;
1850 break;
1851 case ABS_MT_WIDTH_MAJOR:
1852 slot->mInUse = true;
1853 slot->mAbsMTWidthMajor = rawEvent->value;
1854 break;
1855 case ABS_MT_WIDTH_MINOR:
1856 slot->mInUse = true;
1857 slot->mAbsMTWidthMinor = rawEvent->value;
1858 slot->mHaveAbsMTWidthMinor = true;
1859 break;
1860 case ABS_MT_ORIENTATION:
1861 slot->mInUse = true;
1862 slot->mAbsMTOrientation = rawEvent->value;
1863 break;
1864 case ABS_MT_TRACKING_ID:
1865 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1866 // The slot is no longer in use but it retains its previous contents,
1867 // which may be reused for subsequent touches.
1868 slot->mInUse = false;
1869 } else {
1870 slot->mInUse = true;
1871 slot->mAbsMTTrackingId = rawEvent->value;
1872 }
1873 break;
1874 case ABS_MT_PRESSURE:
1875 slot->mInUse = true;
1876 slot->mAbsMTPressure = rawEvent->value;
1877 break;
1878 case ABS_MT_DISTANCE:
1879 slot->mInUse = true;
1880 slot->mAbsMTDistance = rawEvent->value;
1881 break;
1882 case ABS_MT_TOOL_TYPE:
1883 slot->mInUse = true;
1884 slot->mAbsMTToolType = rawEvent->value;
1885 slot->mHaveAbsMTToolType = true;
1886 break;
1887 }
1888 }
1889 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1890 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1891 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001892 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1893 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 }
1895}
1896
1897void MultiTouchMotionAccumulator::finishSync() {
1898 if (!mUsingSlotsProtocol) {
1899 clearSlots(-1);
1900 }
1901}
1902
1903bool MultiTouchMotionAccumulator::hasStylus() const {
1904 return mHaveStylus;
1905}
1906
1907
1908// --- MultiTouchMotionAccumulator::Slot ---
1909
1910MultiTouchMotionAccumulator::Slot::Slot() {
1911 clear();
1912}
1913
1914void MultiTouchMotionAccumulator::Slot::clear() {
1915 mInUse = false;
1916 mHaveAbsMTTouchMinor = false;
1917 mHaveAbsMTWidthMinor = false;
1918 mHaveAbsMTToolType = false;
1919 mAbsMTPositionX = 0;
1920 mAbsMTPositionY = 0;
1921 mAbsMTTouchMajor = 0;
1922 mAbsMTTouchMinor = 0;
1923 mAbsMTWidthMajor = 0;
1924 mAbsMTWidthMinor = 0;
1925 mAbsMTOrientation = 0;
1926 mAbsMTTrackingId = -1;
1927 mAbsMTPressure = 0;
1928 mAbsMTDistance = 0;
1929 mAbsMTToolType = 0;
1930}
1931
1932int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1933 if (mHaveAbsMTToolType) {
1934 switch (mAbsMTToolType) {
1935 case MT_TOOL_FINGER:
1936 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1937 case MT_TOOL_PEN:
1938 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1939 }
1940 }
1941 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1942}
1943
1944
1945// --- InputMapper ---
1946
1947InputMapper::InputMapper(InputDevice* device) :
1948 mDevice(device), mContext(device->getContext()) {
1949}
1950
1951InputMapper::~InputMapper() {
1952}
1953
1954void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1955 info->addSource(getSources());
1956}
1957
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001958void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959}
1960
1961void InputMapper::configure(nsecs_t when,
1962 const InputReaderConfiguration* config, uint32_t changes) {
1963}
1964
1965void InputMapper::reset(nsecs_t when) {
1966}
1967
1968void InputMapper::timeoutExpired(nsecs_t when) {
1969}
1970
1971int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1972 return AKEY_STATE_UNKNOWN;
1973}
1974
1975int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1976 return AKEY_STATE_UNKNOWN;
1977}
1978
1979int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1980 return AKEY_STATE_UNKNOWN;
1981}
1982
1983bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1984 const int32_t* keyCodes, uint8_t* outFlags) {
1985 return false;
1986}
1987
1988void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1989 int32_t token) {
1990}
1991
1992void InputMapper::cancelVibrate(int32_t token) {
1993}
1994
Jeff Brownc9aa6282015-02-11 19:03:28 -08001995void InputMapper::cancelTouch(nsecs_t when) {
1996}
1997
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998int32_t InputMapper::getMetaState() {
1999 return 0;
2000}
2001
Andrii Kulian763a3a42016-03-08 10:46:16 -08002002void InputMapper::updateMetaState(int32_t keyCode) {
2003}
2004
Michael Wright842500e2015-03-13 17:32:02 -07002005void InputMapper::updateExternalStylusState(const StylusState& state) {
2006
2007}
2008
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009void InputMapper::fadePointer() {
2010}
2011
2012status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2013 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2014}
2015
2016void InputMapper::bumpGeneration() {
2017 mDevice->bumpGeneration();
2018}
2019
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002020void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 const RawAbsoluteAxisInfo& axis, const char* name) {
2022 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002023 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2025 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002026 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 }
2028}
2029
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002030void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2031 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2032 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2033 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2034 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002035}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036
2037// --- SwitchInputMapper ---
2038
2039SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002040 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041}
2042
2043SwitchInputMapper::~SwitchInputMapper() {
2044}
2045
2046uint32_t SwitchInputMapper::getSources() {
2047 return AINPUT_SOURCE_SWITCH;
2048}
2049
2050void SwitchInputMapper::process(const RawEvent* rawEvent) {
2051 switch (rawEvent->type) {
2052 case EV_SW:
2053 processSwitch(rawEvent->code, rawEvent->value);
2054 break;
2055
2056 case EV_SYN:
2057 if (rawEvent->code == SYN_REPORT) {
2058 sync(rawEvent->when);
2059 }
2060 }
2061}
2062
2063void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2064 if (switchCode >= 0 && switchCode < 32) {
2065 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002066 mSwitchValues |= 1 << switchCode;
2067 } else {
2068 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
2070 mUpdatedSwitchMask |= 1 << switchCode;
2071 }
2072}
2073
2074void SwitchInputMapper::sync(nsecs_t when) {
2075 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002076 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002077 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 getListener()->notifySwitch(&args);
2079
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 mUpdatedSwitchMask = 0;
2081 }
2082}
2083
2084int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2085 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2086}
2087
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002088void SwitchInputMapper::dump(std::string& dump) {
2089 dump += INDENT2 "Switch Input Mapper:\n";
2090 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002091}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092
2093// --- VibratorInputMapper ---
2094
2095VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2096 InputMapper(device), mVibrating(false) {
2097}
2098
2099VibratorInputMapper::~VibratorInputMapper() {
2100}
2101
2102uint32_t VibratorInputMapper::getSources() {
2103 return 0;
2104}
2105
2106void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2107 InputMapper::populateDeviceInfo(info);
2108
2109 info->setVibrator(true);
2110}
2111
2112void VibratorInputMapper::process(const RawEvent* rawEvent) {
2113 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2114}
2115
2116void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2117 int32_t token) {
2118#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002119 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 for (size_t i = 0; i < patternSize; i++) {
2121 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002122 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002124 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002126 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002127 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128#endif
2129
2130 mVibrating = true;
2131 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2132 mPatternSize = patternSize;
2133 mRepeat = repeat;
2134 mToken = token;
2135 mIndex = -1;
2136
2137 nextStep();
2138}
2139
2140void VibratorInputMapper::cancelVibrate(int32_t token) {
2141#if DEBUG_VIBRATOR
2142 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2143#endif
2144
2145 if (mVibrating && mToken == token) {
2146 stopVibrating();
2147 }
2148}
2149
2150void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2151 if (mVibrating) {
2152 if (when >= mNextStepTime) {
2153 nextStep();
2154 } else {
2155 getContext()->requestTimeoutAtTime(mNextStepTime);
2156 }
2157 }
2158}
2159
2160void VibratorInputMapper::nextStep() {
2161 mIndex += 1;
2162 if (size_t(mIndex) >= mPatternSize) {
2163 if (mRepeat < 0) {
2164 // We are done.
2165 stopVibrating();
2166 return;
2167 }
2168 mIndex = mRepeat;
2169 }
2170
2171 bool vibratorOn = mIndex & 1;
2172 nsecs_t duration = mPattern[mIndex];
2173 if (vibratorOn) {
2174#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002175 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176#endif
2177 getEventHub()->vibrate(getDeviceId(), duration);
2178 } else {
2179#if DEBUG_VIBRATOR
2180 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2181#endif
2182 getEventHub()->cancelVibrate(getDeviceId());
2183 }
2184 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2185 mNextStepTime = now + duration;
2186 getContext()->requestTimeoutAtTime(mNextStepTime);
2187#if DEBUG_VIBRATOR
2188 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2189#endif
2190}
2191
2192void VibratorInputMapper::stopVibrating() {
2193 mVibrating = false;
2194#if DEBUG_VIBRATOR
2195 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2196#endif
2197 getEventHub()->cancelVibrate(getDeviceId());
2198}
2199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002200void VibratorInputMapper::dump(std::string& dump) {
2201 dump += INDENT2 "Vibrator Input Mapper:\n";
2202 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203}
2204
2205
2206// --- KeyboardInputMapper ---
2207
2208KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2209 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002210 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211}
2212
2213KeyboardInputMapper::~KeyboardInputMapper() {
2214}
2215
2216uint32_t KeyboardInputMapper::getSources() {
2217 return mSource;
2218}
2219
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002220int32_t KeyboardInputMapper::getOrientation() {
2221 if (mViewport) {
2222 return mViewport->orientation;
2223 }
2224 return DISPLAY_ORIENTATION_0;
2225}
2226
2227int32_t KeyboardInputMapper::getDisplayId() {
2228 if (mViewport) {
2229 return mViewport->displayId;
2230 }
2231 return ADISPLAY_ID_NONE;
2232}
2233
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2235 InputMapper::populateDeviceInfo(info);
2236
2237 info->setKeyboardType(mKeyboardType);
2238 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2239}
2240
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002241void KeyboardInputMapper::dump(std::string& dump) {
2242 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002244 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002245 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002246 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2247 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2248 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249}
2250
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251void KeyboardInputMapper::configure(nsecs_t when,
2252 const InputReaderConfiguration* config, uint32_t changes) {
2253 InputMapper::configure(when, config, changes);
2254
2255 if (!changes) { // first time only
2256 // Configure basic parameters.
2257 configureParameters();
2258 }
2259
2260 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002261 if (mParameters.orientationAware) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002262 mViewport = config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 }
2264 }
2265}
2266
Ivan Podogovb9afef32017-02-13 15:34:32 +00002267static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2268 int32_t mapped = 0;
2269 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2270 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2271 if (stemKeyRotationMap[i][0] == keyCode) {
2272 stemKeyRotationMap[i][1] = mapped;
2273 return;
2274 }
2275 }
2276 }
2277}
2278
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279void KeyboardInputMapper::configureParameters() {
2280 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002281 const PropertyMap& config = getDevice()->getConfiguration();
2282 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 mParameters.orientationAware);
2284
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002286 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2287 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2288 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2289 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002291
2292 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002293 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002294 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295}
2296
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002297void KeyboardInputMapper::dumpParameters(std::string& dump) {
2298 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002299 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002301 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002302 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303}
2304
2305void KeyboardInputMapper::reset(nsecs_t when) {
2306 mMetaState = AMETA_NONE;
2307 mDownTime = 0;
2308 mKeyDowns.clear();
2309 mCurrentHidUsage = 0;
2310
2311 resetLedState();
2312
2313 InputMapper::reset(when);
2314}
2315
2316void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2317 switch (rawEvent->type) {
2318 case EV_KEY: {
2319 int32_t scanCode = rawEvent->code;
2320 int32_t usageCode = mCurrentHidUsage;
2321 mCurrentHidUsage = 0;
2322
2323 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002324 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
2326 break;
2327 }
2328 case EV_MSC: {
2329 if (rawEvent->code == MSC_SCAN) {
2330 mCurrentHidUsage = rawEvent->value;
2331 }
2332 break;
2333 }
2334 case EV_SYN: {
2335 if (rawEvent->code == SYN_REPORT) {
2336 mCurrentHidUsage = 0;
2337 }
2338 }
2339 }
2340}
2341
2342bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2343 return scanCode < BTN_MOUSE
2344 || scanCode >= KEY_OK
2345 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2346 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2347}
2348
Michael Wright58ba9882017-07-26 16:19:11 +01002349bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2350 switch (keyCode) {
2351 case AKEYCODE_MEDIA_PLAY:
2352 case AKEYCODE_MEDIA_PAUSE:
2353 case AKEYCODE_MEDIA_PLAY_PAUSE:
2354 case AKEYCODE_MUTE:
2355 case AKEYCODE_HEADSETHOOK:
2356 case AKEYCODE_MEDIA_STOP:
2357 case AKEYCODE_MEDIA_NEXT:
2358 case AKEYCODE_MEDIA_PREVIOUS:
2359 case AKEYCODE_MEDIA_REWIND:
2360 case AKEYCODE_MEDIA_RECORD:
2361 case AKEYCODE_MEDIA_FAST_FORWARD:
2362 case AKEYCODE_MEDIA_SKIP_FORWARD:
2363 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2364 case AKEYCODE_MEDIA_STEP_FORWARD:
2365 case AKEYCODE_MEDIA_STEP_BACKWARD:
2366 case AKEYCODE_MEDIA_AUDIO_TRACK:
2367 case AKEYCODE_VOLUME_UP:
2368 case AKEYCODE_VOLUME_DOWN:
2369 case AKEYCODE_VOLUME_MUTE:
2370 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2371 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2372 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2373 return true;
2374 }
2375 return false;
2376}
2377
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002378void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2379 int32_t usageCode) {
2380 int32_t keyCode;
2381 int32_t keyMetaState;
2382 uint32_t policyFlags;
2383
2384 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2385 &keyCode, &keyMetaState, &policyFlags)) {
2386 keyCode = AKEYCODE_UNKNOWN;
2387 keyMetaState = mMetaState;
2388 policyFlags = 0;
2389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390
2391 if (down) {
2392 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002393 if (mParameters.orientationAware) {
2394 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
2396
2397 // Add key down.
2398 ssize_t keyDownIndex = findKeyDown(scanCode);
2399 if (keyDownIndex >= 0) {
2400 // key repeat, be sure to use same keycode as before in case of rotation
2401 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2402 } else {
2403 // key down
2404 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2405 && mContext->shouldDropVirtualKey(when,
2406 getDevice(), keyCode, scanCode)) {
2407 return;
2408 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002409 if (policyFlags & POLICY_FLAG_GESTURE) {
2410 mDevice->cancelTouch(when);
2411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412
2413 mKeyDowns.push();
2414 KeyDown& keyDown = mKeyDowns.editTop();
2415 keyDown.keyCode = keyCode;
2416 keyDown.scanCode = scanCode;
2417 }
2418
2419 mDownTime = when;
2420 } else {
2421 // Remove key down.
2422 ssize_t keyDownIndex = findKeyDown(scanCode);
2423 if (keyDownIndex >= 0) {
2424 // key up, be sure to use same keycode as before in case of rotation
2425 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2426 mKeyDowns.removeAt(size_t(keyDownIndex));
2427 } else {
2428 // key was not actually down
2429 ALOGI("Dropping key up from device %s because the key was not down. "
2430 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002431 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 return;
2433 }
2434 }
2435
Andrii Kulian763a3a42016-03-08 10:46:16 -08002436 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002437 // If global meta state changed send it along with the key.
2438 // If it has not changed then we'll use what keymap gave us,
2439 // since key replacement logic might temporarily reset a few
2440 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002441 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
2443
2444 nsecs_t downTime = mDownTime;
2445
2446 // Key down on external an keyboard should wake the device.
2447 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2448 // For internal keyboards, the key layout file should specify the policy flags for
2449 // each wake key individually.
2450 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002451 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002452 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 }
2454
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002455 if (mParameters.handlesKeyRepeat) {
2456 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2457 }
2458
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002459 NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002461 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 getListener()->notifyKey(&args);
2463}
2464
2465ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2466 size_t n = mKeyDowns.size();
2467 for (size_t i = 0; i < n; i++) {
2468 if (mKeyDowns[i].scanCode == scanCode) {
2469 return i;
2470 }
2471 }
2472 return -1;
2473}
2474
2475int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2476 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2477}
2478
2479int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2480 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2481}
2482
2483bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2484 const int32_t* keyCodes, uint8_t* outFlags) {
2485 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2486}
2487
2488int32_t KeyboardInputMapper::getMetaState() {
2489 return mMetaState;
2490}
2491
Andrii Kulian763a3a42016-03-08 10:46:16 -08002492void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2493 updateMetaStateIfNeeded(keyCode, false);
2494}
2495
2496bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2497 int32_t oldMetaState = mMetaState;
2498 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2499 bool metaStateChanged = oldMetaState != newMetaState;
2500 if (metaStateChanged) {
2501 mMetaState = newMetaState;
2502 updateLedState(false);
2503
2504 getContext()->updateGlobalMetaState();
2505 }
2506
2507 return metaStateChanged;
2508}
2509
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510void KeyboardInputMapper::resetLedState() {
2511 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2512 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2513 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2514
2515 updateLedState(true);
2516}
2517
2518void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2519 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2520 ledState.on = false;
2521}
2522
2523void KeyboardInputMapper::updateLedState(bool reset) {
2524 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2525 AMETA_CAPS_LOCK_ON, reset);
2526 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2527 AMETA_NUM_LOCK_ON, reset);
2528 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2529 AMETA_SCROLL_LOCK_ON, reset);
2530}
2531
2532void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2533 int32_t led, int32_t modifier, bool reset) {
2534 if (ledState.avail) {
2535 bool desiredState = (mMetaState & modifier) != 0;
2536 if (reset || ledState.on != desiredState) {
2537 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2538 ledState.on = desiredState;
2539 }
2540 }
2541}
2542
2543
2544// --- CursorInputMapper ---
2545
2546CursorInputMapper::CursorInputMapper(InputDevice* device) :
2547 InputMapper(device) {
2548}
2549
2550CursorInputMapper::~CursorInputMapper() {
2551}
2552
2553uint32_t CursorInputMapper::getSources() {
2554 return mSource;
2555}
2556
2557void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2558 InputMapper::populateDeviceInfo(info);
2559
2560 if (mParameters.mode == Parameters::MODE_POINTER) {
2561 float minX, minY, maxX, maxY;
2562 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2563 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2564 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2565 }
2566 } else {
2567 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2568 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2569 }
2570 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2571
2572 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2573 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2574 }
2575 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2576 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2577 }
2578}
2579
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002580void CursorInputMapper::dump(std::string& dump) {
2581 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002583 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2584 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2585 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2586 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2587 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002589 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002591 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2592 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2593 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2594 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2595 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2596 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597}
2598
2599void CursorInputMapper::configure(nsecs_t when,
2600 const InputReaderConfiguration* config, uint32_t changes) {
2601 InputMapper::configure(when, config, changes);
2602
2603 if (!changes) { // first time only
2604 mCursorScrollAccumulator.configure(getDevice());
2605
2606 // Configure basic parameters.
2607 configureParameters();
2608
2609 // Configure device mode.
2610 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002611 case Parameters::MODE_POINTER_RELATIVE:
2612 // Should not happen during first time configuration.
2613 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2614 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002615 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 case Parameters::MODE_POINTER:
2617 mSource = AINPUT_SOURCE_MOUSE;
2618 mXPrecision = 1.0f;
2619 mYPrecision = 1.0f;
2620 mXScale = 1.0f;
2621 mYScale = 1.0f;
2622 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2623 break;
2624 case Parameters::MODE_NAVIGATION:
2625 mSource = AINPUT_SOURCE_TRACKBALL;
2626 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2627 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2628 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2629 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2630 break;
2631 }
2632
2633 mVWheelScale = 1.0f;
2634 mHWheelScale = 1.0f;
2635 }
2636
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002637 if ((!changes && config->pointerCapture)
2638 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2639 if (config->pointerCapture) {
2640 if (mParameters.mode == Parameters::MODE_POINTER) {
2641 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2642 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2643 // Keep PointerController around in order to preserve the pointer position.
2644 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2645 } else {
2646 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2647 }
2648 } else {
2649 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2650 mParameters.mode = Parameters::MODE_POINTER;
2651 mSource = AINPUT_SOURCE_MOUSE;
2652 } else {
2653 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2654 }
2655 }
2656 bumpGeneration();
2657 if (changes) {
2658 getDevice()->notifyReset(when);
2659 }
2660 }
2661
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2663 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2664 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2665 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2666 }
2667
2668 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002669 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002671 std::optional<DisplayViewport> internalViewport =
2672 config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "");
2673 if (internalViewport) {
2674 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 }
2677 bumpGeneration();
2678 }
2679}
2680
2681void CursorInputMapper::configureParameters() {
2682 mParameters.mode = Parameters::MODE_POINTER;
2683 String8 cursorModeString;
2684 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2685 if (cursorModeString == "navigation") {
2686 mParameters.mode = Parameters::MODE_NAVIGATION;
2687 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2688 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2689 }
2690 }
2691
2692 mParameters.orientationAware = false;
2693 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2694 mParameters.orientationAware);
2695
2696 mParameters.hasAssociatedDisplay = false;
2697 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2698 mParameters.hasAssociatedDisplay = true;
2699 }
2700}
2701
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002702void CursorInputMapper::dumpParameters(std::string& dump) {
2703 dump += INDENT3 "Parameters:\n";
2704 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 toString(mParameters.hasAssociatedDisplay));
2706
2707 switch (mParameters.mode) {
2708 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002709 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002711 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002712 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002713 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002715 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716 break;
2717 default:
2718 ALOG_ASSERT(false);
2719 }
2720
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002721 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722 toString(mParameters.orientationAware));
2723}
2724
2725void CursorInputMapper::reset(nsecs_t when) {
2726 mButtonState = 0;
2727 mDownTime = 0;
2728
2729 mPointerVelocityControl.reset();
2730 mWheelXVelocityControl.reset();
2731 mWheelYVelocityControl.reset();
2732
2733 mCursorButtonAccumulator.reset(getDevice());
2734 mCursorMotionAccumulator.reset(getDevice());
2735 mCursorScrollAccumulator.reset(getDevice());
2736
2737 InputMapper::reset(when);
2738}
2739
2740void CursorInputMapper::process(const RawEvent* rawEvent) {
2741 mCursorButtonAccumulator.process(rawEvent);
2742 mCursorMotionAccumulator.process(rawEvent);
2743 mCursorScrollAccumulator.process(rawEvent);
2744
2745 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2746 sync(rawEvent->when);
2747 }
2748}
2749
2750void CursorInputMapper::sync(nsecs_t when) {
2751 int32_t lastButtonState = mButtonState;
2752 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2753 mButtonState = currentButtonState;
2754
2755 bool wasDown = isPointerDown(lastButtonState);
2756 bool down = isPointerDown(currentButtonState);
2757 bool downChanged;
2758 if (!wasDown && down) {
2759 mDownTime = when;
2760 downChanged = true;
2761 } else if (wasDown && !down) {
2762 downChanged = true;
2763 } else {
2764 downChanged = false;
2765 }
2766 nsecs_t downTime = mDownTime;
2767 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002768 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2769 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770
2771 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2772 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2773 bool moved = deltaX != 0 || deltaY != 0;
2774
2775 // Rotate delta according to orientation if needed.
2776 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2777 && (deltaX != 0.0f || deltaY != 0.0f)) {
2778 rotateDelta(mOrientation, &deltaX, &deltaY);
2779 }
2780
2781 // Move the pointer.
2782 PointerProperties pointerProperties;
2783 pointerProperties.clear();
2784 pointerProperties.id = 0;
2785 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2786
2787 PointerCoords pointerCoords;
2788 pointerCoords.clear();
2789
2790 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2791 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2792 bool scrolled = vscroll != 0 || hscroll != 0;
2793
Yi Kong9b14ac62018-07-17 13:48:38 -07002794 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2795 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796
2797 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2798
2799 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002800 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 if (moved || scrolled || buttonsChanged) {
2802 mPointerController->setPresentation(
2803 PointerControllerInterface::PRESENTATION_POINTER);
2804
2805 if (moved) {
2806 mPointerController->move(deltaX, deltaY);
2807 }
2808
2809 if (buttonsChanged) {
2810 mPointerController->setButtonState(currentButtonState);
2811 }
2812
2813 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2814 }
2815
2816 float x, y;
2817 mPointerController->getPosition(&x, &y);
2818 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2819 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002820 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2821 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 displayId = ADISPLAY_ID_DEFAULT;
2823 } else {
2824 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2825 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2826 displayId = ADISPLAY_ID_NONE;
2827 }
2828
2829 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2830
2831 // Moving an external trackball or mouse should wake the device.
2832 // We don't do this for internal cursor devices to prevent them from waking up
2833 // the device in your pocket.
2834 // TODO: Use the input device configuration to control this behavior more finely.
2835 uint32_t policyFlags = 0;
2836 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002837 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 }
2839
2840 // Synthesize key down from buttons if needed.
2841 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002842 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843
2844 // Send motion event.
2845 if (downChanged || moved || scrolled || buttonsChanged) {
2846 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002847 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 int32_t motionEventAction;
2849 if (downChanged) {
2850 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002851 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2853 } else {
2854 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2855 }
2856
Michael Wright7b159c92015-05-14 14:48:03 +01002857 if (buttonsReleased) {
2858 BitSet32 released(buttonsReleased);
2859 while (!released.isEmpty()) {
2860 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2861 buttonState &= ~actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002862 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002863 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2864 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002865 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002866 mXPrecision, mYPrecision, downTime);
2867 getListener()->notifyMotion(&releaseArgs);
2868 }
2869 }
2870
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002871 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002872 motionEventAction, 0, 0, metaState, currentButtonState,
2873 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002874 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 mXPrecision, mYPrecision, downTime);
2876 getListener()->notifyMotion(&args);
2877
Michael Wright7b159c92015-05-14 14:48:03 +01002878 if (buttonsPressed) {
2879 BitSet32 pressed(buttonsPressed);
2880 while (!pressed.isEmpty()) {
2881 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2882 buttonState |= actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002883 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002884 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2885 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002886 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002887 mXPrecision, mYPrecision, downTime);
2888 getListener()->notifyMotion(&pressArgs);
2889 }
2890 }
2891
2892 ALOG_ASSERT(buttonState == currentButtonState);
2893
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894 // Send hover move after UP to tell the application that the mouse is hovering now.
2895 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002896 && (mSource == AINPUT_SOURCE_MOUSE)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002897 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002898 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002900 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 mXPrecision, mYPrecision, downTime);
2902 getListener()->notifyMotion(&hoverArgs);
2903 }
2904
2905 // Send scroll events.
2906 if (scrolled) {
2907 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2908 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2909
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002910 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002911 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002913 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 mXPrecision, mYPrecision, downTime);
2915 getListener()->notifyMotion(&scrollArgs);
2916 }
2917 }
2918
2919 // Synthesize key up from buttons if needed.
2920 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002921 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922
2923 mCursorMotionAccumulator.finishSync();
2924 mCursorScrollAccumulator.finishSync();
2925}
2926
2927int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2928 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2929 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2930 } else {
2931 return AKEY_STATE_UNKNOWN;
2932 }
2933}
2934
2935void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002936 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2938 }
2939}
2940
Prashant Malani1941ff52015-08-11 18:29:28 -07002941// --- RotaryEncoderInputMapper ---
2942
2943RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002944 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002945 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2946}
2947
2948RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2949}
2950
2951uint32_t RotaryEncoderInputMapper::getSources() {
2952 return mSource;
2953}
2954
2955void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2956 InputMapper::populateDeviceInfo(info);
2957
2958 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002959 float res = 0.0f;
2960 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2961 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2962 }
2963 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2964 mScalingFactor)) {
2965 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2966 "default to 1.0!\n");
2967 mScalingFactor = 1.0f;
2968 }
2969 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2970 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002971 }
2972}
2973
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002974void RotaryEncoderInputMapper::dump(std::string& dump) {
2975 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2976 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002977 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2978}
2979
2980void RotaryEncoderInputMapper::configure(nsecs_t when,
2981 const InputReaderConfiguration* config, uint32_t changes) {
2982 InputMapper::configure(when, config, changes);
2983 if (!changes) {
2984 mRotaryEncoderScrollAccumulator.configure(getDevice());
2985 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002986 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002987 std::optional<DisplayViewport> internalViewport =
2988 config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "");
2989 if (internalViewport) {
2990 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002991 } else {
2992 mOrientation = DISPLAY_ORIENTATION_0;
2993 }
2994 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002995}
2996
2997void RotaryEncoderInputMapper::reset(nsecs_t when) {
2998 mRotaryEncoderScrollAccumulator.reset(getDevice());
2999
3000 InputMapper::reset(when);
3001}
3002
3003void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3004 mRotaryEncoderScrollAccumulator.process(rawEvent);
3005
3006 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3007 sync(rawEvent->when);
3008 }
3009}
3010
3011void RotaryEncoderInputMapper::sync(nsecs_t when) {
3012 PointerCoords pointerCoords;
3013 pointerCoords.clear();
3014
3015 PointerProperties pointerProperties;
3016 pointerProperties.clear();
3017 pointerProperties.id = 0;
3018 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3019
3020 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3021 bool scrolled = scroll != 0;
3022
3023 // This is not a pointer, so it's not associated with a display.
3024 int32_t displayId = ADISPLAY_ID_NONE;
3025
3026 // Moving the rotary encoder should wake the device (if specified).
3027 uint32_t policyFlags = 0;
3028 if (scrolled && getDevice()->isExternal()) {
3029 policyFlags |= POLICY_FLAG_WAKE;
3030 }
3031
Ivan Podogovad437252016-09-29 16:29:55 +01003032 if (mOrientation == DISPLAY_ORIENTATION_180) {
3033 scroll = -scroll;
3034 }
3035
Prashant Malani1941ff52015-08-11 18:29:28 -07003036 // Send motion event.
3037 if (scrolled) {
3038 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003039 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003040
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003041 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003042 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3043 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003044 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07003045 0, 0, 0);
3046 getListener()->notifyMotion(&scrollArgs);
3047 }
3048
3049 mRotaryEncoderScrollAccumulator.finishSync();
3050}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051
3052// --- TouchInputMapper ---
3053
3054TouchInputMapper::TouchInputMapper(InputDevice* device) :
3055 InputMapper(device),
3056 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3057 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003058 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3060}
3061
3062TouchInputMapper::~TouchInputMapper() {
3063}
3064
3065uint32_t TouchInputMapper::getSources() {
3066 return mSource;
3067}
3068
3069void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3070 InputMapper::populateDeviceInfo(info);
3071
3072 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3073 info->addMotionRange(mOrientedRanges.x);
3074 info->addMotionRange(mOrientedRanges.y);
3075 info->addMotionRange(mOrientedRanges.pressure);
3076
3077 if (mOrientedRanges.haveSize) {
3078 info->addMotionRange(mOrientedRanges.size);
3079 }
3080
3081 if (mOrientedRanges.haveTouchSize) {
3082 info->addMotionRange(mOrientedRanges.touchMajor);
3083 info->addMotionRange(mOrientedRanges.touchMinor);
3084 }
3085
3086 if (mOrientedRanges.haveToolSize) {
3087 info->addMotionRange(mOrientedRanges.toolMajor);
3088 info->addMotionRange(mOrientedRanges.toolMinor);
3089 }
3090
3091 if (mOrientedRanges.haveOrientation) {
3092 info->addMotionRange(mOrientedRanges.orientation);
3093 }
3094
3095 if (mOrientedRanges.haveDistance) {
3096 info->addMotionRange(mOrientedRanges.distance);
3097 }
3098
3099 if (mOrientedRanges.haveTilt) {
3100 info->addMotionRange(mOrientedRanges.tilt);
3101 }
3102
3103 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3104 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3105 0.0f);
3106 }
3107 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3108 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3109 0.0f);
3110 }
3111 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3112 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3113 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3114 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3115 x.fuzz, x.resolution);
3116 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3117 y.fuzz, y.resolution);
3118 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3119 x.fuzz, x.resolution);
3120 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3121 y.fuzz, y.resolution);
3122 }
3123 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3124 }
3125}
3126
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003127void TouchInputMapper::dump(std::string& dump) {
3128 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 dumpParameters(dump);
3130 dumpVirtualKeys(dump);
3131 dumpRawPointerAxes(dump);
3132 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003133 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 dumpSurface(dump);
3135
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003136 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3137 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3138 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3139 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3140 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3141 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3142 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3143 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3144 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3145 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3146 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3147 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3148 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3149 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3150 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3151 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3152 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003154 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3155 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003156 mLastRawState.rawPointerData.pointerCount);
3157 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3158 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003159 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3161 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3162 "toolType=%d, isHovering=%s\n", i,
3163 pointer.id, pointer.x, pointer.y, pointer.pressure,
3164 pointer.touchMajor, pointer.touchMinor,
3165 pointer.toolMajor, pointer.toolMinor,
3166 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3167 pointer.toolType, toString(pointer.isHovering));
3168 }
3169
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003170 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3171 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003172 mLastCookedState.cookedPointerData.pointerCount);
3173 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3174 const PointerProperties& pointerProperties =
3175 mLastCookedState.cookedPointerData.pointerProperties[i];
3176 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003177 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3179 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3180 "toolType=%d, isHovering=%s\n", i,
3181 pointerProperties.id,
3182 pointerCoords.getX(),
3183 pointerCoords.getY(),
3184 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3185 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3186 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3187 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3188 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3189 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3190 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3191 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3192 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003193 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 }
3195
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003196 dump += INDENT3 "Stylus Fusion:\n";
3197 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003198 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003199 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3200 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003201 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003202 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003203 dumpStylusState(dump, mExternalStylusState);
3204
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003206 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3207 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003209 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003211 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003213 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003215 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 mPointerGestureMaxSwipeWidth);
3217 }
3218}
3219
Santos Cordonfa5cf462017-04-05 10:37:00 -07003220const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3221 switch (deviceMode) {
3222 case DEVICE_MODE_DISABLED:
3223 return "disabled";
3224 case DEVICE_MODE_DIRECT:
3225 return "direct";
3226 case DEVICE_MODE_UNSCALED:
3227 return "unscaled";
3228 case DEVICE_MODE_NAVIGATION:
3229 return "navigation";
3230 case DEVICE_MODE_POINTER:
3231 return "pointer";
3232 }
3233 return "unknown";
3234}
3235
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236void TouchInputMapper::configure(nsecs_t when,
3237 const InputReaderConfiguration* config, uint32_t changes) {
3238 InputMapper::configure(when, config, changes);
3239
3240 mConfig = *config;
3241
3242 if (!changes) { // first time only
3243 // Configure basic parameters.
3244 configureParameters();
3245
3246 // Configure common accumulators.
3247 mCursorScrollAccumulator.configure(getDevice());
3248 mTouchButtonAccumulator.configure(getDevice());
3249
3250 // Configure absolute axis information.
3251 configureRawPointerAxes();
3252
3253 // Prepare input device calibration.
3254 parseCalibration();
3255 resolveCalibration();
3256 }
3257
Michael Wright842500e2015-03-13 17:32:02 -07003258 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003259 // Update location calibration to reflect current settings
3260 updateAffineTransformation();
3261 }
3262
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3264 // Update pointer speed.
3265 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3266 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3267 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3268 }
3269
3270 bool resetNeeded = false;
3271 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3272 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003273 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3274 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 // Configure device sources, surface dimensions, orientation and
3276 // scaling factors.
3277 configureSurface(when, &resetNeeded);
3278 }
3279
3280 if (changes && resetNeeded) {
3281 // Send reset, unless this is the first time the device has been configured,
3282 // in which case the reader will call reset itself after all mappers are ready.
3283 getDevice()->notifyReset(when);
3284 }
3285}
3286
Michael Wright842500e2015-03-13 17:32:02 -07003287void TouchInputMapper::resolveExternalStylusPresence() {
3288 Vector<InputDeviceInfo> devices;
3289 mContext->getExternalStylusDevices(devices);
3290 mExternalStylusConnected = !devices.isEmpty();
3291
3292 if (!mExternalStylusConnected) {
3293 resetExternalStylus();
3294 }
3295}
3296
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297void TouchInputMapper::configureParameters() {
3298 // Use the pointer presentation mode for devices that do not support distinct
3299 // multitouch. The spot-based presentation relies on being able to accurately
3300 // locate two or more fingers on the touch pad.
3301 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003302 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303
3304 String8 gestureModeString;
3305 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3306 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003307 if (gestureModeString == "single-touch") {
3308 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3309 } else if (gestureModeString == "multi-touch") {
3310 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 } else if (gestureModeString != "default") {
3312 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3313 }
3314 }
3315
3316 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3317 // The device is a touch screen.
3318 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3319 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3320 // The device is a pointing device like a track pad.
3321 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3322 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3323 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3324 // The device is a cursor device with a touch pad attached.
3325 // By default don't use the touch pad to move the pointer.
3326 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3327 } else {
3328 // The device is a touch pad of unknown purpose.
3329 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3330 }
3331
3332 mParameters.hasButtonUnderPad=
3333 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3334
3335 String8 deviceTypeString;
3336 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3337 deviceTypeString)) {
3338 if (deviceTypeString == "touchScreen") {
3339 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3340 } else if (deviceTypeString == "touchPad") {
3341 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3342 } else if (deviceTypeString == "touchNavigation") {
3343 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3344 } else if (deviceTypeString == "pointer") {
3345 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3346 } else if (deviceTypeString != "default") {
3347 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3348 }
3349 }
3350
3351 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3352 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3353 mParameters.orientationAware);
3354
3355 mParameters.hasAssociatedDisplay = false;
3356 mParameters.associatedDisplayIsExternal = false;
3357 if (mParameters.orientationAware
3358 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3359 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3360 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003361 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3362 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003363 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003364 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003365 uniqueDisplayId);
3366 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003369
3370 // Initial downs on external touch devices should wake the device.
3371 // Normally we don't do this for internal touch screens to prevent them from waking
3372 // up in your pocket but you can enable it using the input device configuration.
3373 mParameters.wake = getDevice()->isExternal();
3374 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3375 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376}
3377
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003378void TouchInputMapper::dumpParameters(std::string& dump) {
3379 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380
3381 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003382 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003383 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003385 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003386 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 break;
3388 default:
3389 assert(false);
3390 }
3391
3392 switch (mParameters.deviceType) {
3393 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003394 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 break;
3396 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003397 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 break;
3399 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003400 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 break;
3402 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003403 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 break;
3405 default:
3406 ALOG_ASSERT(false);
3407 }
3408
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003409 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003410 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003412 toString(mParameters.associatedDisplayIsExternal),
3413 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003414 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 toString(mParameters.orientationAware));
3416}
3417
3418void TouchInputMapper::configureRawPointerAxes() {
3419 mRawPointerAxes.clear();
3420}
3421
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003422void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3423 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3425 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3426 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3427 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3428 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3429 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3430 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3431 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3432 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3433 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3434 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3435 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3436 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3437}
3438
Michael Wright842500e2015-03-13 17:32:02 -07003439bool TouchInputMapper::hasExternalStylus() const {
3440 return mExternalStylusConnected;
3441}
3442
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3444 int32_t oldDeviceMode = mDeviceMode;
3445
Michael Wright842500e2015-03-13 17:32:02 -07003446 resolveExternalStylusPresence();
3447
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 // Determine device mode.
3449 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3450 && mConfig.pointerGesturesEnabled) {
3451 mSource = AINPUT_SOURCE_MOUSE;
3452 mDeviceMode = DEVICE_MODE_POINTER;
3453 if (hasStylus()) {
3454 mSource |= AINPUT_SOURCE_STYLUS;
3455 }
3456 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3457 && mParameters.hasAssociatedDisplay) {
3458 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3459 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003460 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 mSource |= AINPUT_SOURCE_STYLUS;
3462 }
Michael Wright2f78b682015-06-12 15:25:08 +01003463 if (hasExternalStylus()) {
3464 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3467 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3468 mDeviceMode = DEVICE_MODE_NAVIGATION;
3469 } else {
3470 mSource = AINPUT_SOURCE_TOUCHPAD;
3471 mDeviceMode = DEVICE_MODE_UNSCALED;
3472 }
3473
3474 // Ensure we have valid X and Y axes.
3475 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3476 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003477 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 mDeviceMode = DEVICE_MODE_DISABLED;
3479 return;
3480 }
3481
3482 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003483 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3484 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485
3486 // Get associated display dimensions.
3487 DisplayViewport newViewport;
3488 if (mParameters.hasAssociatedDisplay) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003489 std::string uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003490 ViewportType viewportTypeToUse;
3491
3492 if (mParameters.associatedDisplayIsExternal) {
3493 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003494 } else if (!mParameters.uniqueDisplayId.empty()) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003495 // If the IDC file specified a unique display Id, then it expects to be linked to a
3496 // virtual display with the same unique ID.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003497 uniqueDisplayId = mParameters.uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003498 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3499 } else {
3500 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3501 }
3502
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003503 std::optional<DisplayViewport> viewportToUse =
3504 mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId);
3505 if (!viewportToUse) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3507 "display. The device will be inoperable until the display size "
3508 "becomes available.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003509 getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 mDeviceMode = DEVICE_MODE_DISABLED;
3511 return;
3512 }
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003513 newViewport = *viewportToUse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 } else {
3515 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3516 }
3517 bool viewportChanged = mViewport != newViewport;
3518 if (viewportChanged) {
3519 mViewport = newViewport;
3520
3521 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3522 // Convert rotated viewport to natural surface coordinates.
3523 int32_t naturalLogicalWidth, naturalLogicalHeight;
3524 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3525 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3526 int32_t naturalDeviceWidth, naturalDeviceHeight;
3527 switch (mViewport.orientation) {
3528 case DISPLAY_ORIENTATION_90:
3529 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3530 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3531 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3532 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3533 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3534 naturalPhysicalTop = mViewport.physicalLeft;
3535 naturalDeviceWidth = mViewport.deviceHeight;
3536 naturalDeviceHeight = mViewport.deviceWidth;
3537 break;
3538 case DISPLAY_ORIENTATION_180:
3539 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3540 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3541 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3542 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3543 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3544 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3545 naturalDeviceWidth = mViewport.deviceWidth;
3546 naturalDeviceHeight = mViewport.deviceHeight;
3547 break;
3548 case DISPLAY_ORIENTATION_270:
3549 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3550 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3551 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3552 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3553 naturalPhysicalLeft = mViewport.physicalTop;
3554 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3555 naturalDeviceWidth = mViewport.deviceHeight;
3556 naturalDeviceHeight = mViewport.deviceWidth;
3557 break;
3558 case DISPLAY_ORIENTATION_0:
3559 default:
3560 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3561 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3562 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3563 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3564 naturalPhysicalLeft = mViewport.physicalLeft;
3565 naturalPhysicalTop = mViewport.physicalTop;
3566 naturalDeviceWidth = mViewport.deviceWidth;
3567 naturalDeviceHeight = mViewport.deviceHeight;
3568 break;
3569 }
3570
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003571 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3572 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3573 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3574 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3575 }
3576
Michael Wright358bcc72018-08-21 04:01:07 +01003577 mPhysicalWidth = naturalPhysicalWidth;
3578 mPhysicalHeight = naturalPhysicalHeight;
3579 mPhysicalLeft = naturalPhysicalLeft;
3580 mPhysicalTop = naturalPhysicalTop;
3581
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3583 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3584 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3585 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3586
3587 mSurfaceOrientation = mParameters.orientationAware ?
3588 mViewport.orientation : DISPLAY_ORIENTATION_0;
3589 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003590 mPhysicalWidth = rawWidth;
3591 mPhysicalHeight = rawHeight;
3592 mPhysicalLeft = 0;
3593 mPhysicalTop = 0;
3594
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 mSurfaceWidth = rawWidth;
3596 mSurfaceHeight = rawHeight;
3597 mSurfaceLeft = 0;
3598 mSurfaceTop = 0;
3599 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3600 }
3601 }
3602
3603 // If moving between pointer modes, need to reset some state.
3604 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3605 if (deviceModeChanged) {
3606 mOrientedRanges.clear();
3607 }
3608
3609 // Create pointer controller if needed.
3610 if (mDeviceMode == DEVICE_MODE_POINTER ||
3611 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003612 if (mPointerController == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3614 }
3615 } else {
3616 mPointerController.clear();
3617 }
3618
3619 if (viewportChanged || deviceModeChanged) {
3620 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3621 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003622 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3624
3625 // Configure X and Y factors.
3626 mXScale = float(mSurfaceWidth) / rawWidth;
3627 mYScale = float(mSurfaceHeight) / rawHeight;
3628 mXTranslate = -mSurfaceLeft;
3629 mYTranslate = -mSurfaceTop;
3630 mXPrecision = 1.0f / mXScale;
3631 mYPrecision = 1.0f / mYScale;
3632
3633 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3634 mOrientedRanges.x.source = mSource;
3635 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3636 mOrientedRanges.y.source = mSource;
3637
3638 configureVirtualKeys();
3639
3640 // Scale factor for terms that are not oriented in a particular axis.
3641 // If the pixels are square then xScale == yScale otherwise we fake it
3642 // by choosing an average.
3643 mGeometricScale = avg(mXScale, mYScale);
3644
3645 // Size of diagonal axis.
3646 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3647
3648 // Size factors.
3649 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3650 if (mRawPointerAxes.touchMajor.valid
3651 && mRawPointerAxes.touchMajor.maxValue != 0) {
3652 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3653 } else if (mRawPointerAxes.toolMajor.valid
3654 && mRawPointerAxes.toolMajor.maxValue != 0) {
3655 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3656 } else {
3657 mSizeScale = 0.0f;
3658 }
3659
3660 mOrientedRanges.haveTouchSize = true;
3661 mOrientedRanges.haveToolSize = true;
3662 mOrientedRanges.haveSize = true;
3663
3664 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3665 mOrientedRanges.touchMajor.source = mSource;
3666 mOrientedRanges.touchMajor.min = 0;
3667 mOrientedRanges.touchMajor.max = diagonalSize;
3668 mOrientedRanges.touchMajor.flat = 0;
3669 mOrientedRanges.touchMajor.fuzz = 0;
3670 mOrientedRanges.touchMajor.resolution = 0;
3671
3672 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3673 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3674
3675 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3676 mOrientedRanges.toolMajor.source = mSource;
3677 mOrientedRanges.toolMajor.min = 0;
3678 mOrientedRanges.toolMajor.max = diagonalSize;
3679 mOrientedRanges.toolMajor.flat = 0;
3680 mOrientedRanges.toolMajor.fuzz = 0;
3681 mOrientedRanges.toolMajor.resolution = 0;
3682
3683 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3684 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3685
3686 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3687 mOrientedRanges.size.source = mSource;
3688 mOrientedRanges.size.min = 0;
3689 mOrientedRanges.size.max = 1.0;
3690 mOrientedRanges.size.flat = 0;
3691 mOrientedRanges.size.fuzz = 0;
3692 mOrientedRanges.size.resolution = 0;
3693 } else {
3694 mSizeScale = 0.0f;
3695 }
3696
3697 // Pressure factors.
3698 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003699 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3701 || mCalibration.pressureCalibration
3702 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3703 if (mCalibration.havePressureScale) {
3704 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003705 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 } else if (mRawPointerAxes.pressure.valid
3707 && mRawPointerAxes.pressure.maxValue != 0) {
3708 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3709 }
3710 }
3711
3712 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3713 mOrientedRanges.pressure.source = mSource;
3714 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003715 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 mOrientedRanges.pressure.flat = 0;
3717 mOrientedRanges.pressure.fuzz = 0;
3718 mOrientedRanges.pressure.resolution = 0;
3719
3720 // Tilt
3721 mTiltXCenter = 0;
3722 mTiltXScale = 0;
3723 mTiltYCenter = 0;
3724 mTiltYScale = 0;
3725 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3726 if (mHaveTilt) {
3727 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3728 mRawPointerAxes.tiltX.maxValue);
3729 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3730 mRawPointerAxes.tiltY.maxValue);
3731 mTiltXScale = M_PI / 180;
3732 mTiltYScale = M_PI / 180;
3733
3734 mOrientedRanges.haveTilt = true;
3735
3736 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3737 mOrientedRanges.tilt.source = mSource;
3738 mOrientedRanges.tilt.min = 0;
3739 mOrientedRanges.tilt.max = M_PI_2;
3740 mOrientedRanges.tilt.flat = 0;
3741 mOrientedRanges.tilt.fuzz = 0;
3742 mOrientedRanges.tilt.resolution = 0;
3743 }
3744
3745 // Orientation
3746 mOrientationScale = 0;
3747 if (mHaveTilt) {
3748 mOrientedRanges.haveOrientation = true;
3749
3750 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3751 mOrientedRanges.orientation.source = mSource;
3752 mOrientedRanges.orientation.min = -M_PI;
3753 mOrientedRanges.orientation.max = M_PI;
3754 mOrientedRanges.orientation.flat = 0;
3755 mOrientedRanges.orientation.fuzz = 0;
3756 mOrientedRanges.orientation.resolution = 0;
3757 } else if (mCalibration.orientationCalibration !=
3758 Calibration::ORIENTATION_CALIBRATION_NONE) {
3759 if (mCalibration.orientationCalibration
3760 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3761 if (mRawPointerAxes.orientation.valid) {
3762 if (mRawPointerAxes.orientation.maxValue > 0) {
3763 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3764 } else if (mRawPointerAxes.orientation.minValue < 0) {
3765 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3766 } else {
3767 mOrientationScale = 0;
3768 }
3769 }
3770 }
3771
3772 mOrientedRanges.haveOrientation = true;
3773
3774 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3775 mOrientedRanges.orientation.source = mSource;
3776 mOrientedRanges.orientation.min = -M_PI_2;
3777 mOrientedRanges.orientation.max = M_PI_2;
3778 mOrientedRanges.orientation.flat = 0;
3779 mOrientedRanges.orientation.fuzz = 0;
3780 mOrientedRanges.orientation.resolution = 0;
3781 }
3782
3783 // Distance
3784 mDistanceScale = 0;
3785 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3786 if (mCalibration.distanceCalibration
3787 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3788 if (mCalibration.haveDistanceScale) {
3789 mDistanceScale = mCalibration.distanceScale;
3790 } else {
3791 mDistanceScale = 1.0f;
3792 }
3793 }
3794
3795 mOrientedRanges.haveDistance = true;
3796
3797 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3798 mOrientedRanges.distance.source = mSource;
3799 mOrientedRanges.distance.min =
3800 mRawPointerAxes.distance.minValue * mDistanceScale;
3801 mOrientedRanges.distance.max =
3802 mRawPointerAxes.distance.maxValue * mDistanceScale;
3803 mOrientedRanges.distance.flat = 0;
3804 mOrientedRanges.distance.fuzz =
3805 mRawPointerAxes.distance.fuzz * mDistanceScale;
3806 mOrientedRanges.distance.resolution = 0;
3807 }
3808
3809 // Compute oriented precision, scales and ranges.
3810 // Note that the maximum value reported is an inclusive maximum value so it is one
3811 // unit less than the total width or height of surface.
3812 switch (mSurfaceOrientation) {
3813 case DISPLAY_ORIENTATION_90:
3814 case DISPLAY_ORIENTATION_270:
3815 mOrientedXPrecision = mYPrecision;
3816 mOrientedYPrecision = mXPrecision;
3817
3818 mOrientedRanges.x.min = mYTranslate;
3819 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3820 mOrientedRanges.x.flat = 0;
3821 mOrientedRanges.x.fuzz = 0;
3822 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3823
3824 mOrientedRanges.y.min = mXTranslate;
3825 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3826 mOrientedRanges.y.flat = 0;
3827 mOrientedRanges.y.fuzz = 0;
3828 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3829 break;
3830
3831 default:
3832 mOrientedXPrecision = mXPrecision;
3833 mOrientedYPrecision = mYPrecision;
3834
3835 mOrientedRanges.x.min = mXTranslate;
3836 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3837 mOrientedRanges.x.flat = 0;
3838 mOrientedRanges.x.fuzz = 0;
3839 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3840
3841 mOrientedRanges.y.min = mYTranslate;
3842 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3843 mOrientedRanges.y.flat = 0;
3844 mOrientedRanges.y.fuzz = 0;
3845 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3846 break;
3847 }
3848
Jason Gerecke71b16e82014-03-10 09:47:59 -07003849 // Location
3850 updateAffineTransformation();
3851
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 if (mDeviceMode == DEVICE_MODE_POINTER) {
3853 // Compute pointer gesture detection parameters.
3854 float rawDiagonal = hypotf(rawWidth, rawHeight);
3855 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3856
3857 // Scale movements such that one whole swipe of the touch pad covers a
3858 // given area relative to the diagonal size of the display when no acceleration
3859 // is applied.
3860 // Assume that the touch pad has a square aspect ratio such that movements in
3861 // X and Y of the same number of raw units cover the same physical distance.
3862 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3863 * displayDiagonal / rawDiagonal;
3864 mPointerYMovementScale = mPointerXMovementScale;
3865
3866 // Scale zooms to cover a smaller range of the display than movements do.
3867 // This value determines the area around the pointer that is affected by freeform
3868 // pointer gestures.
3869 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3870 * displayDiagonal / rawDiagonal;
3871 mPointerYZoomScale = mPointerXZoomScale;
3872
3873 // Max width between pointers to detect a swipe gesture is more than some fraction
3874 // of the diagonal axis of the touch pad. Touches that are wider than this are
3875 // translated into freeform gestures.
3876 mPointerGestureMaxSwipeWidth =
3877 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3878
3879 // Abort current pointer usages because the state has changed.
3880 abortPointerUsage(when, 0 /*policyFlags*/);
3881 }
3882
3883 // Inform the dispatcher about the changes.
3884 *outResetNeeded = true;
3885 bumpGeneration();
3886 }
3887}
3888
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003889void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003890 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003891 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3892 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3893 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3894 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003895 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3896 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3897 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3898 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003899 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900}
3901
3902void TouchInputMapper::configureVirtualKeys() {
3903 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3904 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3905
3906 mVirtualKeys.clear();
3907
3908 if (virtualKeyDefinitions.size() == 0) {
3909 return;
3910 }
3911
3912 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3913
3914 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3915 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003916 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3917 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918
3919 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3920 const VirtualKeyDefinition& virtualKeyDefinition =
3921 virtualKeyDefinitions[i];
3922
3923 mVirtualKeys.add();
3924 VirtualKey& virtualKey = mVirtualKeys.editTop();
3925
3926 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3927 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003928 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003930 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3931 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3933 virtualKey.scanCode);
3934 mVirtualKeys.pop(); // drop the key
3935 continue;
3936 }
3937
3938 virtualKey.keyCode = keyCode;
3939 virtualKey.flags = flags;
3940
3941 // convert the key definition's display coordinates into touch coordinates for a hit box
3942 int32_t halfWidth = virtualKeyDefinition.width / 2;
3943 int32_t halfHeight = virtualKeyDefinition.height / 2;
3944
3945 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3946 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3947 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3948 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3949 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3950 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3951 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3952 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3953 }
3954}
3955
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003956void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003958 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
3960 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3961 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003962 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3964 i, virtualKey.scanCode, virtualKey.keyCode,
3965 virtualKey.hitLeft, virtualKey.hitRight,
3966 virtualKey.hitTop, virtualKey.hitBottom);
3967 }
3968 }
3969}
3970
3971void TouchInputMapper::parseCalibration() {
3972 const PropertyMap& in = getDevice()->getConfiguration();
3973 Calibration& out = mCalibration;
3974
3975 // Size
3976 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3977 String8 sizeCalibrationString;
3978 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3979 if (sizeCalibrationString == "none") {
3980 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3981 } else if (sizeCalibrationString == "geometric") {
3982 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3983 } else if (sizeCalibrationString == "diameter") {
3984 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3985 } else if (sizeCalibrationString == "box") {
3986 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3987 } else if (sizeCalibrationString == "area") {
3988 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3989 } else if (sizeCalibrationString != "default") {
3990 ALOGW("Invalid value for touch.size.calibration: '%s'",
3991 sizeCalibrationString.string());
3992 }
3993 }
3994
3995 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3996 out.sizeScale);
3997 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3998 out.sizeBias);
3999 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4000 out.sizeIsSummed);
4001
4002 // Pressure
4003 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4004 String8 pressureCalibrationString;
4005 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4006 if (pressureCalibrationString == "none") {
4007 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4008 } else if (pressureCalibrationString == "physical") {
4009 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4010 } else if (pressureCalibrationString == "amplitude") {
4011 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4012 } else if (pressureCalibrationString != "default") {
4013 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4014 pressureCalibrationString.string());
4015 }
4016 }
4017
4018 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4019 out.pressureScale);
4020
4021 // Orientation
4022 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4023 String8 orientationCalibrationString;
4024 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4025 if (orientationCalibrationString == "none") {
4026 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4027 } else if (orientationCalibrationString == "interpolated") {
4028 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4029 } else if (orientationCalibrationString == "vector") {
4030 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4031 } else if (orientationCalibrationString != "default") {
4032 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4033 orientationCalibrationString.string());
4034 }
4035 }
4036
4037 // Distance
4038 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4039 String8 distanceCalibrationString;
4040 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4041 if (distanceCalibrationString == "none") {
4042 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4043 } else if (distanceCalibrationString == "scaled") {
4044 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4045 } else if (distanceCalibrationString != "default") {
4046 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4047 distanceCalibrationString.string());
4048 }
4049 }
4050
4051 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4052 out.distanceScale);
4053
4054 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4055 String8 coverageCalibrationString;
4056 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4057 if (coverageCalibrationString == "none") {
4058 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4059 } else if (coverageCalibrationString == "box") {
4060 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4061 } else if (coverageCalibrationString != "default") {
4062 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4063 coverageCalibrationString.string());
4064 }
4065 }
4066}
4067
4068void TouchInputMapper::resolveCalibration() {
4069 // Size
4070 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4071 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4072 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4073 }
4074 } else {
4075 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4076 }
4077
4078 // Pressure
4079 if (mRawPointerAxes.pressure.valid) {
4080 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4081 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4082 }
4083 } else {
4084 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4085 }
4086
4087 // Orientation
4088 if (mRawPointerAxes.orientation.valid) {
4089 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4090 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4091 }
4092 } else {
4093 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4094 }
4095
4096 // Distance
4097 if (mRawPointerAxes.distance.valid) {
4098 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4099 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4100 }
4101 } else {
4102 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4103 }
4104
4105 // Coverage
4106 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4107 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4108 }
4109}
4110
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004111void TouchInputMapper::dumpCalibration(std::string& dump) {
4112 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113
4114 // Size
4115 switch (mCalibration.sizeCalibration) {
4116 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004117 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 break;
4119 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004120 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 break;
4122 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004123 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 break;
4125 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004126 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 break;
4128 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004129 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 break;
4131 default:
4132 ALOG_ASSERT(false);
4133 }
4134
4135 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004136 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 mCalibration.sizeScale);
4138 }
4139
4140 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004141 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 mCalibration.sizeBias);
4143 }
4144
4145 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004146 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 toString(mCalibration.sizeIsSummed));
4148 }
4149
4150 // Pressure
4151 switch (mCalibration.pressureCalibration) {
4152 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 break;
4155 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 break;
4158 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 break;
4161 default:
4162 ALOG_ASSERT(false);
4163 }
4164
4165 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004166 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 mCalibration.pressureScale);
4168 }
4169
4170 // Orientation
4171 switch (mCalibration.orientationCalibration) {
4172 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004173 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 break;
4175 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004176 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 break;
4178 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004179 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 break;
4181 default:
4182 ALOG_ASSERT(false);
4183 }
4184
4185 // Distance
4186 switch (mCalibration.distanceCalibration) {
4187 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004188 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 break;
4190 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 break;
4193 default:
4194 ALOG_ASSERT(false);
4195 }
4196
4197 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004198 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 mCalibration.distanceScale);
4200 }
4201
4202 switch (mCalibration.coverageCalibration) {
4203 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 break;
4206 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 break;
4209 default:
4210 ALOG_ASSERT(false);
4211 }
4212}
4213
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004214void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4215 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004216
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004217 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4218 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4219 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4220 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4221 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4222 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004223}
4224
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004225void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004226 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4227 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004228}
4229
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230void TouchInputMapper::reset(nsecs_t when) {
4231 mCursorButtonAccumulator.reset(getDevice());
4232 mCursorScrollAccumulator.reset(getDevice());
4233 mTouchButtonAccumulator.reset(getDevice());
4234
4235 mPointerVelocityControl.reset();
4236 mWheelXVelocityControl.reset();
4237 mWheelYVelocityControl.reset();
4238
Michael Wright842500e2015-03-13 17:32:02 -07004239 mRawStatesPending.clear();
4240 mCurrentRawState.clear();
4241 mCurrentCookedState.clear();
4242 mLastRawState.clear();
4243 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 mPointerUsage = POINTER_USAGE_NONE;
4245 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004246 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004247 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 mDownTime = 0;
4249
4250 mCurrentVirtualKey.down = false;
4251
4252 mPointerGesture.reset();
4253 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004254 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255
Yi Kong9b14ac62018-07-17 13:48:38 -07004256 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4258 mPointerController->clearSpots();
4259 }
4260
4261 InputMapper::reset(when);
4262}
4263
Michael Wright842500e2015-03-13 17:32:02 -07004264void TouchInputMapper::resetExternalStylus() {
4265 mExternalStylusState.clear();
4266 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004267 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004268 mExternalStylusDataPending = false;
4269}
4270
Michael Wright43fd19f2015-04-21 19:02:58 +01004271void TouchInputMapper::clearStylusDataPendingFlags() {
4272 mExternalStylusDataPending = false;
4273 mExternalStylusFusionTimeout = LLONG_MAX;
4274}
4275
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276void TouchInputMapper::process(const RawEvent* rawEvent) {
4277 mCursorButtonAccumulator.process(rawEvent);
4278 mCursorScrollAccumulator.process(rawEvent);
4279 mTouchButtonAccumulator.process(rawEvent);
4280
4281 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4282 sync(rawEvent->when);
4283 }
4284}
4285
4286void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004287 const RawState* last = mRawStatesPending.isEmpty() ?
4288 &mCurrentRawState : &mRawStatesPending.top();
4289
4290 // Push a new state.
4291 mRawStatesPending.push();
4292 RawState* next = &mRawStatesPending.editTop();
4293 next->clear();
4294 next->when = when;
4295
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004297 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 | mCursorButtonAccumulator.getButtonState();
4299
Michael Wright842500e2015-03-13 17:32:02 -07004300 // Sync scroll
4301 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4302 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 mCursorScrollAccumulator.finishSync();
4304
Michael Wright842500e2015-03-13 17:32:02 -07004305 // Sync touch
4306 syncTouch(when, next);
4307
4308 // Assign pointer ids.
4309 if (!mHavePointerIds) {
4310 assignPointerIds(last, next);
4311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312
4313#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004314 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4315 "hovering ids 0x%08x -> 0x%08x",
4316 last->rawPointerData.pointerCount,
4317 next->rawPointerData.pointerCount,
4318 last->rawPointerData.touchingIdBits.value,
4319 next->rawPointerData.touchingIdBits.value,
4320 last->rawPointerData.hoveringIdBits.value,
4321 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322#endif
4323
Michael Wright842500e2015-03-13 17:32:02 -07004324 processRawTouches(false /*timeout*/);
4325}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
Michael Wright842500e2015-03-13 17:32:02 -07004327void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4329 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004330 mCurrentRawState.clear();
4331 mRawStatesPending.clear();
4332 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 }
4334
Michael Wright842500e2015-03-13 17:32:02 -07004335 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4336 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4337 // touching the current state will only observe the events that have been dispatched to the
4338 // rest of the pipeline.
4339 const size_t N = mRawStatesPending.size();
4340 size_t count;
4341 for(count = 0; count < N; count++) {
4342 const RawState& next = mRawStatesPending[count];
4343
4344 // A failure to assign the stylus id means that we're waiting on stylus data
4345 // and so should defer the rest of the pipeline.
4346 if (assignExternalStylusId(next, timeout)) {
4347 break;
4348 }
4349
4350 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004351 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004352 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004353 if (mCurrentRawState.when < mLastRawState.when) {
4354 mCurrentRawState.when = mLastRawState.when;
4355 }
Michael Wright842500e2015-03-13 17:32:02 -07004356 cookAndDispatch(mCurrentRawState.when);
4357 }
4358 if (count != 0) {
4359 mRawStatesPending.removeItemsAt(0, count);
4360 }
4361
Michael Wright842500e2015-03-13 17:32:02 -07004362 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004363 if (timeout) {
4364 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4365 clearStylusDataPendingFlags();
4366 mCurrentRawState.copyFrom(mLastRawState);
4367#if DEBUG_STYLUS_FUSION
4368 ALOGD("Timeout expired, synthesizing event with new stylus data");
4369#endif
4370 cookAndDispatch(when);
4371 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4372 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4373 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4374 }
Michael Wright842500e2015-03-13 17:32:02 -07004375 }
4376}
4377
4378void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4379 // Always start with a clean state.
4380 mCurrentCookedState.clear();
4381
4382 // Apply stylus buttons to current raw state.
4383 applyExternalStylusButtonState(when);
4384
4385 // Handle policy on initial down or hover events.
4386 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4387 && mCurrentRawState.rawPointerData.pointerCount != 0;
4388
4389 uint32_t policyFlags = 0;
4390 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4391 if (initialDown || buttonsPressed) {
4392 // If this is a touch screen, hide the pointer on an initial down.
4393 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4394 getContext()->fadePointer();
4395 }
4396
4397 if (mParameters.wake) {
4398 policyFlags |= POLICY_FLAG_WAKE;
4399 }
4400 }
4401
4402 // Consume raw off-screen touches before cooking pointer data.
4403 // If touches are consumed, subsequent code will not receive any pointer data.
4404 if (consumeRawTouches(when, policyFlags)) {
4405 mCurrentRawState.rawPointerData.clear();
4406 }
4407
4408 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4409 // with cooked pointer data that has the same ids and indices as the raw data.
4410 // The following code can use either the raw or cooked data, as needed.
4411 cookPointerData();
4412
4413 // Apply stylus pressure to current cooked state.
4414 applyExternalStylusTouchState(when);
4415
4416 // Synthesize key down from raw buttons if needed.
4417 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004418 mViewport.displayId, policyFlags,
4419 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004420
4421 // Dispatch the touches either directly or by translation through a pointer on screen.
4422 if (mDeviceMode == DEVICE_MODE_POINTER) {
4423 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4424 !idBits.isEmpty(); ) {
4425 uint32_t id = idBits.clearFirstMarkedBit();
4426 const RawPointerData::Pointer& pointer =
4427 mCurrentRawState.rawPointerData.pointerForId(id);
4428 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4429 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4430 mCurrentCookedState.stylusIdBits.markBit(id);
4431 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4432 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4433 mCurrentCookedState.fingerIdBits.markBit(id);
4434 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4435 mCurrentCookedState.mouseIdBits.markBit(id);
4436 }
4437 }
4438 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4439 !idBits.isEmpty(); ) {
4440 uint32_t id = idBits.clearFirstMarkedBit();
4441 const RawPointerData::Pointer& pointer =
4442 mCurrentRawState.rawPointerData.pointerForId(id);
4443 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4444 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4445 mCurrentCookedState.stylusIdBits.markBit(id);
4446 }
4447 }
4448
4449 // Stylus takes precedence over all tools, then mouse, then finger.
4450 PointerUsage pointerUsage = mPointerUsage;
4451 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4452 mCurrentCookedState.mouseIdBits.clear();
4453 mCurrentCookedState.fingerIdBits.clear();
4454 pointerUsage = POINTER_USAGE_STYLUS;
4455 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4456 mCurrentCookedState.fingerIdBits.clear();
4457 pointerUsage = POINTER_USAGE_MOUSE;
4458 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4459 isPointerDown(mCurrentRawState.buttonState)) {
4460 pointerUsage = POINTER_USAGE_GESTURES;
4461 }
4462
4463 dispatchPointerUsage(when, policyFlags, pointerUsage);
4464 } else {
4465 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004466 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004467 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4468 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4469
4470 mPointerController->setButtonState(mCurrentRawState.buttonState);
4471 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4472 mCurrentCookedState.cookedPointerData.idToIndex,
4473 mCurrentCookedState.cookedPointerData.touchingIdBits);
4474 }
4475
Michael Wright8e812822015-06-22 16:18:21 +01004476 if (!mCurrentMotionAborted) {
4477 dispatchButtonRelease(when, policyFlags);
4478 dispatchHoverExit(when, policyFlags);
4479 dispatchTouches(when, policyFlags);
4480 dispatchHoverEnterAndMove(when, policyFlags);
4481 dispatchButtonPress(when, policyFlags);
4482 }
4483
4484 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4485 mCurrentMotionAborted = false;
4486 }
Michael Wright842500e2015-03-13 17:32:02 -07004487 }
4488
4489 // Synthesize key up from raw buttons if needed.
4490 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004491 mViewport.displayId, policyFlags,
4492 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493
4494 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004495 mCurrentRawState.rawVScroll = 0;
4496 mCurrentRawState.rawHScroll = 0;
4497
4498 // Copy current touch to last touch in preparation for the next cycle.
4499 mLastRawState.copyFrom(mCurrentRawState);
4500 mLastCookedState.copyFrom(mCurrentCookedState);
4501}
4502
4503void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004504 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004505 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4506 }
4507}
4508
4509void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004510 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4511 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004512
Michael Wright53dca3a2015-04-23 17:39:53 +01004513 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4514 float pressure = mExternalStylusState.pressure;
4515 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4516 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4517 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4518 }
4519 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4520 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4521
4522 PointerProperties& properties =
4523 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004524 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4525 properties.toolType = mExternalStylusState.toolType;
4526 }
4527 }
4528}
4529
4530bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4531 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4532 return false;
4533 }
4534
4535 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4536 && state.rawPointerData.pointerCount != 0;
4537 if (initialDown) {
4538 if (mExternalStylusState.pressure != 0.0f) {
4539#if DEBUG_STYLUS_FUSION
4540 ALOGD("Have both stylus and touch data, beginning fusion");
4541#endif
4542 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4543 } else if (timeout) {
4544#if DEBUG_STYLUS_FUSION
4545 ALOGD("Timeout expired, assuming touch is not a stylus.");
4546#endif
4547 resetExternalStylus();
4548 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004549 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4550 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004551 }
4552#if DEBUG_STYLUS_FUSION
4553 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004554 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004555#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004556 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004557 return true;
4558 }
4559 }
4560
4561 // Check if the stylus pointer has gone up.
4562 if (mExternalStylusId != -1 &&
4563 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4564#if DEBUG_STYLUS_FUSION
4565 ALOGD("Stylus pointer is going up");
4566#endif
4567 mExternalStylusId = -1;
4568 }
4569
4570 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571}
4572
4573void TouchInputMapper::timeoutExpired(nsecs_t when) {
4574 if (mDeviceMode == DEVICE_MODE_POINTER) {
4575 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4576 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4577 }
Michael Wright842500e2015-03-13 17:32:02 -07004578 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004579 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004580 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004581 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4582 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004583 }
4584 }
4585}
4586
4587void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004588 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004589 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004590 // We're either in the middle of a fused stream of data or we're waiting on data before
4591 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4592 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004593 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004594 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 }
4596}
4597
4598bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4599 // Check for release of a virtual key.
4600 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004601 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602 // Pointer went up while virtual key was down.
4603 mCurrentVirtualKey.down = false;
4604 if (!mCurrentVirtualKey.ignored) {
4605#if DEBUG_VIRTUAL_KEYS
4606 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4607 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4608#endif
4609 dispatchVirtualKey(when, policyFlags,
4610 AKEY_EVENT_ACTION_UP,
4611 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4612 }
4613 return true;
4614 }
4615
Michael Wright842500e2015-03-13 17:32:02 -07004616 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4617 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4618 const RawPointerData::Pointer& pointer =
4619 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4621 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4622 // Pointer is still within the space of the virtual key.
4623 return true;
4624 }
4625 }
4626
4627 // Pointer left virtual key area or another pointer also went down.
4628 // Send key cancellation but do not consume the touch yet.
4629 // This is useful when the user swipes through from the virtual key area
4630 // into the main display surface.
4631 mCurrentVirtualKey.down = false;
4632 if (!mCurrentVirtualKey.ignored) {
4633#if DEBUG_VIRTUAL_KEYS
4634 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4635 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4636#endif
4637 dispatchVirtualKey(when, policyFlags,
4638 AKEY_EVENT_ACTION_UP,
4639 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4640 | AKEY_EVENT_FLAG_CANCELED);
4641 }
4642 }
4643
Michael Wright842500e2015-03-13 17:32:02 -07004644 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4645 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004647 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4648 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4650 // If exactly one pointer went down, check for virtual key hit.
4651 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004652 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4654 if (virtualKey) {
4655 mCurrentVirtualKey.down = true;
4656 mCurrentVirtualKey.downTime = when;
4657 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4658 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4659 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4660 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4661
4662 if (!mCurrentVirtualKey.ignored) {
4663#if DEBUG_VIRTUAL_KEYS
4664 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4665 mCurrentVirtualKey.keyCode,
4666 mCurrentVirtualKey.scanCode);
4667#endif
4668 dispatchVirtualKey(when, policyFlags,
4669 AKEY_EVENT_ACTION_DOWN,
4670 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4671 }
4672 }
4673 }
4674 return true;
4675 }
4676 }
4677
4678 // Disable all virtual key touches that happen within a short time interval of the
4679 // most recent touch within the screen area. The idea is to filter out stray
4680 // virtual key presses when interacting with the touch screen.
4681 //
4682 // Problems we're trying to solve:
4683 //
4684 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4685 // virtual key area that is implemented by a separate touch panel and accidentally
4686 // triggers a virtual key.
4687 //
4688 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4689 // area and accidentally triggers a virtual key. This often happens when virtual keys
4690 // are layed out below the screen near to where the on screen keyboard's space bar
4691 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004692 if (mConfig.virtualKeyQuietTime > 0 &&
4693 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4695 }
4696 return false;
4697}
4698
4699void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4700 int32_t keyEventAction, int32_t keyEventFlags) {
4701 int32_t keyCode = mCurrentVirtualKey.keyCode;
4702 int32_t scanCode = mCurrentVirtualKey.scanCode;
4703 nsecs_t downTime = mCurrentVirtualKey.downTime;
4704 int32_t metaState = mContext->getGlobalMetaState();
4705 policyFlags |= POLICY_FLAG_VIRTUAL;
4706
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004707 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
4708 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 getListener()->notifyKey(&args);
4710}
4711
Michael Wright8e812822015-06-22 16:18:21 +01004712void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4713 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4714 if (!currentIdBits.isEmpty()) {
4715 int32_t metaState = getContext()->getGlobalMetaState();
4716 int32_t buttonState = mCurrentCookedState.buttonState;
4717 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4718 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004719 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004720 mCurrentCookedState.cookedPointerData.pointerProperties,
4721 mCurrentCookedState.cookedPointerData.pointerCoords,
4722 mCurrentCookedState.cookedPointerData.idToIndex,
4723 currentIdBits, -1,
4724 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4725 mCurrentMotionAborted = true;
4726 }
4727}
4728
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004730 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4731 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004733 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734
4735 if (currentIdBits == lastIdBits) {
4736 if (!currentIdBits.isEmpty()) {
4737 // No pointer id changes so this is a move event.
4738 // The listener takes care of batching moves so we don't have to deal with that here.
4739 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004740 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004742 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004743 mCurrentCookedState.cookedPointerData.pointerProperties,
4744 mCurrentCookedState.cookedPointerData.pointerCoords,
4745 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 currentIdBits, -1,
4747 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4748 }
4749 } else {
4750 // There may be pointers going up and pointers going down and pointers moving
4751 // all at the same time.
4752 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4753 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4754 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4755 BitSet32 dispatchedIdBits(lastIdBits.value);
4756
4757 // Update last coordinates of pointers that have moved so that we observe the new
4758 // pointer positions at the same time as other pointers that have just gone up.
4759 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004760 mCurrentCookedState.cookedPointerData.pointerProperties,
4761 mCurrentCookedState.cookedPointerData.pointerCoords,
4762 mCurrentCookedState.cookedPointerData.idToIndex,
4763 mLastCookedState.cookedPointerData.pointerProperties,
4764 mLastCookedState.cookedPointerData.pointerCoords,
4765 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004767 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 moveNeeded = true;
4769 }
4770
4771 // Dispatch pointer up events.
4772 while (!upIdBits.isEmpty()) {
4773 uint32_t upId = upIdBits.clearFirstMarkedBit();
4774
4775 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004776 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004777 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004778 mLastCookedState.cookedPointerData.pointerProperties,
4779 mLastCookedState.cookedPointerData.pointerCoords,
4780 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004781 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 dispatchedIdBits.clearBit(upId);
4783 }
4784
4785 // Dispatch move events if any of the remaining pointers moved from their old locations.
4786 // Although applications receive new locations as part of individual pointer up
4787 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004788 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4790 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004791 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004792 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004793 mCurrentCookedState.cookedPointerData.pointerProperties,
4794 mCurrentCookedState.cookedPointerData.pointerCoords,
4795 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004796 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 }
4798
4799 // Dispatch pointer down events using the new pointer locations.
4800 while (!downIdBits.isEmpty()) {
4801 uint32_t downId = downIdBits.clearFirstMarkedBit();
4802 dispatchedIdBits.markBit(downId);
4803
4804 if (dispatchedIdBits.count() == 1) {
4805 // First pointer is going down. Set down time.
4806 mDownTime = when;
4807 }
4808
4809 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004810 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004811 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004812 mCurrentCookedState.cookedPointerData.pointerProperties,
4813 mCurrentCookedState.cookedPointerData.pointerCoords,
4814 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004815 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 }
4817 }
4818}
4819
4820void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4821 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004822 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4823 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 int32_t metaState = getContext()->getGlobalMetaState();
4825 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004826 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004827 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004828 mLastCookedState.cookedPointerData.pointerProperties,
4829 mLastCookedState.cookedPointerData.pointerCoords,
4830 mLastCookedState.cookedPointerData.idToIndex,
4831 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4833 mSentHoverEnter = false;
4834 }
4835}
4836
4837void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004838 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4839 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 int32_t metaState = getContext()->getGlobalMetaState();
4841 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004842 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004843 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004844 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004845 mCurrentCookedState.cookedPointerData.pointerProperties,
4846 mCurrentCookedState.cookedPointerData.pointerCoords,
4847 mCurrentCookedState.cookedPointerData.idToIndex,
4848 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4850 mSentHoverEnter = true;
4851 }
4852
4853 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004854 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004855 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004856 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004857 mCurrentCookedState.cookedPointerData.pointerProperties,
4858 mCurrentCookedState.cookedPointerData.pointerCoords,
4859 mCurrentCookedState.cookedPointerData.idToIndex,
4860 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4862 }
4863}
4864
Michael Wright7b159c92015-05-14 14:48:03 +01004865void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4866 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4867 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4868 const int32_t metaState = getContext()->getGlobalMetaState();
4869 int32_t buttonState = mLastCookedState.buttonState;
4870 while (!releasedButtons.isEmpty()) {
4871 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4872 buttonState &= ~actionButton;
4873 dispatchMotion(when, policyFlags, mSource,
4874 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4875 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004876 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004877 mCurrentCookedState.cookedPointerData.pointerProperties,
4878 mCurrentCookedState.cookedPointerData.pointerCoords,
4879 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4880 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4881 }
4882}
4883
4884void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4885 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4886 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4887 const int32_t metaState = getContext()->getGlobalMetaState();
4888 int32_t buttonState = mLastCookedState.buttonState;
4889 while (!pressedButtons.isEmpty()) {
4890 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4891 buttonState |= actionButton;
4892 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4893 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004894 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004895 mCurrentCookedState.cookedPointerData.pointerProperties,
4896 mCurrentCookedState.cookedPointerData.pointerCoords,
4897 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4898 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4899 }
4900}
4901
4902const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4903 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4904 return cookedPointerData.touchingIdBits;
4905 }
4906 return cookedPointerData.hoveringIdBits;
4907}
4908
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004910 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911
Michael Wright842500e2015-03-13 17:32:02 -07004912 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004913 mCurrentCookedState.deviceTimestamp =
4914 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004915 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4916 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4917 mCurrentRawState.rawPointerData.hoveringIdBits;
4918 mCurrentCookedState.cookedPointerData.touchingIdBits =
4919 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920
Michael Wright7b159c92015-05-14 14:48:03 +01004921 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4922 mCurrentCookedState.buttonState = 0;
4923 } else {
4924 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4925 }
4926
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 // Walk through the the active pointers and map device coordinates onto
4928 // surface coordinates and adjust for display orientation.
4929 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004930 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931
4932 // Size
4933 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4934 switch (mCalibration.sizeCalibration) {
4935 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4936 case Calibration::SIZE_CALIBRATION_DIAMETER:
4937 case Calibration::SIZE_CALIBRATION_BOX:
4938 case Calibration::SIZE_CALIBRATION_AREA:
4939 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4940 touchMajor = in.touchMajor;
4941 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4942 toolMajor = in.toolMajor;
4943 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4944 size = mRawPointerAxes.touchMinor.valid
4945 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4946 } else if (mRawPointerAxes.touchMajor.valid) {
4947 toolMajor = touchMajor = in.touchMajor;
4948 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4949 ? in.touchMinor : in.touchMajor;
4950 size = mRawPointerAxes.touchMinor.valid
4951 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4952 } else if (mRawPointerAxes.toolMajor.valid) {
4953 touchMajor = toolMajor = in.toolMajor;
4954 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4955 ? in.toolMinor : in.toolMajor;
4956 size = mRawPointerAxes.toolMinor.valid
4957 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4958 } else {
4959 ALOG_ASSERT(false, "No touch or tool axes. "
4960 "Size calibration should have been resolved to NONE.");
4961 touchMajor = 0;
4962 touchMinor = 0;
4963 toolMajor = 0;
4964 toolMinor = 0;
4965 size = 0;
4966 }
4967
4968 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004969 uint32_t touchingCount =
4970 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 if (touchingCount > 1) {
4972 touchMajor /= touchingCount;
4973 touchMinor /= touchingCount;
4974 toolMajor /= touchingCount;
4975 toolMinor /= touchingCount;
4976 size /= touchingCount;
4977 }
4978 }
4979
4980 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4981 touchMajor *= mGeometricScale;
4982 touchMinor *= mGeometricScale;
4983 toolMajor *= mGeometricScale;
4984 toolMinor *= mGeometricScale;
4985 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4986 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4987 touchMinor = touchMajor;
4988 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4989 toolMinor = toolMajor;
4990 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4991 touchMinor = touchMajor;
4992 toolMinor = toolMajor;
4993 }
4994
4995 mCalibration.applySizeScaleAndBias(&touchMajor);
4996 mCalibration.applySizeScaleAndBias(&touchMinor);
4997 mCalibration.applySizeScaleAndBias(&toolMajor);
4998 mCalibration.applySizeScaleAndBias(&toolMinor);
4999 size *= mSizeScale;
5000 break;
5001 default:
5002 touchMajor = 0;
5003 touchMinor = 0;
5004 toolMajor = 0;
5005 toolMinor = 0;
5006 size = 0;
5007 break;
5008 }
5009
5010 // Pressure
5011 float pressure;
5012 switch (mCalibration.pressureCalibration) {
5013 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5014 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5015 pressure = in.pressure * mPressureScale;
5016 break;
5017 default:
5018 pressure = in.isHovering ? 0 : 1;
5019 break;
5020 }
5021
5022 // Tilt and Orientation
5023 float tilt;
5024 float orientation;
5025 if (mHaveTilt) {
5026 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5027 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5028 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5029 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5030 } else {
5031 tilt = 0;
5032
5033 switch (mCalibration.orientationCalibration) {
5034 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5035 orientation = in.orientation * mOrientationScale;
5036 break;
5037 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5038 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5039 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5040 if (c1 != 0 || c2 != 0) {
5041 orientation = atan2f(c1, c2) * 0.5f;
5042 float confidence = hypotf(c1, c2);
5043 float scale = 1.0f + confidence / 16.0f;
5044 touchMajor *= scale;
5045 touchMinor /= scale;
5046 toolMajor *= scale;
5047 toolMinor /= scale;
5048 } else {
5049 orientation = 0;
5050 }
5051 break;
5052 }
5053 default:
5054 orientation = 0;
5055 }
5056 }
5057
5058 // Distance
5059 float distance;
5060 switch (mCalibration.distanceCalibration) {
5061 case Calibration::DISTANCE_CALIBRATION_SCALED:
5062 distance = in.distance * mDistanceScale;
5063 break;
5064 default:
5065 distance = 0;
5066 }
5067
5068 // Coverage
5069 int32_t rawLeft, rawTop, rawRight, rawBottom;
5070 switch (mCalibration.coverageCalibration) {
5071 case Calibration::COVERAGE_CALIBRATION_BOX:
5072 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5073 rawRight = in.toolMinor & 0x0000ffff;
5074 rawBottom = in.toolMajor & 0x0000ffff;
5075 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5076 break;
5077 default:
5078 rawLeft = rawTop = rawRight = rawBottom = 0;
5079 break;
5080 }
5081
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005082 // Adjust X,Y coords for device calibration
5083 // TODO: Adjust coverage coords?
5084 float xTransformed = in.x, yTransformed = in.y;
5085 mAffineTransform.applyTo(xTransformed, yTransformed);
5086
5087 // Adjust X, Y, and coverage coords for surface orientation.
5088 float x, y;
5089 float left, top, right, bottom;
5090
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 switch (mSurfaceOrientation) {
5092 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005093 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5094 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5096 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5097 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5098 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5099 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005100 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5102 }
5103 break;
5104 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005105 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005106 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005107 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5108 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5110 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5111 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005112 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5114 }
5115 break;
5116 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005117 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005118 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005119 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5120 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5122 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5123 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005124 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5126 }
5127 break;
5128 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005129 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5130 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5132 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5133 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5134 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5135 break;
5136 }
5137
5138 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005139 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 out.clear();
5141 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5142 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5143 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5144 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5145 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5146 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5147 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5148 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5149 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5150 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5151 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5152 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5153 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5154 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5155 } else {
5156 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5157 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5158 }
5159
5160 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005161 PointerProperties& properties =
5162 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 uint32_t id = in.id;
5164 properties.clear();
5165 properties.id = id;
5166 properties.toolType = in.toolType;
5167
5168 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005169 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 }
5171}
5172
5173void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5174 PointerUsage pointerUsage) {
5175 if (pointerUsage != mPointerUsage) {
5176 abortPointerUsage(when, policyFlags);
5177 mPointerUsage = pointerUsage;
5178 }
5179
5180 switch (mPointerUsage) {
5181 case POINTER_USAGE_GESTURES:
5182 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5183 break;
5184 case POINTER_USAGE_STYLUS:
5185 dispatchPointerStylus(when, policyFlags);
5186 break;
5187 case POINTER_USAGE_MOUSE:
5188 dispatchPointerMouse(when, policyFlags);
5189 break;
5190 default:
5191 break;
5192 }
5193}
5194
5195void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5196 switch (mPointerUsage) {
5197 case POINTER_USAGE_GESTURES:
5198 abortPointerGestures(when, policyFlags);
5199 break;
5200 case POINTER_USAGE_STYLUS:
5201 abortPointerStylus(when, policyFlags);
5202 break;
5203 case POINTER_USAGE_MOUSE:
5204 abortPointerMouse(when, policyFlags);
5205 break;
5206 default:
5207 break;
5208 }
5209
5210 mPointerUsage = POINTER_USAGE_NONE;
5211}
5212
5213void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5214 bool isTimeout) {
5215 // Update current gesture coordinates.
5216 bool cancelPreviousGesture, finishPreviousGesture;
5217 bool sendEvents = preparePointerGestures(when,
5218 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5219 if (!sendEvents) {
5220 return;
5221 }
5222 if (finishPreviousGesture) {
5223 cancelPreviousGesture = false;
5224 }
5225
5226 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005227 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5228 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 if (finishPreviousGesture || cancelPreviousGesture) {
5230 mPointerController->clearSpots();
5231 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005232
5233 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5234 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5235 mPointerGesture.currentGestureIdToIndex,
5236 mPointerGesture.currentGestureIdBits);
5237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238 } else {
5239 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5240 }
5241
5242 // Show or hide the pointer if needed.
5243 switch (mPointerGesture.currentGestureMode) {
5244 case PointerGesture::NEUTRAL:
5245 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005246 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5247 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 // Remind the user of where the pointer is after finishing a gesture with spots.
5249 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5250 }
5251 break;
5252 case PointerGesture::TAP:
5253 case PointerGesture::TAP_DRAG:
5254 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5255 case PointerGesture::HOVER:
5256 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005257 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 // Unfade the pointer when the current gesture manipulates the
5259 // area directly under the pointer.
5260 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5261 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 case PointerGesture::FREEFORM:
5263 // Fade the pointer when the current gesture manipulates a different
5264 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005265 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5267 } else {
5268 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5269 }
5270 break;
5271 }
5272
5273 // Send events!
5274 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005275 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276
5277 // Update last coordinates of pointers that have moved so that we observe the new
5278 // pointer positions at the same time as other pointers that have just gone up.
5279 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5280 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5281 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5282 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5283 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5284 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5285 bool moveNeeded = false;
5286 if (down && !cancelPreviousGesture && !finishPreviousGesture
5287 && !mPointerGesture.lastGestureIdBits.isEmpty()
5288 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5289 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5290 & mPointerGesture.lastGestureIdBits.value);
5291 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5292 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5293 mPointerGesture.lastGestureProperties,
5294 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5295 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005296 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 moveNeeded = true;
5298 }
5299 }
5300
5301 // Send motion events for all pointers that went up or were canceled.
5302 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5303 if (!dispatchedGestureIdBits.isEmpty()) {
5304 if (cancelPreviousGesture) {
5305 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005306 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005307 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 mPointerGesture.lastGestureProperties,
5309 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005310 dispatchedGestureIdBits, -1, 0,
5311 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312
5313 dispatchedGestureIdBits.clear();
5314 } else {
5315 BitSet32 upGestureIdBits;
5316 if (finishPreviousGesture) {
5317 upGestureIdBits = dispatchedGestureIdBits;
5318 } else {
5319 upGestureIdBits.value = dispatchedGestureIdBits.value
5320 & ~mPointerGesture.currentGestureIdBits.value;
5321 }
5322 while (!upGestureIdBits.isEmpty()) {
5323 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5324
5325 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005326 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005328 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 mPointerGesture.lastGestureProperties,
5330 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5331 dispatchedGestureIdBits, id,
5332 0, 0, mPointerGesture.downTime);
5333
5334 dispatchedGestureIdBits.clearBit(id);
5335 }
5336 }
5337 }
5338
5339 // Send motion events for all pointers that moved.
5340 if (moveNeeded) {
5341 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005342 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005343 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 mPointerGesture.currentGestureProperties,
5345 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5346 dispatchedGestureIdBits, -1,
5347 0, 0, mPointerGesture.downTime);
5348 }
5349
5350 // Send motion events for all pointers that went down.
5351 if (down) {
5352 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5353 & ~dispatchedGestureIdBits.value);
5354 while (!downGestureIdBits.isEmpty()) {
5355 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5356 dispatchedGestureIdBits.markBit(id);
5357
5358 if (dispatchedGestureIdBits.count() == 1) {
5359 mPointerGesture.downTime = when;
5360 }
5361
5362 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005363 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005364 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365 mPointerGesture.currentGestureProperties,
5366 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5367 dispatchedGestureIdBits, id,
5368 0, 0, mPointerGesture.downTime);
5369 }
5370 }
5371
5372 // Send motion events for hover.
5373 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5374 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005375 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005376 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 mPointerGesture.currentGestureProperties,
5378 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5379 mPointerGesture.currentGestureIdBits, -1,
5380 0, 0, mPointerGesture.downTime);
5381 } else if (dispatchedGestureIdBits.isEmpty()
5382 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5383 // Synthesize a hover move event after all pointers go up to indicate that
5384 // the pointer is hovering again even if the user is not currently touching
5385 // the touch pad. This ensures that a view will receive a fresh hover enter
5386 // event after a tap.
5387 float x, y;
5388 mPointerController->getPosition(&x, &y);
5389
5390 PointerProperties pointerProperties;
5391 pointerProperties.clear();
5392 pointerProperties.id = 0;
5393 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5394
5395 PointerCoords pointerCoords;
5396 pointerCoords.clear();
5397 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5398 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5399
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005400 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005401 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005403 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 0, 0, mPointerGesture.downTime);
5405 getListener()->notifyMotion(&args);
5406 }
5407
5408 // Update state.
5409 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5410 if (!down) {
5411 mPointerGesture.lastGestureIdBits.clear();
5412 } else {
5413 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5414 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5415 uint32_t id = idBits.clearFirstMarkedBit();
5416 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5417 mPointerGesture.lastGestureProperties[index].copyFrom(
5418 mPointerGesture.currentGestureProperties[index]);
5419 mPointerGesture.lastGestureCoords[index].copyFrom(
5420 mPointerGesture.currentGestureCoords[index]);
5421 mPointerGesture.lastGestureIdToIndex[id] = index;
5422 }
5423 }
5424}
5425
5426void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5427 // Cancel previously dispatches pointers.
5428 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5429 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005430 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005432 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005433 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434 mPointerGesture.lastGestureProperties,
5435 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5436 mPointerGesture.lastGestureIdBits, -1,
5437 0, 0, mPointerGesture.downTime);
5438 }
5439
5440 // Reset the current pointer gesture.
5441 mPointerGesture.reset();
5442 mPointerVelocityControl.reset();
5443
5444 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005445 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5447 mPointerController->clearSpots();
5448 }
5449}
5450
5451bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5452 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5453 *outCancelPreviousGesture = false;
5454 *outFinishPreviousGesture = false;
5455
5456 // Handle TAP timeout.
5457 if (isTimeout) {
5458#if DEBUG_GESTURES
5459 ALOGD("Gestures: Processing timeout");
5460#endif
5461
5462 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5463 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5464 // The tap/drag timeout has not yet expired.
5465 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5466 + mConfig.pointerGestureTapDragInterval);
5467 } else {
5468 // The tap is finished.
5469#if DEBUG_GESTURES
5470 ALOGD("Gestures: TAP finished");
5471#endif
5472 *outFinishPreviousGesture = true;
5473
5474 mPointerGesture.activeGestureId = -1;
5475 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5476 mPointerGesture.currentGestureIdBits.clear();
5477
5478 mPointerVelocityControl.reset();
5479 return true;
5480 }
5481 }
5482
5483 // We did not handle this timeout.
5484 return false;
5485 }
5486
Michael Wright842500e2015-03-13 17:32:02 -07005487 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5488 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005489
5490 // Update the velocity tracker.
5491 {
5492 VelocityTracker::Position positions[MAX_POINTERS];
5493 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005494 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005496 const RawPointerData::Pointer& pointer =
5497 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 positions[count].x = pointer.x * mPointerXMovementScale;
5499 positions[count].y = pointer.y * mPointerYMovementScale;
5500 }
5501 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005502 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503 }
5504
5505 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5506 // to NEUTRAL, then we should not generate tap event.
5507 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5508 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5509 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5510 mPointerGesture.resetTap();
5511 }
5512
5513 // Pick a new active touch id if needed.
5514 // Choose an arbitrary pointer that just went down, if there is one.
5515 // Otherwise choose an arbitrary remaining pointer.
5516 // This guarantees we always have an active touch id when there is at least one pointer.
5517 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5519 int32_t activeTouchId = lastActiveTouchId;
5520 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005521 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005523 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 mPointerGesture.firstTouchTime = when;
5525 }
Michael Wright842500e2015-03-13 17:32:02 -07005526 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005527 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005529 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530 } else {
5531 activeTouchId = mPointerGesture.activeTouchId = -1;
5532 }
5533 }
5534
5535 // Determine whether we are in quiet time.
5536 bool isQuietTime = false;
5537 if (activeTouchId < 0) {
5538 mPointerGesture.resetQuietTime();
5539 } else {
5540 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5541 if (!isQuietTime) {
5542 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5543 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5544 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5545 && currentFingerCount < 2) {
5546 // Enter quiet time when exiting swipe or freeform state.
5547 // This is to prevent accidentally entering the hover state and flinging the
5548 // pointer when finishing a swipe and there is still one pointer left onscreen.
5549 isQuietTime = true;
5550 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5551 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005552 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 // Enter quiet time when releasing the button and there are still two or more
5554 // fingers down. This may indicate that one finger was used to press the button
5555 // but it has not gone up yet.
5556 isQuietTime = true;
5557 }
5558 if (isQuietTime) {
5559 mPointerGesture.quietTime = when;
5560 }
5561 }
5562 }
5563
5564 // Switch states based on button and pointer state.
5565 if (isQuietTime) {
5566 // Case 1: Quiet time. (QUIET)
5567#if DEBUG_GESTURES
5568 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5569 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5570#endif
5571 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5572 *outFinishPreviousGesture = true;
5573 }
5574
5575 mPointerGesture.activeGestureId = -1;
5576 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5577 mPointerGesture.currentGestureIdBits.clear();
5578
5579 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005580 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5582 // The pointer follows the active touch point.
5583 // Emit DOWN, MOVE, UP events at the pointer location.
5584 //
5585 // Only the active touch matters; other fingers are ignored. This policy helps
5586 // to handle the case where the user places a second finger on the touch pad
5587 // to apply the necessary force to depress an integrated button below the surface.
5588 // We don't want the second finger to be delivered to applications.
5589 //
5590 // For this to work well, we need to make sure to track the pointer that is really
5591 // active. If the user first puts one finger down to click then adds another
5592 // finger to drag then the active pointer should switch to the finger that is
5593 // being dragged.
5594#if DEBUG_GESTURES
5595 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5596 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5597#endif
5598 // Reset state when just starting.
5599 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5600 *outFinishPreviousGesture = true;
5601 mPointerGesture.activeGestureId = 0;
5602 }
5603
5604 // Switch pointers if needed.
5605 // Find the fastest pointer and follow it.
5606 if (activeTouchId >= 0 && currentFingerCount > 1) {
5607 int32_t bestId = -1;
5608 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005609 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 uint32_t id = idBits.clearFirstMarkedBit();
5611 float vx, vy;
5612 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5613 float speed = hypotf(vx, vy);
5614 if (speed > bestSpeed) {
5615 bestId = id;
5616 bestSpeed = speed;
5617 }
5618 }
5619 }
5620 if (bestId >= 0 && bestId != activeTouchId) {
5621 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622#if DEBUG_GESTURES
5623 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5624 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5625#endif
5626 }
5627 }
5628
Jun Mukaifa1706a2015-12-03 01:14:46 -08005629 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005630 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005632 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005634 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005635 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5636 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637
5638 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5639 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5640
5641 // Move the pointer using a relative motion.
5642 // When using spots, the click will occur at the position of the anchor
5643 // spot and all other spots will move there.
5644 mPointerController->move(deltaX, deltaY);
5645 } else {
5646 mPointerVelocityControl.reset();
5647 }
5648
5649 float x, y;
5650 mPointerController->getPosition(&x, &y);
5651
5652 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5653 mPointerGesture.currentGestureIdBits.clear();
5654 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5655 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5656 mPointerGesture.currentGestureProperties[0].clear();
5657 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5658 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5659 mPointerGesture.currentGestureCoords[0].clear();
5660 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5661 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5662 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5663 } else if (currentFingerCount == 0) {
5664 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5665 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5666 *outFinishPreviousGesture = true;
5667 }
5668
5669 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5670 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5671 bool tapped = false;
5672 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5673 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5674 && lastFingerCount == 1) {
5675 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5676 float x, y;
5677 mPointerController->getPosition(&x, &y);
5678 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5679 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5680#if DEBUG_GESTURES
5681 ALOGD("Gestures: TAP");
5682#endif
5683
5684 mPointerGesture.tapUpTime = when;
5685 getContext()->requestTimeoutAtTime(when
5686 + mConfig.pointerGestureTapDragInterval);
5687
5688 mPointerGesture.activeGestureId = 0;
5689 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5690 mPointerGesture.currentGestureIdBits.clear();
5691 mPointerGesture.currentGestureIdBits.markBit(
5692 mPointerGesture.activeGestureId);
5693 mPointerGesture.currentGestureIdToIndex[
5694 mPointerGesture.activeGestureId] = 0;
5695 mPointerGesture.currentGestureProperties[0].clear();
5696 mPointerGesture.currentGestureProperties[0].id =
5697 mPointerGesture.activeGestureId;
5698 mPointerGesture.currentGestureProperties[0].toolType =
5699 AMOTION_EVENT_TOOL_TYPE_FINGER;
5700 mPointerGesture.currentGestureCoords[0].clear();
5701 mPointerGesture.currentGestureCoords[0].setAxisValue(
5702 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5703 mPointerGesture.currentGestureCoords[0].setAxisValue(
5704 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5705 mPointerGesture.currentGestureCoords[0].setAxisValue(
5706 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5707
5708 tapped = true;
5709 } else {
5710#if DEBUG_GESTURES
5711 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5712 x - mPointerGesture.tapX,
5713 y - mPointerGesture.tapY);
5714#endif
5715 }
5716 } else {
5717#if DEBUG_GESTURES
5718 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5719 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5720 (when - mPointerGesture.tapDownTime) * 0.000001f);
5721 } else {
5722 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5723 }
5724#endif
5725 }
5726 }
5727
5728 mPointerVelocityControl.reset();
5729
5730 if (!tapped) {
5731#if DEBUG_GESTURES
5732 ALOGD("Gestures: NEUTRAL");
5733#endif
5734 mPointerGesture.activeGestureId = -1;
5735 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5736 mPointerGesture.currentGestureIdBits.clear();
5737 }
5738 } else if (currentFingerCount == 1) {
5739 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5740 // The pointer follows the active touch point.
5741 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5742 // When in TAP_DRAG, emit MOVE events at the pointer location.
5743 ALOG_ASSERT(activeTouchId >= 0);
5744
5745 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5746 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5747 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5748 float x, y;
5749 mPointerController->getPosition(&x, &y);
5750 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5751 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5752 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5753 } else {
5754#if DEBUG_GESTURES
5755 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5756 x - mPointerGesture.tapX,
5757 y - mPointerGesture.tapY);
5758#endif
5759 }
5760 } else {
5761#if DEBUG_GESTURES
5762 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5763 (when - mPointerGesture.tapUpTime) * 0.000001f);
5764#endif
5765 }
5766 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5767 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5768 }
5769
Jun Mukaifa1706a2015-12-03 01:14:46 -08005770 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005771 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005773 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005774 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005775 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005776 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5777 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778
5779 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5780 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5781
5782 // Move the pointer using a relative motion.
5783 // When using spots, the hover or drag will occur at the position of the anchor spot.
5784 mPointerController->move(deltaX, deltaY);
5785 } else {
5786 mPointerVelocityControl.reset();
5787 }
5788
5789 bool down;
5790 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5791#if DEBUG_GESTURES
5792 ALOGD("Gestures: TAP_DRAG");
5793#endif
5794 down = true;
5795 } else {
5796#if DEBUG_GESTURES
5797 ALOGD("Gestures: HOVER");
5798#endif
5799 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5800 *outFinishPreviousGesture = true;
5801 }
5802 mPointerGesture.activeGestureId = 0;
5803 down = false;
5804 }
5805
5806 float x, y;
5807 mPointerController->getPosition(&x, &y);
5808
5809 mPointerGesture.currentGestureIdBits.clear();
5810 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5811 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5812 mPointerGesture.currentGestureProperties[0].clear();
5813 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5814 mPointerGesture.currentGestureProperties[0].toolType =
5815 AMOTION_EVENT_TOOL_TYPE_FINGER;
5816 mPointerGesture.currentGestureCoords[0].clear();
5817 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5818 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5819 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5820 down ? 1.0f : 0.0f);
5821
5822 if (lastFingerCount == 0 && currentFingerCount != 0) {
5823 mPointerGesture.resetTap();
5824 mPointerGesture.tapDownTime = when;
5825 mPointerGesture.tapX = x;
5826 mPointerGesture.tapY = y;
5827 }
5828 } else {
5829 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5830 // We need to provide feedback for each finger that goes down so we cannot wait
5831 // for the fingers to move before deciding what to do.
5832 //
5833 // The ambiguous case is deciding what to do when there are two fingers down but they
5834 // have not moved enough to determine whether they are part of a drag or part of a
5835 // freeform gesture, or just a press or long-press at the pointer location.
5836 //
5837 // When there are two fingers we start with the PRESS hypothesis and we generate a
5838 // down at the pointer location.
5839 //
5840 // When the two fingers move enough or when additional fingers are added, we make
5841 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5842 ALOG_ASSERT(activeTouchId >= 0);
5843
5844 bool settled = when >= mPointerGesture.firstTouchTime
5845 + mConfig.pointerGestureMultitouchSettleInterval;
5846 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5847 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5848 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5849 *outFinishPreviousGesture = true;
5850 } else if (!settled && currentFingerCount > lastFingerCount) {
5851 // Additional pointers have gone down but not yet settled.
5852 // Reset the gesture.
5853#if DEBUG_GESTURES
5854 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5855 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5856 + mConfig.pointerGestureMultitouchSettleInterval - when)
5857 * 0.000001f);
5858#endif
5859 *outCancelPreviousGesture = true;
5860 } else {
5861 // Continue previous gesture.
5862 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5863 }
5864
5865 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5866 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5867 mPointerGesture.activeGestureId = 0;
5868 mPointerGesture.referenceIdBits.clear();
5869 mPointerVelocityControl.reset();
5870
5871 // Use the centroid and pointer location as the reference points for the gesture.
5872#if DEBUG_GESTURES
5873 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5874 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5875 + mConfig.pointerGestureMultitouchSettleInterval - when)
5876 * 0.000001f);
5877#endif
Michael Wright842500e2015-03-13 17:32:02 -07005878 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 &mPointerGesture.referenceTouchX,
5880 &mPointerGesture.referenceTouchY);
5881 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5882 &mPointerGesture.referenceGestureY);
5883 }
5884
5885 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005886 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5888 uint32_t id = idBits.clearFirstMarkedBit();
5889 mPointerGesture.referenceDeltas[id].dx = 0;
5890 mPointerGesture.referenceDeltas[id].dy = 0;
5891 }
Michael Wright842500e2015-03-13 17:32:02 -07005892 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893
5894 // Add delta for all fingers and calculate a common movement delta.
5895 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005896 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5897 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5899 bool first = (idBits == commonIdBits);
5900 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005901 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5902 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005903 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5904 delta.dx += cpd.x - lpd.x;
5905 delta.dy += cpd.y - lpd.y;
5906
5907 if (first) {
5908 commonDeltaX = delta.dx;
5909 commonDeltaY = delta.dy;
5910 } else {
5911 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5912 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5913 }
5914 }
5915
5916 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5917 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5918 float dist[MAX_POINTER_ID + 1];
5919 int32_t distOverThreshold = 0;
5920 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5921 uint32_t id = idBits.clearFirstMarkedBit();
5922 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5923 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5924 delta.dy * mPointerYZoomScale);
5925 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5926 distOverThreshold += 1;
5927 }
5928 }
5929
5930 // Only transition when at least two pointers have moved further than
5931 // the minimum distance threshold.
5932 if (distOverThreshold >= 2) {
5933 if (currentFingerCount > 2) {
5934 // There are more than two pointers, switch to FREEFORM.
5935#if DEBUG_GESTURES
5936 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5937 currentFingerCount);
5938#endif
5939 *outCancelPreviousGesture = true;
5940 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5941 } else {
5942 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005943 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005944 uint32_t id1 = idBits.clearFirstMarkedBit();
5945 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005946 const RawPointerData::Pointer& p1 =
5947 mCurrentRawState.rawPointerData.pointerForId(id1);
5948 const RawPointerData::Pointer& p2 =
5949 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5951 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5952 // There are two pointers but they are too far apart for a SWIPE,
5953 // switch to FREEFORM.
5954#if DEBUG_GESTURES
5955 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5956 mutualDistance, mPointerGestureMaxSwipeWidth);
5957#endif
5958 *outCancelPreviousGesture = true;
5959 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5960 } else {
5961 // There are two pointers. Wait for both pointers to start moving
5962 // before deciding whether this is a SWIPE or FREEFORM gesture.
5963 float dist1 = dist[id1];
5964 float dist2 = dist[id2];
5965 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5966 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5967 // Calculate the dot product of the displacement vectors.
5968 // When the vectors are oriented in approximately the same direction,
5969 // the angle betweeen them is near zero and the cosine of the angle
5970 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5971 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5972 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5973 float dx1 = delta1.dx * mPointerXZoomScale;
5974 float dy1 = delta1.dy * mPointerYZoomScale;
5975 float dx2 = delta2.dx * mPointerXZoomScale;
5976 float dy2 = delta2.dy * mPointerYZoomScale;
5977 float dot = dx1 * dx2 + dy1 * dy2;
5978 float cosine = dot / (dist1 * dist2); // denominator always > 0
5979 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5980 // Pointers are moving in the same direction. Switch to SWIPE.
5981#if DEBUG_GESTURES
5982 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5983 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5984 "cosine %0.3f >= %0.3f",
5985 dist1, mConfig.pointerGestureMultitouchMinDistance,
5986 dist2, mConfig.pointerGestureMultitouchMinDistance,
5987 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5988#endif
5989 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5990 } else {
5991 // Pointers are moving in different directions. Switch to FREEFORM.
5992#if DEBUG_GESTURES
5993 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5994 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5995 "cosine %0.3f < %0.3f",
5996 dist1, mConfig.pointerGestureMultitouchMinDistance,
5997 dist2, mConfig.pointerGestureMultitouchMinDistance,
5998 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5999#endif
6000 *outCancelPreviousGesture = true;
6001 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6002 }
6003 }
6004 }
6005 }
6006 }
6007 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6008 // Switch from SWIPE to FREEFORM if additional pointers go down.
6009 // Cancel previous gesture.
6010 if (currentFingerCount > 2) {
6011#if DEBUG_GESTURES
6012 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6013 currentFingerCount);
6014#endif
6015 *outCancelPreviousGesture = true;
6016 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6017 }
6018 }
6019
6020 // Move the reference points based on the overall group motion of the fingers
6021 // except in PRESS mode while waiting for a transition to occur.
6022 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6023 && (commonDeltaX || commonDeltaY)) {
6024 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6025 uint32_t id = idBits.clearFirstMarkedBit();
6026 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6027 delta.dx = 0;
6028 delta.dy = 0;
6029 }
6030
6031 mPointerGesture.referenceTouchX += commonDeltaX;
6032 mPointerGesture.referenceTouchY += commonDeltaY;
6033
6034 commonDeltaX *= mPointerXMovementScale;
6035 commonDeltaY *= mPointerYMovementScale;
6036
6037 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6038 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6039
6040 mPointerGesture.referenceGestureX += commonDeltaX;
6041 mPointerGesture.referenceGestureY += commonDeltaY;
6042 }
6043
6044 // Report gestures.
6045 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6046 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6047 // PRESS or SWIPE mode.
6048#if DEBUG_GESTURES
6049 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6050 "activeGestureId=%d, currentTouchPointerCount=%d",
6051 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6052#endif
6053 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6054
6055 mPointerGesture.currentGestureIdBits.clear();
6056 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6057 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6058 mPointerGesture.currentGestureProperties[0].clear();
6059 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6060 mPointerGesture.currentGestureProperties[0].toolType =
6061 AMOTION_EVENT_TOOL_TYPE_FINGER;
6062 mPointerGesture.currentGestureCoords[0].clear();
6063 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6064 mPointerGesture.referenceGestureX);
6065 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6066 mPointerGesture.referenceGestureY);
6067 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6068 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6069 // FREEFORM mode.
6070#if DEBUG_GESTURES
6071 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6072 "activeGestureId=%d, currentTouchPointerCount=%d",
6073 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6074#endif
6075 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6076
6077 mPointerGesture.currentGestureIdBits.clear();
6078
6079 BitSet32 mappedTouchIdBits;
6080 BitSet32 usedGestureIdBits;
6081 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6082 // Initially, assign the active gesture id to the active touch point
6083 // if there is one. No other touch id bits are mapped yet.
6084 if (!*outCancelPreviousGesture) {
6085 mappedTouchIdBits.markBit(activeTouchId);
6086 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6087 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6088 mPointerGesture.activeGestureId;
6089 } else {
6090 mPointerGesture.activeGestureId = -1;
6091 }
6092 } else {
6093 // Otherwise, assume we mapped all touches from the previous frame.
6094 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006095 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6096 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6098
6099 // Check whether we need to choose a new active gesture id because the
6100 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006101 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6102 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103 !upTouchIdBits.isEmpty(); ) {
6104 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6105 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6106 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6107 mPointerGesture.activeGestureId = -1;
6108 break;
6109 }
6110 }
6111 }
6112
6113#if DEBUG_GESTURES
6114 ALOGD("Gestures: FREEFORM follow up "
6115 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6116 "activeGestureId=%d",
6117 mappedTouchIdBits.value, usedGestureIdBits.value,
6118 mPointerGesture.activeGestureId);
6119#endif
6120
Michael Wright842500e2015-03-13 17:32:02 -07006121 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006122 for (uint32_t i = 0; i < currentFingerCount; i++) {
6123 uint32_t touchId = idBits.clearFirstMarkedBit();
6124 uint32_t gestureId;
6125 if (!mappedTouchIdBits.hasBit(touchId)) {
6126 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6127 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6128#if DEBUG_GESTURES
6129 ALOGD("Gestures: FREEFORM "
6130 "new mapping for touch id %d -> gesture id %d",
6131 touchId, gestureId);
6132#endif
6133 } else {
6134 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6135#if DEBUG_GESTURES
6136 ALOGD("Gestures: FREEFORM "
6137 "existing mapping for touch id %d -> gesture id %d",
6138 touchId, gestureId);
6139#endif
6140 }
6141 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6142 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6143
6144 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006145 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006146 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6147 * mPointerXZoomScale;
6148 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6149 * mPointerYZoomScale;
6150 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6151
6152 mPointerGesture.currentGestureProperties[i].clear();
6153 mPointerGesture.currentGestureProperties[i].id = gestureId;
6154 mPointerGesture.currentGestureProperties[i].toolType =
6155 AMOTION_EVENT_TOOL_TYPE_FINGER;
6156 mPointerGesture.currentGestureCoords[i].clear();
6157 mPointerGesture.currentGestureCoords[i].setAxisValue(
6158 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6159 mPointerGesture.currentGestureCoords[i].setAxisValue(
6160 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6161 mPointerGesture.currentGestureCoords[i].setAxisValue(
6162 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6163 }
6164
6165 if (mPointerGesture.activeGestureId < 0) {
6166 mPointerGesture.activeGestureId =
6167 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6168#if DEBUG_GESTURES
6169 ALOGD("Gestures: FREEFORM new "
6170 "activeGestureId=%d", mPointerGesture.activeGestureId);
6171#endif
6172 }
6173 }
6174 }
6175
Michael Wright842500e2015-03-13 17:32:02 -07006176 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006177
6178#if DEBUG_GESTURES
6179 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6180 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6181 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6182 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6183 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6184 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6185 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6186 uint32_t id = idBits.clearFirstMarkedBit();
6187 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6188 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6189 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6190 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6191 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6192 id, index, properties.toolType,
6193 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6194 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6195 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6196 }
6197 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6198 uint32_t id = idBits.clearFirstMarkedBit();
6199 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6200 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6201 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6202 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6203 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6204 id, index, properties.toolType,
6205 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6206 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6207 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6208 }
6209#endif
6210 return true;
6211}
6212
6213void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6214 mPointerSimple.currentCoords.clear();
6215 mPointerSimple.currentProperties.clear();
6216
6217 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006218 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6219 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6220 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6221 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6222 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223 mPointerController->setPosition(x, y);
6224
Michael Wright842500e2015-03-13 17:32:02 -07006225 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 down = !hovering;
6227
6228 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006229 mPointerSimple.currentCoords.copyFrom(
6230 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6232 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6233 mPointerSimple.currentProperties.id = 0;
6234 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006235 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236 } else {
6237 down = false;
6238 hovering = false;
6239 }
6240
6241 dispatchPointerSimple(when, policyFlags, down, hovering);
6242}
6243
6244void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6245 abortPointerSimple(when, policyFlags);
6246}
6247
6248void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6249 mPointerSimple.currentCoords.clear();
6250 mPointerSimple.currentProperties.clear();
6251
6252 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006253 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6254 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6255 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006256 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006257 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6258 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006259 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006260 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006261 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006262 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006263 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264 * mPointerYMovementScale;
6265
6266 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6267 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6268
6269 mPointerController->move(deltaX, deltaY);
6270 } else {
6271 mPointerVelocityControl.reset();
6272 }
6273
Michael Wright842500e2015-03-13 17:32:02 -07006274 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006275 hovering = !down;
6276
6277 float x, y;
6278 mPointerController->getPosition(&x, &y);
6279 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006280 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006281 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6282 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6283 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6284 hovering ? 0.0f : 1.0f);
6285 mPointerSimple.currentProperties.id = 0;
6286 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006287 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006288 } else {
6289 mPointerVelocityControl.reset();
6290
6291 down = false;
6292 hovering = false;
6293 }
6294
6295 dispatchPointerSimple(when, policyFlags, down, hovering);
6296}
6297
6298void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6299 abortPointerSimple(when, policyFlags);
6300
6301 mPointerVelocityControl.reset();
6302}
6303
6304void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6305 bool down, bool hovering) {
6306 int32_t metaState = getContext()->getGlobalMetaState();
6307
Yi Kong9b14ac62018-07-17 13:48:38 -07006308 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 if (down || hovering) {
6310 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6311 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006312 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6314 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6315 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6316 }
6317 }
6318
6319 if (mPointerSimple.down && !down) {
6320 mPointerSimple.down = false;
6321
6322 // Send up.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006323 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006324 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006325 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006326 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6327 mOrientedXPrecision, mOrientedYPrecision,
6328 mPointerSimple.downTime);
6329 getListener()->notifyMotion(&args);
6330 }
6331
6332 if (mPointerSimple.hovering && !hovering) {
6333 mPointerSimple.hovering = false;
6334
6335 // Send hover exit.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006336 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006337 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006338 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006339 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6340 mOrientedXPrecision, mOrientedYPrecision,
6341 mPointerSimple.downTime);
6342 getListener()->notifyMotion(&args);
6343 }
6344
6345 if (down) {
6346 if (!mPointerSimple.down) {
6347 mPointerSimple.down = true;
6348 mPointerSimple.downTime = when;
6349
6350 // Send down.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006351 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006352 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006353 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006354 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6355 mOrientedXPrecision, mOrientedYPrecision,
6356 mPointerSimple.downTime);
6357 getListener()->notifyMotion(&args);
6358 }
6359
6360 // Send move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006361 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006362 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006363 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6365 mOrientedXPrecision, mOrientedYPrecision,
6366 mPointerSimple.downTime);
6367 getListener()->notifyMotion(&args);
6368 }
6369
6370 if (hovering) {
6371 if (!mPointerSimple.hovering) {
6372 mPointerSimple.hovering = true;
6373
6374 // Send hover enter.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006375 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006376 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006377 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006378 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006379 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6380 mOrientedXPrecision, mOrientedYPrecision,
6381 mPointerSimple.downTime);
6382 getListener()->notifyMotion(&args);
6383 }
6384
6385 // Send hover move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006386 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006387 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006388 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006389 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6391 mOrientedXPrecision, mOrientedYPrecision,
6392 mPointerSimple.downTime);
6393 getListener()->notifyMotion(&args);
6394 }
6395
Michael Wright842500e2015-03-13 17:32:02 -07006396 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6397 float vscroll = mCurrentRawState.rawVScroll;
6398 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006399 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6400 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401
6402 // Send scroll.
6403 PointerCoords pointerCoords;
6404 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6405 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6406 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6407
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006408 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006409 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006410 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006411 1, &mPointerSimple.currentProperties, &pointerCoords,
6412 mOrientedXPrecision, mOrientedYPrecision,
6413 mPointerSimple.downTime);
6414 getListener()->notifyMotion(&args);
6415 }
6416
6417 // Save state.
6418 if (down || hovering) {
6419 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6420 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6421 } else {
6422 mPointerSimple.reset();
6423 }
6424}
6425
6426void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6427 mPointerSimple.currentCoords.clear();
6428 mPointerSimple.currentProperties.clear();
6429
6430 dispatchPointerSimple(when, policyFlags, false, false);
6431}
6432
6433void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006434 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006435 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006436 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006437 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6438 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006439 PointerCoords pointerCoords[MAX_POINTERS];
6440 PointerProperties pointerProperties[MAX_POINTERS];
6441 uint32_t pointerCount = 0;
6442 while (!idBits.isEmpty()) {
6443 uint32_t id = idBits.clearFirstMarkedBit();
6444 uint32_t index = idToIndex[id];
6445 pointerProperties[pointerCount].copyFrom(properties[index]);
6446 pointerCoords[pointerCount].copyFrom(coords[index]);
6447
6448 if (changedId >= 0 && id == uint32_t(changedId)) {
6449 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6450 }
6451
6452 pointerCount += 1;
6453 }
6454
6455 ALOG_ASSERT(pointerCount != 0);
6456
6457 if (changedId >= 0 && pointerCount == 1) {
6458 // Replace initial down and final up action.
6459 // We can compare the action without masking off the changed pointer index
6460 // because we know the index is 0.
6461 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6462 action = AMOTION_EVENT_ACTION_DOWN;
6463 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6464 action = AMOTION_EVENT_ACTION_UP;
6465 } else {
6466 // Can't happen.
6467 ALOG_ASSERT(false);
6468 }
6469 }
6470
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006471 NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006472 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006473 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006474 xPrecision, yPrecision, downTime);
6475 getListener()->notifyMotion(&args);
6476}
6477
6478bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6479 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6480 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6481 BitSet32 idBits) const {
6482 bool changed = false;
6483 while (!idBits.isEmpty()) {
6484 uint32_t id = idBits.clearFirstMarkedBit();
6485 uint32_t inIndex = inIdToIndex[id];
6486 uint32_t outIndex = outIdToIndex[id];
6487
6488 const PointerProperties& curInProperties = inProperties[inIndex];
6489 const PointerCoords& curInCoords = inCoords[inIndex];
6490 PointerProperties& curOutProperties = outProperties[outIndex];
6491 PointerCoords& curOutCoords = outCoords[outIndex];
6492
6493 if (curInProperties != curOutProperties) {
6494 curOutProperties.copyFrom(curInProperties);
6495 changed = true;
6496 }
6497
6498 if (curInCoords != curOutCoords) {
6499 curOutCoords.copyFrom(curInCoords);
6500 changed = true;
6501 }
6502 }
6503 return changed;
6504}
6505
6506void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006507 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006508 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6509 }
6510}
6511
Jeff Brownc9aa6282015-02-11 19:03:28 -08006512void TouchInputMapper::cancelTouch(nsecs_t when) {
6513 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006514 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006515}
6516
Michael Wrightd02c5b62014-02-10 15:10:22 -08006517bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006518 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006519 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006520 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006521 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6522 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6523 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006524}
6525
6526const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6527 int32_t x, int32_t y) {
6528 size_t numVirtualKeys = mVirtualKeys.size();
6529 for (size_t i = 0; i < numVirtualKeys; i++) {
6530 const VirtualKey& virtualKey = mVirtualKeys[i];
6531
6532#if DEBUG_VIRTUAL_KEYS
6533 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6534 "left=%d, top=%d, right=%d, bottom=%d",
6535 x, y,
6536 virtualKey.keyCode, virtualKey.scanCode,
6537 virtualKey.hitLeft, virtualKey.hitTop,
6538 virtualKey.hitRight, virtualKey.hitBottom);
6539#endif
6540
6541 if (virtualKey.isHit(x, y)) {
6542 return & virtualKey;
6543 }
6544 }
6545
Yi Kong9b14ac62018-07-17 13:48:38 -07006546 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006547}
6548
Michael Wright842500e2015-03-13 17:32:02 -07006549void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6550 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6551 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552
Michael Wright842500e2015-03-13 17:32:02 -07006553 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554
6555 if (currentPointerCount == 0) {
6556 // No pointers to assign.
6557 return;
6558 }
6559
6560 if (lastPointerCount == 0) {
6561 // All pointers are new.
6562 for (uint32_t i = 0; i < currentPointerCount; i++) {
6563 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006564 current->rawPointerData.pointers[i].id = id;
6565 current->rawPointerData.idToIndex[id] = i;
6566 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567 }
6568 return;
6569 }
6570
6571 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006572 && current->rawPointerData.pointers[0].toolType
6573 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006574 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006575 uint32_t id = last->rawPointerData.pointers[0].id;
6576 current->rawPointerData.pointers[0].id = id;
6577 current->rawPointerData.idToIndex[id] = 0;
6578 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006579 return;
6580 }
6581
6582 // General case.
6583 // We build a heap of squared euclidean distances between current and last pointers
6584 // associated with the current and last pointer indices. Then, we find the best
6585 // match (by distance) for each current pointer.
6586 // The pointers must have the same tool type but it is possible for them to
6587 // transition from hovering to touching or vice-versa while retaining the same id.
6588 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6589
6590 uint32_t heapSize = 0;
6591 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6592 currentPointerIndex++) {
6593 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6594 lastPointerIndex++) {
6595 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006596 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006598 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006599 if (currentPointer.toolType == lastPointer.toolType) {
6600 int64_t deltaX = currentPointer.x - lastPointer.x;
6601 int64_t deltaY = currentPointer.y - lastPointer.y;
6602
6603 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6604
6605 // Insert new element into the heap (sift up).
6606 heap[heapSize].currentPointerIndex = currentPointerIndex;
6607 heap[heapSize].lastPointerIndex = lastPointerIndex;
6608 heap[heapSize].distance = distance;
6609 heapSize += 1;
6610 }
6611 }
6612 }
6613
6614 // Heapify
6615 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6616 startIndex -= 1;
6617 for (uint32_t parentIndex = startIndex; ;) {
6618 uint32_t childIndex = parentIndex * 2 + 1;
6619 if (childIndex >= heapSize) {
6620 break;
6621 }
6622
6623 if (childIndex + 1 < heapSize
6624 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6625 childIndex += 1;
6626 }
6627
6628 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6629 break;
6630 }
6631
6632 swap(heap[parentIndex], heap[childIndex]);
6633 parentIndex = childIndex;
6634 }
6635 }
6636
6637#if DEBUG_POINTER_ASSIGNMENT
6638 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6639 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006640 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006641 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6642 heap[i].distance);
6643 }
6644#endif
6645
6646 // Pull matches out by increasing order of distance.
6647 // To avoid reassigning pointers that have already been matched, the loop keeps track
6648 // of which last and current pointers have been matched using the matchedXXXBits variables.
6649 // It also tracks the used pointer id bits.
6650 BitSet32 matchedLastBits(0);
6651 BitSet32 matchedCurrentBits(0);
6652 BitSet32 usedIdBits(0);
6653 bool first = true;
6654 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6655 while (heapSize > 0) {
6656 if (first) {
6657 // The first time through the loop, we just consume the root element of
6658 // the heap (the one with smallest distance).
6659 first = false;
6660 } else {
6661 // Previous iterations consumed the root element of the heap.
6662 // Pop root element off of the heap (sift down).
6663 heap[0] = heap[heapSize];
6664 for (uint32_t parentIndex = 0; ;) {
6665 uint32_t childIndex = parentIndex * 2 + 1;
6666 if (childIndex >= heapSize) {
6667 break;
6668 }
6669
6670 if (childIndex + 1 < heapSize
6671 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6672 childIndex += 1;
6673 }
6674
6675 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6676 break;
6677 }
6678
6679 swap(heap[parentIndex], heap[childIndex]);
6680 parentIndex = childIndex;
6681 }
6682
6683#if DEBUG_POINTER_ASSIGNMENT
6684 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6685 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006686 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006687 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6688 heap[i].distance);
6689 }
6690#endif
6691 }
6692
6693 heapSize -= 1;
6694
6695 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6696 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6697
6698 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6699 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6700
6701 matchedCurrentBits.markBit(currentPointerIndex);
6702 matchedLastBits.markBit(lastPointerIndex);
6703
Michael Wright842500e2015-03-13 17:32:02 -07006704 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6705 current->rawPointerData.pointers[currentPointerIndex].id = id;
6706 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6707 current->rawPointerData.markIdBit(id,
6708 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006709 usedIdBits.markBit(id);
6710
6711#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006712 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6713 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006714 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6715#endif
6716 break;
6717 }
6718 }
6719
6720 // Assign fresh ids to pointers that were not matched in the process.
6721 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6722 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6723 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6724
Michael Wright842500e2015-03-13 17:32:02 -07006725 current->rawPointerData.pointers[currentPointerIndex].id = id;
6726 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6727 current->rawPointerData.markIdBit(id,
6728 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006729
6730#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006731 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006732#endif
6733 }
6734}
6735
6736int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6737 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6738 return AKEY_STATE_VIRTUAL;
6739 }
6740
6741 size_t numVirtualKeys = mVirtualKeys.size();
6742 for (size_t i = 0; i < numVirtualKeys; i++) {
6743 const VirtualKey& virtualKey = mVirtualKeys[i];
6744 if (virtualKey.keyCode == keyCode) {
6745 return AKEY_STATE_UP;
6746 }
6747 }
6748
6749 return AKEY_STATE_UNKNOWN;
6750}
6751
6752int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6753 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6754 return AKEY_STATE_VIRTUAL;
6755 }
6756
6757 size_t numVirtualKeys = mVirtualKeys.size();
6758 for (size_t i = 0; i < numVirtualKeys; i++) {
6759 const VirtualKey& virtualKey = mVirtualKeys[i];
6760 if (virtualKey.scanCode == scanCode) {
6761 return AKEY_STATE_UP;
6762 }
6763 }
6764
6765 return AKEY_STATE_UNKNOWN;
6766}
6767
6768bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6769 const int32_t* keyCodes, uint8_t* outFlags) {
6770 size_t numVirtualKeys = mVirtualKeys.size();
6771 for (size_t i = 0; i < numVirtualKeys; i++) {
6772 const VirtualKey& virtualKey = mVirtualKeys[i];
6773
6774 for (size_t i = 0; i < numCodes; i++) {
6775 if (virtualKey.keyCode == keyCodes[i]) {
6776 outFlags[i] = 1;
6777 }
6778 }
6779 }
6780
6781 return true;
6782}
6783
6784
6785// --- SingleTouchInputMapper ---
6786
6787SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6788 TouchInputMapper(device) {
6789}
6790
6791SingleTouchInputMapper::~SingleTouchInputMapper() {
6792}
6793
6794void SingleTouchInputMapper::reset(nsecs_t when) {
6795 mSingleTouchMotionAccumulator.reset(getDevice());
6796
6797 TouchInputMapper::reset(when);
6798}
6799
6800void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6801 TouchInputMapper::process(rawEvent);
6802
6803 mSingleTouchMotionAccumulator.process(rawEvent);
6804}
6805
Michael Wright842500e2015-03-13 17:32:02 -07006806void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006807 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006808 outState->rawPointerData.pointerCount = 1;
6809 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006810
6811 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6812 && (mTouchButtonAccumulator.isHovering()
6813 || (mRawPointerAxes.pressure.valid
6814 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006815 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006816
Michael Wright842500e2015-03-13 17:32:02 -07006817 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006818 outPointer.id = 0;
6819 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6820 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6821 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6822 outPointer.touchMajor = 0;
6823 outPointer.touchMinor = 0;
6824 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6825 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6826 outPointer.orientation = 0;
6827 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6828 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6829 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6830 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6831 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6832 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6833 }
6834 outPointer.isHovering = isHovering;
6835 }
6836}
6837
6838void SingleTouchInputMapper::configureRawPointerAxes() {
6839 TouchInputMapper::configureRawPointerAxes();
6840
6841 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6842 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6843 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6844 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6845 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6846 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6847 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6848}
6849
6850bool SingleTouchInputMapper::hasStylus() const {
6851 return mTouchButtonAccumulator.hasStylus();
6852}
6853
6854
6855// --- MultiTouchInputMapper ---
6856
6857MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6858 TouchInputMapper(device) {
6859}
6860
6861MultiTouchInputMapper::~MultiTouchInputMapper() {
6862}
6863
6864void MultiTouchInputMapper::reset(nsecs_t when) {
6865 mMultiTouchMotionAccumulator.reset(getDevice());
6866
6867 mPointerIdBits.clear();
6868
6869 TouchInputMapper::reset(when);
6870}
6871
6872void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6873 TouchInputMapper::process(rawEvent);
6874
6875 mMultiTouchMotionAccumulator.process(rawEvent);
6876}
6877
Michael Wright842500e2015-03-13 17:32:02 -07006878void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006879 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6880 size_t outCount = 0;
6881 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006882 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006883
6884 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6885 const MultiTouchMotionAccumulator::Slot* inSlot =
6886 mMultiTouchMotionAccumulator.getSlot(inIndex);
6887 if (!inSlot->isInUse()) {
6888 continue;
6889 }
6890
6891 if (outCount >= MAX_POINTERS) {
6892#if DEBUG_POINTERS
6893 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6894 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006895 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006896#endif
6897 break; // too many fingers!
6898 }
6899
Michael Wright842500e2015-03-13 17:32:02 -07006900 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006901 outPointer.x = inSlot->getX();
6902 outPointer.y = inSlot->getY();
6903 outPointer.pressure = inSlot->getPressure();
6904 outPointer.touchMajor = inSlot->getTouchMajor();
6905 outPointer.touchMinor = inSlot->getTouchMinor();
6906 outPointer.toolMajor = inSlot->getToolMajor();
6907 outPointer.toolMinor = inSlot->getToolMinor();
6908 outPointer.orientation = inSlot->getOrientation();
6909 outPointer.distance = inSlot->getDistance();
6910 outPointer.tiltX = 0;
6911 outPointer.tiltY = 0;
6912
6913 outPointer.toolType = inSlot->getToolType();
6914 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6915 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6916 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6917 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6918 }
6919 }
6920
6921 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6922 && (mTouchButtonAccumulator.isHovering()
6923 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6924 outPointer.isHovering = isHovering;
6925
6926 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006927 if (mHavePointerIds) {
6928 int32_t trackingId = inSlot->getTrackingId();
6929 int32_t id = -1;
6930 if (trackingId >= 0) {
6931 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6932 uint32_t n = idBits.clearFirstMarkedBit();
6933 if (mPointerTrackingIdMap[n] == trackingId) {
6934 id = n;
6935 }
6936 }
6937
6938 if (id < 0 && !mPointerIdBits.isFull()) {
6939 id = mPointerIdBits.markFirstUnmarkedBit();
6940 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006941 }
Michael Wright842500e2015-03-13 17:32:02 -07006942 }
gaoshang1a632de2016-08-24 10:23:50 +08006943 if (id < 0) {
6944 mHavePointerIds = false;
6945 outState->rawPointerData.clearIdBits();
6946 newPointerIdBits.clear();
6947 } else {
6948 outPointer.id = id;
6949 outState->rawPointerData.idToIndex[id] = outCount;
6950 outState->rawPointerData.markIdBit(id, isHovering);
6951 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006952 }
Michael Wright842500e2015-03-13 17:32:02 -07006953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006954 outCount += 1;
6955 }
6956
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006957 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006958 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006959 mPointerIdBits = newPointerIdBits;
6960
6961 mMultiTouchMotionAccumulator.finishSync();
6962}
6963
6964void MultiTouchInputMapper::configureRawPointerAxes() {
6965 TouchInputMapper::configureRawPointerAxes();
6966
6967 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6968 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6969 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6970 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6971 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6972 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6973 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6974 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6975 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6976 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6977 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6978
6979 if (mRawPointerAxes.trackingId.valid
6980 && mRawPointerAxes.slot.valid
6981 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6982 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6983 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006984 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6985 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006986 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006987 slotCount = MAX_SLOTS;
6988 }
6989 mMultiTouchMotionAccumulator.configure(getDevice(),
6990 slotCount, true /*usingSlotsProtocol*/);
6991 } else {
6992 mMultiTouchMotionAccumulator.configure(getDevice(),
6993 MAX_POINTERS, false /*usingSlotsProtocol*/);
6994 }
6995}
6996
6997bool MultiTouchInputMapper::hasStylus() const {
6998 return mMultiTouchMotionAccumulator.hasStylus()
6999 || mTouchButtonAccumulator.hasStylus();
7000}
7001
Michael Wright842500e2015-03-13 17:32:02 -07007002// --- ExternalStylusInputMapper
7003
7004ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7005 InputMapper(device) {
7006
7007}
7008
7009uint32_t ExternalStylusInputMapper::getSources() {
7010 return AINPUT_SOURCE_STYLUS;
7011}
7012
7013void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7014 InputMapper::populateDeviceInfo(info);
7015 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7016 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7017}
7018
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007019void ExternalStylusInputMapper::dump(std::string& dump) {
7020 dump += INDENT2 "External Stylus Input Mapper:\n";
7021 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007022 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007023 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007024 dumpStylusState(dump, mStylusState);
7025}
7026
7027void ExternalStylusInputMapper::configure(nsecs_t when,
7028 const InputReaderConfiguration* config, uint32_t changes) {
7029 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7030 mTouchButtonAccumulator.configure(getDevice());
7031}
7032
7033void ExternalStylusInputMapper::reset(nsecs_t when) {
7034 InputDevice* device = getDevice();
7035 mSingleTouchMotionAccumulator.reset(device);
7036 mTouchButtonAccumulator.reset(device);
7037 InputMapper::reset(when);
7038}
7039
7040void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7041 mSingleTouchMotionAccumulator.process(rawEvent);
7042 mTouchButtonAccumulator.process(rawEvent);
7043
7044 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7045 sync(rawEvent->when);
7046 }
7047}
7048
7049void ExternalStylusInputMapper::sync(nsecs_t when) {
7050 mStylusState.clear();
7051
7052 mStylusState.when = when;
7053
Michael Wright45ccacf2015-04-21 19:01:58 +01007054 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7055 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7056 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7057 }
7058
Michael Wright842500e2015-03-13 17:32:02 -07007059 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7060 if (mRawPressureAxis.valid) {
7061 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7062 } else if (mTouchButtonAccumulator.isToolActive()) {
7063 mStylusState.pressure = 1.0f;
7064 } else {
7065 mStylusState.pressure = 0.0f;
7066 }
7067
7068 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007069
7070 mContext->dispatchExternalStylusState(mStylusState);
7071}
7072
Michael Wrightd02c5b62014-02-10 15:10:22 -08007073
7074// --- JoystickInputMapper ---
7075
7076JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7077 InputMapper(device) {
7078}
7079
7080JoystickInputMapper::~JoystickInputMapper() {
7081}
7082
7083uint32_t JoystickInputMapper::getSources() {
7084 return AINPUT_SOURCE_JOYSTICK;
7085}
7086
7087void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7088 InputMapper::populateDeviceInfo(info);
7089
7090 for (size_t i = 0; i < mAxes.size(); i++) {
7091 const Axis& axis = mAxes.valueAt(i);
7092 addMotionRange(axis.axisInfo.axis, axis, info);
7093
7094 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7095 addMotionRange(axis.axisInfo.highAxis, axis, info);
7096
7097 }
7098 }
7099}
7100
7101void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7102 InputDeviceInfo* info) {
7103 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7104 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7105 /* In order to ease the transition for developers from using the old axes
7106 * to the newer, more semantically correct axes, we'll continue to register
7107 * the old axes as duplicates of their corresponding new ones. */
7108 int32_t compatAxis = getCompatAxis(axisId);
7109 if (compatAxis >= 0) {
7110 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7111 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7112 }
7113}
7114
7115/* A mapping from axes the joystick actually has to the axes that should be
7116 * artificially created for compatibility purposes.
7117 * Returns -1 if no compatibility axis is needed. */
7118int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7119 switch(axis) {
7120 case AMOTION_EVENT_AXIS_LTRIGGER:
7121 return AMOTION_EVENT_AXIS_BRAKE;
7122 case AMOTION_EVENT_AXIS_RTRIGGER:
7123 return AMOTION_EVENT_AXIS_GAS;
7124 }
7125 return -1;
7126}
7127
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007128void JoystickInputMapper::dump(std::string& dump) {
7129 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007130
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007131 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007132 size_t numAxes = mAxes.size();
7133 for (size_t i = 0; i < numAxes; i++) {
7134 const Axis& axis = mAxes.valueAt(i);
7135 const char* label = getAxisLabel(axis.axisInfo.axis);
7136 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007137 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007138 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007139 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007140 }
7141 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7142 label = getAxisLabel(axis.axisInfo.highAxis);
7143 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007144 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007145 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007146 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007147 axis.axisInfo.splitValue);
7148 }
7149 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007150 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007151 }
7152
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007153 dump += StringPrintf(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007154 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007155 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007156 "highScale=%0.5f, highOffset=%0.5f\n",
7157 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007158 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007159 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7160 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7161 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7162 }
7163}
7164
7165void JoystickInputMapper::configure(nsecs_t when,
7166 const InputReaderConfiguration* config, uint32_t changes) {
7167 InputMapper::configure(when, config, changes);
7168
7169 if (!changes) { // first time only
7170 // Collect all axes.
7171 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7172 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7173 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7174 continue; // axis must be claimed by a different device
7175 }
7176
7177 RawAbsoluteAxisInfo rawAxisInfo;
7178 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7179 if (rawAxisInfo.valid) {
7180 // Map axis.
7181 AxisInfo axisInfo;
7182 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7183 if (!explicitlyMapped) {
7184 // Axis is not explicitly mapped, will choose a generic axis later.
7185 axisInfo.mode = AxisInfo::MODE_NORMAL;
7186 axisInfo.axis = -1;
7187 }
7188
7189 // Apply flat override.
7190 int32_t rawFlat = axisInfo.flatOverride < 0
7191 ? rawAxisInfo.flat : axisInfo.flatOverride;
7192
7193 // Calculate scaling factors and limits.
7194 Axis axis;
7195 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7196 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7197 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7198 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7199 scale, 0.0f, highScale, 0.0f,
7200 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7201 rawAxisInfo.resolution * scale);
7202 } else if (isCenteredAxis(axisInfo.axis)) {
7203 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7204 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7205 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7206 scale, offset, scale, offset,
7207 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7208 rawAxisInfo.resolution * scale);
7209 } else {
7210 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7211 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7212 scale, 0.0f, scale, 0.0f,
7213 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7214 rawAxisInfo.resolution * scale);
7215 }
7216
7217 // To eliminate noise while the joystick is at rest, filter out small variations
7218 // in axis values up front.
7219 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7220
7221 mAxes.add(abs, axis);
7222 }
7223 }
7224
7225 // If there are too many axes, start dropping them.
7226 // Prefer to keep explicitly mapped axes.
7227 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007228 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007229 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007230 pruneAxes(true);
7231 pruneAxes(false);
7232 }
7233
7234 // Assign generic axis ids to remaining axes.
7235 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7236 size_t numAxes = mAxes.size();
7237 for (size_t i = 0; i < numAxes; i++) {
7238 Axis& axis = mAxes.editValueAt(i);
7239 if (axis.axisInfo.axis < 0) {
7240 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7241 && haveAxis(nextGenericAxisId)) {
7242 nextGenericAxisId += 1;
7243 }
7244
7245 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7246 axis.axisInfo.axis = nextGenericAxisId;
7247 nextGenericAxisId += 1;
7248 } else {
7249 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7250 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007251 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007252 mAxes.removeItemsAt(i--);
7253 numAxes -= 1;
7254 }
7255 }
7256 }
7257 }
7258}
7259
7260bool JoystickInputMapper::haveAxis(int32_t axisId) {
7261 size_t numAxes = mAxes.size();
7262 for (size_t i = 0; i < numAxes; i++) {
7263 const Axis& axis = mAxes.valueAt(i);
7264 if (axis.axisInfo.axis == axisId
7265 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7266 && axis.axisInfo.highAxis == axisId)) {
7267 return true;
7268 }
7269 }
7270 return false;
7271}
7272
7273void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7274 size_t i = mAxes.size();
7275 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7276 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7277 continue;
7278 }
7279 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007280 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007281 mAxes.removeItemsAt(i);
7282 }
7283}
7284
7285bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7286 switch (axis) {
7287 case AMOTION_EVENT_AXIS_X:
7288 case AMOTION_EVENT_AXIS_Y:
7289 case AMOTION_EVENT_AXIS_Z:
7290 case AMOTION_EVENT_AXIS_RX:
7291 case AMOTION_EVENT_AXIS_RY:
7292 case AMOTION_EVENT_AXIS_RZ:
7293 case AMOTION_EVENT_AXIS_HAT_X:
7294 case AMOTION_EVENT_AXIS_HAT_Y:
7295 case AMOTION_EVENT_AXIS_ORIENTATION:
7296 case AMOTION_EVENT_AXIS_RUDDER:
7297 case AMOTION_EVENT_AXIS_WHEEL:
7298 return true;
7299 default:
7300 return false;
7301 }
7302}
7303
7304void JoystickInputMapper::reset(nsecs_t when) {
7305 // Recenter all axes.
7306 size_t numAxes = mAxes.size();
7307 for (size_t i = 0; i < numAxes; i++) {
7308 Axis& axis = mAxes.editValueAt(i);
7309 axis.resetValue();
7310 }
7311
7312 InputMapper::reset(when);
7313}
7314
7315void JoystickInputMapper::process(const RawEvent* rawEvent) {
7316 switch (rawEvent->type) {
7317 case EV_ABS: {
7318 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7319 if (index >= 0) {
7320 Axis& axis = mAxes.editValueAt(index);
7321 float newValue, highNewValue;
7322 switch (axis.axisInfo.mode) {
7323 case AxisInfo::MODE_INVERT:
7324 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7325 * axis.scale + axis.offset;
7326 highNewValue = 0.0f;
7327 break;
7328 case AxisInfo::MODE_SPLIT:
7329 if (rawEvent->value < axis.axisInfo.splitValue) {
7330 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7331 * axis.scale + axis.offset;
7332 highNewValue = 0.0f;
7333 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7334 newValue = 0.0f;
7335 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7336 * axis.highScale + axis.highOffset;
7337 } else {
7338 newValue = 0.0f;
7339 highNewValue = 0.0f;
7340 }
7341 break;
7342 default:
7343 newValue = rawEvent->value * axis.scale + axis.offset;
7344 highNewValue = 0.0f;
7345 break;
7346 }
7347 axis.newValue = newValue;
7348 axis.highNewValue = highNewValue;
7349 }
7350 break;
7351 }
7352
7353 case EV_SYN:
7354 switch (rawEvent->code) {
7355 case SYN_REPORT:
7356 sync(rawEvent->when, false /*force*/);
7357 break;
7358 }
7359 break;
7360 }
7361}
7362
7363void JoystickInputMapper::sync(nsecs_t when, bool force) {
7364 if (!filterAxes(force)) {
7365 return;
7366 }
7367
7368 int32_t metaState = mContext->getGlobalMetaState();
7369 int32_t buttonState = 0;
7370
7371 PointerProperties pointerProperties;
7372 pointerProperties.clear();
7373 pointerProperties.id = 0;
7374 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7375
7376 PointerCoords pointerCoords;
7377 pointerCoords.clear();
7378
7379 size_t numAxes = mAxes.size();
7380 for (size_t i = 0; i < numAxes; i++) {
7381 const Axis& axis = mAxes.valueAt(i);
7382 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7383 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7384 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7385 axis.highCurrentValue);
7386 }
7387 }
7388
7389 // Moving a joystick axis should not wake the device because joysticks can
7390 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7391 // button will likely wake the device.
7392 // TODO: Use the input device configuration to control this behavior more finely.
7393 uint32_t policyFlags = 0;
7394
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007395 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE,
7396 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007397 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007398 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007399 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007400 getListener()->notifyMotion(&args);
7401}
7402
7403void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7404 int32_t axis, float value) {
7405 pointerCoords->setAxisValue(axis, value);
7406 /* In order to ease the transition for developers from using the old axes
7407 * to the newer, more semantically correct axes, we'll continue to produce
7408 * values for the old axes as mirrors of the value of their corresponding
7409 * new axes. */
7410 int32_t compatAxis = getCompatAxis(axis);
7411 if (compatAxis >= 0) {
7412 pointerCoords->setAxisValue(compatAxis, value);
7413 }
7414}
7415
7416bool JoystickInputMapper::filterAxes(bool force) {
7417 bool atLeastOneSignificantChange = force;
7418 size_t numAxes = mAxes.size();
7419 for (size_t i = 0; i < numAxes; i++) {
7420 Axis& axis = mAxes.editValueAt(i);
7421 if (force || hasValueChangedSignificantly(axis.filter,
7422 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7423 axis.currentValue = axis.newValue;
7424 atLeastOneSignificantChange = true;
7425 }
7426 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7427 if (force || hasValueChangedSignificantly(axis.filter,
7428 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7429 axis.highCurrentValue = axis.highNewValue;
7430 atLeastOneSignificantChange = true;
7431 }
7432 }
7433 }
7434 return atLeastOneSignificantChange;
7435}
7436
7437bool JoystickInputMapper::hasValueChangedSignificantly(
7438 float filter, float newValue, float currentValue, float min, float max) {
7439 if (newValue != currentValue) {
7440 // Filter out small changes in value unless the value is converging on the axis
7441 // bounds or center point. This is intended to reduce the amount of information
7442 // sent to applications by particularly noisy joysticks (such as PS3).
7443 if (fabs(newValue - currentValue) > filter
7444 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7445 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7446 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7447 return true;
7448 }
7449 }
7450 return false;
7451}
7452
7453bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7454 float filter, float newValue, float currentValue, float thresholdValue) {
7455 float newDistance = fabs(newValue - thresholdValue);
7456 if (newDistance < filter) {
7457 float oldDistance = fabs(currentValue - thresholdValue);
7458 if (newDistance < oldDistance) {
7459 return true;
7460 }
7461 }
7462 return false;
7463}
7464
7465} // namespace android