blob: 64070e3fa371ed93187f8a52ea606664dd7552cc [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
25#define DEBUG_HACKS 0
26
27// Log debug messages about virtual key processing.
28#define DEBUG_VIRTUAL_KEYS 0
29
30// Log debug messages about pointers.
31#define DEBUG_POINTERS 0
32
33// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
36// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
39// Log debug messages about the vibrator.
40#define DEBUG_VIBRATOR 0
41
Michael Wright842500e2015-03-13 17:32:02 -070042// Log debug messages about fusing stylus data.
43#define DEBUG_STYLUS_FUSION 0
44
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include "InputReader.h"
46
Mark Salyzyna5e161b2016-09-29 08:08:05 -070047#include <errno.h>
Michael Wright842500e2015-03-13 17:32:02 -070048#include <inttypes.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070049#include <limits.h>
50#include <math.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <stddef.h>
52#include <stdlib.h>
53#include <unistd.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054
Mark Salyzyn7823e122016-09-29 08:08:05 -070055#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <input/Keyboard.h>
59#include <input/VirtualKeyMap.h>
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080060#include <statslog.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65#define INDENT4 " "
66#define INDENT5 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// --- Constants ---
73
74// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080075static constexpr size_t MAX_SLOTS = 32;
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Michael Wright842500e2015-03-13 17:32:02 -070077// Maximum amount of latency to add to touch events while waiting for data from an
78// external stylus.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080079static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070080
Michael Wright43fd19f2015-04-21 19:02:58 +010081// Maximum amount of time to wait on touch data before pushing out new pressure data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080082static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
Michael Wright43fd19f2015-04-21 19:02:58 +010083
84// Artificial latency on synthetic events created from stylus data without corresponding touch
85// data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080086static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
87
88// How often to report input event statistics
89static constexpr nsecs_t STATISTICS_REPORT_FREQUENCY = seconds_to_nanoseconds(5 * 60);
Michael Wright43fd19f2015-04-21 19:02:58 +010090
Michael Wrightd02c5b62014-02-10 15:10:22 -080091// --- Static Functions ---
92
93template<typename T>
94inline static T abs(const T& value) {
95 return value < 0 ? - value : value;
96}
97
98template<typename T>
99inline static T min(const T& a, const T& b) {
100 return a < b ? a : b;
101}
102
103template<typename T>
104inline static void swap(T& a, T& b) {
105 T temp = a;
106 a = b;
107 b = temp;
108}
109
110inline static float avg(float x, float y) {
111 return (x + y) / 2;
112}
113
114inline static float distance(float x1, float y1, float x2, float y2) {
115 return hypotf(x1 - x2, y1 - y2);
116}
117
118inline static int32_t signExtendNybble(int32_t value) {
119 return value >= 8 ? value - 16 : value;
120}
121
122static inline const char* toString(bool value) {
123 return value ? "true" : "false";
124}
125
126static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
127 const int32_t map[][4], size_t mapSize) {
128 if (orientation != DISPLAY_ORIENTATION_0) {
129 for (size_t i = 0; i < mapSize; i++) {
130 if (value == map[i][0]) {
131 return map[i][orientation];
132 }
133 }
134 }
135 return value;
136}
137
138static const int32_t keyCodeRotationMap[][4] = {
139 // key codes enumerated counter-clockwise with the original (unrotated) key first
140 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
141 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
142 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
143 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
144 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700145 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
146 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
147 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
148 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
149 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
150 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
151 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
152 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153};
154static const size_t keyCodeRotationMapSize =
155 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
156
Ivan Podogovb9afef32017-02-13 15:34:32 +0000157static int32_t rotateStemKey(int32_t value, int32_t orientation,
158 const int32_t map[][2], size_t mapSize) {
159 if (orientation == DISPLAY_ORIENTATION_180) {
160 for (size_t i = 0; i < mapSize; i++) {
161 if (value == map[i][0]) {
162 return map[i][1];
163 }
164 }
165 }
166 return value;
167}
168
169// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
170static int32_t stemKeyRotationMap[][2] = {
171 // key codes enumerated with the original (unrotated) key first
172 // no rotation, 180 degree rotation
173 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
174 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
175 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
176 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
177};
178static const size_t stemKeyRotationMapSize =
179 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
180
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000182 keyCode = rotateStemKey(keyCode, orientation,
183 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 return rotateValueUsingRotationMap(keyCode, orientation,
185 keyCodeRotationMap, keyCodeRotationMapSize);
186}
187
188static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
189 float temp;
190 switch (orientation) {
191 case DISPLAY_ORIENTATION_90:
192 temp = *deltaX;
193 *deltaX = *deltaY;
194 *deltaY = -temp;
195 break;
196
197 case DISPLAY_ORIENTATION_180:
198 *deltaX = -*deltaX;
199 *deltaY = -*deltaY;
200 break;
201
202 case DISPLAY_ORIENTATION_270:
203 temp = *deltaX;
204 *deltaX = -*deltaY;
205 *deltaY = temp;
206 break;
207 }
208}
209
210static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
211 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
212}
213
214// Returns true if the pointer should be reported as being down given the specified
215// button states. This determines whether the event is reported as a touch event.
216static bool isPointerDown(int32_t buttonState) {
217 return buttonState &
218 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
219 | AMOTION_EVENT_BUTTON_TERTIARY);
220}
221
222static float calculateCommonVector(float a, float b) {
223 if (a > 0 && b > 0) {
224 return a < b ? a : b;
225 } else if (a < 0 && b < 0) {
226 return a > b ? a : b;
227 } else {
228 return 0;
229 }
230}
231
232static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100233 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
235 int32_t buttonState, int32_t keyCode) {
236 if (
237 (action == AKEY_EVENT_ACTION_DOWN
238 && !(lastButtonState & buttonState)
239 && (currentButtonState & buttonState))
240 || (action == AKEY_EVENT_ACTION_UP
241 && (lastButtonState & buttonState)
242 && !(currentButtonState & buttonState))) {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800243 NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
244 policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245 context->getListener()->notifyKey(&args);
246 }
247}
248
249static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100250 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100252 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 lastButtonState, currentButtonState,
254 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100255 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 lastButtonState, currentButtonState,
257 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
258}
259
260
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261// --- InputReader ---
262
263InputReader::InputReader(const sp<EventHubInterface>& eventHub,
264 const sp<InputReaderPolicyInterface>& policy,
265 const sp<InputListenerInterface>& listener) :
266 mContext(this), mEventHub(eventHub), mPolicy(policy),
Prabir Pradhan42611e02018-11-27 14:04:02 -0800267 mNextSequenceNum(1), mGlobalMetaState(0), mGeneration(1),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
269 mConfigurationChangesToRefresh(0) {
270 mQueuedListener = new QueuedInputListener(listener);
271
272 { // acquire lock
273 AutoMutex _l(mLock);
274
275 refreshConfigurationLocked(0);
276 updateGlobalMetaStateLocked();
277 } // release lock
278}
279
280InputReader::~InputReader() {
281 for (size_t i = 0; i < mDevices.size(); i++) {
282 delete mDevices.valueAt(i);
283 }
284}
285
286void InputReader::loopOnce() {
287 int32_t oldGeneration;
288 int32_t timeoutMillis;
289 bool inputDevicesChanged = false;
290 Vector<InputDeviceInfo> inputDevices;
291 { // acquire lock
292 AutoMutex _l(mLock);
293
294 oldGeneration = mGeneration;
295 timeoutMillis = -1;
296
297 uint32_t changes = mConfigurationChangesToRefresh;
298 if (changes) {
299 mConfigurationChangesToRefresh = 0;
300 timeoutMillis = 0;
301 refreshConfigurationLocked(changes);
302 } else if (mNextTimeout != LLONG_MAX) {
303 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
304 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
305 }
306 } // release lock
307
308 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
309
310 { // acquire lock
311 AutoMutex _l(mLock);
312 mReaderIsAliveCondition.broadcast();
313
314 if (count) {
315 processEventsLocked(mEventBuffer, count);
316 }
317
318 if (mNextTimeout != LLONG_MAX) {
319 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
320 if (now >= mNextTimeout) {
321#if DEBUG_RAW_EVENTS
322 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
323#endif
324 mNextTimeout = LLONG_MAX;
325 timeoutExpiredLocked(now);
326 }
327 }
328
329 if (oldGeneration != mGeneration) {
330 inputDevicesChanged = true;
331 getInputDevicesLocked(inputDevices);
332 }
333 } // release lock
334
335 // Send out a message that the describes the changed input devices.
336 if (inputDevicesChanged) {
337 mPolicy->notifyInputDevicesChanged(inputDevices);
338 }
339
340 // Flush queued events out to the listener.
341 // This must happen outside of the lock because the listener could potentially call
342 // back into the InputReader's methods, such as getScanCodeState, or become blocked
343 // on another thread similarly waiting to acquire the InputReader lock thereby
344 // resulting in a deadlock. This situation is actually quite plausible because the
345 // listener is actually the input dispatcher, which calls into the window manager,
346 // which occasionally calls into the input reader.
347 mQueuedListener->flush();
348}
349
350void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
351 for (const RawEvent* rawEvent = rawEvents; count;) {
352 int32_t type = rawEvent->type;
353 size_t batchSize = 1;
354 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
355 int32_t deviceId = rawEvent->deviceId;
356 while (batchSize < count) {
357 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
358 || rawEvent[batchSize].deviceId != deviceId) {
359 break;
360 }
361 batchSize += 1;
362 }
363#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700364 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365#endif
366 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
367 } else {
368 switch (rawEvent->type) {
369 case EventHubInterface::DEVICE_ADDED:
370 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
371 break;
372 case EventHubInterface::DEVICE_REMOVED:
373 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
374 break;
375 case EventHubInterface::FINISHED_DEVICE_SCAN:
376 handleConfigurationChangedLocked(rawEvent->when);
377 break;
378 default:
379 ALOG_ASSERT(false); // can't happen
380 break;
381 }
382 }
383 count -= batchSize;
384 rawEvent += batchSize;
385 }
386}
387
388void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
389 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
390 if (deviceIndex >= 0) {
391 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
392 return;
393 }
394
395 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
396 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
397 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
398
399 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
400 device->configure(when, &mConfig, 0);
401 device->reset(when);
402
403 if (device->isIgnored()) {
404 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100405 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 } else {
407 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100408 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 }
410
411 mDevices.add(deviceId, device);
412 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700413
414 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
415 notifyExternalStylusPresenceChanged();
416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417}
418
419void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700420 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
422 if (deviceIndex < 0) {
423 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
424 return;
425 }
426
427 device = mDevices.valueAt(deviceIndex);
428 mDevices.removeItemsAt(deviceIndex, 1);
429 bumpGenerationLocked();
430
431 if (device->isIgnored()) {
432 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100433 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 } else {
435 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100436 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 }
438
Michael Wright842500e2015-03-13 17:32:02 -0700439 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
440 notifyExternalStylusPresenceChanged();
441 }
442
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 device->reset(when);
444 delete device;
445}
446
447InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
448 const InputDeviceIdentifier& identifier, uint32_t classes) {
449 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
450 controllerNumber, identifier, classes);
451
452 // External devices.
453 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
454 device->setExternal(true);
455 }
456
Tim Kilbourn063ff532015-04-08 10:26:18 -0700457 // Devices with mics.
458 if (classes & INPUT_DEVICE_CLASS_MIC) {
459 device->setMic(true);
460 }
461
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462 // Switch-like devices.
463 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
464 device->addMapper(new SwitchInputMapper(device));
465 }
466
Prashant Malani1941ff52015-08-11 18:29:28 -0700467 // Scroll wheel-like devices.
468 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
469 device->addMapper(new RotaryEncoderInputMapper(device));
470 }
471
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 // Vibrator-like devices.
473 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
474 device->addMapper(new VibratorInputMapper(device));
475 }
476
477 // Keyboard-like devices.
478 uint32_t keyboardSource = 0;
479 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
480 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
481 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
482 }
483 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
484 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
485 }
486 if (classes & INPUT_DEVICE_CLASS_DPAD) {
487 keyboardSource |= AINPUT_SOURCE_DPAD;
488 }
489 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
490 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
491 }
492
493 if (keyboardSource != 0) {
494 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
495 }
496
497 // Cursor-like devices.
498 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
499 device->addMapper(new CursorInputMapper(device));
500 }
501
502 // Touchscreens and touchpad devices.
503 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
504 device->addMapper(new MultiTouchInputMapper(device));
505 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
506 device->addMapper(new SingleTouchInputMapper(device));
507 }
508
509 // Joystick-like devices.
510 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
511 device->addMapper(new JoystickInputMapper(device));
512 }
513
Michael Wright842500e2015-03-13 17:32:02 -0700514 // External stylus-like devices.
515 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
516 device->addMapper(new ExternalStylusInputMapper(device));
517 }
518
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 return device;
520}
521
522void InputReader::processEventsForDeviceLocked(int32_t deviceId,
523 const RawEvent* rawEvents, size_t count) {
524 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
525 if (deviceIndex < 0) {
526 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
527 return;
528 }
529
530 InputDevice* device = mDevices.valueAt(deviceIndex);
531 if (device->isIgnored()) {
532 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
533 return;
534 }
535
536 device->process(rawEvents, count);
537}
538
539void InputReader::timeoutExpiredLocked(nsecs_t when) {
540 for (size_t i = 0; i < mDevices.size(); i++) {
541 InputDevice* device = mDevices.valueAt(i);
542 if (!device->isIgnored()) {
543 device->timeoutExpired(when);
544 }
545 }
546}
547
548void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
549 // Reset global meta state because it depends on the list of all configured devices.
550 updateGlobalMetaStateLocked();
551
552 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800553 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 mQueuedListener->notifyConfigurationChanged(&args);
555}
556
557void InputReader::refreshConfigurationLocked(uint32_t changes) {
558 mPolicy->getReaderConfiguration(&mConfig);
559 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
560
561 if (changes) {
562 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
563 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
564
565 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
566 mEventHub->requestReopenDevices();
567 } else {
568 for (size_t i = 0; i < mDevices.size(); i++) {
569 InputDevice* device = mDevices.valueAt(i);
570 device->configure(now, &mConfig, changes);
571 }
572 }
573 }
574}
575
576void InputReader::updateGlobalMetaStateLocked() {
577 mGlobalMetaState = 0;
578
579 for (size_t i = 0; i < mDevices.size(); i++) {
580 InputDevice* device = mDevices.valueAt(i);
581 mGlobalMetaState |= device->getMetaState();
582 }
583}
584
585int32_t InputReader::getGlobalMetaStateLocked() {
586 return mGlobalMetaState;
587}
588
Michael Wright842500e2015-03-13 17:32:02 -0700589void InputReader::notifyExternalStylusPresenceChanged() {
590 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
591}
592
593void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
594 for (size_t i = 0; i < mDevices.size(); i++) {
595 InputDevice* device = mDevices.valueAt(i);
596 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
597 outDevices.push();
598 device->getDeviceInfo(&outDevices.editTop());
599 }
600 }
601}
602
603void InputReader::dispatchExternalStylusState(const StylusState& state) {
604 for (size_t i = 0; i < mDevices.size(); i++) {
605 InputDevice* device = mDevices.valueAt(i);
606 device->updateExternalStylusState(state);
607 }
608}
609
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
611 mDisableVirtualKeysTimeout = time;
612}
613
614bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
615 InputDevice* device, int32_t keyCode, int32_t scanCode) {
616 if (now < mDisableVirtualKeysTimeout) {
617 ALOGI("Dropping virtual key from device %s because virtual keys are "
618 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100619 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 (mDisableVirtualKeysTimeout - now) * 0.000001,
621 keyCode, scanCode);
622 return true;
623 } else {
624 return false;
625 }
626}
627
628void InputReader::fadePointerLocked() {
629 for (size_t i = 0; i < mDevices.size(); i++) {
630 InputDevice* device = mDevices.valueAt(i);
631 device->fadePointer();
632 }
633}
634
635void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
636 if (when < mNextTimeout) {
637 mNextTimeout = when;
638 mEventHub->wake();
639 }
640}
641
642int32_t InputReader::bumpGenerationLocked() {
643 return ++mGeneration;
644}
645
646void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
647 AutoMutex _l(mLock);
648 getInputDevicesLocked(outInputDevices);
649}
650
651void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
652 outInputDevices.clear();
653
654 size_t numDevices = mDevices.size();
655 for (size_t i = 0; i < numDevices; i++) {
656 InputDevice* device = mDevices.valueAt(i);
657 if (!device->isIgnored()) {
658 outInputDevices.push();
659 device->getDeviceInfo(&outInputDevices.editTop());
660 }
661 }
662}
663
664int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
665 int32_t keyCode) {
666 AutoMutex _l(mLock);
667
668 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
669}
670
671int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
672 int32_t scanCode) {
673 AutoMutex _l(mLock);
674
675 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
676}
677
678int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
679 AutoMutex _l(mLock);
680
681 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
682}
683
684int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
685 GetStateFunc getStateFunc) {
686 int32_t result = AKEY_STATE_UNKNOWN;
687 if (deviceId >= 0) {
688 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
689 if (deviceIndex >= 0) {
690 InputDevice* device = mDevices.valueAt(deviceIndex);
691 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
692 result = (device->*getStateFunc)(sourceMask, code);
693 }
694 }
695 } else {
696 size_t numDevices = mDevices.size();
697 for (size_t i = 0; i < numDevices; i++) {
698 InputDevice* device = mDevices.valueAt(i);
699 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
700 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
701 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
702 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
703 if (currentResult >= AKEY_STATE_DOWN) {
704 return currentResult;
705 } else if (currentResult == AKEY_STATE_UP) {
706 result = currentResult;
707 }
708 }
709 }
710 }
711 return result;
712}
713
Andrii Kulian763a3a42016-03-08 10:46:16 -0800714void InputReader::toggleCapsLockState(int32_t deviceId) {
715 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
716 if (deviceIndex < 0) {
717 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
718 return;
719 }
720
721 InputDevice* device = mDevices.valueAt(deviceIndex);
722 if (device->isIgnored()) {
723 return;
724 }
725
726 device->updateMetaState(AKEYCODE_CAPS_LOCK);
727}
728
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
730 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
731 AutoMutex _l(mLock);
732
733 memset(outFlags, 0, numCodes);
734 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
735}
736
737bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
738 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
739 bool result = false;
740 if (deviceId >= 0) {
741 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
742 if (deviceIndex >= 0) {
743 InputDevice* device = mDevices.valueAt(deviceIndex);
744 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
745 result = device->markSupportedKeyCodes(sourceMask,
746 numCodes, keyCodes, outFlags);
747 }
748 }
749 } else {
750 size_t numDevices = mDevices.size();
751 for (size_t i = 0; i < numDevices; i++) {
752 InputDevice* device = mDevices.valueAt(i);
753 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
754 result |= device->markSupportedKeyCodes(sourceMask,
755 numCodes, keyCodes, outFlags);
756 }
757 }
758 }
759 return result;
760}
761
762void InputReader::requestRefreshConfiguration(uint32_t changes) {
763 AutoMutex _l(mLock);
764
765 if (changes) {
766 bool needWake = !mConfigurationChangesToRefresh;
767 mConfigurationChangesToRefresh |= changes;
768
769 if (needWake) {
770 mEventHub->wake();
771 }
772 }
773}
774
775void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
776 ssize_t repeat, int32_t token) {
777 AutoMutex _l(mLock);
778
779 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
780 if (deviceIndex >= 0) {
781 InputDevice* device = mDevices.valueAt(deviceIndex);
782 device->vibrate(pattern, patternSize, repeat, token);
783 }
784}
785
786void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
787 AutoMutex _l(mLock);
788
789 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
790 if (deviceIndex >= 0) {
791 InputDevice* device = mDevices.valueAt(deviceIndex);
792 device->cancelVibrate(token);
793 }
794}
795
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700796bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
797 AutoMutex _l(mLock);
798
799 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
800 if (deviceIndex >= 0) {
801 InputDevice* device = mDevices.valueAt(deviceIndex);
802 return device->isEnabled();
803 }
804 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
805 return false;
806}
807
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800808void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 AutoMutex _l(mLock);
810
811 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800812 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800814 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815
816 for (size_t i = 0; i < mDevices.size(); i++) {
817 mDevices.valueAt(i)->dump(dump);
818 }
819
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800820 dump += INDENT "Configuration:\n";
821 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
823 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800824 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100826 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800828 dump += "]\n";
829 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 mConfig.virtualKeyQuietTime * 0.000001f);
831
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800832 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
834 mConfig.pointerVelocityControlParameters.scale,
835 mConfig.pointerVelocityControlParameters.lowThreshold,
836 mConfig.pointerVelocityControlParameters.highThreshold,
837 mConfig.pointerVelocityControlParameters.acceleration);
838
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800839 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
841 mConfig.wheelVelocityControlParameters.scale,
842 mConfig.wheelVelocityControlParameters.lowThreshold,
843 mConfig.wheelVelocityControlParameters.highThreshold,
844 mConfig.wheelVelocityControlParameters.acceleration);
845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846 dump += StringPrintf(INDENT2 "PointerGesture:\n");
847 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800849 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800851 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800853 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800855 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800857 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800859 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800861 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800863 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800865 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800867 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800869 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700871
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800872 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700873 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874}
875
876void InputReader::monitor() {
877 // Acquire and release the lock to ensure that the reader has not deadlocked.
878 mLock.lock();
879 mEventHub->wake();
880 mReaderIsAliveCondition.wait(mLock);
881 mLock.unlock();
882
883 // Check the EventHub
884 mEventHub->monitor();
885}
886
887
888// --- InputReader::ContextImpl ---
889
890InputReader::ContextImpl::ContextImpl(InputReader* reader) :
891 mReader(reader) {
892}
893
894void InputReader::ContextImpl::updateGlobalMetaState() {
895 // lock is already held by the input loop
896 mReader->updateGlobalMetaStateLocked();
897}
898
899int32_t InputReader::ContextImpl::getGlobalMetaState() {
900 // lock is already held by the input loop
901 return mReader->getGlobalMetaStateLocked();
902}
903
904void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
905 // lock is already held by the input loop
906 mReader->disableVirtualKeysUntilLocked(time);
907}
908
909bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
910 InputDevice* device, int32_t keyCode, int32_t scanCode) {
911 // lock is already held by the input loop
912 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
913}
914
915void InputReader::ContextImpl::fadePointer() {
916 // lock is already held by the input loop
917 mReader->fadePointerLocked();
918}
919
920void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
921 // lock is already held by the input loop
922 mReader->requestTimeoutAtTimeLocked(when);
923}
924
925int32_t InputReader::ContextImpl::bumpGeneration() {
926 // lock is already held by the input loop
927 return mReader->bumpGenerationLocked();
928}
929
Michael Wright842500e2015-03-13 17:32:02 -0700930void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
931 // lock is already held by whatever called refreshConfigurationLocked
932 mReader->getExternalStylusDevicesLocked(outDevices);
933}
934
935void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
936 mReader->dispatchExternalStylusState(state);
937}
938
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
940 return mReader->mPolicy.get();
941}
942
943InputListenerInterface* InputReader::ContextImpl::getListener() {
944 return mReader->mQueuedListener.get();
945}
946
947EventHubInterface* InputReader::ContextImpl::getEventHub() {
948 return mReader->mEventHub.get();
949}
950
Prabir Pradhan42611e02018-11-27 14:04:02 -0800951uint32_t InputReader::ContextImpl::getNextSequenceNum() {
952 return (mReader->mNextSequenceNum)++;
953}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955// --- InputDevice ---
956
957InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
958 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
959 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
960 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700961 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962}
963
964InputDevice::~InputDevice() {
965 size_t numMappers = mMappers.size();
966 for (size_t i = 0; i < numMappers; i++) {
967 delete mMappers[i];
968 }
969 mMappers.clear();
970}
971
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700972bool InputDevice::isEnabled() {
973 return getEventHub()->isDeviceEnabled(mId);
974}
975
976void InputDevice::setEnabled(bool enabled, nsecs_t when) {
977 if (isEnabled() == enabled) {
978 return;
979 }
980
981 if (enabled) {
982 getEventHub()->enableDevice(mId);
983 reset(when);
984 } else {
985 reset(when);
986 getEventHub()->disableDevice(mId);
987 }
988 // Must change generation to flag this device as changed
989 bumpGeneration();
990}
991
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800992void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -0700994 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800996 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100997 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800998 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
999 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001000 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1001 if (mAssociatedDisplayPort) {
1002 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1003 } else {
1004 dump += "<none>\n";
1005 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001006 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1007 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1008 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009
1010 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1011 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001012 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 for (size_t i = 0; i < ranges.size(); i++) {
1014 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1015 const char* label = getAxisLabel(range.axis);
1016 char name[32];
1017 if (label) {
1018 strncpy(name, label, sizeof(name));
1019 name[sizeof(name) - 1] = '\0';
1020 } else {
1021 snprintf(name, sizeof(name), "%d", range.axis);
1022 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001023 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1025 name, range.source, range.min, range.max, range.flat, range.fuzz,
1026 range.resolution);
1027 }
1028 }
1029
1030 size_t numMappers = mMappers.size();
1031 for (size_t i = 0; i < numMappers; i++) {
1032 InputMapper* mapper = mMappers[i];
1033 mapper->dump(dump);
1034 }
1035}
1036
1037void InputDevice::addMapper(InputMapper* mapper) {
1038 mMappers.add(mapper);
1039}
1040
1041void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1042 mSources = 0;
1043
1044 if (!isIgnored()) {
1045 if (!changes) { // first time only
1046 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1047 }
1048
1049 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1050 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1051 sp<KeyCharacterMap> keyboardLayout =
1052 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1053 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1054 bumpGeneration();
1055 }
1056 }
1057 }
1058
1059 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1060 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001061 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 if (mAlias != alias) {
1063 mAlias = alias;
1064 bumpGeneration();
1065 }
1066 }
1067 }
1068
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001069 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1070 ssize_t index = config->disabledDevices.indexOf(mId);
1071 bool enabled = index < 0;
1072 setEnabled(enabled, when);
1073 }
1074
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001075 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1076 // In most situations, no port will be specified.
1077 mAssociatedDisplayPort = std::nullopt;
1078 // Find the display port that corresponds to the current input port.
1079 const std::string& inputPort = mIdentifier.location;
1080 if (!inputPort.empty()) {
1081 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1082 const auto& displayPort = ports.find(inputPort);
1083 if (displayPort != ports.end()) {
1084 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1085 }
1086 }
1087 }
1088
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 size_t numMappers = mMappers.size();
1090 for (size_t i = 0; i < numMappers; i++) {
1091 InputMapper* mapper = mMappers[i];
1092 mapper->configure(when, config, changes);
1093 mSources |= mapper->getSources();
1094 }
1095 }
1096}
1097
1098void InputDevice::reset(nsecs_t when) {
1099 size_t numMappers = mMappers.size();
1100 for (size_t i = 0; i < numMappers; i++) {
1101 InputMapper* mapper = mMappers[i];
1102 mapper->reset(when);
1103 }
1104
1105 mContext->updateGlobalMetaState();
1106
1107 notifyReset(when);
1108}
1109
1110void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1111 // Process all of the events in order for each mapper.
1112 // We cannot simply ask each mapper to process them in bulk because mappers may
1113 // have side-effects that must be interleaved. For example, joystick movement events and
1114 // gamepad button presses are handled by different mappers but they should be dispatched
1115 // in the order received.
1116 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001117 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001119 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1121 rawEvent->when);
1122#endif
1123
1124 if (mDropUntilNextSync) {
1125 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1126 mDropUntilNextSync = false;
1127#if DEBUG_RAW_EVENTS
1128 ALOGD("Recovered from input event buffer overrun.");
1129#endif
1130 } else {
1131#if DEBUG_RAW_EVENTS
1132 ALOGD("Dropped input event while waiting for next input sync.");
1133#endif
1134 }
1135 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001136 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 mDropUntilNextSync = true;
1138 reset(rawEvent->when);
1139 } else {
1140 for (size_t i = 0; i < numMappers; i++) {
1141 InputMapper* mapper = mMappers[i];
1142 mapper->process(rawEvent);
1143 }
1144 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001145 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 }
1147}
1148
1149void InputDevice::timeoutExpired(nsecs_t when) {
1150 size_t numMappers = mMappers.size();
1151 for (size_t i = 0; i < numMappers; i++) {
1152 InputMapper* mapper = mMappers[i];
1153 mapper->timeoutExpired(when);
1154 }
1155}
1156
Michael Wright842500e2015-03-13 17:32:02 -07001157void InputDevice::updateExternalStylusState(const StylusState& state) {
1158 size_t numMappers = mMappers.size();
1159 for (size_t i = 0; i < numMappers; i++) {
1160 InputMapper* mapper = mMappers[i];
1161 mapper->updateExternalStylusState(state);
1162 }
1163}
1164
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1166 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001167 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 size_t numMappers = mMappers.size();
1169 for (size_t i = 0; i < numMappers; i++) {
1170 InputMapper* mapper = mMappers[i];
1171 mapper->populateDeviceInfo(outDeviceInfo);
1172 }
1173}
1174
1175int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1176 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1177}
1178
1179int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1180 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1181}
1182
1183int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1184 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1185}
1186
1187int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1188 int32_t result = AKEY_STATE_UNKNOWN;
1189 size_t numMappers = mMappers.size();
1190 for (size_t i = 0; i < numMappers; i++) {
1191 InputMapper* mapper = mMappers[i];
1192 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1193 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1194 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1195 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1196 if (currentResult >= AKEY_STATE_DOWN) {
1197 return currentResult;
1198 } else if (currentResult == AKEY_STATE_UP) {
1199 result = currentResult;
1200 }
1201 }
1202 }
1203 return result;
1204}
1205
1206bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1207 const int32_t* keyCodes, uint8_t* outFlags) {
1208 bool result = false;
1209 size_t numMappers = mMappers.size();
1210 for (size_t i = 0; i < numMappers; i++) {
1211 InputMapper* mapper = mMappers[i];
1212 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1213 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1214 }
1215 }
1216 return result;
1217}
1218
1219void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1220 int32_t token) {
1221 size_t numMappers = mMappers.size();
1222 for (size_t i = 0; i < numMappers; i++) {
1223 InputMapper* mapper = mMappers[i];
1224 mapper->vibrate(pattern, patternSize, repeat, token);
1225 }
1226}
1227
1228void InputDevice::cancelVibrate(int32_t token) {
1229 size_t numMappers = mMappers.size();
1230 for (size_t i = 0; i < numMappers; i++) {
1231 InputMapper* mapper = mMappers[i];
1232 mapper->cancelVibrate(token);
1233 }
1234}
1235
Jeff Brownc9aa6282015-02-11 19:03:28 -08001236void InputDevice::cancelTouch(nsecs_t when) {
1237 size_t numMappers = mMappers.size();
1238 for (size_t i = 0; i < numMappers; i++) {
1239 InputMapper* mapper = mMappers[i];
1240 mapper->cancelTouch(when);
1241 }
1242}
1243
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244int32_t InputDevice::getMetaState() {
1245 int32_t result = 0;
1246 size_t numMappers = mMappers.size();
1247 for (size_t i = 0; i < numMappers; i++) {
1248 InputMapper* mapper = mMappers[i];
1249 result |= mapper->getMetaState();
1250 }
1251 return result;
1252}
1253
Andrii Kulian763a3a42016-03-08 10:46:16 -08001254void InputDevice::updateMetaState(int32_t keyCode) {
1255 size_t numMappers = mMappers.size();
1256 for (size_t i = 0; i < numMappers; i++) {
1257 mMappers[i]->updateMetaState(keyCode);
1258 }
1259}
1260
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261void InputDevice::fadePointer() {
1262 size_t numMappers = mMappers.size();
1263 for (size_t i = 0; i < numMappers; i++) {
1264 InputMapper* mapper = mMappers[i];
1265 mapper->fadePointer();
1266 }
1267}
1268
1269void InputDevice::bumpGeneration() {
1270 mGeneration = mContext->bumpGeneration();
1271}
1272
1273void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001274 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 mContext->getListener()->notifyDeviceReset(&args);
1276}
1277
1278
1279// --- CursorButtonAccumulator ---
1280
1281CursorButtonAccumulator::CursorButtonAccumulator() {
1282 clearButtons();
1283}
1284
1285void CursorButtonAccumulator::reset(InputDevice* device) {
1286 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1287 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1288 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1289 mBtnBack = device->isKeyPressed(BTN_BACK);
1290 mBtnSide = device->isKeyPressed(BTN_SIDE);
1291 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1292 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1293 mBtnTask = device->isKeyPressed(BTN_TASK);
1294}
1295
1296void CursorButtonAccumulator::clearButtons() {
1297 mBtnLeft = 0;
1298 mBtnRight = 0;
1299 mBtnMiddle = 0;
1300 mBtnBack = 0;
1301 mBtnSide = 0;
1302 mBtnForward = 0;
1303 mBtnExtra = 0;
1304 mBtnTask = 0;
1305}
1306
1307void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1308 if (rawEvent->type == EV_KEY) {
1309 switch (rawEvent->code) {
1310 case BTN_LEFT:
1311 mBtnLeft = rawEvent->value;
1312 break;
1313 case BTN_RIGHT:
1314 mBtnRight = rawEvent->value;
1315 break;
1316 case BTN_MIDDLE:
1317 mBtnMiddle = rawEvent->value;
1318 break;
1319 case BTN_BACK:
1320 mBtnBack = rawEvent->value;
1321 break;
1322 case BTN_SIDE:
1323 mBtnSide = rawEvent->value;
1324 break;
1325 case BTN_FORWARD:
1326 mBtnForward = rawEvent->value;
1327 break;
1328 case BTN_EXTRA:
1329 mBtnExtra = rawEvent->value;
1330 break;
1331 case BTN_TASK:
1332 mBtnTask = rawEvent->value;
1333 break;
1334 }
1335 }
1336}
1337
1338uint32_t CursorButtonAccumulator::getButtonState() const {
1339 uint32_t result = 0;
1340 if (mBtnLeft) {
1341 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1342 }
1343 if (mBtnRight) {
1344 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1345 }
1346 if (mBtnMiddle) {
1347 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1348 }
1349 if (mBtnBack || mBtnSide) {
1350 result |= AMOTION_EVENT_BUTTON_BACK;
1351 }
1352 if (mBtnForward || mBtnExtra) {
1353 result |= AMOTION_EVENT_BUTTON_FORWARD;
1354 }
1355 return result;
1356}
1357
1358
1359// --- CursorMotionAccumulator ---
1360
1361CursorMotionAccumulator::CursorMotionAccumulator() {
1362 clearRelativeAxes();
1363}
1364
1365void CursorMotionAccumulator::reset(InputDevice* device) {
1366 clearRelativeAxes();
1367}
1368
1369void CursorMotionAccumulator::clearRelativeAxes() {
1370 mRelX = 0;
1371 mRelY = 0;
1372}
1373
1374void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1375 if (rawEvent->type == EV_REL) {
1376 switch (rawEvent->code) {
1377 case REL_X:
1378 mRelX = rawEvent->value;
1379 break;
1380 case REL_Y:
1381 mRelY = rawEvent->value;
1382 break;
1383 }
1384 }
1385}
1386
1387void CursorMotionAccumulator::finishSync() {
1388 clearRelativeAxes();
1389}
1390
1391
1392// --- CursorScrollAccumulator ---
1393
1394CursorScrollAccumulator::CursorScrollAccumulator() :
1395 mHaveRelWheel(false), mHaveRelHWheel(false) {
1396 clearRelativeAxes();
1397}
1398
1399void CursorScrollAccumulator::configure(InputDevice* device) {
1400 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1401 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1402}
1403
1404void CursorScrollAccumulator::reset(InputDevice* device) {
1405 clearRelativeAxes();
1406}
1407
1408void CursorScrollAccumulator::clearRelativeAxes() {
1409 mRelWheel = 0;
1410 mRelHWheel = 0;
1411}
1412
1413void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1414 if (rawEvent->type == EV_REL) {
1415 switch (rawEvent->code) {
1416 case REL_WHEEL:
1417 mRelWheel = rawEvent->value;
1418 break;
1419 case REL_HWHEEL:
1420 mRelHWheel = rawEvent->value;
1421 break;
1422 }
1423 }
1424}
1425
1426void CursorScrollAccumulator::finishSync() {
1427 clearRelativeAxes();
1428}
1429
1430
1431// --- TouchButtonAccumulator ---
1432
1433TouchButtonAccumulator::TouchButtonAccumulator() :
1434 mHaveBtnTouch(false), mHaveStylus(false) {
1435 clearButtons();
1436}
1437
1438void TouchButtonAccumulator::configure(InputDevice* device) {
1439 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1440 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1441 || device->hasKey(BTN_TOOL_RUBBER)
1442 || device->hasKey(BTN_TOOL_BRUSH)
1443 || device->hasKey(BTN_TOOL_PENCIL)
1444 || device->hasKey(BTN_TOOL_AIRBRUSH);
1445}
1446
1447void TouchButtonAccumulator::reset(InputDevice* device) {
1448 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1449 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001450 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1451 mBtnStylus2 =
1452 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1454 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1455 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1456 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1457 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1458 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1459 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1460 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1461 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1462 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1463 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1464}
1465
1466void TouchButtonAccumulator::clearButtons() {
1467 mBtnTouch = 0;
1468 mBtnStylus = 0;
1469 mBtnStylus2 = 0;
1470 mBtnToolFinger = 0;
1471 mBtnToolPen = 0;
1472 mBtnToolRubber = 0;
1473 mBtnToolBrush = 0;
1474 mBtnToolPencil = 0;
1475 mBtnToolAirbrush = 0;
1476 mBtnToolMouse = 0;
1477 mBtnToolLens = 0;
1478 mBtnToolDoubleTap = 0;
1479 mBtnToolTripleTap = 0;
1480 mBtnToolQuadTap = 0;
1481}
1482
1483void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1484 if (rawEvent->type == EV_KEY) {
1485 switch (rawEvent->code) {
1486 case BTN_TOUCH:
1487 mBtnTouch = rawEvent->value;
1488 break;
1489 case BTN_STYLUS:
1490 mBtnStylus = rawEvent->value;
1491 break;
1492 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001493 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 mBtnStylus2 = rawEvent->value;
1495 break;
1496 case BTN_TOOL_FINGER:
1497 mBtnToolFinger = rawEvent->value;
1498 break;
1499 case BTN_TOOL_PEN:
1500 mBtnToolPen = rawEvent->value;
1501 break;
1502 case BTN_TOOL_RUBBER:
1503 mBtnToolRubber = rawEvent->value;
1504 break;
1505 case BTN_TOOL_BRUSH:
1506 mBtnToolBrush = rawEvent->value;
1507 break;
1508 case BTN_TOOL_PENCIL:
1509 mBtnToolPencil = rawEvent->value;
1510 break;
1511 case BTN_TOOL_AIRBRUSH:
1512 mBtnToolAirbrush = rawEvent->value;
1513 break;
1514 case BTN_TOOL_MOUSE:
1515 mBtnToolMouse = rawEvent->value;
1516 break;
1517 case BTN_TOOL_LENS:
1518 mBtnToolLens = rawEvent->value;
1519 break;
1520 case BTN_TOOL_DOUBLETAP:
1521 mBtnToolDoubleTap = rawEvent->value;
1522 break;
1523 case BTN_TOOL_TRIPLETAP:
1524 mBtnToolTripleTap = rawEvent->value;
1525 break;
1526 case BTN_TOOL_QUADTAP:
1527 mBtnToolQuadTap = rawEvent->value;
1528 break;
1529 }
1530 }
1531}
1532
1533uint32_t TouchButtonAccumulator::getButtonState() const {
1534 uint32_t result = 0;
1535 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001536 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 }
1538 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001539 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 }
1541 return result;
1542}
1543
1544int32_t TouchButtonAccumulator::getToolType() const {
1545 if (mBtnToolMouse || mBtnToolLens) {
1546 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1547 }
1548 if (mBtnToolRubber) {
1549 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1550 }
1551 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1552 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1553 }
1554 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1555 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1556 }
1557 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1558}
1559
1560bool TouchButtonAccumulator::isToolActive() const {
1561 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1562 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1563 || mBtnToolMouse || mBtnToolLens
1564 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1565}
1566
1567bool TouchButtonAccumulator::isHovering() const {
1568 return mHaveBtnTouch && !mBtnTouch;
1569}
1570
1571bool TouchButtonAccumulator::hasStylus() const {
1572 return mHaveStylus;
1573}
1574
1575
1576// --- RawPointerAxes ---
1577
1578RawPointerAxes::RawPointerAxes() {
1579 clear();
1580}
1581
1582void RawPointerAxes::clear() {
1583 x.clear();
1584 y.clear();
1585 pressure.clear();
1586 touchMajor.clear();
1587 touchMinor.clear();
1588 toolMajor.clear();
1589 toolMinor.clear();
1590 orientation.clear();
1591 distance.clear();
1592 tiltX.clear();
1593 tiltY.clear();
1594 trackingId.clear();
1595 slot.clear();
1596}
1597
1598
1599// --- RawPointerData ---
1600
1601RawPointerData::RawPointerData() {
1602 clear();
1603}
1604
1605void RawPointerData::clear() {
1606 pointerCount = 0;
1607 clearIdBits();
1608}
1609
1610void RawPointerData::copyFrom(const RawPointerData& other) {
1611 pointerCount = other.pointerCount;
1612 hoveringIdBits = other.hoveringIdBits;
1613 touchingIdBits = other.touchingIdBits;
1614
1615 for (uint32_t i = 0; i < pointerCount; i++) {
1616 pointers[i] = other.pointers[i];
1617
1618 int id = pointers[i].id;
1619 idToIndex[id] = other.idToIndex[id];
1620 }
1621}
1622
1623void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1624 float x = 0, y = 0;
1625 uint32_t count = touchingIdBits.count();
1626 if (count) {
1627 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1628 uint32_t id = idBits.clearFirstMarkedBit();
1629 const Pointer& pointer = pointerForId(id);
1630 x += pointer.x;
1631 y += pointer.y;
1632 }
1633 x /= count;
1634 y /= count;
1635 }
1636 *outX = x;
1637 *outY = y;
1638}
1639
1640
1641// --- CookedPointerData ---
1642
1643CookedPointerData::CookedPointerData() {
1644 clear();
1645}
1646
1647void CookedPointerData::clear() {
1648 pointerCount = 0;
1649 hoveringIdBits.clear();
1650 touchingIdBits.clear();
1651}
1652
1653void CookedPointerData::copyFrom(const CookedPointerData& other) {
1654 pointerCount = other.pointerCount;
1655 hoveringIdBits = other.hoveringIdBits;
1656 touchingIdBits = other.touchingIdBits;
1657
1658 for (uint32_t i = 0; i < pointerCount; i++) {
1659 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1660 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1661
1662 int id = pointerProperties[i].id;
1663 idToIndex[id] = other.idToIndex[id];
1664 }
1665}
1666
1667
1668// --- SingleTouchMotionAccumulator ---
1669
1670SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1671 clearAbsoluteAxes();
1672}
1673
1674void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1675 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1676 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1677 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1678 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1679 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1680 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1681 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1682}
1683
1684void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1685 mAbsX = 0;
1686 mAbsY = 0;
1687 mAbsPressure = 0;
1688 mAbsToolWidth = 0;
1689 mAbsDistance = 0;
1690 mAbsTiltX = 0;
1691 mAbsTiltY = 0;
1692}
1693
1694void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1695 if (rawEvent->type == EV_ABS) {
1696 switch (rawEvent->code) {
1697 case ABS_X:
1698 mAbsX = rawEvent->value;
1699 break;
1700 case ABS_Y:
1701 mAbsY = rawEvent->value;
1702 break;
1703 case ABS_PRESSURE:
1704 mAbsPressure = rawEvent->value;
1705 break;
1706 case ABS_TOOL_WIDTH:
1707 mAbsToolWidth = rawEvent->value;
1708 break;
1709 case ABS_DISTANCE:
1710 mAbsDistance = rawEvent->value;
1711 break;
1712 case ABS_TILT_X:
1713 mAbsTiltX = rawEvent->value;
1714 break;
1715 case ABS_TILT_Y:
1716 mAbsTiltY = rawEvent->value;
1717 break;
1718 }
1719 }
1720}
1721
1722
1723// --- MultiTouchMotionAccumulator ---
1724
1725MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001726 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001727 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728}
1729
1730MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1731 delete[] mSlots;
1732}
1733
1734void MultiTouchMotionAccumulator::configure(InputDevice* device,
1735 size_t slotCount, bool usingSlotsProtocol) {
1736 mSlotCount = slotCount;
1737 mUsingSlotsProtocol = usingSlotsProtocol;
1738 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1739
1740 delete[] mSlots;
1741 mSlots = new Slot[slotCount];
1742}
1743
1744void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1745 // Unfortunately there is no way to read the initial contents of the slots.
1746 // So when we reset the accumulator, we must assume they are all zeroes.
1747 if (mUsingSlotsProtocol) {
1748 // Query the driver for the current slot index and use it as the initial slot
1749 // before we start reading events from the device. It is possible that the
1750 // current slot index will not be the same as it was when the first event was
1751 // written into the evdev buffer, which means the input mapper could start
1752 // out of sync with the initial state of the events in the evdev buffer.
1753 // In the extremely unlikely case that this happens, the data from
1754 // two slots will be confused until the next ABS_MT_SLOT event is received.
1755 // This can cause the touch point to "jump", but at least there will be
1756 // no stuck touches.
1757 int32_t initialSlot;
1758 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1759 ABS_MT_SLOT, &initialSlot);
1760 if (status) {
1761 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1762 initialSlot = -1;
1763 }
1764 clearSlots(initialSlot);
1765 } else {
1766 clearSlots(-1);
1767 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001768 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769}
1770
1771void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1772 if (mSlots) {
1773 for (size_t i = 0; i < mSlotCount; i++) {
1774 mSlots[i].clear();
1775 }
1776 }
1777 mCurrentSlot = initialSlot;
1778}
1779
1780void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1781 if (rawEvent->type == EV_ABS) {
1782 bool newSlot = false;
1783 if (mUsingSlotsProtocol) {
1784 if (rawEvent->code == ABS_MT_SLOT) {
1785 mCurrentSlot = rawEvent->value;
1786 newSlot = true;
1787 }
1788 } else if (mCurrentSlot < 0) {
1789 mCurrentSlot = 0;
1790 }
1791
1792 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1793#if DEBUG_POINTERS
1794 if (newSlot) {
1795 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001796 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 mCurrentSlot, mSlotCount - 1);
1798 }
1799#endif
1800 } else {
1801 Slot* slot = &mSlots[mCurrentSlot];
1802
1803 switch (rawEvent->code) {
1804 case ABS_MT_POSITION_X:
1805 slot->mInUse = true;
1806 slot->mAbsMTPositionX = rawEvent->value;
1807 break;
1808 case ABS_MT_POSITION_Y:
1809 slot->mInUse = true;
1810 slot->mAbsMTPositionY = rawEvent->value;
1811 break;
1812 case ABS_MT_TOUCH_MAJOR:
1813 slot->mInUse = true;
1814 slot->mAbsMTTouchMajor = rawEvent->value;
1815 break;
1816 case ABS_MT_TOUCH_MINOR:
1817 slot->mInUse = true;
1818 slot->mAbsMTTouchMinor = rawEvent->value;
1819 slot->mHaveAbsMTTouchMinor = true;
1820 break;
1821 case ABS_MT_WIDTH_MAJOR:
1822 slot->mInUse = true;
1823 slot->mAbsMTWidthMajor = rawEvent->value;
1824 break;
1825 case ABS_MT_WIDTH_MINOR:
1826 slot->mInUse = true;
1827 slot->mAbsMTWidthMinor = rawEvent->value;
1828 slot->mHaveAbsMTWidthMinor = true;
1829 break;
1830 case ABS_MT_ORIENTATION:
1831 slot->mInUse = true;
1832 slot->mAbsMTOrientation = rawEvent->value;
1833 break;
1834 case ABS_MT_TRACKING_ID:
1835 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1836 // The slot is no longer in use but it retains its previous contents,
1837 // which may be reused for subsequent touches.
1838 slot->mInUse = false;
1839 } else {
1840 slot->mInUse = true;
1841 slot->mAbsMTTrackingId = rawEvent->value;
1842 }
1843 break;
1844 case ABS_MT_PRESSURE:
1845 slot->mInUse = true;
1846 slot->mAbsMTPressure = rawEvent->value;
1847 break;
1848 case ABS_MT_DISTANCE:
1849 slot->mInUse = true;
1850 slot->mAbsMTDistance = rawEvent->value;
1851 break;
1852 case ABS_MT_TOOL_TYPE:
1853 slot->mInUse = true;
1854 slot->mAbsMTToolType = rawEvent->value;
1855 slot->mHaveAbsMTToolType = true;
1856 break;
1857 }
1858 }
1859 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1860 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1861 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001862 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1863 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 }
1865}
1866
1867void MultiTouchMotionAccumulator::finishSync() {
1868 if (!mUsingSlotsProtocol) {
1869 clearSlots(-1);
1870 }
1871}
1872
1873bool MultiTouchMotionAccumulator::hasStylus() const {
1874 return mHaveStylus;
1875}
1876
1877
1878// --- MultiTouchMotionAccumulator::Slot ---
1879
1880MultiTouchMotionAccumulator::Slot::Slot() {
1881 clear();
1882}
1883
1884void MultiTouchMotionAccumulator::Slot::clear() {
1885 mInUse = false;
1886 mHaveAbsMTTouchMinor = false;
1887 mHaveAbsMTWidthMinor = false;
1888 mHaveAbsMTToolType = false;
1889 mAbsMTPositionX = 0;
1890 mAbsMTPositionY = 0;
1891 mAbsMTTouchMajor = 0;
1892 mAbsMTTouchMinor = 0;
1893 mAbsMTWidthMajor = 0;
1894 mAbsMTWidthMinor = 0;
1895 mAbsMTOrientation = 0;
1896 mAbsMTTrackingId = -1;
1897 mAbsMTPressure = 0;
1898 mAbsMTDistance = 0;
1899 mAbsMTToolType = 0;
1900}
1901
1902int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1903 if (mHaveAbsMTToolType) {
1904 switch (mAbsMTToolType) {
1905 case MT_TOOL_FINGER:
1906 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1907 case MT_TOOL_PEN:
1908 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1909 }
1910 }
1911 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1912}
1913
1914
1915// --- InputMapper ---
1916
1917InputMapper::InputMapper(InputDevice* device) :
1918 mDevice(device), mContext(device->getContext()) {
1919}
1920
1921InputMapper::~InputMapper() {
1922}
1923
1924void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1925 info->addSource(getSources());
1926}
1927
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001928void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929}
1930
1931void InputMapper::configure(nsecs_t when,
1932 const InputReaderConfiguration* config, uint32_t changes) {
1933}
1934
1935void InputMapper::reset(nsecs_t when) {
1936}
1937
1938void InputMapper::timeoutExpired(nsecs_t when) {
1939}
1940
1941int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1942 return AKEY_STATE_UNKNOWN;
1943}
1944
1945int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1946 return AKEY_STATE_UNKNOWN;
1947}
1948
1949int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1950 return AKEY_STATE_UNKNOWN;
1951}
1952
1953bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1954 const int32_t* keyCodes, uint8_t* outFlags) {
1955 return false;
1956}
1957
1958void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1959 int32_t token) {
1960}
1961
1962void InputMapper::cancelVibrate(int32_t token) {
1963}
1964
Jeff Brownc9aa6282015-02-11 19:03:28 -08001965void InputMapper::cancelTouch(nsecs_t when) {
1966}
1967
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968int32_t InputMapper::getMetaState() {
1969 return 0;
1970}
1971
Andrii Kulian763a3a42016-03-08 10:46:16 -08001972void InputMapper::updateMetaState(int32_t keyCode) {
1973}
1974
Michael Wright842500e2015-03-13 17:32:02 -07001975void InputMapper::updateExternalStylusState(const StylusState& state) {
1976
1977}
1978
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979void InputMapper::fadePointer() {
1980}
1981
1982status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1983 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1984}
1985
1986void InputMapper::bumpGeneration() {
1987 mDevice->bumpGeneration();
1988}
1989
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001990void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 const RawAbsoluteAxisInfo& axis, const char* name) {
1992 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001993 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1995 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001996 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998}
1999
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002000void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2001 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2002 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2003 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2004 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002005}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006
2007// --- SwitchInputMapper ---
2008
2009SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002010 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011}
2012
2013SwitchInputMapper::~SwitchInputMapper() {
2014}
2015
2016uint32_t SwitchInputMapper::getSources() {
2017 return AINPUT_SOURCE_SWITCH;
2018}
2019
2020void SwitchInputMapper::process(const RawEvent* rawEvent) {
2021 switch (rawEvent->type) {
2022 case EV_SW:
2023 processSwitch(rawEvent->code, rawEvent->value);
2024 break;
2025
2026 case EV_SYN:
2027 if (rawEvent->code == SYN_REPORT) {
2028 sync(rawEvent->when);
2029 }
2030 }
2031}
2032
2033void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2034 if (switchCode >= 0 && switchCode < 32) {
2035 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002036 mSwitchValues |= 1 << switchCode;
2037 } else {
2038 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 }
2040 mUpdatedSwitchMask |= 1 << switchCode;
2041 }
2042}
2043
2044void SwitchInputMapper::sync(nsecs_t when) {
2045 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002046 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002047 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2048 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 getListener()->notifySwitch(&args);
2050
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 mUpdatedSwitchMask = 0;
2052 }
2053}
2054
2055int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2056 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2057}
2058
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002059void SwitchInputMapper::dump(std::string& dump) {
2060 dump += INDENT2 "Switch Input Mapper:\n";
2061 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002062}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063
2064// --- VibratorInputMapper ---
2065
2066VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2067 InputMapper(device), mVibrating(false) {
2068}
2069
2070VibratorInputMapper::~VibratorInputMapper() {
2071}
2072
2073uint32_t VibratorInputMapper::getSources() {
2074 return 0;
2075}
2076
2077void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2078 InputMapper::populateDeviceInfo(info);
2079
2080 info->setVibrator(true);
2081}
2082
2083void VibratorInputMapper::process(const RawEvent* rawEvent) {
2084 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2085}
2086
2087void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2088 int32_t token) {
2089#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002090 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 for (size_t i = 0; i < patternSize; i++) {
2092 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002093 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002095 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002097 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002098 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099#endif
2100
2101 mVibrating = true;
2102 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2103 mPatternSize = patternSize;
2104 mRepeat = repeat;
2105 mToken = token;
2106 mIndex = -1;
2107
2108 nextStep();
2109}
2110
2111void VibratorInputMapper::cancelVibrate(int32_t token) {
2112#if DEBUG_VIBRATOR
2113 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2114#endif
2115
2116 if (mVibrating && mToken == token) {
2117 stopVibrating();
2118 }
2119}
2120
2121void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2122 if (mVibrating) {
2123 if (when >= mNextStepTime) {
2124 nextStep();
2125 } else {
2126 getContext()->requestTimeoutAtTime(mNextStepTime);
2127 }
2128 }
2129}
2130
2131void VibratorInputMapper::nextStep() {
2132 mIndex += 1;
2133 if (size_t(mIndex) >= mPatternSize) {
2134 if (mRepeat < 0) {
2135 // We are done.
2136 stopVibrating();
2137 return;
2138 }
2139 mIndex = mRepeat;
2140 }
2141
2142 bool vibratorOn = mIndex & 1;
2143 nsecs_t duration = mPattern[mIndex];
2144 if (vibratorOn) {
2145#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002146 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147#endif
2148 getEventHub()->vibrate(getDeviceId(), duration);
2149 } else {
2150#if DEBUG_VIBRATOR
2151 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2152#endif
2153 getEventHub()->cancelVibrate(getDeviceId());
2154 }
2155 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2156 mNextStepTime = now + duration;
2157 getContext()->requestTimeoutAtTime(mNextStepTime);
2158#if DEBUG_VIBRATOR
2159 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2160#endif
2161}
2162
2163void VibratorInputMapper::stopVibrating() {
2164 mVibrating = false;
2165#if DEBUG_VIBRATOR
2166 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2167#endif
2168 getEventHub()->cancelVibrate(getDeviceId());
2169}
2170
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002171void VibratorInputMapper::dump(std::string& dump) {
2172 dump += INDENT2 "Vibrator Input Mapper:\n";
2173 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174}
2175
2176
2177// --- KeyboardInputMapper ---
2178
2179KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2180 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002181 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182}
2183
2184KeyboardInputMapper::~KeyboardInputMapper() {
2185}
2186
2187uint32_t KeyboardInputMapper::getSources() {
2188 return mSource;
2189}
2190
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002191int32_t KeyboardInputMapper::getOrientation() {
2192 if (mViewport) {
2193 return mViewport->orientation;
2194 }
2195 return DISPLAY_ORIENTATION_0;
2196}
2197
2198int32_t KeyboardInputMapper::getDisplayId() {
2199 if (mViewport) {
2200 return mViewport->displayId;
2201 }
2202 return ADISPLAY_ID_NONE;
2203}
2204
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2206 InputMapper::populateDeviceInfo(info);
2207
2208 info->setKeyboardType(mKeyboardType);
2209 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2210}
2211
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002212void KeyboardInputMapper::dump(std::string& dump) {
2213 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002215 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002216 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002217 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2218 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2219 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220}
2221
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222void KeyboardInputMapper::configure(nsecs_t when,
2223 const InputReaderConfiguration* config, uint32_t changes) {
2224 InputMapper::configure(when, config, changes);
2225
2226 if (!changes) { // first time only
2227 // Configure basic parameters.
2228 configureParameters();
2229 }
2230
2231 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002232 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002233 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
2235 }
2236}
2237
Ivan Podogovb9afef32017-02-13 15:34:32 +00002238static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2239 int32_t mapped = 0;
2240 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2241 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2242 if (stemKeyRotationMap[i][0] == keyCode) {
2243 stemKeyRotationMap[i][1] = mapped;
2244 return;
2245 }
2246 }
2247 }
2248}
2249
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250void KeyboardInputMapper::configureParameters() {
2251 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002252 const PropertyMap& config = getDevice()->getConfiguration();
2253 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 mParameters.orientationAware);
2255
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002257 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2258 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2259 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2260 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002262
2263 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002264 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002265 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266}
2267
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002268void KeyboardInputMapper::dumpParameters(std::string& dump) {
2269 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002270 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002272 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002273 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274}
2275
2276void KeyboardInputMapper::reset(nsecs_t when) {
2277 mMetaState = AMETA_NONE;
2278 mDownTime = 0;
2279 mKeyDowns.clear();
2280 mCurrentHidUsage = 0;
2281
2282 resetLedState();
2283
2284 InputMapper::reset(when);
2285}
2286
2287void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2288 switch (rawEvent->type) {
2289 case EV_KEY: {
2290 int32_t scanCode = rawEvent->code;
2291 int32_t usageCode = mCurrentHidUsage;
2292 mCurrentHidUsage = 0;
2293
2294 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002295 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297 break;
2298 }
2299 case EV_MSC: {
2300 if (rawEvent->code == MSC_SCAN) {
2301 mCurrentHidUsage = rawEvent->value;
2302 }
2303 break;
2304 }
2305 case EV_SYN: {
2306 if (rawEvent->code == SYN_REPORT) {
2307 mCurrentHidUsage = 0;
2308 }
2309 }
2310 }
2311}
2312
2313bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2314 return scanCode < BTN_MOUSE
2315 || scanCode >= KEY_OK
2316 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2317 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2318}
2319
Michael Wright58ba9882017-07-26 16:19:11 +01002320bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2321 switch (keyCode) {
2322 case AKEYCODE_MEDIA_PLAY:
2323 case AKEYCODE_MEDIA_PAUSE:
2324 case AKEYCODE_MEDIA_PLAY_PAUSE:
2325 case AKEYCODE_MUTE:
2326 case AKEYCODE_HEADSETHOOK:
2327 case AKEYCODE_MEDIA_STOP:
2328 case AKEYCODE_MEDIA_NEXT:
2329 case AKEYCODE_MEDIA_PREVIOUS:
2330 case AKEYCODE_MEDIA_REWIND:
2331 case AKEYCODE_MEDIA_RECORD:
2332 case AKEYCODE_MEDIA_FAST_FORWARD:
2333 case AKEYCODE_MEDIA_SKIP_FORWARD:
2334 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2335 case AKEYCODE_MEDIA_STEP_FORWARD:
2336 case AKEYCODE_MEDIA_STEP_BACKWARD:
2337 case AKEYCODE_MEDIA_AUDIO_TRACK:
2338 case AKEYCODE_VOLUME_UP:
2339 case AKEYCODE_VOLUME_DOWN:
2340 case AKEYCODE_VOLUME_MUTE:
2341 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2342 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2343 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2344 return true;
2345 }
2346 return false;
2347}
2348
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002349void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2350 int32_t usageCode) {
2351 int32_t keyCode;
2352 int32_t keyMetaState;
2353 uint32_t policyFlags;
2354
2355 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2356 &keyCode, &keyMetaState, &policyFlags)) {
2357 keyCode = AKEYCODE_UNKNOWN;
2358 keyMetaState = mMetaState;
2359 policyFlags = 0;
2360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361
2362 if (down) {
2363 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002364 if (mParameters.orientationAware) {
2365 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 }
2367
2368 // Add key down.
2369 ssize_t keyDownIndex = findKeyDown(scanCode);
2370 if (keyDownIndex >= 0) {
2371 // key repeat, be sure to use same keycode as before in case of rotation
2372 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2373 } else {
2374 // key down
2375 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2376 && mContext->shouldDropVirtualKey(when,
2377 getDevice(), keyCode, scanCode)) {
2378 return;
2379 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002380 if (policyFlags & POLICY_FLAG_GESTURE) {
2381 mDevice->cancelTouch(when);
2382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383
2384 mKeyDowns.push();
2385 KeyDown& keyDown = mKeyDowns.editTop();
2386 keyDown.keyCode = keyCode;
2387 keyDown.scanCode = scanCode;
2388 }
2389
2390 mDownTime = when;
2391 } else {
2392 // Remove key down.
2393 ssize_t keyDownIndex = findKeyDown(scanCode);
2394 if (keyDownIndex >= 0) {
2395 // key up, be sure to use same keycode as before in case of rotation
2396 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2397 mKeyDowns.removeAt(size_t(keyDownIndex));
2398 } else {
2399 // key was not actually down
2400 ALOGI("Dropping key up from device %s because the key was not down. "
2401 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002402 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 return;
2404 }
2405 }
2406
Andrii Kulian763a3a42016-03-08 10:46:16 -08002407 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002408 // If global meta state changed send it along with the key.
2409 // If it has not changed then we'll use what keymap gave us,
2410 // since key replacement logic might temporarily reset a few
2411 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002412 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 }
2414
2415 nsecs_t downTime = mDownTime;
2416
2417 // Key down on external an keyboard should wake the device.
2418 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2419 // For internal keyboards, the key layout file should specify the policy flags for
2420 // each wake key individually.
2421 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002422 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002423 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
2425
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002426 if (mParameters.handlesKeyRepeat) {
2427 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2428 }
2429
Prabir Pradhan42611e02018-11-27 14:04:02 -08002430 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2431 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002432 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 getListener()->notifyKey(&args);
2434}
2435
2436ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2437 size_t n = mKeyDowns.size();
2438 for (size_t i = 0; i < n; i++) {
2439 if (mKeyDowns[i].scanCode == scanCode) {
2440 return i;
2441 }
2442 }
2443 return -1;
2444}
2445
2446int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2447 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2448}
2449
2450int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2451 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2452}
2453
2454bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2455 const int32_t* keyCodes, uint8_t* outFlags) {
2456 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2457}
2458
2459int32_t KeyboardInputMapper::getMetaState() {
2460 return mMetaState;
2461}
2462
Andrii Kulian763a3a42016-03-08 10:46:16 -08002463void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2464 updateMetaStateIfNeeded(keyCode, false);
2465}
2466
2467bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2468 int32_t oldMetaState = mMetaState;
2469 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2470 bool metaStateChanged = oldMetaState != newMetaState;
2471 if (metaStateChanged) {
2472 mMetaState = newMetaState;
2473 updateLedState(false);
2474
2475 getContext()->updateGlobalMetaState();
2476 }
2477
2478 return metaStateChanged;
2479}
2480
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481void KeyboardInputMapper::resetLedState() {
2482 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2483 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2484 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2485
2486 updateLedState(true);
2487}
2488
2489void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2490 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2491 ledState.on = false;
2492}
2493
2494void KeyboardInputMapper::updateLedState(bool reset) {
2495 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2496 AMETA_CAPS_LOCK_ON, reset);
2497 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2498 AMETA_NUM_LOCK_ON, reset);
2499 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2500 AMETA_SCROLL_LOCK_ON, reset);
2501}
2502
2503void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2504 int32_t led, int32_t modifier, bool reset) {
2505 if (ledState.avail) {
2506 bool desiredState = (mMetaState & modifier) != 0;
2507 if (reset || ledState.on != desiredState) {
2508 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2509 ledState.on = desiredState;
2510 }
2511 }
2512}
2513
2514
2515// --- CursorInputMapper ---
2516
2517CursorInputMapper::CursorInputMapper(InputDevice* device) :
2518 InputMapper(device) {
2519}
2520
2521CursorInputMapper::~CursorInputMapper() {
2522}
2523
2524uint32_t CursorInputMapper::getSources() {
2525 return mSource;
2526}
2527
2528void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2529 InputMapper::populateDeviceInfo(info);
2530
2531 if (mParameters.mode == Parameters::MODE_POINTER) {
2532 float minX, minY, maxX, maxY;
2533 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2534 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2535 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2536 }
2537 } else {
2538 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2539 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2540 }
2541 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2542
2543 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2544 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2545 }
2546 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2547 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2548 }
2549}
2550
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002551void CursorInputMapper::dump(std::string& dump) {
2552 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002554 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2555 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2556 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2557 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2558 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002560 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002562 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2563 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2564 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2565 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2566 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2567 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568}
2569
2570void CursorInputMapper::configure(nsecs_t when,
2571 const InputReaderConfiguration* config, uint32_t changes) {
2572 InputMapper::configure(when, config, changes);
2573
2574 if (!changes) { // first time only
2575 mCursorScrollAccumulator.configure(getDevice());
2576
2577 // Configure basic parameters.
2578 configureParameters();
2579
2580 // Configure device mode.
2581 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002582 case Parameters::MODE_POINTER_RELATIVE:
2583 // Should not happen during first time configuration.
2584 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2585 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002586 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 case Parameters::MODE_POINTER:
2588 mSource = AINPUT_SOURCE_MOUSE;
2589 mXPrecision = 1.0f;
2590 mYPrecision = 1.0f;
2591 mXScale = 1.0f;
2592 mYScale = 1.0f;
2593 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2594 break;
2595 case Parameters::MODE_NAVIGATION:
2596 mSource = AINPUT_SOURCE_TRACKBALL;
2597 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2598 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2599 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2600 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2601 break;
2602 }
2603
2604 mVWheelScale = 1.0f;
2605 mHWheelScale = 1.0f;
2606 }
2607
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002608 if ((!changes && config->pointerCapture)
2609 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2610 if (config->pointerCapture) {
2611 if (mParameters.mode == Parameters::MODE_POINTER) {
2612 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2613 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2614 // Keep PointerController around in order to preserve the pointer position.
2615 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2616 } else {
2617 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2618 }
2619 } else {
2620 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2621 mParameters.mode = Parameters::MODE_POINTER;
2622 mSource = AINPUT_SOURCE_MOUSE;
2623 } else {
2624 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2625 }
2626 }
2627 bumpGeneration();
2628 if (changes) {
2629 getDevice()->notifyReset(when);
2630 }
2631 }
2632
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2634 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2635 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2636 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2637 }
2638
2639 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002640 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002642 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002643 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002644 if (internalViewport) {
2645 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002648
2649 // Update the PointerController if viewports changed.
2650 if (mParameters.hasAssociatedDisplay) {
2651 getPolicy()->obtainPointerController(getDeviceId());
2652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 bumpGeneration();
2654 }
2655}
2656
2657void CursorInputMapper::configureParameters() {
2658 mParameters.mode = Parameters::MODE_POINTER;
2659 String8 cursorModeString;
2660 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2661 if (cursorModeString == "navigation") {
2662 mParameters.mode = Parameters::MODE_NAVIGATION;
2663 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2664 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2665 }
2666 }
2667
2668 mParameters.orientationAware = false;
2669 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2670 mParameters.orientationAware);
2671
2672 mParameters.hasAssociatedDisplay = false;
2673 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2674 mParameters.hasAssociatedDisplay = true;
2675 }
2676}
2677
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002678void CursorInputMapper::dumpParameters(std::string& dump) {
2679 dump += INDENT3 "Parameters:\n";
2680 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 toString(mParameters.hasAssociatedDisplay));
2682
2683 switch (mParameters.mode) {
2684 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002685 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002687 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002688 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002689 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002691 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 break;
2693 default:
2694 ALOG_ASSERT(false);
2695 }
2696
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002697 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 toString(mParameters.orientationAware));
2699}
2700
2701void CursorInputMapper::reset(nsecs_t when) {
2702 mButtonState = 0;
2703 mDownTime = 0;
2704
2705 mPointerVelocityControl.reset();
2706 mWheelXVelocityControl.reset();
2707 mWheelYVelocityControl.reset();
2708
2709 mCursorButtonAccumulator.reset(getDevice());
2710 mCursorMotionAccumulator.reset(getDevice());
2711 mCursorScrollAccumulator.reset(getDevice());
2712
2713 InputMapper::reset(when);
2714}
2715
2716void CursorInputMapper::process(const RawEvent* rawEvent) {
2717 mCursorButtonAccumulator.process(rawEvent);
2718 mCursorMotionAccumulator.process(rawEvent);
2719 mCursorScrollAccumulator.process(rawEvent);
2720
2721 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2722 sync(rawEvent->when);
2723 }
2724}
2725
2726void CursorInputMapper::sync(nsecs_t when) {
2727 int32_t lastButtonState = mButtonState;
2728 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2729 mButtonState = currentButtonState;
2730
2731 bool wasDown = isPointerDown(lastButtonState);
2732 bool down = isPointerDown(currentButtonState);
2733 bool downChanged;
2734 if (!wasDown && down) {
2735 mDownTime = when;
2736 downChanged = true;
2737 } else if (wasDown && !down) {
2738 downChanged = true;
2739 } else {
2740 downChanged = false;
2741 }
2742 nsecs_t downTime = mDownTime;
2743 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002744 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2745 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746
2747 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2748 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2749 bool moved = deltaX != 0 || deltaY != 0;
2750
2751 // Rotate delta according to orientation if needed.
2752 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2753 && (deltaX != 0.0f || deltaY != 0.0f)) {
2754 rotateDelta(mOrientation, &deltaX, &deltaY);
2755 }
2756
2757 // Move the pointer.
2758 PointerProperties pointerProperties;
2759 pointerProperties.clear();
2760 pointerProperties.id = 0;
2761 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2762
2763 PointerCoords pointerCoords;
2764 pointerCoords.clear();
2765
2766 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2767 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2768 bool scrolled = vscroll != 0 || hscroll != 0;
2769
Yi Kong9b14ac62018-07-17 13:48:38 -07002770 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2771 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772
2773 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2774
2775 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002776 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 if (moved || scrolled || buttonsChanged) {
2778 mPointerController->setPresentation(
2779 PointerControllerInterface::PRESENTATION_POINTER);
2780
2781 if (moved) {
2782 mPointerController->move(deltaX, deltaY);
2783 }
2784
2785 if (buttonsChanged) {
2786 mPointerController->setButtonState(currentButtonState);
2787 }
2788
2789 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2790 }
2791
2792 float x, y;
2793 mPointerController->getPosition(&x, &y);
2794 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2795 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002796 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2797 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002798 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799 } else {
2800 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2801 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2802 displayId = ADISPLAY_ID_NONE;
2803 }
2804
2805 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2806
2807 // Moving an external trackball or mouse should wake the device.
2808 // We don't do this for internal cursor devices to prevent them from waking up
2809 // the device in your pocket.
2810 // TODO: Use the input device configuration to control this behavior more finely.
2811 uint32_t policyFlags = 0;
2812 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002813 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 }
2815
2816 // Synthesize key down from buttons if needed.
2817 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002818 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819
2820 // Send motion event.
2821 if (downChanged || moved || scrolled || buttonsChanged) {
2822 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002823 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 int32_t motionEventAction;
2825 if (downChanged) {
2826 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002827 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2829 } else {
2830 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2831 }
2832
Michael Wright7b159c92015-05-14 14:48:03 +01002833 if (buttonsReleased) {
2834 BitSet32 released(buttonsReleased);
2835 while (!released.isEmpty()) {
2836 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2837 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002838 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2839 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002840 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002841 metaState, buttonState,
2842 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002843 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002844 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002845 getListener()->notifyMotion(&releaseArgs);
2846 }
2847 }
2848
Prabir Pradhan42611e02018-11-27 14:04:02 -08002849 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2850 displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002851 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002852 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002853 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 getListener()->notifyMotion(&args);
2855
Michael Wright7b159c92015-05-14 14:48:03 +01002856 if (buttonsPressed) {
2857 BitSet32 pressed(buttonsPressed);
2858 while (!pressed.isEmpty()) {
2859 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2860 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002861 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2862 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002863 actionButton, 0, metaState, buttonState,
2864 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002865 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002866 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002867 getListener()->notifyMotion(&pressArgs);
2868 }
2869 }
2870
2871 ALOG_ASSERT(buttonState == currentButtonState);
2872
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 // Send hover move after UP to tell the application that the mouse is hovering now.
2874 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002875 && (mSource == AINPUT_SOURCE_MOUSE)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08002876 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2877 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002878 metaState, currentButtonState,
2879 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002880 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002881 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 getListener()->notifyMotion(&hoverArgs);
2883 }
2884
2885 // Send scroll events.
2886 if (scrolled) {
2887 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2888 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2889
Prabir Pradhan42611e02018-11-27 14:04:02 -08002890 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2891 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002892 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002893 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002894 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002895 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896 getListener()->notifyMotion(&scrollArgs);
2897 }
2898 }
2899
2900 // Synthesize key up from buttons if needed.
2901 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002902 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903
2904 mCursorMotionAccumulator.finishSync();
2905 mCursorScrollAccumulator.finishSync();
2906}
2907
2908int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2909 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2910 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2911 } else {
2912 return AKEY_STATE_UNKNOWN;
2913 }
2914}
2915
2916void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002917 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2919 }
2920}
2921
Prashant Malani1941ff52015-08-11 18:29:28 -07002922// --- RotaryEncoderInputMapper ---
2923
2924RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002925 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002926 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2927}
2928
2929RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2930}
2931
2932uint32_t RotaryEncoderInputMapper::getSources() {
2933 return mSource;
2934}
2935
2936void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2937 InputMapper::populateDeviceInfo(info);
2938
2939 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002940 float res = 0.0f;
2941 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2942 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2943 }
2944 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2945 mScalingFactor)) {
2946 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2947 "default to 1.0!\n");
2948 mScalingFactor = 1.0f;
2949 }
2950 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2951 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002952 }
2953}
2954
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002955void RotaryEncoderInputMapper::dump(std::string& dump) {
2956 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2957 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002958 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2959}
2960
2961void RotaryEncoderInputMapper::configure(nsecs_t when,
2962 const InputReaderConfiguration* config, uint32_t changes) {
2963 InputMapper::configure(when, config, changes);
2964 if (!changes) {
2965 mRotaryEncoderScrollAccumulator.configure(getDevice());
2966 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002967 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002968 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002969 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002970 if (internalViewport) {
2971 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002972 } else {
2973 mOrientation = DISPLAY_ORIENTATION_0;
2974 }
2975 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002976}
2977
2978void RotaryEncoderInputMapper::reset(nsecs_t when) {
2979 mRotaryEncoderScrollAccumulator.reset(getDevice());
2980
2981 InputMapper::reset(when);
2982}
2983
2984void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2985 mRotaryEncoderScrollAccumulator.process(rawEvent);
2986
2987 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2988 sync(rawEvent->when);
2989 }
2990}
2991
2992void RotaryEncoderInputMapper::sync(nsecs_t when) {
2993 PointerCoords pointerCoords;
2994 pointerCoords.clear();
2995
2996 PointerProperties pointerProperties;
2997 pointerProperties.clear();
2998 pointerProperties.id = 0;
2999 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3000
3001 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3002 bool scrolled = scroll != 0;
3003
3004 // This is not a pointer, so it's not associated with a display.
3005 int32_t displayId = ADISPLAY_ID_NONE;
3006
3007 // Moving the rotary encoder should wake the device (if specified).
3008 uint32_t policyFlags = 0;
3009 if (scrolled && getDevice()->isExternal()) {
3010 policyFlags |= POLICY_FLAG_WAKE;
3011 }
3012
Ivan Podogovad437252016-09-29 16:29:55 +01003013 if (mOrientation == DISPLAY_ORIENTATION_180) {
3014 scroll = -scroll;
3015 }
3016
Prashant Malani1941ff52015-08-11 18:29:28 -07003017 // Send motion event.
3018 if (scrolled) {
3019 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003020 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003021
Prabir Pradhan42611e02018-11-27 14:04:02 -08003022 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
3023 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08003024 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, /* buttonState */ 0,
3025 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003026 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08003027 0, 0, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003028 getListener()->notifyMotion(&scrollArgs);
3029 }
3030
3031 mRotaryEncoderScrollAccumulator.finishSync();
3032}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033
3034// --- TouchInputMapper ---
3035
3036TouchInputMapper::TouchInputMapper(InputDevice* device) :
3037 InputMapper(device),
3038 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3039 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003040 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3042}
3043
3044TouchInputMapper::~TouchInputMapper() {
3045}
3046
3047uint32_t TouchInputMapper::getSources() {
3048 return mSource;
3049}
3050
3051void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3052 InputMapper::populateDeviceInfo(info);
3053
3054 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3055 info->addMotionRange(mOrientedRanges.x);
3056 info->addMotionRange(mOrientedRanges.y);
3057 info->addMotionRange(mOrientedRanges.pressure);
3058
3059 if (mOrientedRanges.haveSize) {
3060 info->addMotionRange(mOrientedRanges.size);
3061 }
3062
3063 if (mOrientedRanges.haveTouchSize) {
3064 info->addMotionRange(mOrientedRanges.touchMajor);
3065 info->addMotionRange(mOrientedRanges.touchMinor);
3066 }
3067
3068 if (mOrientedRanges.haveToolSize) {
3069 info->addMotionRange(mOrientedRanges.toolMajor);
3070 info->addMotionRange(mOrientedRanges.toolMinor);
3071 }
3072
3073 if (mOrientedRanges.haveOrientation) {
3074 info->addMotionRange(mOrientedRanges.orientation);
3075 }
3076
3077 if (mOrientedRanges.haveDistance) {
3078 info->addMotionRange(mOrientedRanges.distance);
3079 }
3080
3081 if (mOrientedRanges.haveTilt) {
3082 info->addMotionRange(mOrientedRanges.tilt);
3083 }
3084
3085 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3086 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3087 0.0f);
3088 }
3089 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3090 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3091 0.0f);
3092 }
3093 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3094 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3095 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3096 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3097 x.fuzz, x.resolution);
3098 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3099 y.fuzz, y.resolution);
3100 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3101 x.fuzz, x.resolution);
3102 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3103 y.fuzz, y.resolution);
3104 }
3105 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3106 }
3107}
3108
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003109void TouchInputMapper::dump(std::string& dump) {
3110 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 dumpParameters(dump);
3112 dumpVirtualKeys(dump);
3113 dumpRawPointerAxes(dump);
3114 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003115 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 dumpSurface(dump);
3117
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003118 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3119 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3120 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3121 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3122 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3123 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3124 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3125 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3126 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3127 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3128 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3129 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3130 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3131 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3132 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3133 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3134 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003136 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3137 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003138 mLastRawState.rawPointerData.pointerCount);
3139 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3140 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003141 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3143 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3144 "toolType=%d, isHovering=%s\n", i,
3145 pointer.id, pointer.x, pointer.y, pointer.pressure,
3146 pointer.touchMajor, pointer.touchMinor,
3147 pointer.toolMajor, pointer.toolMinor,
3148 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3149 pointer.toolType, toString(pointer.isHovering));
3150 }
3151
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003152 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3153 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003154 mLastCookedState.cookedPointerData.pointerCount);
3155 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3156 const PointerProperties& pointerProperties =
3157 mLastCookedState.cookedPointerData.pointerProperties[i];
3158 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003159 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3161 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3162 "toolType=%d, isHovering=%s\n", i,
3163 pointerProperties.id,
3164 pointerCoords.getX(),
3165 pointerCoords.getY(),
3166 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3167 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3168 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3169 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3170 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3171 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3172 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3173 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3174 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003175 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 }
3177
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003178 dump += INDENT3 "Stylus Fusion:\n";
3179 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003180 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003181 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3182 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003183 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003184 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003185 dumpStylusState(dump, mExternalStylusState);
3186
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003188 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3189 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003191 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003193 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003195 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003197 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 mPointerGestureMaxSwipeWidth);
3199 }
3200}
3201
Santos Cordonfa5cf462017-04-05 10:37:00 -07003202const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3203 switch (deviceMode) {
3204 case DEVICE_MODE_DISABLED:
3205 return "disabled";
3206 case DEVICE_MODE_DIRECT:
3207 return "direct";
3208 case DEVICE_MODE_UNSCALED:
3209 return "unscaled";
3210 case DEVICE_MODE_NAVIGATION:
3211 return "navigation";
3212 case DEVICE_MODE_POINTER:
3213 return "pointer";
3214 }
3215 return "unknown";
3216}
3217
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218void TouchInputMapper::configure(nsecs_t when,
3219 const InputReaderConfiguration* config, uint32_t changes) {
3220 InputMapper::configure(when, config, changes);
3221
3222 mConfig = *config;
3223
3224 if (!changes) { // first time only
3225 // Configure basic parameters.
3226 configureParameters();
3227
3228 // Configure common accumulators.
3229 mCursorScrollAccumulator.configure(getDevice());
3230 mTouchButtonAccumulator.configure(getDevice());
3231
3232 // Configure absolute axis information.
3233 configureRawPointerAxes();
3234
3235 // Prepare input device calibration.
3236 parseCalibration();
3237 resolveCalibration();
3238 }
3239
Michael Wright842500e2015-03-13 17:32:02 -07003240 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003241 // Update location calibration to reflect current settings
3242 updateAffineTransformation();
3243 }
3244
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3246 // Update pointer speed.
3247 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3248 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3249 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3250 }
3251
3252 bool resetNeeded = false;
3253 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3254 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003255 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3256 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 // Configure device sources, surface dimensions, orientation and
3258 // scaling factors.
3259 configureSurface(when, &resetNeeded);
3260 }
3261
3262 if (changes && resetNeeded) {
3263 // Send reset, unless this is the first time the device has been configured,
3264 // in which case the reader will call reset itself after all mappers are ready.
3265 getDevice()->notifyReset(when);
3266 }
3267}
3268
Michael Wright842500e2015-03-13 17:32:02 -07003269void TouchInputMapper::resolveExternalStylusPresence() {
3270 Vector<InputDeviceInfo> devices;
3271 mContext->getExternalStylusDevices(devices);
3272 mExternalStylusConnected = !devices.isEmpty();
3273
3274 if (!mExternalStylusConnected) {
3275 resetExternalStylus();
3276 }
3277}
3278
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279void TouchInputMapper::configureParameters() {
3280 // Use the pointer presentation mode for devices that do not support distinct
3281 // multitouch. The spot-based presentation relies on being able to accurately
3282 // locate two or more fingers on the touch pad.
3283 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003284 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
3286 String8 gestureModeString;
3287 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3288 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003289 if (gestureModeString == "single-touch") {
3290 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3291 } else if (gestureModeString == "multi-touch") {
3292 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293 } else if (gestureModeString != "default") {
3294 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3295 }
3296 }
3297
3298 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3299 // The device is a touch screen.
3300 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3301 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3302 // The device is a pointing device like a track pad.
3303 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3304 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3305 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3306 // The device is a cursor device with a touch pad attached.
3307 // By default don't use the touch pad to move the pointer.
3308 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3309 } else {
3310 // The device is a touch pad of unknown purpose.
3311 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3312 }
3313
3314 mParameters.hasButtonUnderPad=
3315 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3316
3317 String8 deviceTypeString;
3318 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3319 deviceTypeString)) {
3320 if (deviceTypeString == "touchScreen") {
3321 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3322 } else if (deviceTypeString == "touchPad") {
3323 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3324 } else if (deviceTypeString == "touchNavigation") {
3325 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3326 } else if (deviceTypeString == "pointer") {
3327 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3328 } else if (deviceTypeString != "default") {
3329 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3330 }
3331 }
3332
3333 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3334 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3335 mParameters.orientationAware);
3336
3337 mParameters.hasAssociatedDisplay = false;
3338 mParameters.associatedDisplayIsExternal = false;
3339 if (mParameters.orientationAware
3340 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3341 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3342 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003343 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3344 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003345 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003346 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003347 uniqueDisplayId);
3348 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003351 if (getDevice()->getAssociatedDisplayPort()) {
3352 mParameters.hasAssociatedDisplay = true;
3353 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003354
3355 // Initial downs on external touch devices should wake the device.
3356 // Normally we don't do this for internal touch screens to prevent them from waking
3357 // up in your pocket but you can enable it using the input device configuration.
3358 mParameters.wake = getDevice()->isExternal();
3359 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3360 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361}
3362
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003363void TouchInputMapper::dumpParameters(std::string& dump) {
3364 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365
3366 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003367 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003368 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003370 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003371 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 break;
3373 default:
3374 assert(false);
3375 }
3376
3377 switch (mParameters.deviceType) {
3378 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003379 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 break;
3381 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003382 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 break;
3384 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003385 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 break;
3387 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003388 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 break;
3390 default:
3391 ALOG_ASSERT(false);
3392 }
3393
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003394 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003395 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003397 toString(mParameters.associatedDisplayIsExternal),
3398 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003399 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 toString(mParameters.orientationAware));
3401}
3402
3403void TouchInputMapper::configureRawPointerAxes() {
3404 mRawPointerAxes.clear();
3405}
3406
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003407void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3408 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3410 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3411 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3412 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3413 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3414 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3415 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3416 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3417 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3418 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3419 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3420 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3421 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3422}
3423
Michael Wright842500e2015-03-13 17:32:02 -07003424bool TouchInputMapper::hasExternalStylus() const {
3425 return mExternalStylusConnected;
3426}
3427
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003428/**
3429 * Determine which DisplayViewport to use.
3430 * 1. If display port is specified, return the matching viewport. If matching viewport not
3431 * found, then return.
3432 * 2. If a device has associated display, get the matching viewport by either unique id or by
3433 * the display type (internal or external).
3434 * 3. Otherwise, use a non-display viewport.
3435 */
3436std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3437 if (mParameters.hasAssociatedDisplay) {
3438 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3439 if (displayPort) {
3440 // Find the viewport that contains the same port
3441 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3442 if (!v) {
3443 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3444 "but the corresponding viewport is not found.",
3445 getDeviceName().c_str(), *displayPort);
3446 }
3447 return v;
3448 }
3449
3450 if (!mParameters.uniqueDisplayId.empty()) {
3451 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3452 }
3453
3454 ViewportType viewportTypeToUse;
3455 if (mParameters.associatedDisplayIsExternal) {
3456 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3457 } else {
3458 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3459 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003460
3461 std::optional<DisplayViewport> viewport =
3462 mConfig.getDisplayViewportByType(viewportTypeToUse);
3463 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3464 ALOGW("Input device %s should be associated with external display, "
3465 "fallback to internal one for the external viewport is not found.",
3466 getDeviceName().c_str());
3467 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3468 }
3469
3470 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003471 }
3472
3473 DisplayViewport newViewport;
3474 // Raw width and height in the natural orientation.
3475 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3476 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3477 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3478 return std::make_optional(newViewport);
3479}
3480
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3482 int32_t oldDeviceMode = mDeviceMode;
3483
Michael Wright842500e2015-03-13 17:32:02 -07003484 resolveExternalStylusPresence();
3485
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 // Determine device mode.
3487 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3488 && mConfig.pointerGesturesEnabled) {
3489 mSource = AINPUT_SOURCE_MOUSE;
3490 mDeviceMode = DEVICE_MODE_POINTER;
3491 if (hasStylus()) {
3492 mSource |= AINPUT_SOURCE_STYLUS;
3493 }
3494 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3495 && mParameters.hasAssociatedDisplay) {
3496 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3497 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003498 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 mSource |= AINPUT_SOURCE_STYLUS;
3500 }
Michael Wright2f78b682015-06-12 15:25:08 +01003501 if (hasExternalStylus()) {
3502 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3505 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3506 mDeviceMode = DEVICE_MODE_NAVIGATION;
3507 } else {
3508 mSource = AINPUT_SOURCE_TOUCHPAD;
3509 mDeviceMode = DEVICE_MODE_UNSCALED;
3510 }
3511
3512 // Ensure we have valid X and Y axes.
3513 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003514 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003515 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 mDeviceMode = DEVICE_MODE_DISABLED;
3517 return;
3518 }
3519
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003520 // Get associated display dimensions.
3521 std::optional<DisplayViewport> newViewport = findViewport();
3522 if (!newViewport) {
3523 ALOGI("Touch device '%s' could not query the properties of its associated "
3524 "display. The device will be inoperable until the display size "
3525 "becomes available.",
3526 getDeviceName().c_str());
3527 mDeviceMode = DEVICE_MODE_DISABLED;
3528 return;
3529 }
3530
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003532 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3533 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003535 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003537 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538
3539 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3540 // Convert rotated viewport to natural surface coordinates.
3541 int32_t naturalLogicalWidth, naturalLogicalHeight;
3542 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3543 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3544 int32_t naturalDeviceWidth, naturalDeviceHeight;
3545 switch (mViewport.orientation) {
3546 case DISPLAY_ORIENTATION_90:
3547 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3548 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3549 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3550 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3551 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3552 naturalPhysicalTop = mViewport.physicalLeft;
3553 naturalDeviceWidth = mViewport.deviceHeight;
3554 naturalDeviceHeight = mViewport.deviceWidth;
3555 break;
3556 case DISPLAY_ORIENTATION_180:
3557 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3558 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3559 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3560 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3561 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3562 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3563 naturalDeviceWidth = mViewport.deviceWidth;
3564 naturalDeviceHeight = mViewport.deviceHeight;
3565 break;
3566 case DISPLAY_ORIENTATION_270:
3567 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3568 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3569 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3570 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3571 naturalPhysicalLeft = mViewport.physicalTop;
3572 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3573 naturalDeviceWidth = mViewport.deviceHeight;
3574 naturalDeviceHeight = mViewport.deviceWidth;
3575 break;
3576 case DISPLAY_ORIENTATION_0:
3577 default:
3578 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3579 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3580 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3581 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3582 naturalPhysicalLeft = mViewport.physicalLeft;
3583 naturalPhysicalTop = mViewport.physicalTop;
3584 naturalDeviceWidth = mViewport.deviceWidth;
3585 naturalDeviceHeight = mViewport.deviceHeight;
3586 break;
3587 }
3588
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003589 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3590 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3591 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3592 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3593 }
3594
Michael Wright358bcc72018-08-21 04:01:07 +01003595 mPhysicalWidth = naturalPhysicalWidth;
3596 mPhysicalHeight = naturalPhysicalHeight;
3597 mPhysicalLeft = naturalPhysicalLeft;
3598 mPhysicalTop = naturalPhysicalTop;
3599
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3601 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3602 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3603 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3604
3605 mSurfaceOrientation = mParameters.orientationAware ?
3606 mViewport.orientation : DISPLAY_ORIENTATION_0;
3607 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003608 mPhysicalWidth = rawWidth;
3609 mPhysicalHeight = rawHeight;
3610 mPhysicalLeft = 0;
3611 mPhysicalTop = 0;
3612
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 mSurfaceWidth = rawWidth;
3614 mSurfaceHeight = rawHeight;
3615 mSurfaceLeft = 0;
3616 mSurfaceTop = 0;
3617 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3618 }
3619 }
3620
3621 // If moving between pointer modes, need to reset some state.
3622 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3623 if (deviceModeChanged) {
3624 mOrientedRanges.clear();
3625 }
3626
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003627 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 if (mDeviceMode == DEVICE_MODE_POINTER ||
3629 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003630 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3632 }
3633 } else {
3634 mPointerController.clear();
3635 }
3636
3637 if (viewportChanged || deviceModeChanged) {
3638 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3639 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003640 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3642
3643 // Configure X and Y factors.
3644 mXScale = float(mSurfaceWidth) / rawWidth;
3645 mYScale = float(mSurfaceHeight) / rawHeight;
3646 mXTranslate = -mSurfaceLeft;
3647 mYTranslate = -mSurfaceTop;
3648 mXPrecision = 1.0f / mXScale;
3649 mYPrecision = 1.0f / mYScale;
3650
3651 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3652 mOrientedRanges.x.source = mSource;
3653 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3654 mOrientedRanges.y.source = mSource;
3655
3656 configureVirtualKeys();
3657
3658 // Scale factor for terms that are not oriented in a particular axis.
3659 // If the pixels are square then xScale == yScale otherwise we fake it
3660 // by choosing an average.
3661 mGeometricScale = avg(mXScale, mYScale);
3662
3663 // Size of diagonal axis.
3664 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3665
3666 // Size factors.
3667 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3668 if (mRawPointerAxes.touchMajor.valid
3669 && mRawPointerAxes.touchMajor.maxValue != 0) {
3670 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3671 } else if (mRawPointerAxes.toolMajor.valid
3672 && mRawPointerAxes.toolMajor.maxValue != 0) {
3673 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3674 } else {
3675 mSizeScale = 0.0f;
3676 }
3677
3678 mOrientedRanges.haveTouchSize = true;
3679 mOrientedRanges.haveToolSize = true;
3680 mOrientedRanges.haveSize = true;
3681
3682 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3683 mOrientedRanges.touchMajor.source = mSource;
3684 mOrientedRanges.touchMajor.min = 0;
3685 mOrientedRanges.touchMajor.max = diagonalSize;
3686 mOrientedRanges.touchMajor.flat = 0;
3687 mOrientedRanges.touchMajor.fuzz = 0;
3688 mOrientedRanges.touchMajor.resolution = 0;
3689
3690 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3691 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3692
3693 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3694 mOrientedRanges.toolMajor.source = mSource;
3695 mOrientedRanges.toolMajor.min = 0;
3696 mOrientedRanges.toolMajor.max = diagonalSize;
3697 mOrientedRanges.toolMajor.flat = 0;
3698 mOrientedRanges.toolMajor.fuzz = 0;
3699 mOrientedRanges.toolMajor.resolution = 0;
3700
3701 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3702 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3703
3704 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3705 mOrientedRanges.size.source = mSource;
3706 mOrientedRanges.size.min = 0;
3707 mOrientedRanges.size.max = 1.0;
3708 mOrientedRanges.size.flat = 0;
3709 mOrientedRanges.size.fuzz = 0;
3710 mOrientedRanges.size.resolution = 0;
3711 } else {
3712 mSizeScale = 0.0f;
3713 }
3714
3715 // Pressure factors.
3716 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003717 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3719 || mCalibration.pressureCalibration
3720 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3721 if (mCalibration.havePressureScale) {
3722 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003723 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 } else if (mRawPointerAxes.pressure.valid
3725 && mRawPointerAxes.pressure.maxValue != 0) {
3726 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3727 }
3728 }
3729
3730 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3731 mOrientedRanges.pressure.source = mSource;
3732 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003733 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 mOrientedRanges.pressure.flat = 0;
3735 mOrientedRanges.pressure.fuzz = 0;
3736 mOrientedRanges.pressure.resolution = 0;
3737
3738 // Tilt
3739 mTiltXCenter = 0;
3740 mTiltXScale = 0;
3741 mTiltYCenter = 0;
3742 mTiltYScale = 0;
3743 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3744 if (mHaveTilt) {
3745 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3746 mRawPointerAxes.tiltX.maxValue);
3747 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3748 mRawPointerAxes.tiltY.maxValue);
3749 mTiltXScale = M_PI / 180;
3750 mTiltYScale = M_PI / 180;
3751
3752 mOrientedRanges.haveTilt = true;
3753
3754 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3755 mOrientedRanges.tilt.source = mSource;
3756 mOrientedRanges.tilt.min = 0;
3757 mOrientedRanges.tilt.max = M_PI_2;
3758 mOrientedRanges.tilt.flat = 0;
3759 mOrientedRanges.tilt.fuzz = 0;
3760 mOrientedRanges.tilt.resolution = 0;
3761 }
3762
3763 // Orientation
3764 mOrientationScale = 0;
3765 if (mHaveTilt) {
3766 mOrientedRanges.haveOrientation = true;
3767
3768 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3769 mOrientedRanges.orientation.source = mSource;
3770 mOrientedRanges.orientation.min = -M_PI;
3771 mOrientedRanges.orientation.max = M_PI;
3772 mOrientedRanges.orientation.flat = 0;
3773 mOrientedRanges.orientation.fuzz = 0;
3774 mOrientedRanges.orientation.resolution = 0;
3775 } else if (mCalibration.orientationCalibration !=
3776 Calibration::ORIENTATION_CALIBRATION_NONE) {
3777 if (mCalibration.orientationCalibration
3778 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3779 if (mRawPointerAxes.orientation.valid) {
3780 if (mRawPointerAxes.orientation.maxValue > 0) {
3781 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3782 } else if (mRawPointerAxes.orientation.minValue < 0) {
3783 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3784 } else {
3785 mOrientationScale = 0;
3786 }
3787 }
3788 }
3789
3790 mOrientedRanges.haveOrientation = true;
3791
3792 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3793 mOrientedRanges.orientation.source = mSource;
3794 mOrientedRanges.orientation.min = -M_PI_2;
3795 mOrientedRanges.orientation.max = M_PI_2;
3796 mOrientedRanges.orientation.flat = 0;
3797 mOrientedRanges.orientation.fuzz = 0;
3798 mOrientedRanges.orientation.resolution = 0;
3799 }
3800
3801 // Distance
3802 mDistanceScale = 0;
3803 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3804 if (mCalibration.distanceCalibration
3805 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3806 if (mCalibration.haveDistanceScale) {
3807 mDistanceScale = mCalibration.distanceScale;
3808 } else {
3809 mDistanceScale = 1.0f;
3810 }
3811 }
3812
3813 mOrientedRanges.haveDistance = true;
3814
3815 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3816 mOrientedRanges.distance.source = mSource;
3817 mOrientedRanges.distance.min =
3818 mRawPointerAxes.distance.minValue * mDistanceScale;
3819 mOrientedRanges.distance.max =
3820 mRawPointerAxes.distance.maxValue * mDistanceScale;
3821 mOrientedRanges.distance.flat = 0;
3822 mOrientedRanges.distance.fuzz =
3823 mRawPointerAxes.distance.fuzz * mDistanceScale;
3824 mOrientedRanges.distance.resolution = 0;
3825 }
3826
3827 // Compute oriented precision, scales and ranges.
3828 // Note that the maximum value reported is an inclusive maximum value so it is one
3829 // unit less than the total width or height of surface.
3830 switch (mSurfaceOrientation) {
3831 case DISPLAY_ORIENTATION_90:
3832 case DISPLAY_ORIENTATION_270:
3833 mOrientedXPrecision = mYPrecision;
3834 mOrientedYPrecision = mXPrecision;
3835
3836 mOrientedRanges.x.min = mYTranslate;
3837 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3838 mOrientedRanges.x.flat = 0;
3839 mOrientedRanges.x.fuzz = 0;
3840 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3841
3842 mOrientedRanges.y.min = mXTranslate;
3843 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3844 mOrientedRanges.y.flat = 0;
3845 mOrientedRanges.y.fuzz = 0;
3846 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3847 break;
3848
3849 default:
3850 mOrientedXPrecision = mXPrecision;
3851 mOrientedYPrecision = mYPrecision;
3852
3853 mOrientedRanges.x.min = mXTranslate;
3854 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3855 mOrientedRanges.x.flat = 0;
3856 mOrientedRanges.x.fuzz = 0;
3857 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3858
3859 mOrientedRanges.y.min = mYTranslate;
3860 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3861 mOrientedRanges.y.flat = 0;
3862 mOrientedRanges.y.fuzz = 0;
3863 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3864 break;
3865 }
3866
Jason Gerecke71b16e82014-03-10 09:47:59 -07003867 // Location
3868 updateAffineTransformation();
3869
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 if (mDeviceMode == DEVICE_MODE_POINTER) {
3871 // Compute pointer gesture detection parameters.
3872 float rawDiagonal = hypotf(rawWidth, rawHeight);
3873 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3874
3875 // Scale movements such that one whole swipe of the touch pad covers a
3876 // given area relative to the diagonal size of the display when no acceleration
3877 // is applied.
3878 // Assume that the touch pad has a square aspect ratio such that movements in
3879 // X and Y of the same number of raw units cover the same physical distance.
3880 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3881 * displayDiagonal / rawDiagonal;
3882 mPointerYMovementScale = mPointerXMovementScale;
3883
3884 // Scale zooms to cover a smaller range of the display than movements do.
3885 // This value determines the area around the pointer that is affected by freeform
3886 // pointer gestures.
3887 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3888 * displayDiagonal / rawDiagonal;
3889 mPointerYZoomScale = mPointerXZoomScale;
3890
3891 // Max width between pointers to detect a swipe gesture is more than some fraction
3892 // of the diagonal axis of the touch pad. Touches that are wider than this are
3893 // translated into freeform gestures.
3894 mPointerGestureMaxSwipeWidth =
3895 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3896
3897 // Abort current pointer usages because the state has changed.
3898 abortPointerUsage(when, 0 /*policyFlags*/);
3899 }
3900
3901 // Inform the dispatcher about the changes.
3902 *outResetNeeded = true;
3903 bumpGeneration();
3904 }
3905}
3906
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003907void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003908 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003909 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3910 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3911 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3912 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003913 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3914 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3915 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3916 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003917 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918}
3919
3920void TouchInputMapper::configureVirtualKeys() {
3921 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3922 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3923
3924 mVirtualKeys.clear();
3925
3926 if (virtualKeyDefinitions.size() == 0) {
3927 return;
3928 }
3929
3930 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3931
3932 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3933 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003934 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3935 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936
3937 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3938 const VirtualKeyDefinition& virtualKeyDefinition =
3939 virtualKeyDefinitions[i];
3940
3941 mVirtualKeys.add();
3942 VirtualKey& virtualKey = mVirtualKeys.editTop();
3943
3944 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3945 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003946 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003948 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3949 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3951 virtualKey.scanCode);
3952 mVirtualKeys.pop(); // drop the key
3953 continue;
3954 }
3955
3956 virtualKey.keyCode = keyCode;
3957 virtualKey.flags = flags;
3958
3959 // convert the key definition's display coordinates into touch coordinates for a hit box
3960 int32_t halfWidth = virtualKeyDefinition.width / 2;
3961 int32_t halfHeight = virtualKeyDefinition.height / 2;
3962
3963 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3964 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3965 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3966 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3967 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3968 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3969 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3970 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3971 }
3972}
3973
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003974void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003976 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977
3978 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3979 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003980 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3982 i, virtualKey.scanCode, virtualKey.keyCode,
3983 virtualKey.hitLeft, virtualKey.hitRight,
3984 virtualKey.hitTop, virtualKey.hitBottom);
3985 }
3986 }
3987}
3988
3989void TouchInputMapper::parseCalibration() {
3990 const PropertyMap& in = getDevice()->getConfiguration();
3991 Calibration& out = mCalibration;
3992
3993 // Size
3994 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3995 String8 sizeCalibrationString;
3996 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3997 if (sizeCalibrationString == "none") {
3998 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3999 } else if (sizeCalibrationString == "geometric") {
4000 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4001 } else if (sizeCalibrationString == "diameter") {
4002 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4003 } else if (sizeCalibrationString == "box") {
4004 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4005 } else if (sizeCalibrationString == "area") {
4006 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4007 } else if (sizeCalibrationString != "default") {
4008 ALOGW("Invalid value for touch.size.calibration: '%s'",
4009 sizeCalibrationString.string());
4010 }
4011 }
4012
4013 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4014 out.sizeScale);
4015 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4016 out.sizeBias);
4017 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4018 out.sizeIsSummed);
4019
4020 // Pressure
4021 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4022 String8 pressureCalibrationString;
4023 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4024 if (pressureCalibrationString == "none") {
4025 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4026 } else if (pressureCalibrationString == "physical") {
4027 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4028 } else if (pressureCalibrationString == "amplitude") {
4029 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4030 } else if (pressureCalibrationString != "default") {
4031 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4032 pressureCalibrationString.string());
4033 }
4034 }
4035
4036 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4037 out.pressureScale);
4038
4039 // Orientation
4040 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4041 String8 orientationCalibrationString;
4042 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4043 if (orientationCalibrationString == "none") {
4044 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4045 } else if (orientationCalibrationString == "interpolated") {
4046 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4047 } else if (orientationCalibrationString == "vector") {
4048 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4049 } else if (orientationCalibrationString != "default") {
4050 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4051 orientationCalibrationString.string());
4052 }
4053 }
4054
4055 // Distance
4056 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4057 String8 distanceCalibrationString;
4058 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4059 if (distanceCalibrationString == "none") {
4060 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4061 } else if (distanceCalibrationString == "scaled") {
4062 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4063 } else if (distanceCalibrationString != "default") {
4064 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4065 distanceCalibrationString.string());
4066 }
4067 }
4068
4069 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4070 out.distanceScale);
4071
4072 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4073 String8 coverageCalibrationString;
4074 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4075 if (coverageCalibrationString == "none") {
4076 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4077 } else if (coverageCalibrationString == "box") {
4078 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4079 } else if (coverageCalibrationString != "default") {
4080 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4081 coverageCalibrationString.string());
4082 }
4083 }
4084}
4085
4086void TouchInputMapper::resolveCalibration() {
4087 // Size
4088 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4089 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4090 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4091 }
4092 } else {
4093 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4094 }
4095
4096 // Pressure
4097 if (mRawPointerAxes.pressure.valid) {
4098 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4099 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4100 }
4101 } else {
4102 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4103 }
4104
4105 // Orientation
4106 if (mRawPointerAxes.orientation.valid) {
4107 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4108 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4109 }
4110 } else {
4111 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4112 }
4113
4114 // Distance
4115 if (mRawPointerAxes.distance.valid) {
4116 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4117 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4118 }
4119 } else {
4120 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4121 }
4122
4123 // Coverage
4124 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4125 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4126 }
4127}
4128
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004129void TouchInputMapper::dumpCalibration(std::string& dump) {
4130 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131
4132 // Size
4133 switch (mCalibration.sizeCalibration) {
4134 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004135 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 break;
4137 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004138 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 break;
4140 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004141 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 break;
4143 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004144 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 break;
4146 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004147 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 break;
4149 default:
4150 ALOG_ASSERT(false);
4151 }
4152
4153 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004154 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 mCalibration.sizeScale);
4156 }
4157
4158 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 mCalibration.sizeBias);
4161 }
4162
4163 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 toString(mCalibration.sizeIsSummed));
4166 }
4167
4168 // Pressure
4169 switch (mCalibration.pressureCalibration) {
4170 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004171 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 break;
4173 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 break;
4176 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 break;
4179 default:
4180 ALOG_ASSERT(false);
4181 }
4182
4183 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004184 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 mCalibration.pressureScale);
4186 }
4187
4188 // Orientation
4189 switch (mCalibration.orientationCalibration) {
4190 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 break;
4193 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 break;
4196 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 break;
4199 default:
4200 ALOG_ASSERT(false);
4201 }
4202
4203 // Distance
4204 switch (mCalibration.distanceCalibration) {
4205 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 break;
4208 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004209 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 break;
4211 default:
4212 ALOG_ASSERT(false);
4213 }
4214
4215 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004216 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 mCalibration.distanceScale);
4218 }
4219
4220 switch (mCalibration.coverageCalibration) {
4221 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004222 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 break;
4224 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 break;
4227 default:
4228 ALOG_ASSERT(false);
4229 }
4230}
4231
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004232void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4233 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004234
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004235 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4236 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4237 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4238 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4239 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4240 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004241}
4242
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004243void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004244 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4245 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004246}
4247
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248void TouchInputMapper::reset(nsecs_t when) {
4249 mCursorButtonAccumulator.reset(getDevice());
4250 mCursorScrollAccumulator.reset(getDevice());
4251 mTouchButtonAccumulator.reset(getDevice());
4252
4253 mPointerVelocityControl.reset();
4254 mWheelXVelocityControl.reset();
4255 mWheelYVelocityControl.reset();
4256
Michael Wright842500e2015-03-13 17:32:02 -07004257 mRawStatesPending.clear();
4258 mCurrentRawState.clear();
4259 mCurrentCookedState.clear();
4260 mLastRawState.clear();
4261 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 mPointerUsage = POINTER_USAGE_NONE;
4263 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004264 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004265 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 mDownTime = 0;
4267
4268 mCurrentVirtualKey.down = false;
4269
4270 mPointerGesture.reset();
4271 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004272 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Yi Kong9b14ac62018-07-17 13:48:38 -07004274 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4276 mPointerController->clearSpots();
4277 }
4278
4279 InputMapper::reset(when);
4280}
4281
Michael Wright842500e2015-03-13 17:32:02 -07004282void TouchInputMapper::resetExternalStylus() {
4283 mExternalStylusState.clear();
4284 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004285 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004286 mExternalStylusDataPending = false;
4287}
4288
Michael Wright43fd19f2015-04-21 19:02:58 +01004289void TouchInputMapper::clearStylusDataPendingFlags() {
4290 mExternalStylusDataPending = false;
4291 mExternalStylusFusionTimeout = LLONG_MAX;
4292}
4293
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004294void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4295 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4296 nsecs_t latency = now - evdevTime;
4297 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4298 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4299 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
4300 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED,
4301 mStatistics.min, mStatistics.max, mStatistics.mean(), mStatistics.stdev());
4302 mStatistics.reset(now);
4303 }
4304}
4305
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306void TouchInputMapper::process(const RawEvent* rawEvent) {
4307 mCursorButtonAccumulator.process(rawEvent);
4308 mCursorScrollAccumulator.process(rawEvent);
4309 mTouchButtonAccumulator.process(rawEvent);
4310
4311 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004312 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 sync(rawEvent->when);
4314 }
4315}
4316
4317void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004318 const RawState* last = mRawStatesPending.isEmpty() ?
4319 &mCurrentRawState : &mRawStatesPending.top();
4320
4321 // Push a new state.
4322 mRawStatesPending.push();
4323 RawState* next = &mRawStatesPending.editTop();
4324 next->clear();
4325 next->when = when;
4326
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004328 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 | mCursorButtonAccumulator.getButtonState();
4330
Michael Wright842500e2015-03-13 17:32:02 -07004331 // Sync scroll
4332 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4333 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 mCursorScrollAccumulator.finishSync();
4335
Michael Wright842500e2015-03-13 17:32:02 -07004336 // Sync touch
4337 syncTouch(when, next);
4338
4339 // Assign pointer ids.
4340 if (!mHavePointerIds) {
4341 assignPointerIds(last, next);
4342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
4344#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004345 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4346 "hovering ids 0x%08x -> 0x%08x",
4347 last->rawPointerData.pointerCount,
4348 next->rawPointerData.pointerCount,
4349 last->rawPointerData.touchingIdBits.value,
4350 next->rawPointerData.touchingIdBits.value,
4351 last->rawPointerData.hoveringIdBits.value,
4352 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353#endif
4354
Michael Wright842500e2015-03-13 17:32:02 -07004355 processRawTouches(false /*timeout*/);
4356}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357
Michael Wright842500e2015-03-13 17:32:02 -07004358void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4360 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004361 mCurrentRawState.clear();
4362 mRawStatesPending.clear();
4363 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 }
4365
Michael Wright842500e2015-03-13 17:32:02 -07004366 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4367 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4368 // touching the current state will only observe the events that have been dispatched to the
4369 // rest of the pipeline.
4370 const size_t N = mRawStatesPending.size();
4371 size_t count;
4372 for(count = 0; count < N; count++) {
4373 const RawState& next = mRawStatesPending[count];
4374
4375 // A failure to assign the stylus id means that we're waiting on stylus data
4376 // and so should defer the rest of the pipeline.
4377 if (assignExternalStylusId(next, timeout)) {
4378 break;
4379 }
4380
4381 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004382 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004383 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004384 if (mCurrentRawState.when < mLastRawState.when) {
4385 mCurrentRawState.when = mLastRawState.when;
4386 }
Michael Wright842500e2015-03-13 17:32:02 -07004387 cookAndDispatch(mCurrentRawState.when);
4388 }
4389 if (count != 0) {
4390 mRawStatesPending.removeItemsAt(0, count);
4391 }
4392
Michael Wright842500e2015-03-13 17:32:02 -07004393 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004394 if (timeout) {
4395 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4396 clearStylusDataPendingFlags();
4397 mCurrentRawState.copyFrom(mLastRawState);
4398#if DEBUG_STYLUS_FUSION
4399 ALOGD("Timeout expired, synthesizing event with new stylus data");
4400#endif
4401 cookAndDispatch(when);
4402 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4403 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4404 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4405 }
Michael Wright842500e2015-03-13 17:32:02 -07004406 }
4407}
4408
4409void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4410 // Always start with a clean state.
4411 mCurrentCookedState.clear();
4412
4413 // Apply stylus buttons to current raw state.
4414 applyExternalStylusButtonState(when);
4415
4416 // Handle policy on initial down or hover events.
4417 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4418 && mCurrentRawState.rawPointerData.pointerCount != 0;
4419
4420 uint32_t policyFlags = 0;
4421 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4422 if (initialDown || buttonsPressed) {
4423 // If this is a touch screen, hide the pointer on an initial down.
4424 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4425 getContext()->fadePointer();
4426 }
4427
4428 if (mParameters.wake) {
4429 policyFlags |= POLICY_FLAG_WAKE;
4430 }
4431 }
4432
4433 // Consume raw off-screen touches before cooking pointer data.
4434 // If touches are consumed, subsequent code will not receive any pointer data.
4435 if (consumeRawTouches(when, policyFlags)) {
4436 mCurrentRawState.rawPointerData.clear();
4437 }
4438
4439 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4440 // with cooked pointer data that has the same ids and indices as the raw data.
4441 // The following code can use either the raw or cooked data, as needed.
4442 cookPointerData();
4443
4444 // Apply stylus pressure to current cooked state.
4445 applyExternalStylusTouchState(when);
4446
4447 // Synthesize key down from raw buttons if needed.
4448 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004449 mViewport.displayId, policyFlags,
4450 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004451
4452 // Dispatch the touches either directly or by translation through a pointer on screen.
4453 if (mDeviceMode == DEVICE_MODE_POINTER) {
4454 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4455 !idBits.isEmpty(); ) {
4456 uint32_t id = idBits.clearFirstMarkedBit();
4457 const RawPointerData::Pointer& pointer =
4458 mCurrentRawState.rawPointerData.pointerForId(id);
4459 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4460 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4461 mCurrentCookedState.stylusIdBits.markBit(id);
4462 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4463 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4464 mCurrentCookedState.fingerIdBits.markBit(id);
4465 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4466 mCurrentCookedState.mouseIdBits.markBit(id);
4467 }
4468 }
4469 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4470 !idBits.isEmpty(); ) {
4471 uint32_t id = idBits.clearFirstMarkedBit();
4472 const RawPointerData::Pointer& pointer =
4473 mCurrentRawState.rawPointerData.pointerForId(id);
4474 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4475 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4476 mCurrentCookedState.stylusIdBits.markBit(id);
4477 }
4478 }
4479
4480 // Stylus takes precedence over all tools, then mouse, then finger.
4481 PointerUsage pointerUsage = mPointerUsage;
4482 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4483 mCurrentCookedState.mouseIdBits.clear();
4484 mCurrentCookedState.fingerIdBits.clear();
4485 pointerUsage = POINTER_USAGE_STYLUS;
4486 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4487 mCurrentCookedState.fingerIdBits.clear();
4488 pointerUsage = POINTER_USAGE_MOUSE;
4489 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4490 isPointerDown(mCurrentRawState.buttonState)) {
4491 pointerUsage = POINTER_USAGE_GESTURES;
4492 }
4493
4494 dispatchPointerUsage(when, policyFlags, pointerUsage);
4495 } else {
4496 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004497 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004498 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4499 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4500
4501 mPointerController->setButtonState(mCurrentRawState.buttonState);
4502 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4503 mCurrentCookedState.cookedPointerData.idToIndex,
4504 mCurrentCookedState.cookedPointerData.touchingIdBits);
4505 }
4506
Michael Wright8e812822015-06-22 16:18:21 +01004507 if (!mCurrentMotionAborted) {
4508 dispatchButtonRelease(when, policyFlags);
4509 dispatchHoverExit(when, policyFlags);
4510 dispatchTouches(when, policyFlags);
4511 dispatchHoverEnterAndMove(when, policyFlags);
4512 dispatchButtonPress(when, policyFlags);
4513 }
4514
4515 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4516 mCurrentMotionAborted = false;
4517 }
Michael Wright842500e2015-03-13 17:32:02 -07004518 }
4519
4520 // Synthesize key up from raw buttons if needed.
4521 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004522 mViewport.displayId, policyFlags,
4523 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524
4525 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004526 mCurrentRawState.rawVScroll = 0;
4527 mCurrentRawState.rawHScroll = 0;
4528
4529 // Copy current touch to last touch in preparation for the next cycle.
4530 mLastRawState.copyFrom(mCurrentRawState);
4531 mLastCookedState.copyFrom(mCurrentCookedState);
4532}
4533
4534void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004535 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004536 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4537 }
4538}
4539
4540void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004541 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4542 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004543
Michael Wright53dca3a2015-04-23 17:39:53 +01004544 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4545 float pressure = mExternalStylusState.pressure;
4546 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4547 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4548 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4549 }
4550 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4551 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4552
4553 PointerProperties& properties =
4554 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004555 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4556 properties.toolType = mExternalStylusState.toolType;
4557 }
4558 }
4559}
4560
4561bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4562 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4563 return false;
4564 }
4565
4566 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4567 && state.rawPointerData.pointerCount != 0;
4568 if (initialDown) {
4569 if (mExternalStylusState.pressure != 0.0f) {
4570#if DEBUG_STYLUS_FUSION
4571 ALOGD("Have both stylus and touch data, beginning fusion");
4572#endif
4573 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4574 } else if (timeout) {
4575#if DEBUG_STYLUS_FUSION
4576 ALOGD("Timeout expired, assuming touch is not a stylus.");
4577#endif
4578 resetExternalStylus();
4579 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004580 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4581 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004582 }
4583#if DEBUG_STYLUS_FUSION
4584 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004585 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004586#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004587 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004588 return true;
4589 }
4590 }
4591
4592 // Check if the stylus pointer has gone up.
4593 if (mExternalStylusId != -1 &&
4594 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4595#if DEBUG_STYLUS_FUSION
4596 ALOGD("Stylus pointer is going up");
4597#endif
4598 mExternalStylusId = -1;
4599 }
4600
4601 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602}
4603
4604void TouchInputMapper::timeoutExpired(nsecs_t when) {
4605 if (mDeviceMode == DEVICE_MODE_POINTER) {
4606 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4607 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4608 }
Michael Wright842500e2015-03-13 17:32:02 -07004609 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004610 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004611 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004612 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4613 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004614 }
4615 }
4616}
4617
4618void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004619 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004620 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004621 // We're either in the middle of a fused stream of data or we're waiting on data before
4622 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4623 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004624 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004625 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 }
4627}
4628
4629bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4630 // Check for release of a virtual key.
4631 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004632 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633 // Pointer went up while virtual key was down.
4634 mCurrentVirtualKey.down = false;
4635 if (!mCurrentVirtualKey.ignored) {
4636#if DEBUG_VIRTUAL_KEYS
4637 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4638 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4639#endif
4640 dispatchVirtualKey(when, policyFlags,
4641 AKEY_EVENT_ACTION_UP,
4642 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4643 }
4644 return true;
4645 }
4646
Michael Wright842500e2015-03-13 17:32:02 -07004647 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4648 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4649 const RawPointerData::Pointer& pointer =
4650 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4652 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4653 // Pointer is still within the space of the virtual key.
4654 return true;
4655 }
4656 }
4657
4658 // Pointer left virtual key area or another pointer also went down.
4659 // Send key cancellation but do not consume the touch yet.
4660 // This is useful when the user swipes through from the virtual key area
4661 // into the main display surface.
4662 mCurrentVirtualKey.down = false;
4663 if (!mCurrentVirtualKey.ignored) {
4664#if DEBUG_VIRTUAL_KEYS
4665 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4666 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4667#endif
4668 dispatchVirtualKey(when, policyFlags,
4669 AKEY_EVENT_ACTION_UP,
4670 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4671 | AKEY_EVENT_FLAG_CANCELED);
4672 }
4673 }
4674
Michael Wright842500e2015-03-13 17:32:02 -07004675 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4676 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004678 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4679 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4681 // If exactly one pointer went down, check for virtual key hit.
4682 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004683 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4685 if (virtualKey) {
4686 mCurrentVirtualKey.down = true;
4687 mCurrentVirtualKey.downTime = when;
4688 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4689 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4690 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4691 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4692
4693 if (!mCurrentVirtualKey.ignored) {
4694#if DEBUG_VIRTUAL_KEYS
4695 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4696 mCurrentVirtualKey.keyCode,
4697 mCurrentVirtualKey.scanCode);
4698#endif
4699 dispatchVirtualKey(when, policyFlags,
4700 AKEY_EVENT_ACTION_DOWN,
4701 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4702 }
4703 }
4704 }
4705 return true;
4706 }
4707 }
4708
4709 // Disable all virtual key touches that happen within a short time interval of the
4710 // most recent touch within the screen area. The idea is to filter out stray
4711 // virtual key presses when interacting with the touch screen.
4712 //
4713 // Problems we're trying to solve:
4714 //
4715 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4716 // virtual key area that is implemented by a separate touch panel and accidentally
4717 // triggers a virtual key.
4718 //
4719 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4720 // area and accidentally triggers a virtual key. This often happens when virtual keys
4721 // are layed out below the screen near to where the on screen keyboard's space bar
4722 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004723 if (mConfig.virtualKeyQuietTime > 0 &&
4724 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4726 }
4727 return false;
4728}
4729
4730void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4731 int32_t keyEventAction, int32_t keyEventFlags) {
4732 int32_t keyCode = mCurrentVirtualKey.keyCode;
4733 int32_t scanCode = mCurrentVirtualKey.scanCode;
4734 nsecs_t downTime = mCurrentVirtualKey.downTime;
4735 int32_t metaState = mContext->getGlobalMetaState();
4736 policyFlags |= POLICY_FLAG_VIRTUAL;
4737
Prabir Pradhan42611e02018-11-27 14:04:02 -08004738 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4739 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004740 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 getListener()->notifyKey(&args);
4742}
4743
Michael Wright8e812822015-06-22 16:18:21 +01004744void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4745 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4746 if (!currentIdBits.isEmpty()) {
4747 int32_t metaState = getContext()->getGlobalMetaState();
4748 int32_t buttonState = mCurrentCookedState.buttonState;
4749 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4750 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004751 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004752 mCurrentCookedState.cookedPointerData.pointerProperties,
4753 mCurrentCookedState.cookedPointerData.pointerCoords,
4754 mCurrentCookedState.cookedPointerData.idToIndex,
4755 currentIdBits, -1,
4756 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4757 mCurrentMotionAborted = true;
4758 }
4759}
4760
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004762 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4763 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004765 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766
4767 if (currentIdBits == lastIdBits) {
4768 if (!currentIdBits.isEmpty()) {
4769 // No pointer id changes so this is a move event.
4770 // The listener takes care of batching moves so we don't have to deal with that here.
4771 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004772 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004774 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004775 mCurrentCookedState.cookedPointerData.pointerProperties,
4776 mCurrentCookedState.cookedPointerData.pointerCoords,
4777 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778 currentIdBits, -1,
4779 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4780 }
4781 } else {
4782 // There may be pointers going up and pointers going down and pointers moving
4783 // all at the same time.
4784 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4785 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4786 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4787 BitSet32 dispatchedIdBits(lastIdBits.value);
4788
4789 // Update last coordinates of pointers that have moved so that we observe the new
4790 // pointer positions at the same time as other pointers that have just gone up.
4791 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004792 mCurrentCookedState.cookedPointerData.pointerProperties,
4793 mCurrentCookedState.cookedPointerData.pointerCoords,
4794 mCurrentCookedState.cookedPointerData.idToIndex,
4795 mLastCookedState.cookedPointerData.pointerProperties,
4796 mLastCookedState.cookedPointerData.pointerCoords,
4797 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004799 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 moveNeeded = true;
4801 }
4802
4803 // Dispatch pointer up events.
4804 while (!upIdBits.isEmpty()) {
4805 uint32_t upId = upIdBits.clearFirstMarkedBit();
4806
4807 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004808 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004809 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004810 mLastCookedState.cookedPointerData.pointerProperties,
4811 mLastCookedState.cookedPointerData.pointerCoords,
4812 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004813 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 dispatchedIdBits.clearBit(upId);
4815 }
4816
4817 // Dispatch move events if any of the remaining pointers moved from their old locations.
4818 // Although applications receive new locations as part of individual pointer up
4819 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004820 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4822 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004823 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004824 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004825 mCurrentCookedState.cookedPointerData.pointerProperties,
4826 mCurrentCookedState.cookedPointerData.pointerCoords,
4827 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004828 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829 }
4830
4831 // Dispatch pointer down events using the new pointer locations.
4832 while (!downIdBits.isEmpty()) {
4833 uint32_t downId = downIdBits.clearFirstMarkedBit();
4834 dispatchedIdBits.markBit(downId);
4835
4836 if (dispatchedIdBits.count() == 1) {
4837 // First pointer is going down. Set down time.
4838 mDownTime = when;
4839 }
4840
4841 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004842 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004843 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004844 mCurrentCookedState.cookedPointerData.pointerProperties,
4845 mCurrentCookedState.cookedPointerData.pointerCoords,
4846 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004847 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 }
4849 }
4850}
4851
4852void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4853 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004854 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4855 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856 int32_t metaState = getContext()->getGlobalMetaState();
4857 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004858 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004859 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004860 mLastCookedState.cookedPointerData.pointerProperties,
4861 mLastCookedState.cookedPointerData.pointerCoords,
4862 mLastCookedState.cookedPointerData.idToIndex,
4863 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4865 mSentHoverEnter = false;
4866 }
4867}
4868
4869void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004870 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4871 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 int32_t metaState = getContext()->getGlobalMetaState();
4873 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004874 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004875 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004876 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004877 mCurrentCookedState.cookedPointerData.pointerProperties,
4878 mCurrentCookedState.cookedPointerData.pointerCoords,
4879 mCurrentCookedState.cookedPointerData.idToIndex,
4880 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4882 mSentHoverEnter = true;
4883 }
4884
4885 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004886 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004887 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004888 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004889 mCurrentCookedState.cookedPointerData.pointerProperties,
4890 mCurrentCookedState.cookedPointerData.pointerCoords,
4891 mCurrentCookedState.cookedPointerData.idToIndex,
4892 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4894 }
4895}
4896
Michael Wright7b159c92015-05-14 14:48:03 +01004897void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4898 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4899 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4900 const int32_t metaState = getContext()->getGlobalMetaState();
4901 int32_t buttonState = mLastCookedState.buttonState;
4902 while (!releasedButtons.isEmpty()) {
4903 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4904 buttonState &= ~actionButton;
4905 dispatchMotion(when, policyFlags, mSource,
4906 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4907 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004908 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004909 mCurrentCookedState.cookedPointerData.pointerProperties,
4910 mCurrentCookedState.cookedPointerData.pointerCoords,
4911 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4912 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4913 }
4914}
4915
4916void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4917 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4918 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4919 const int32_t metaState = getContext()->getGlobalMetaState();
4920 int32_t buttonState = mLastCookedState.buttonState;
4921 while (!pressedButtons.isEmpty()) {
4922 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4923 buttonState |= actionButton;
4924 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4925 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004926 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004927 mCurrentCookedState.cookedPointerData.pointerProperties,
4928 mCurrentCookedState.cookedPointerData.pointerCoords,
4929 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4930 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4931 }
4932}
4933
4934const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4935 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4936 return cookedPointerData.touchingIdBits;
4937 }
4938 return cookedPointerData.hoveringIdBits;
4939}
4940
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004942 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943
Michael Wright842500e2015-03-13 17:32:02 -07004944 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004945 mCurrentCookedState.deviceTimestamp =
4946 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004947 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4948 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4949 mCurrentRawState.rawPointerData.hoveringIdBits;
4950 mCurrentCookedState.cookedPointerData.touchingIdBits =
4951 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952
Michael Wright7b159c92015-05-14 14:48:03 +01004953 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4954 mCurrentCookedState.buttonState = 0;
4955 } else {
4956 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4957 }
4958
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 // Walk through the the active pointers and map device coordinates onto
4960 // surface coordinates and adjust for display orientation.
4961 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004962 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963
4964 // Size
4965 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4966 switch (mCalibration.sizeCalibration) {
4967 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4968 case Calibration::SIZE_CALIBRATION_DIAMETER:
4969 case Calibration::SIZE_CALIBRATION_BOX:
4970 case Calibration::SIZE_CALIBRATION_AREA:
4971 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4972 touchMajor = in.touchMajor;
4973 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4974 toolMajor = in.toolMajor;
4975 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4976 size = mRawPointerAxes.touchMinor.valid
4977 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4978 } else if (mRawPointerAxes.touchMajor.valid) {
4979 toolMajor = touchMajor = in.touchMajor;
4980 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4981 ? in.touchMinor : in.touchMajor;
4982 size = mRawPointerAxes.touchMinor.valid
4983 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4984 } else if (mRawPointerAxes.toolMajor.valid) {
4985 touchMajor = toolMajor = in.toolMajor;
4986 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4987 ? in.toolMinor : in.toolMajor;
4988 size = mRawPointerAxes.toolMinor.valid
4989 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4990 } else {
4991 ALOG_ASSERT(false, "No touch or tool axes. "
4992 "Size calibration should have been resolved to NONE.");
4993 touchMajor = 0;
4994 touchMinor = 0;
4995 toolMajor = 0;
4996 toolMinor = 0;
4997 size = 0;
4998 }
4999
5000 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005001 uint32_t touchingCount =
5002 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003 if (touchingCount > 1) {
5004 touchMajor /= touchingCount;
5005 touchMinor /= touchingCount;
5006 toolMajor /= touchingCount;
5007 toolMinor /= touchingCount;
5008 size /= touchingCount;
5009 }
5010 }
5011
5012 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5013 touchMajor *= mGeometricScale;
5014 touchMinor *= mGeometricScale;
5015 toolMajor *= mGeometricScale;
5016 toolMinor *= mGeometricScale;
5017 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5018 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5019 touchMinor = touchMajor;
5020 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5021 toolMinor = toolMajor;
5022 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5023 touchMinor = touchMajor;
5024 toolMinor = toolMajor;
5025 }
5026
5027 mCalibration.applySizeScaleAndBias(&touchMajor);
5028 mCalibration.applySizeScaleAndBias(&touchMinor);
5029 mCalibration.applySizeScaleAndBias(&toolMajor);
5030 mCalibration.applySizeScaleAndBias(&toolMinor);
5031 size *= mSizeScale;
5032 break;
5033 default:
5034 touchMajor = 0;
5035 touchMinor = 0;
5036 toolMajor = 0;
5037 toolMinor = 0;
5038 size = 0;
5039 break;
5040 }
5041
5042 // Pressure
5043 float pressure;
5044 switch (mCalibration.pressureCalibration) {
5045 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5046 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5047 pressure = in.pressure * mPressureScale;
5048 break;
5049 default:
5050 pressure = in.isHovering ? 0 : 1;
5051 break;
5052 }
5053
5054 // Tilt and Orientation
5055 float tilt;
5056 float orientation;
5057 if (mHaveTilt) {
5058 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5059 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5060 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5061 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5062 } else {
5063 tilt = 0;
5064
5065 switch (mCalibration.orientationCalibration) {
5066 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5067 orientation = in.orientation * mOrientationScale;
5068 break;
5069 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5070 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5071 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5072 if (c1 != 0 || c2 != 0) {
5073 orientation = atan2f(c1, c2) * 0.5f;
5074 float confidence = hypotf(c1, c2);
5075 float scale = 1.0f + confidence / 16.0f;
5076 touchMajor *= scale;
5077 touchMinor /= scale;
5078 toolMajor *= scale;
5079 toolMinor /= scale;
5080 } else {
5081 orientation = 0;
5082 }
5083 break;
5084 }
5085 default:
5086 orientation = 0;
5087 }
5088 }
5089
5090 // Distance
5091 float distance;
5092 switch (mCalibration.distanceCalibration) {
5093 case Calibration::DISTANCE_CALIBRATION_SCALED:
5094 distance = in.distance * mDistanceScale;
5095 break;
5096 default:
5097 distance = 0;
5098 }
5099
5100 // Coverage
5101 int32_t rawLeft, rawTop, rawRight, rawBottom;
5102 switch (mCalibration.coverageCalibration) {
5103 case Calibration::COVERAGE_CALIBRATION_BOX:
5104 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5105 rawRight = in.toolMinor & 0x0000ffff;
5106 rawBottom = in.toolMajor & 0x0000ffff;
5107 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5108 break;
5109 default:
5110 rawLeft = rawTop = rawRight = rawBottom = 0;
5111 break;
5112 }
5113
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005114 // Adjust X,Y coords for device calibration
5115 // TODO: Adjust coverage coords?
5116 float xTransformed = in.x, yTransformed = in.y;
5117 mAffineTransform.applyTo(xTransformed, yTransformed);
5118
5119 // Adjust X, Y, and coverage coords for surface orientation.
5120 float x, y;
5121 float left, top, right, bottom;
5122
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 switch (mSurfaceOrientation) {
5124 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005125 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5126 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5128 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5129 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5130 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5131 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005132 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5134 }
5135 break;
5136 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005137 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005138 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005139 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5140 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5142 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5143 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005144 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5146 }
5147 break;
5148 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005149 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005150 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005151 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5152 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5154 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5155 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005156 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5158 }
5159 break;
5160 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005161 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5162 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5164 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5165 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5166 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5167 break;
5168 }
5169
5170 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005171 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 out.clear();
5173 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5174 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5175 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5176 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5177 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5178 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5179 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5180 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5181 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5182 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5183 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5184 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5185 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5186 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5187 } else {
5188 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5189 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5190 }
5191
5192 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005193 PointerProperties& properties =
5194 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195 uint32_t id = in.id;
5196 properties.clear();
5197 properties.id = id;
5198 properties.toolType = in.toolType;
5199
5200 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005201 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 }
5203}
5204
5205void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5206 PointerUsage pointerUsage) {
5207 if (pointerUsage != mPointerUsage) {
5208 abortPointerUsage(when, policyFlags);
5209 mPointerUsage = pointerUsage;
5210 }
5211
5212 switch (mPointerUsage) {
5213 case POINTER_USAGE_GESTURES:
5214 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5215 break;
5216 case POINTER_USAGE_STYLUS:
5217 dispatchPointerStylus(when, policyFlags);
5218 break;
5219 case POINTER_USAGE_MOUSE:
5220 dispatchPointerMouse(when, policyFlags);
5221 break;
5222 default:
5223 break;
5224 }
5225}
5226
5227void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5228 switch (mPointerUsage) {
5229 case POINTER_USAGE_GESTURES:
5230 abortPointerGestures(when, policyFlags);
5231 break;
5232 case POINTER_USAGE_STYLUS:
5233 abortPointerStylus(when, policyFlags);
5234 break;
5235 case POINTER_USAGE_MOUSE:
5236 abortPointerMouse(when, policyFlags);
5237 break;
5238 default:
5239 break;
5240 }
5241
5242 mPointerUsage = POINTER_USAGE_NONE;
5243}
5244
5245void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5246 bool isTimeout) {
5247 // Update current gesture coordinates.
5248 bool cancelPreviousGesture, finishPreviousGesture;
5249 bool sendEvents = preparePointerGestures(when,
5250 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5251 if (!sendEvents) {
5252 return;
5253 }
5254 if (finishPreviousGesture) {
5255 cancelPreviousGesture = false;
5256 }
5257
5258 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005259 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5260 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 if (finishPreviousGesture || cancelPreviousGesture) {
5262 mPointerController->clearSpots();
5263 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005264
5265 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5266 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5267 mPointerGesture.currentGestureIdToIndex,
5268 mPointerGesture.currentGestureIdBits);
5269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270 } else {
5271 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5272 }
5273
5274 // Show or hide the pointer if needed.
5275 switch (mPointerGesture.currentGestureMode) {
5276 case PointerGesture::NEUTRAL:
5277 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005278 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5279 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 // Remind the user of where the pointer is after finishing a gesture with spots.
5281 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5282 }
5283 break;
5284 case PointerGesture::TAP:
5285 case PointerGesture::TAP_DRAG:
5286 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5287 case PointerGesture::HOVER:
5288 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005289 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 // Unfade the pointer when the current gesture manipulates the
5291 // area directly under the pointer.
5292 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5293 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 case PointerGesture::FREEFORM:
5295 // Fade the pointer when the current gesture manipulates a different
5296 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005297 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5299 } else {
5300 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5301 }
5302 break;
5303 }
5304
5305 // Send events!
5306 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005307 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308
5309 // Update last coordinates of pointers that have moved so that we observe the new
5310 // pointer positions at the same time as other pointers that have just gone up.
5311 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5312 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5313 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5314 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5315 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5316 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5317 bool moveNeeded = false;
5318 if (down && !cancelPreviousGesture && !finishPreviousGesture
5319 && !mPointerGesture.lastGestureIdBits.isEmpty()
5320 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5321 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5322 & mPointerGesture.lastGestureIdBits.value);
5323 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5324 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5325 mPointerGesture.lastGestureProperties,
5326 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5327 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005328 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 moveNeeded = true;
5330 }
5331 }
5332
5333 // Send motion events for all pointers that went up or were canceled.
5334 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5335 if (!dispatchedGestureIdBits.isEmpty()) {
5336 if (cancelPreviousGesture) {
5337 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005338 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005339 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 mPointerGesture.lastGestureProperties,
5341 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005342 dispatchedGestureIdBits, -1, 0,
5343 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344
5345 dispatchedGestureIdBits.clear();
5346 } else {
5347 BitSet32 upGestureIdBits;
5348 if (finishPreviousGesture) {
5349 upGestureIdBits = dispatchedGestureIdBits;
5350 } else {
5351 upGestureIdBits.value = dispatchedGestureIdBits.value
5352 & ~mPointerGesture.currentGestureIdBits.value;
5353 }
5354 while (!upGestureIdBits.isEmpty()) {
5355 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5356
5357 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005358 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005360 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 mPointerGesture.lastGestureProperties,
5362 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5363 dispatchedGestureIdBits, id,
5364 0, 0, mPointerGesture.downTime);
5365
5366 dispatchedGestureIdBits.clearBit(id);
5367 }
5368 }
5369 }
5370
5371 // Send motion events for all pointers that moved.
5372 if (moveNeeded) {
5373 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005374 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005375 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 mPointerGesture.currentGestureProperties,
5377 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5378 dispatchedGestureIdBits, -1,
5379 0, 0, mPointerGesture.downTime);
5380 }
5381
5382 // Send motion events for all pointers that went down.
5383 if (down) {
5384 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5385 & ~dispatchedGestureIdBits.value);
5386 while (!downGestureIdBits.isEmpty()) {
5387 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5388 dispatchedGestureIdBits.markBit(id);
5389
5390 if (dispatchedGestureIdBits.count() == 1) {
5391 mPointerGesture.downTime = when;
5392 }
5393
5394 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005395 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005396 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397 mPointerGesture.currentGestureProperties,
5398 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5399 dispatchedGestureIdBits, id,
5400 0, 0, mPointerGesture.downTime);
5401 }
5402 }
5403
5404 // Send motion events for hover.
5405 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5406 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005407 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005408 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409 mPointerGesture.currentGestureProperties,
5410 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5411 mPointerGesture.currentGestureIdBits, -1,
5412 0, 0, mPointerGesture.downTime);
5413 } else if (dispatchedGestureIdBits.isEmpty()
5414 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5415 // Synthesize a hover move event after all pointers go up to indicate that
5416 // the pointer is hovering again even if the user is not currently touching
5417 // the touch pad. This ensures that a view will receive a fresh hover enter
5418 // event after a tap.
5419 float x, y;
5420 mPointerController->getPosition(&x, &y);
5421
5422 PointerProperties pointerProperties;
5423 pointerProperties.clear();
5424 pointerProperties.id = 0;
5425 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5426
5427 PointerCoords pointerCoords;
5428 pointerCoords.clear();
5429 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5430 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5431
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005432 const int32_t displayId = mPointerController->getDisplayId();
Dan Harmsaca28402018-12-17 13:55:20 -08005433 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005434 mSource, displayId, policyFlags,
Dan Harmsaca28402018-12-17 13:55:20 -08005435 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08005436 metaState, buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005437 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08005438 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 getListener()->notifyMotion(&args);
5440 }
5441
5442 // Update state.
5443 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5444 if (!down) {
5445 mPointerGesture.lastGestureIdBits.clear();
5446 } else {
5447 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5448 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5449 uint32_t id = idBits.clearFirstMarkedBit();
5450 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5451 mPointerGesture.lastGestureProperties[index].copyFrom(
5452 mPointerGesture.currentGestureProperties[index]);
5453 mPointerGesture.lastGestureCoords[index].copyFrom(
5454 mPointerGesture.currentGestureCoords[index]);
5455 mPointerGesture.lastGestureIdToIndex[id] = index;
5456 }
5457 }
5458}
5459
5460void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5461 // Cancel previously dispatches pointers.
5462 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5463 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005464 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005466 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005467 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 mPointerGesture.lastGestureProperties,
5469 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5470 mPointerGesture.lastGestureIdBits, -1,
5471 0, 0, mPointerGesture.downTime);
5472 }
5473
5474 // Reset the current pointer gesture.
5475 mPointerGesture.reset();
5476 mPointerVelocityControl.reset();
5477
5478 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005479 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5481 mPointerController->clearSpots();
5482 }
5483}
5484
5485bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5486 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5487 *outCancelPreviousGesture = false;
5488 *outFinishPreviousGesture = false;
5489
5490 // Handle TAP timeout.
5491 if (isTimeout) {
5492#if DEBUG_GESTURES
5493 ALOGD("Gestures: Processing timeout");
5494#endif
5495
5496 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5497 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5498 // The tap/drag timeout has not yet expired.
5499 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5500 + mConfig.pointerGestureTapDragInterval);
5501 } else {
5502 // The tap is finished.
5503#if DEBUG_GESTURES
5504 ALOGD("Gestures: TAP finished");
5505#endif
5506 *outFinishPreviousGesture = true;
5507
5508 mPointerGesture.activeGestureId = -1;
5509 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5510 mPointerGesture.currentGestureIdBits.clear();
5511
5512 mPointerVelocityControl.reset();
5513 return true;
5514 }
5515 }
5516
5517 // We did not handle this timeout.
5518 return false;
5519 }
5520
Michael Wright842500e2015-03-13 17:32:02 -07005521 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5522 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523
5524 // Update the velocity tracker.
5525 {
5526 VelocityTracker::Position positions[MAX_POINTERS];
5527 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005528 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005530 const RawPointerData::Pointer& pointer =
5531 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 positions[count].x = pointer.x * mPointerXMovementScale;
5533 positions[count].y = pointer.y * mPointerYMovementScale;
5534 }
5535 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005536 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 }
5538
5539 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5540 // to NEUTRAL, then we should not generate tap event.
5541 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5542 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5543 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5544 mPointerGesture.resetTap();
5545 }
5546
5547 // Pick a new active touch id if needed.
5548 // Choose an arbitrary pointer that just went down, if there is one.
5549 // Otherwise choose an arbitrary remaining pointer.
5550 // This guarantees we always have an active touch id when there is at least one pointer.
5551 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5553 int32_t activeTouchId = lastActiveTouchId;
5554 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005555 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005557 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 mPointerGesture.firstTouchTime = when;
5559 }
Michael Wright842500e2015-03-13 17:32:02 -07005560 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005561 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005563 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 } else {
5565 activeTouchId = mPointerGesture.activeTouchId = -1;
5566 }
5567 }
5568
5569 // Determine whether we are in quiet time.
5570 bool isQuietTime = false;
5571 if (activeTouchId < 0) {
5572 mPointerGesture.resetQuietTime();
5573 } else {
5574 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5575 if (!isQuietTime) {
5576 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5577 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5578 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5579 && currentFingerCount < 2) {
5580 // Enter quiet time when exiting swipe or freeform state.
5581 // This is to prevent accidentally entering the hover state and flinging the
5582 // pointer when finishing a swipe and there is still one pointer left onscreen.
5583 isQuietTime = true;
5584 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5585 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005586 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587 // Enter quiet time when releasing the button and there are still two or more
5588 // fingers down. This may indicate that one finger was used to press the button
5589 // but it has not gone up yet.
5590 isQuietTime = true;
5591 }
5592 if (isQuietTime) {
5593 mPointerGesture.quietTime = when;
5594 }
5595 }
5596 }
5597
5598 // Switch states based on button and pointer state.
5599 if (isQuietTime) {
5600 // Case 1: Quiet time. (QUIET)
5601#if DEBUG_GESTURES
5602 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5603 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5604#endif
5605 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5606 *outFinishPreviousGesture = true;
5607 }
5608
5609 mPointerGesture.activeGestureId = -1;
5610 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5611 mPointerGesture.currentGestureIdBits.clear();
5612
5613 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005614 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5616 // The pointer follows the active touch point.
5617 // Emit DOWN, MOVE, UP events at the pointer location.
5618 //
5619 // Only the active touch matters; other fingers are ignored. This policy helps
5620 // to handle the case where the user places a second finger on the touch pad
5621 // to apply the necessary force to depress an integrated button below the surface.
5622 // We don't want the second finger to be delivered to applications.
5623 //
5624 // For this to work well, we need to make sure to track the pointer that is really
5625 // active. If the user first puts one finger down to click then adds another
5626 // finger to drag then the active pointer should switch to the finger that is
5627 // being dragged.
5628#if DEBUG_GESTURES
5629 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5630 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5631#endif
5632 // Reset state when just starting.
5633 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5634 *outFinishPreviousGesture = true;
5635 mPointerGesture.activeGestureId = 0;
5636 }
5637
5638 // Switch pointers if needed.
5639 // Find the fastest pointer and follow it.
5640 if (activeTouchId >= 0 && currentFingerCount > 1) {
5641 int32_t bestId = -1;
5642 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005643 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644 uint32_t id = idBits.clearFirstMarkedBit();
5645 float vx, vy;
5646 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5647 float speed = hypotf(vx, vy);
5648 if (speed > bestSpeed) {
5649 bestId = id;
5650 bestSpeed = speed;
5651 }
5652 }
5653 }
5654 if (bestId >= 0 && bestId != activeTouchId) {
5655 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656#if DEBUG_GESTURES
5657 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5658 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5659#endif
5660 }
5661 }
5662
Jun Mukaifa1706a2015-12-03 01:14:46 -08005663 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005664 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005666 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005668 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005669 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5670 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005671
5672 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5673 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5674
5675 // Move the pointer using a relative motion.
5676 // When using spots, the click will occur at the position of the anchor
5677 // spot and all other spots will move there.
5678 mPointerController->move(deltaX, deltaY);
5679 } else {
5680 mPointerVelocityControl.reset();
5681 }
5682
5683 float x, y;
5684 mPointerController->getPosition(&x, &y);
5685
5686 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5687 mPointerGesture.currentGestureIdBits.clear();
5688 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5689 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5690 mPointerGesture.currentGestureProperties[0].clear();
5691 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5692 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5693 mPointerGesture.currentGestureCoords[0].clear();
5694 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5695 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5696 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5697 } else if (currentFingerCount == 0) {
5698 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5699 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5700 *outFinishPreviousGesture = true;
5701 }
5702
5703 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5704 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5705 bool tapped = false;
5706 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5707 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5708 && lastFingerCount == 1) {
5709 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5710 float x, y;
5711 mPointerController->getPosition(&x, &y);
5712 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5713 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5714#if DEBUG_GESTURES
5715 ALOGD("Gestures: TAP");
5716#endif
5717
5718 mPointerGesture.tapUpTime = when;
5719 getContext()->requestTimeoutAtTime(when
5720 + mConfig.pointerGestureTapDragInterval);
5721
5722 mPointerGesture.activeGestureId = 0;
5723 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5724 mPointerGesture.currentGestureIdBits.clear();
5725 mPointerGesture.currentGestureIdBits.markBit(
5726 mPointerGesture.activeGestureId);
5727 mPointerGesture.currentGestureIdToIndex[
5728 mPointerGesture.activeGestureId] = 0;
5729 mPointerGesture.currentGestureProperties[0].clear();
5730 mPointerGesture.currentGestureProperties[0].id =
5731 mPointerGesture.activeGestureId;
5732 mPointerGesture.currentGestureProperties[0].toolType =
5733 AMOTION_EVENT_TOOL_TYPE_FINGER;
5734 mPointerGesture.currentGestureCoords[0].clear();
5735 mPointerGesture.currentGestureCoords[0].setAxisValue(
5736 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5737 mPointerGesture.currentGestureCoords[0].setAxisValue(
5738 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5739 mPointerGesture.currentGestureCoords[0].setAxisValue(
5740 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5741
5742 tapped = true;
5743 } else {
5744#if DEBUG_GESTURES
5745 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5746 x - mPointerGesture.tapX,
5747 y - mPointerGesture.tapY);
5748#endif
5749 }
5750 } else {
5751#if DEBUG_GESTURES
5752 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5753 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5754 (when - mPointerGesture.tapDownTime) * 0.000001f);
5755 } else {
5756 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5757 }
5758#endif
5759 }
5760 }
5761
5762 mPointerVelocityControl.reset();
5763
5764 if (!tapped) {
5765#if DEBUG_GESTURES
5766 ALOGD("Gestures: NEUTRAL");
5767#endif
5768 mPointerGesture.activeGestureId = -1;
5769 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5770 mPointerGesture.currentGestureIdBits.clear();
5771 }
5772 } else if (currentFingerCount == 1) {
5773 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5774 // The pointer follows the active touch point.
5775 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5776 // When in TAP_DRAG, emit MOVE events at the pointer location.
5777 ALOG_ASSERT(activeTouchId >= 0);
5778
5779 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5780 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5781 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5782 float x, y;
5783 mPointerController->getPosition(&x, &y);
5784 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5785 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5786 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5787 } else {
5788#if DEBUG_GESTURES
5789 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5790 x - mPointerGesture.tapX,
5791 y - mPointerGesture.tapY);
5792#endif
5793 }
5794 } else {
5795#if DEBUG_GESTURES
5796 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5797 (when - mPointerGesture.tapUpTime) * 0.000001f);
5798#endif
5799 }
5800 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5801 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5802 }
5803
Jun Mukaifa1706a2015-12-03 01:14:46 -08005804 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005805 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005807 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005809 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005810 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5811 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812
5813 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5814 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5815
5816 // Move the pointer using a relative motion.
5817 // When using spots, the hover or drag will occur at the position of the anchor spot.
5818 mPointerController->move(deltaX, deltaY);
5819 } else {
5820 mPointerVelocityControl.reset();
5821 }
5822
5823 bool down;
5824 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5825#if DEBUG_GESTURES
5826 ALOGD("Gestures: TAP_DRAG");
5827#endif
5828 down = true;
5829 } else {
5830#if DEBUG_GESTURES
5831 ALOGD("Gestures: HOVER");
5832#endif
5833 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5834 *outFinishPreviousGesture = true;
5835 }
5836 mPointerGesture.activeGestureId = 0;
5837 down = false;
5838 }
5839
5840 float x, y;
5841 mPointerController->getPosition(&x, &y);
5842
5843 mPointerGesture.currentGestureIdBits.clear();
5844 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5845 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5846 mPointerGesture.currentGestureProperties[0].clear();
5847 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5848 mPointerGesture.currentGestureProperties[0].toolType =
5849 AMOTION_EVENT_TOOL_TYPE_FINGER;
5850 mPointerGesture.currentGestureCoords[0].clear();
5851 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5852 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5853 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5854 down ? 1.0f : 0.0f);
5855
5856 if (lastFingerCount == 0 && currentFingerCount != 0) {
5857 mPointerGesture.resetTap();
5858 mPointerGesture.tapDownTime = when;
5859 mPointerGesture.tapX = x;
5860 mPointerGesture.tapY = y;
5861 }
5862 } else {
5863 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5864 // We need to provide feedback for each finger that goes down so we cannot wait
5865 // for the fingers to move before deciding what to do.
5866 //
5867 // The ambiguous case is deciding what to do when there are two fingers down but they
5868 // have not moved enough to determine whether they are part of a drag or part of a
5869 // freeform gesture, or just a press or long-press at the pointer location.
5870 //
5871 // When there are two fingers we start with the PRESS hypothesis and we generate a
5872 // down at the pointer location.
5873 //
5874 // When the two fingers move enough or when additional fingers are added, we make
5875 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5876 ALOG_ASSERT(activeTouchId >= 0);
5877
5878 bool settled = when >= mPointerGesture.firstTouchTime
5879 + mConfig.pointerGestureMultitouchSettleInterval;
5880 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5881 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5882 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5883 *outFinishPreviousGesture = true;
5884 } else if (!settled && currentFingerCount > lastFingerCount) {
5885 // Additional pointers have gone down but not yet settled.
5886 // Reset the gesture.
5887#if DEBUG_GESTURES
5888 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5889 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5890 + mConfig.pointerGestureMultitouchSettleInterval - when)
5891 * 0.000001f);
5892#endif
5893 *outCancelPreviousGesture = true;
5894 } else {
5895 // Continue previous gesture.
5896 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5897 }
5898
5899 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5900 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5901 mPointerGesture.activeGestureId = 0;
5902 mPointerGesture.referenceIdBits.clear();
5903 mPointerVelocityControl.reset();
5904
5905 // Use the centroid and pointer location as the reference points for the gesture.
5906#if DEBUG_GESTURES
5907 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5908 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5909 + mConfig.pointerGestureMultitouchSettleInterval - when)
5910 * 0.000001f);
5911#endif
Michael Wright842500e2015-03-13 17:32:02 -07005912 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 &mPointerGesture.referenceTouchX,
5914 &mPointerGesture.referenceTouchY);
5915 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5916 &mPointerGesture.referenceGestureY);
5917 }
5918
5919 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005920 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5922 uint32_t id = idBits.clearFirstMarkedBit();
5923 mPointerGesture.referenceDeltas[id].dx = 0;
5924 mPointerGesture.referenceDeltas[id].dy = 0;
5925 }
Michael Wright842500e2015-03-13 17:32:02 -07005926 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927
5928 // Add delta for all fingers and calculate a common movement delta.
5929 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005930 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5931 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5933 bool first = (idBits == commonIdBits);
5934 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005935 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5936 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5938 delta.dx += cpd.x - lpd.x;
5939 delta.dy += cpd.y - lpd.y;
5940
5941 if (first) {
5942 commonDeltaX = delta.dx;
5943 commonDeltaY = delta.dy;
5944 } else {
5945 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5946 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5947 }
5948 }
5949
5950 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5951 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5952 float dist[MAX_POINTER_ID + 1];
5953 int32_t distOverThreshold = 0;
5954 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5955 uint32_t id = idBits.clearFirstMarkedBit();
5956 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5957 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5958 delta.dy * mPointerYZoomScale);
5959 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5960 distOverThreshold += 1;
5961 }
5962 }
5963
5964 // Only transition when at least two pointers have moved further than
5965 // the minimum distance threshold.
5966 if (distOverThreshold >= 2) {
5967 if (currentFingerCount > 2) {
5968 // There are more than two pointers, switch to FREEFORM.
5969#if DEBUG_GESTURES
5970 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5971 currentFingerCount);
5972#endif
5973 *outCancelPreviousGesture = true;
5974 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5975 } else {
5976 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005977 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978 uint32_t id1 = idBits.clearFirstMarkedBit();
5979 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005980 const RawPointerData::Pointer& p1 =
5981 mCurrentRawState.rawPointerData.pointerForId(id1);
5982 const RawPointerData::Pointer& p2 =
5983 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5985 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5986 // There are two pointers but they are too far apart for a SWIPE,
5987 // switch to FREEFORM.
5988#if DEBUG_GESTURES
5989 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5990 mutualDistance, mPointerGestureMaxSwipeWidth);
5991#endif
5992 *outCancelPreviousGesture = true;
5993 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5994 } else {
5995 // There are two pointers. Wait for both pointers to start moving
5996 // before deciding whether this is a SWIPE or FREEFORM gesture.
5997 float dist1 = dist[id1];
5998 float dist2 = dist[id2];
5999 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6000 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6001 // Calculate the dot product of the displacement vectors.
6002 // When the vectors are oriented in approximately the same direction,
6003 // the angle betweeen them is near zero and the cosine of the angle
6004 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6005 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6006 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6007 float dx1 = delta1.dx * mPointerXZoomScale;
6008 float dy1 = delta1.dy * mPointerYZoomScale;
6009 float dx2 = delta2.dx * mPointerXZoomScale;
6010 float dy2 = delta2.dy * mPointerYZoomScale;
6011 float dot = dx1 * dx2 + dy1 * dy2;
6012 float cosine = dot / (dist1 * dist2); // denominator always > 0
6013 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6014 // Pointers are moving in the same direction. Switch to SWIPE.
6015#if DEBUG_GESTURES
6016 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6017 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6018 "cosine %0.3f >= %0.3f",
6019 dist1, mConfig.pointerGestureMultitouchMinDistance,
6020 dist2, mConfig.pointerGestureMultitouchMinDistance,
6021 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6022#endif
6023 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6024 } else {
6025 // Pointers are moving in different directions. Switch to FREEFORM.
6026#if DEBUG_GESTURES
6027 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6028 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6029 "cosine %0.3f < %0.3f",
6030 dist1, mConfig.pointerGestureMultitouchMinDistance,
6031 dist2, mConfig.pointerGestureMultitouchMinDistance,
6032 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6033#endif
6034 *outCancelPreviousGesture = true;
6035 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6036 }
6037 }
6038 }
6039 }
6040 }
6041 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6042 // Switch from SWIPE to FREEFORM if additional pointers go down.
6043 // Cancel previous gesture.
6044 if (currentFingerCount > 2) {
6045#if DEBUG_GESTURES
6046 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6047 currentFingerCount);
6048#endif
6049 *outCancelPreviousGesture = true;
6050 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6051 }
6052 }
6053
6054 // Move the reference points based on the overall group motion of the fingers
6055 // except in PRESS mode while waiting for a transition to occur.
6056 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6057 && (commonDeltaX || commonDeltaY)) {
6058 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6059 uint32_t id = idBits.clearFirstMarkedBit();
6060 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6061 delta.dx = 0;
6062 delta.dy = 0;
6063 }
6064
6065 mPointerGesture.referenceTouchX += commonDeltaX;
6066 mPointerGesture.referenceTouchY += commonDeltaY;
6067
6068 commonDeltaX *= mPointerXMovementScale;
6069 commonDeltaY *= mPointerYMovementScale;
6070
6071 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6072 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6073
6074 mPointerGesture.referenceGestureX += commonDeltaX;
6075 mPointerGesture.referenceGestureY += commonDeltaY;
6076 }
6077
6078 // Report gestures.
6079 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6080 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6081 // PRESS or SWIPE mode.
6082#if DEBUG_GESTURES
6083 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6084 "activeGestureId=%d, currentTouchPointerCount=%d",
6085 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6086#endif
6087 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6088
6089 mPointerGesture.currentGestureIdBits.clear();
6090 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6091 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6092 mPointerGesture.currentGestureProperties[0].clear();
6093 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6094 mPointerGesture.currentGestureProperties[0].toolType =
6095 AMOTION_EVENT_TOOL_TYPE_FINGER;
6096 mPointerGesture.currentGestureCoords[0].clear();
6097 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6098 mPointerGesture.referenceGestureX);
6099 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6100 mPointerGesture.referenceGestureY);
6101 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6102 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6103 // FREEFORM mode.
6104#if DEBUG_GESTURES
6105 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6106 "activeGestureId=%d, currentTouchPointerCount=%d",
6107 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6108#endif
6109 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6110
6111 mPointerGesture.currentGestureIdBits.clear();
6112
6113 BitSet32 mappedTouchIdBits;
6114 BitSet32 usedGestureIdBits;
6115 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6116 // Initially, assign the active gesture id to the active touch point
6117 // if there is one. No other touch id bits are mapped yet.
6118 if (!*outCancelPreviousGesture) {
6119 mappedTouchIdBits.markBit(activeTouchId);
6120 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6121 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6122 mPointerGesture.activeGestureId;
6123 } else {
6124 mPointerGesture.activeGestureId = -1;
6125 }
6126 } else {
6127 // Otherwise, assume we mapped all touches from the previous frame.
6128 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006129 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6130 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6132
6133 // Check whether we need to choose a new active gesture id because the
6134 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006135 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6136 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006137 !upTouchIdBits.isEmpty(); ) {
6138 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6139 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6140 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6141 mPointerGesture.activeGestureId = -1;
6142 break;
6143 }
6144 }
6145 }
6146
6147#if DEBUG_GESTURES
6148 ALOGD("Gestures: FREEFORM follow up "
6149 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6150 "activeGestureId=%d",
6151 mappedTouchIdBits.value, usedGestureIdBits.value,
6152 mPointerGesture.activeGestureId);
6153#endif
6154
Michael Wright842500e2015-03-13 17:32:02 -07006155 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006156 for (uint32_t i = 0; i < currentFingerCount; i++) {
6157 uint32_t touchId = idBits.clearFirstMarkedBit();
6158 uint32_t gestureId;
6159 if (!mappedTouchIdBits.hasBit(touchId)) {
6160 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6161 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6162#if DEBUG_GESTURES
6163 ALOGD("Gestures: FREEFORM "
6164 "new mapping for touch id %d -> gesture id %d",
6165 touchId, gestureId);
6166#endif
6167 } else {
6168 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6169#if DEBUG_GESTURES
6170 ALOGD("Gestures: FREEFORM "
6171 "existing mapping for touch id %d -> gesture id %d",
6172 touchId, gestureId);
6173#endif
6174 }
6175 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6176 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6177
6178 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006179 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6181 * mPointerXZoomScale;
6182 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6183 * mPointerYZoomScale;
6184 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6185
6186 mPointerGesture.currentGestureProperties[i].clear();
6187 mPointerGesture.currentGestureProperties[i].id = gestureId;
6188 mPointerGesture.currentGestureProperties[i].toolType =
6189 AMOTION_EVENT_TOOL_TYPE_FINGER;
6190 mPointerGesture.currentGestureCoords[i].clear();
6191 mPointerGesture.currentGestureCoords[i].setAxisValue(
6192 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6193 mPointerGesture.currentGestureCoords[i].setAxisValue(
6194 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6195 mPointerGesture.currentGestureCoords[i].setAxisValue(
6196 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6197 }
6198
6199 if (mPointerGesture.activeGestureId < 0) {
6200 mPointerGesture.activeGestureId =
6201 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6202#if DEBUG_GESTURES
6203 ALOGD("Gestures: FREEFORM new "
6204 "activeGestureId=%d", mPointerGesture.activeGestureId);
6205#endif
6206 }
6207 }
6208 }
6209
Michael Wright842500e2015-03-13 17:32:02 -07006210 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211
6212#if DEBUG_GESTURES
6213 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6214 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6215 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6216 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6217 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6218 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6219 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6220 uint32_t id = idBits.clearFirstMarkedBit();
6221 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6222 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6223 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6224 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6225 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6226 id, index, properties.toolType,
6227 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6228 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6229 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6230 }
6231 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6232 uint32_t id = idBits.clearFirstMarkedBit();
6233 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6234 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6235 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6236 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6237 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6238 id, index, properties.toolType,
6239 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6240 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6241 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6242 }
6243#endif
6244 return true;
6245}
6246
6247void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6248 mPointerSimple.currentCoords.clear();
6249 mPointerSimple.currentProperties.clear();
6250
6251 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006252 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6253 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6254 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6255 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6256 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006257 mPointerController->setPosition(x, y);
6258
Michael Wright842500e2015-03-13 17:32:02 -07006259 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260 down = !hovering;
6261
6262 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006263 mPointerSimple.currentCoords.copyFrom(
6264 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006265 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6266 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6267 mPointerSimple.currentProperties.id = 0;
6268 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006269 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270 } else {
6271 down = false;
6272 hovering = false;
6273 }
6274
6275 dispatchPointerSimple(when, policyFlags, down, hovering);
6276}
6277
6278void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6279 abortPointerSimple(when, policyFlags);
6280}
6281
6282void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6283 mPointerSimple.currentCoords.clear();
6284 mPointerSimple.currentProperties.clear();
6285
6286 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006287 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6288 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6289 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006290 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006291 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6292 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006293 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006294 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006296 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006297 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298 * mPointerYMovementScale;
6299
6300 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6301 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6302
6303 mPointerController->move(deltaX, deltaY);
6304 } else {
6305 mPointerVelocityControl.reset();
6306 }
6307
Michael Wright842500e2015-03-13 17:32:02 -07006308 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 hovering = !down;
6310
6311 float x, y;
6312 mPointerController->getPosition(&x, &y);
6313 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006314 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006315 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6316 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6317 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6318 hovering ? 0.0f : 1.0f);
6319 mPointerSimple.currentProperties.id = 0;
6320 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006321 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006322 } else {
6323 mPointerVelocityControl.reset();
6324
6325 down = false;
6326 hovering = false;
6327 }
6328
6329 dispatchPointerSimple(when, policyFlags, down, hovering);
6330}
6331
6332void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6333 abortPointerSimple(when, policyFlags);
6334
6335 mPointerVelocityControl.reset();
6336}
6337
6338void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6339 bool down, bool hovering) {
6340 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006341 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342
Yi Kong9b14ac62018-07-17 13:48:38 -07006343 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006344 if (down || hovering) {
6345 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6346 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006347 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006348 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6349 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6350 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6351 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006352 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353 }
6354
6355 if (mPointerSimple.down && !down) {
6356 mPointerSimple.down = false;
6357
6358 // Send up.
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006359 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006360 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006361 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState,
6362 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Dan Harmsaca28402018-12-17 13:55:20 -08006363 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6364 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006365 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366 getListener()->notifyMotion(&args);
6367 }
6368
6369 if (mPointerSimple.hovering && !hovering) {
6370 mPointerSimple.hovering = false;
6371
6372 // Send hover exit.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006373 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6374 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006375 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState,
6376 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006377 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6378 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006379 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380 getListener()->notifyMotion(&args);
6381 }
6382
6383 if (down) {
6384 if (!mPointerSimple.down) {
6385 mPointerSimple.down = true;
6386 mPointerSimple.downTime = when;
6387
6388 // Send down.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006389 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6390 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006391 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState,
6392 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006393 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006394 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6395 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006396 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006397 getListener()->notifyMotion(&args);
6398 }
6399
6400 // Send move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006401 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6402 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006403 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState,
6404 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006405 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6406 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006407 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006408 getListener()->notifyMotion(&args);
6409 }
6410
6411 if (hovering) {
6412 if (!mPointerSimple.hovering) {
6413 mPointerSimple.hovering = true;
6414
6415 // Send hover enter.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006416 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6417 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006418 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006419 mCurrentRawState.buttonState, MotionClassification::NONE,
6420 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006421 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6422 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006423 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006424 getListener()->notifyMotion(&args);
6425 }
6426
6427 // Send hover move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006428 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6429 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006430 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006431 mCurrentRawState.buttonState, MotionClassification::NONE,
6432 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006433 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6434 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006435 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006436 getListener()->notifyMotion(&args);
6437 }
6438
Michael Wright842500e2015-03-13 17:32:02 -07006439 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6440 float vscroll = mCurrentRawState.rawVScroll;
6441 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006442 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6443 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006444
6445 // Send scroll.
6446 PointerCoords pointerCoords;
6447 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6448 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6449 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6450
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006451 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6452 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006453 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState,
6454 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006455 1, &mPointerSimple.currentProperties, &pointerCoords,
6456 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006457 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006458 getListener()->notifyMotion(&args);
6459 }
6460
6461 // Save state.
6462 if (down || hovering) {
6463 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6464 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6465 } else {
6466 mPointerSimple.reset();
6467 }
6468}
6469
6470void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6471 mPointerSimple.currentCoords.clear();
6472 mPointerSimple.currentProperties.clear();
6473
6474 dispatchPointerSimple(when, policyFlags, false, false);
6475}
6476
6477void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006478 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006479 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006480 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006481 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6482 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006483 PointerCoords pointerCoords[MAX_POINTERS];
6484 PointerProperties pointerProperties[MAX_POINTERS];
6485 uint32_t pointerCount = 0;
6486 while (!idBits.isEmpty()) {
6487 uint32_t id = idBits.clearFirstMarkedBit();
6488 uint32_t index = idToIndex[id];
6489 pointerProperties[pointerCount].copyFrom(properties[index]);
6490 pointerCoords[pointerCount].copyFrom(coords[index]);
6491
6492 if (changedId >= 0 && id == uint32_t(changedId)) {
6493 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6494 }
6495
6496 pointerCount += 1;
6497 }
6498
6499 ALOG_ASSERT(pointerCount != 0);
6500
6501 if (changedId >= 0 && pointerCount == 1) {
6502 // Replace initial down and final up action.
6503 // We can compare the action without masking off the changed pointer index
6504 // because we know the index is 0.
6505 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6506 action = AMOTION_EVENT_ACTION_DOWN;
6507 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6508 action = AMOTION_EVENT_ACTION_UP;
6509 } else {
6510 // Can't happen.
6511 ALOG_ASSERT(false);
6512 }
6513 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006514 const int32_t displayId = mPointerController != nullptr ?
6515 mPointerController->getDisplayId() : mViewport.displayId;
Dan Harmsaca28402018-12-17 13:55:20 -08006516
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006517 const int32_t deviceId = getDeviceId();
6518 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
6519 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006520 source, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006521 action, actionButton, flags, metaState, buttonState, MotionClassification::NONE,
6522 edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006523 xPrecision, yPrecision, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006524 getListener()->notifyMotion(&args);
6525}
6526
6527bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6528 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6529 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6530 BitSet32 idBits) const {
6531 bool changed = false;
6532 while (!idBits.isEmpty()) {
6533 uint32_t id = idBits.clearFirstMarkedBit();
6534 uint32_t inIndex = inIdToIndex[id];
6535 uint32_t outIndex = outIdToIndex[id];
6536
6537 const PointerProperties& curInProperties = inProperties[inIndex];
6538 const PointerCoords& curInCoords = inCoords[inIndex];
6539 PointerProperties& curOutProperties = outProperties[outIndex];
6540 PointerCoords& curOutCoords = outCoords[outIndex];
6541
6542 if (curInProperties != curOutProperties) {
6543 curOutProperties.copyFrom(curInProperties);
6544 changed = true;
6545 }
6546
6547 if (curInCoords != curOutCoords) {
6548 curOutCoords.copyFrom(curInCoords);
6549 changed = true;
6550 }
6551 }
6552 return changed;
6553}
6554
6555void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006556 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6558 }
6559}
6560
Jeff Brownc9aa6282015-02-11 19:03:28 -08006561void TouchInputMapper::cancelTouch(nsecs_t when) {
6562 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006563 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006564}
6565
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006567 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006568 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006570 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6571 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6572 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573}
6574
6575const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6576 int32_t x, int32_t y) {
6577 size_t numVirtualKeys = mVirtualKeys.size();
6578 for (size_t i = 0; i < numVirtualKeys; i++) {
6579 const VirtualKey& virtualKey = mVirtualKeys[i];
6580
6581#if DEBUG_VIRTUAL_KEYS
6582 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6583 "left=%d, top=%d, right=%d, bottom=%d",
6584 x, y,
6585 virtualKey.keyCode, virtualKey.scanCode,
6586 virtualKey.hitLeft, virtualKey.hitTop,
6587 virtualKey.hitRight, virtualKey.hitBottom);
6588#endif
6589
6590 if (virtualKey.isHit(x, y)) {
6591 return & virtualKey;
6592 }
6593 }
6594
Yi Kong9b14ac62018-07-17 13:48:38 -07006595 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006596}
6597
Michael Wright842500e2015-03-13 17:32:02 -07006598void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6599 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6600 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006601
Michael Wright842500e2015-03-13 17:32:02 -07006602 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603
6604 if (currentPointerCount == 0) {
6605 // No pointers to assign.
6606 return;
6607 }
6608
6609 if (lastPointerCount == 0) {
6610 // All pointers are new.
6611 for (uint32_t i = 0; i < currentPointerCount; i++) {
6612 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006613 current->rawPointerData.pointers[i].id = id;
6614 current->rawPointerData.idToIndex[id] = i;
6615 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006616 }
6617 return;
6618 }
6619
6620 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006621 && current->rawPointerData.pointers[0].toolType
6622 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006623 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006624 uint32_t id = last->rawPointerData.pointers[0].id;
6625 current->rawPointerData.pointers[0].id = id;
6626 current->rawPointerData.idToIndex[id] = 0;
6627 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006628 return;
6629 }
6630
6631 // General case.
6632 // We build a heap of squared euclidean distances between current and last pointers
6633 // associated with the current and last pointer indices. Then, we find the best
6634 // match (by distance) for each current pointer.
6635 // The pointers must have the same tool type but it is possible for them to
6636 // transition from hovering to touching or vice-versa while retaining the same id.
6637 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6638
6639 uint32_t heapSize = 0;
6640 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6641 currentPointerIndex++) {
6642 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6643 lastPointerIndex++) {
6644 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006645 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006646 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006647 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006648 if (currentPointer.toolType == lastPointer.toolType) {
6649 int64_t deltaX = currentPointer.x - lastPointer.x;
6650 int64_t deltaY = currentPointer.y - lastPointer.y;
6651
6652 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6653
6654 // Insert new element into the heap (sift up).
6655 heap[heapSize].currentPointerIndex = currentPointerIndex;
6656 heap[heapSize].lastPointerIndex = lastPointerIndex;
6657 heap[heapSize].distance = distance;
6658 heapSize += 1;
6659 }
6660 }
6661 }
6662
6663 // Heapify
6664 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6665 startIndex -= 1;
6666 for (uint32_t parentIndex = startIndex; ;) {
6667 uint32_t childIndex = parentIndex * 2 + 1;
6668 if (childIndex >= heapSize) {
6669 break;
6670 }
6671
6672 if (childIndex + 1 < heapSize
6673 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6674 childIndex += 1;
6675 }
6676
6677 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6678 break;
6679 }
6680
6681 swap(heap[parentIndex], heap[childIndex]);
6682 parentIndex = childIndex;
6683 }
6684 }
6685
6686#if DEBUG_POINTER_ASSIGNMENT
6687 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6688 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006689 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006690 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6691 heap[i].distance);
6692 }
6693#endif
6694
6695 // Pull matches out by increasing order of distance.
6696 // To avoid reassigning pointers that have already been matched, the loop keeps track
6697 // of which last and current pointers have been matched using the matchedXXXBits variables.
6698 // It also tracks the used pointer id bits.
6699 BitSet32 matchedLastBits(0);
6700 BitSet32 matchedCurrentBits(0);
6701 BitSet32 usedIdBits(0);
6702 bool first = true;
6703 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6704 while (heapSize > 0) {
6705 if (first) {
6706 // The first time through the loop, we just consume the root element of
6707 // the heap (the one with smallest distance).
6708 first = false;
6709 } else {
6710 // Previous iterations consumed the root element of the heap.
6711 // Pop root element off of the heap (sift down).
6712 heap[0] = heap[heapSize];
6713 for (uint32_t parentIndex = 0; ;) {
6714 uint32_t childIndex = parentIndex * 2 + 1;
6715 if (childIndex >= heapSize) {
6716 break;
6717 }
6718
6719 if (childIndex + 1 < heapSize
6720 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6721 childIndex += 1;
6722 }
6723
6724 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6725 break;
6726 }
6727
6728 swap(heap[parentIndex], heap[childIndex]);
6729 parentIndex = childIndex;
6730 }
6731
6732#if DEBUG_POINTER_ASSIGNMENT
6733 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6734 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006735 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006736 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6737 heap[i].distance);
6738 }
6739#endif
6740 }
6741
6742 heapSize -= 1;
6743
6744 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6745 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6746
6747 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6748 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6749
6750 matchedCurrentBits.markBit(currentPointerIndex);
6751 matchedLastBits.markBit(lastPointerIndex);
6752
Michael Wright842500e2015-03-13 17:32:02 -07006753 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6754 current->rawPointerData.pointers[currentPointerIndex].id = id;
6755 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6756 current->rawPointerData.markIdBit(id,
6757 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006758 usedIdBits.markBit(id);
6759
6760#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006761 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6762 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006763 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6764#endif
6765 break;
6766 }
6767 }
6768
6769 // Assign fresh ids to pointers that were not matched in the process.
6770 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6771 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6772 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6773
Michael Wright842500e2015-03-13 17:32:02 -07006774 current->rawPointerData.pointers[currentPointerIndex].id = id;
6775 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6776 current->rawPointerData.markIdBit(id,
6777 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006778
6779#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006780 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006781#endif
6782 }
6783}
6784
6785int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6786 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6787 return AKEY_STATE_VIRTUAL;
6788 }
6789
6790 size_t numVirtualKeys = mVirtualKeys.size();
6791 for (size_t i = 0; i < numVirtualKeys; i++) {
6792 const VirtualKey& virtualKey = mVirtualKeys[i];
6793 if (virtualKey.keyCode == keyCode) {
6794 return AKEY_STATE_UP;
6795 }
6796 }
6797
6798 return AKEY_STATE_UNKNOWN;
6799}
6800
6801int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6802 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6803 return AKEY_STATE_VIRTUAL;
6804 }
6805
6806 size_t numVirtualKeys = mVirtualKeys.size();
6807 for (size_t i = 0; i < numVirtualKeys; i++) {
6808 const VirtualKey& virtualKey = mVirtualKeys[i];
6809 if (virtualKey.scanCode == scanCode) {
6810 return AKEY_STATE_UP;
6811 }
6812 }
6813
6814 return AKEY_STATE_UNKNOWN;
6815}
6816
6817bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6818 const int32_t* keyCodes, uint8_t* outFlags) {
6819 size_t numVirtualKeys = mVirtualKeys.size();
6820 for (size_t i = 0; i < numVirtualKeys; i++) {
6821 const VirtualKey& virtualKey = mVirtualKeys[i];
6822
6823 for (size_t i = 0; i < numCodes; i++) {
6824 if (virtualKey.keyCode == keyCodes[i]) {
6825 outFlags[i] = 1;
6826 }
6827 }
6828 }
6829
6830 return true;
6831}
6832
6833
6834// --- SingleTouchInputMapper ---
6835
6836SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6837 TouchInputMapper(device) {
6838}
6839
6840SingleTouchInputMapper::~SingleTouchInputMapper() {
6841}
6842
6843void SingleTouchInputMapper::reset(nsecs_t when) {
6844 mSingleTouchMotionAccumulator.reset(getDevice());
6845
6846 TouchInputMapper::reset(when);
6847}
6848
6849void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6850 TouchInputMapper::process(rawEvent);
6851
6852 mSingleTouchMotionAccumulator.process(rawEvent);
6853}
6854
Michael Wright842500e2015-03-13 17:32:02 -07006855void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006856 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006857 outState->rawPointerData.pointerCount = 1;
6858 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006859
6860 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6861 && (mTouchButtonAccumulator.isHovering()
6862 || (mRawPointerAxes.pressure.valid
6863 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006864 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006865
Michael Wright842500e2015-03-13 17:32:02 -07006866 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006867 outPointer.id = 0;
6868 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6869 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6870 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6871 outPointer.touchMajor = 0;
6872 outPointer.touchMinor = 0;
6873 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6874 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6875 outPointer.orientation = 0;
6876 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6877 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6878 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6879 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6880 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6881 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6882 }
6883 outPointer.isHovering = isHovering;
6884 }
6885}
6886
6887void SingleTouchInputMapper::configureRawPointerAxes() {
6888 TouchInputMapper::configureRawPointerAxes();
6889
6890 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6891 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6892 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6893 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6894 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6895 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6896 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6897}
6898
6899bool SingleTouchInputMapper::hasStylus() const {
6900 return mTouchButtonAccumulator.hasStylus();
6901}
6902
6903
6904// --- MultiTouchInputMapper ---
6905
6906MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6907 TouchInputMapper(device) {
6908}
6909
6910MultiTouchInputMapper::~MultiTouchInputMapper() {
6911}
6912
6913void MultiTouchInputMapper::reset(nsecs_t when) {
6914 mMultiTouchMotionAccumulator.reset(getDevice());
6915
6916 mPointerIdBits.clear();
6917
6918 TouchInputMapper::reset(when);
6919}
6920
6921void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6922 TouchInputMapper::process(rawEvent);
6923
6924 mMultiTouchMotionAccumulator.process(rawEvent);
6925}
6926
Michael Wright842500e2015-03-13 17:32:02 -07006927void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006928 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6929 size_t outCount = 0;
6930 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006931 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006932
6933 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6934 const MultiTouchMotionAccumulator::Slot* inSlot =
6935 mMultiTouchMotionAccumulator.getSlot(inIndex);
6936 if (!inSlot->isInUse()) {
6937 continue;
6938 }
6939
6940 if (outCount >= MAX_POINTERS) {
6941#if DEBUG_POINTERS
6942 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6943 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006944 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006945#endif
6946 break; // too many fingers!
6947 }
6948
Michael Wright842500e2015-03-13 17:32:02 -07006949 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006950 outPointer.x = inSlot->getX();
6951 outPointer.y = inSlot->getY();
6952 outPointer.pressure = inSlot->getPressure();
6953 outPointer.touchMajor = inSlot->getTouchMajor();
6954 outPointer.touchMinor = inSlot->getTouchMinor();
6955 outPointer.toolMajor = inSlot->getToolMajor();
6956 outPointer.toolMinor = inSlot->getToolMinor();
6957 outPointer.orientation = inSlot->getOrientation();
6958 outPointer.distance = inSlot->getDistance();
6959 outPointer.tiltX = 0;
6960 outPointer.tiltY = 0;
6961
6962 outPointer.toolType = inSlot->getToolType();
6963 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6964 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6965 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6966 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6967 }
6968 }
6969
6970 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6971 && (mTouchButtonAccumulator.isHovering()
6972 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6973 outPointer.isHovering = isHovering;
6974
6975 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006976 if (mHavePointerIds) {
6977 int32_t trackingId = inSlot->getTrackingId();
6978 int32_t id = -1;
6979 if (trackingId >= 0) {
6980 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6981 uint32_t n = idBits.clearFirstMarkedBit();
6982 if (mPointerTrackingIdMap[n] == trackingId) {
6983 id = n;
6984 }
6985 }
6986
6987 if (id < 0 && !mPointerIdBits.isFull()) {
6988 id = mPointerIdBits.markFirstUnmarkedBit();
6989 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006990 }
Michael Wright842500e2015-03-13 17:32:02 -07006991 }
gaoshang1a632de2016-08-24 10:23:50 +08006992 if (id < 0) {
6993 mHavePointerIds = false;
6994 outState->rawPointerData.clearIdBits();
6995 newPointerIdBits.clear();
6996 } else {
6997 outPointer.id = id;
6998 outState->rawPointerData.idToIndex[id] = outCount;
6999 outState->rawPointerData.markIdBit(id, isHovering);
7000 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007001 }
Michael Wright842500e2015-03-13 17:32:02 -07007002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007003 outCount += 1;
7004 }
7005
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007006 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07007007 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007008 mPointerIdBits = newPointerIdBits;
7009
7010 mMultiTouchMotionAccumulator.finishSync();
7011}
7012
7013void MultiTouchInputMapper::configureRawPointerAxes() {
7014 TouchInputMapper::configureRawPointerAxes();
7015
7016 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7017 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7018 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7019 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7020 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7021 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7022 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7023 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7024 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7025 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7026 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7027
7028 if (mRawPointerAxes.trackingId.valid
7029 && mRawPointerAxes.slot.valid
7030 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7031 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7032 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007033 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7034 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007035 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007036 slotCount = MAX_SLOTS;
7037 }
7038 mMultiTouchMotionAccumulator.configure(getDevice(),
7039 slotCount, true /*usingSlotsProtocol*/);
7040 } else {
7041 mMultiTouchMotionAccumulator.configure(getDevice(),
7042 MAX_POINTERS, false /*usingSlotsProtocol*/);
7043 }
7044}
7045
7046bool MultiTouchInputMapper::hasStylus() const {
7047 return mMultiTouchMotionAccumulator.hasStylus()
7048 || mTouchButtonAccumulator.hasStylus();
7049}
7050
Michael Wright842500e2015-03-13 17:32:02 -07007051// --- ExternalStylusInputMapper
7052
7053ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7054 InputMapper(device) {
7055
7056}
7057
7058uint32_t ExternalStylusInputMapper::getSources() {
7059 return AINPUT_SOURCE_STYLUS;
7060}
7061
7062void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7063 InputMapper::populateDeviceInfo(info);
7064 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7065 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7066}
7067
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007068void ExternalStylusInputMapper::dump(std::string& dump) {
7069 dump += INDENT2 "External Stylus Input Mapper:\n";
7070 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007071 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007072 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007073 dumpStylusState(dump, mStylusState);
7074}
7075
7076void ExternalStylusInputMapper::configure(nsecs_t when,
7077 const InputReaderConfiguration* config, uint32_t changes) {
7078 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7079 mTouchButtonAccumulator.configure(getDevice());
7080}
7081
7082void ExternalStylusInputMapper::reset(nsecs_t when) {
7083 InputDevice* device = getDevice();
7084 mSingleTouchMotionAccumulator.reset(device);
7085 mTouchButtonAccumulator.reset(device);
7086 InputMapper::reset(when);
7087}
7088
7089void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7090 mSingleTouchMotionAccumulator.process(rawEvent);
7091 mTouchButtonAccumulator.process(rawEvent);
7092
7093 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7094 sync(rawEvent->when);
7095 }
7096}
7097
7098void ExternalStylusInputMapper::sync(nsecs_t when) {
7099 mStylusState.clear();
7100
7101 mStylusState.when = when;
7102
Michael Wright45ccacf2015-04-21 19:01:58 +01007103 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7104 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7105 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7106 }
7107
Michael Wright842500e2015-03-13 17:32:02 -07007108 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7109 if (mRawPressureAxis.valid) {
7110 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7111 } else if (mTouchButtonAccumulator.isToolActive()) {
7112 mStylusState.pressure = 1.0f;
7113 } else {
7114 mStylusState.pressure = 0.0f;
7115 }
7116
7117 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007118
7119 mContext->dispatchExternalStylusState(mStylusState);
7120}
7121
Michael Wrightd02c5b62014-02-10 15:10:22 -08007122
7123// --- JoystickInputMapper ---
7124
7125JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7126 InputMapper(device) {
7127}
7128
7129JoystickInputMapper::~JoystickInputMapper() {
7130}
7131
7132uint32_t JoystickInputMapper::getSources() {
7133 return AINPUT_SOURCE_JOYSTICK;
7134}
7135
7136void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7137 InputMapper::populateDeviceInfo(info);
7138
7139 for (size_t i = 0; i < mAxes.size(); i++) {
7140 const Axis& axis = mAxes.valueAt(i);
7141 addMotionRange(axis.axisInfo.axis, axis, info);
7142
7143 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7144 addMotionRange(axis.axisInfo.highAxis, axis, info);
7145
7146 }
7147 }
7148}
7149
7150void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7151 InputDeviceInfo* info) {
7152 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7153 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7154 /* In order to ease the transition for developers from using the old axes
7155 * to the newer, more semantically correct axes, we'll continue to register
7156 * the old axes as duplicates of their corresponding new ones. */
7157 int32_t compatAxis = getCompatAxis(axisId);
7158 if (compatAxis >= 0) {
7159 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7160 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7161 }
7162}
7163
7164/* A mapping from axes the joystick actually has to the axes that should be
7165 * artificially created for compatibility purposes.
7166 * Returns -1 if no compatibility axis is needed. */
7167int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7168 switch(axis) {
7169 case AMOTION_EVENT_AXIS_LTRIGGER:
7170 return AMOTION_EVENT_AXIS_BRAKE;
7171 case AMOTION_EVENT_AXIS_RTRIGGER:
7172 return AMOTION_EVENT_AXIS_GAS;
7173 }
7174 return -1;
7175}
7176
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007177void JoystickInputMapper::dump(std::string& dump) {
7178 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007179
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007180 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007181 size_t numAxes = mAxes.size();
7182 for (size_t i = 0; i < numAxes; i++) {
7183 const Axis& axis = mAxes.valueAt(i);
7184 const char* label = getAxisLabel(axis.axisInfo.axis);
7185 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007186 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007187 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007188 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007189 }
7190 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7191 label = getAxisLabel(axis.axisInfo.highAxis);
7192 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007193 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007194 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007195 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007196 axis.axisInfo.splitValue);
7197 }
7198 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007199 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007200 }
7201
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007202 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 -08007203 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007204 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007205 "highScale=%0.5f, highOffset=%0.5f\n",
7206 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007207 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007208 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7209 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7210 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7211 }
7212}
7213
7214void JoystickInputMapper::configure(nsecs_t when,
7215 const InputReaderConfiguration* config, uint32_t changes) {
7216 InputMapper::configure(when, config, changes);
7217
7218 if (!changes) { // first time only
7219 // Collect all axes.
7220 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7221 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7222 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7223 continue; // axis must be claimed by a different device
7224 }
7225
7226 RawAbsoluteAxisInfo rawAxisInfo;
7227 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7228 if (rawAxisInfo.valid) {
7229 // Map axis.
7230 AxisInfo axisInfo;
7231 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7232 if (!explicitlyMapped) {
7233 // Axis is not explicitly mapped, will choose a generic axis later.
7234 axisInfo.mode = AxisInfo::MODE_NORMAL;
7235 axisInfo.axis = -1;
7236 }
7237
7238 // Apply flat override.
7239 int32_t rawFlat = axisInfo.flatOverride < 0
7240 ? rawAxisInfo.flat : axisInfo.flatOverride;
7241
7242 // Calculate scaling factors and limits.
7243 Axis axis;
7244 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7245 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7246 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7247 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7248 scale, 0.0f, highScale, 0.0f,
7249 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7250 rawAxisInfo.resolution * scale);
7251 } else if (isCenteredAxis(axisInfo.axis)) {
7252 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7253 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7254 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7255 scale, offset, scale, offset,
7256 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7257 rawAxisInfo.resolution * scale);
7258 } else {
7259 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7260 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7261 scale, 0.0f, scale, 0.0f,
7262 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7263 rawAxisInfo.resolution * scale);
7264 }
7265
7266 // To eliminate noise while the joystick is at rest, filter out small variations
7267 // in axis values up front.
7268 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7269
7270 mAxes.add(abs, axis);
7271 }
7272 }
7273
7274 // If there are too many axes, start dropping them.
7275 // Prefer to keep explicitly mapped axes.
7276 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007277 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007278 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007279 pruneAxes(true);
7280 pruneAxes(false);
7281 }
7282
7283 // Assign generic axis ids to remaining axes.
7284 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7285 size_t numAxes = mAxes.size();
7286 for (size_t i = 0; i < numAxes; i++) {
7287 Axis& axis = mAxes.editValueAt(i);
7288 if (axis.axisInfo.axis < 0) {
7289 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7290 && haveAxis(nextGenericAxisId)) {
7291 nextGenericAxisId += 1;
7292 }
7293
7294 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7295 axis.axisInfo.axis = nextGenericAxisId;
7296 nextGenericAxisId += 1;
7297 } else {
7298 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7299 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007300 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007301 mAxes.removeItemsAt(i--);
7302 numAxes -= 1;
7303 }
7304 }
7305 }
7306 }
7307}
7308
7309bool JoystickInputMapper::haveAxis(int32_t axisId) {
7310 size_t numAxes = mAxes.size();
7311 for (size_t i = 0; i < numAxes; i++) {
7312 const Axis& axis = mAxes.valueAt(i);
7313 if (axis.axisInfo.axis == axisId
7314 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7315 && axis.axisInfo.highAxis == axisId)) {
7316 return true;
7317 }
7318 }
7319 return false;
7320}
7321
7322void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7323 size_t i = mAxes.size();
7324 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7325 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7326 continue;
7327 }
7328 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007329 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007330 mAxes.removeItemsAt(i);
7331 }
7332}
7333
7334bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7335 switch (axis) {
7336 case AMOTION_EVENT_AXIS_X:
7337 case AMOTION_EVENT_AXIS_Y:
7338 case AMOTION_EVENT_AXIS_Z:
7339 case AMOTION_EVENT_AXIS_RX:
7340 case AMOTION_EVENT_AXIS_RY:
7341 case AMOTION_EVENT_AXIS_RZ:
7342 case AMOTION_EVENT_AXIS_HAT_X:
7343 case AMOTION_EVENT_AXIS_HAT_Y:
7344 case AMOTION_EVENT_AXIS_ORIENTATION:
7345 case AMOTION_EVENT_AXIS_RUDDER:
7346 case AMOTION_EVENT_AXIS_WHEEL:
7347 return true;
7348 default:
7349 return false;
7350 }
7351}
7352
7353void JoystickInputMapper::reset(nsecs_t when) {
7354 // Recenter all axes.
7355 size_t numAxes = mAxes.size();
7356 for (size_t i = 0; i < numAxes; i++) {
7357 Axis& axis = mAxes.editValueAt(i);
7358 axis.resetValue();
7359 }
7360
7361 InputMapper::reset(when);
7362}
7363
7364void JoystickInputMapper::process(const RawEvent* rawEvent) {
7365 switch (rawEvent->type) {
7366 case EV_ABS: {
7367 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7368 if (index >= 0) {
7369 Axis& axis = mAxes.editValueAt(index);
7370 float newValue, highNewValue;
7371 switch (axis.axisInfo.mode) {
7372 case AxisInfo::MODE_INVERT:
7373 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7374 * axis.scale + axis.offset;
7375 highNewValue = 0.0f;
7376 break;
7377 case AxisInfo::MODE_SPLIT:
7378 if (rawEvent->value < axis.axisInfo.splitValue) {
7379 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7380 * axis.scale + axis.offset;
7381 highNewValue = 0.0f;
7382 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7383 newValue = 0.0f;
7384 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7385 * axis.highScale + axis.highOffset;
7386 } else {
7387 newValue = 0.0f;
7388 highNewValue = 0.0f;
7389 }
7390 break;
7391 default:
7392 newValue = rawEvent->value * axis.scale + axis.offset;
7393 highNewValue = 0.0f;
7394 break;
7395 }
7396 axis.newValue = newValue;
7397 axis.highNewValue = highNewValue;
7398 }
7399 break;
7400 }
7401
7402 case EV_SYN:
7403 switch (rawEvent->code) {
7404 case SYN_REPORT:
7405 sync(rawEvent->when, false /*force*/);
7406 break;
7407 }
7408 break;
7409 }
7410}
7411
7412void JoystickInputMapper::sync(nsecs_t when, bool force) {
7413 if (!filterAxes(force)) {
7414 return;
7415 }
7416
7417 int32_t metaState = mContext->getGlobalMetaState();
7418 int32_t buttonState = 0;
7419
7420 PointerProperties pointerProperties;
7421 pointerProperties.clear();
7422 pointerProperties.id = 0;
7423 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7424
7425 PointerCoords pointerCoords;
7426 pointerCoords.clear();
7427
7428 size_t numAxes = mAxes.size();
7429 for (size_t i = 0; i < numAxes; i++) {
7430 const Axis& axis = mAxes.valueAt(i);
7431 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7432 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7433 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7434 axis.highCurrentValue);
7435 }
7436 }
7437
7438 // Moving a joystick axis should not wake the device because joysticks can
7439 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7440 // button will likely wake the device.
7441 // TODO: Use the input device configuration to control this behavior more finely.
7442 uint32_t policyFlags = 0;
7443
Prabir Pradhan42611e02018-11-27 14:04:02 -08007444 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7445 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08007446 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, MotionClassification::NONE,
7447 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
7448 &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007449 getListener()->notifyMotion(&args);
7450}
7451
7452void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7453 int32_t axis, float value) {
7454 pointerCoords->setAxisValue(axis, value);
7455 /* In order to ease the transition for developers from using the old axes
7456 * to the newer, more semantically correct axes, we'll continue to produce
7457 * values for the old axes as mirrors of the value of their corresponding
7458 * new axes. */
7459 int32_t compatAxis = getCompatAxis(axis);
7460 if (compatAxis >= 0) {
7461 pointerCoords->setAxisValue(compatAxis, value);
7462 }
7463}
7464
7465bool JoystickInputMapper::filterAxes(bool force) {
7466 bool atLeastOneSignificantChange = force;
7467 size_t numAxes = mAxes.size();
7468 for (size_t i = 0; i < numAxes; i++) {
7469 Axis& axis = mAxes.editValueAt(i);
7470 if (force || hasValueChangedSignificantly(axis.filter,
7471 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7472 axis.currentValue = axis.newValue;
7473 atLeastOneSignificantChange = true;
7474 }
7475 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7476 if (force || hasValueChangedSignificantly(axis.filter,
7477 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7478 axis.highCurrentValue = axis.highNewValue;
7479 atLeastOneSignificantChange = true;
7480 }
7481 }
7482 }
7483 return atLeastOneSignificantChange;
7484}
7485
7486bool JoystickInputMapper::hasValueChangedSignificantly(
7487 float filter, float newValue, float currentValue, float min, float max) {
7488 if (newValue != currentValue) {
7489 // Filter out small changes in value unless the value is converging on the axis
7490 // bounds or center point. This is intended to reduce the amount of information
7491 // sent to applications by particularly noisy joysticks (such as PS3).
7492 if (fabs(newValue - currentValue) > filter
7493 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7494 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7495 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7496 return true;
7497 }
7498 }
7499 return false;
7500}
7501
7502bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7503 float filter, float newValue, float currentValue, float thresholdValue) {
7504 float newDistance = fabs(newValue - thresholdValue);
7505 if (newDistance < filter) {
7506 float oldDistance = fabs(currentValue - thresholdValue);
7507 if (newDistance < oldDistance) {
7508 return true;
7509 }
7510 }
7511 return false;
7512}
7513
7514} // namespace android