blob: 33bf163abb0a9ca21115ea16c846a2191d78386f [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
25#define DEBUG_HACKS 0
26
27// Log debug messages about virtual key processing.
28#define DEBUG_VIRTUAL_KEYS 0
29
30// Log debug messages about pointers.
31#define DEBUG_POINTERS 0
32
33// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
36// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
39// Log debug messages about the vibrator.
40#define DEBUG_VIBRATOR 0
41
Michael Wright842500e2015-03-13 17:32:02 -070042// Log debug messages about fusing stylus data.
43#define DEBUG_STYLUS_FUSION 0
44
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include "InputReader.h"
46
Mark Salyzyna5e161b2016-09-29 08:08:05 -070047#include <errno.h>
Michael Wright842500e2015-03-13 17:32:02 -070048#include <inttypes.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070049#include <limits.h>
50#include <math.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <stddef.h>
52#include <stdlib.h>
53#include <unistd.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054
Mark Salyzyn7823e122016-09-29 08:08:05 -070055#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <input/Keyboard.h>
59#include <input/VirtualKeyMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61#define INDENT " "
62#define INDENT2 " "
63#define INDENT3 " "
64#define INDENT4 " "
65#define INDENT5 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// --- Constants ---
72
73// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
74static const size_t MAX_SLOTS = 32;
75
Michael Wright842500e2015-03-13 17:32:02 -070076// Maximum amount of latency to add to touch events while waiting for data from an
77// external stylus.
Michael Wright5e17a5d2015-04-21 22:45:13 +010078static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070079
Michael Wright43fd19f2015-04-21 19:02:58 +010080// Maximum amount of time to wait on touch data before pushing out new pressure data.
81static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
82
83// Artificial latency on synthetic events created from stylus data without corresponding touch
84// data.
85static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087// --- Static Functions ---
88
89template<typename T>
90inline static T abs(const T& value) {
91 return value < 0 ? - value : value;
92}
93
94template<typename T>
95inline static T min(const T& a, const T& b) {
96 return a < b ? a : b;
97}
98
99template<typename T>
100inline static void swap(T& a, T& b) {
101 T temp = a;
102 a = b;
103 b = temp;
104}
105
106inline static float avg(float x, float y) {
107 return (x + y) / 2;
108}
109
110inline static float distance(float x1, float y1, float x2, float y2) {
111 return hypotf(x1 - x2, y1 - y2);
112}
113
114inline static int32_t signExtendNybble(int32_t value) {
115 return value >= 8 ? value - 16 : value;
116}
117
118static inline const char* toString(bool value) {
119 return value ? "true" : "false";
120}
121
122static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
123 const int32_t map[][4], size_t mapSize) {
124 if (orientation != DISPLAY_ORIENTATION_0) {
125 for (size_t i = 0; i < mapSize; i++) {
126 if (value == map[i][0]) {
127 return map[i][orientation];
128 }
129 }
130 }
131 return value;
132}
133
134static const int32_t keyCodeRotationMap[][4] = {
135 // key codes enumerated counter-clockwise with the original (unrotated) key first
136 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
137 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
138 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
139 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
140 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700141 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
142 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
143 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
144 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
145 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
146 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
147 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
148 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149};
150static const size_t keyCodeRotationMapSize =
151 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
152
Ivan Podogovb9afef32017-02-13 15:34:32 +0000153static int32_t rotateStemKey(int32_t value, int32_t orientation,
154 const int32_t map[][2], size_t mapSize) {
155 if (orientation == DISPLAY_ORIENTATION_180) {
156 for (size_t i = 0; i < mapSize; i++) {
157 if (value == map[i][0]) {
158 return map[i][1];
159 }
160 }
161 }
162 return value;
163}
164
165// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
166static int32_t stemKeyRotationMap[][2] = {
167 // key codes enumerated with the original (unrotated) key first
168 // no rotation, 180 degree rotation
169 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
170 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
171 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
172 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
173};
174static const size_t stemKeyRotationMapSize =
175 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
176
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000178 keyCode = rotateStemKey(keyCode, orientation,
179 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return rotateValueUsingRotationMap(keyCode, orientation,
181 keyCodeRotationMap, keyCodeRotationMapSize);
182}
183
184static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
185 float temp;
186 switch (orientation) {
187 case DISPLAY_ORIENTATION_90:
188 temp = *deltaX;
189 *deltaX = *deltaY;
190 *deltaY = -temp;
191 break;
192
193 case DISPLAY_ORIENTATION_180:
194 *deltaX = -*deltaX;
195 *deltaY = -*deltaY;
196 break;
197
198 case DISPLAY_ORIENTATION_270:
199 temp = *deltaX;
200 *deltaX = -*deltaY;
201 *deltaY = temp;
202 break;
203 }
204}
205
206static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
207 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
208}
209
210// Returns true if the pointer should be reported as being down given the specified
211// button states. This determines whether the event is reported as a touch event.
212static bool isPointerDown(int32_t buttonState) {
213 return buttonState &
214 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
215 | AMOTION_EVENT_BUTTON_TERTIARY);
216}
217
218static float calculateCommonVector(float a, float b) {
219 if (a > 0 && b > 0) {
220 return a < b ? a : b;
221 } else if (a < 0 && b < 0) {
222 return a > b ? a : b;
223 } else {
224 return 0;
225 }
226}
227
228static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100229 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
231 int32_t buttonState, int32_t keyCode) {
232 if (
233 (action == AKEY_EVENT_ACTION_DOWN
234 && !(lastButtonState & buttonState)
235 && (currentButtonState & buttonState))
236 || (action == AKEY_EVENT_ACTION_UP
237 && (lastButtonState & buttonState)
238 && !(currentButtonState & buttonState))) {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800239 NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
240 policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 context->getListener()->notifyKey(&args);
242 }
243}
244
245static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100246 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100248 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 lastButtonState, currentButtonState,
250 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100251 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 lastButtonState, currentButtonState,
253 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
254}
255
256
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257// --- InputReader ---
258
259InputReader::InputReader(const sp<EventHubInterface>& eventHub,
260 const sp<InputReaderPolicyInterface>& policy,
261 const sp<InputListenerInterface>& listener) :
262 mContext(this), mEventHub(eventHub), mPolicy(policy),
Prabir Pradhan42611e02018-11-27 14:04:02 -0800263 mNextSequenceNum(1), mGlobalMetaState(0), mGeneration(1),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800264 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
265 mConfigurationChangesToRefresh(0) {
266 mQueuedListener = new QueuedInputListener(listener);
267
268 { // acquire lock
269 AutoMutex _l(mLock);
270
271 refreshConfigurationLocked(0);
272 updateGlobalMetaStateLocked();
273 } // release lock
274}
275
276InputReader::~InputReader() {
277 for (size_t i = 0; i < mDevices.size(); i++) {
278 delete mDevices.valueAt(i);
279 }
280}
281
282void InputReader::loopOnce() {
283 int32_t oldGeneration;
284 int32_t timeoutMillis;
285 bool inputDevicesChanged = false;
286 Vector<InputDeviceInfo> inputDevices;
287 { // acquire lock
288 AutoMutex _l(mLock);
289
290 oldGeneration = mGeneration;
291 timeoutMillis = -1;
292
293 uint32_t changes = mConfigurationChangesToRefresh;
294 if (changes) {
295 mConfigurationChangesToRefresh = 0;
296 timeoutMillis = 0;
297 refreshConfigurationLocked(changes);
298 } else if (mNextTimeout != LLONG_MAX) {
299 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
300 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
301 }
302 } // release lock
303
304 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
305
306 { // acquire lock
307 AutoMutex _l(mLock);
308 mReaderIsAliveCondition.broadcast();
309
310 if (count) {
311 processEventsLocked(mEventBuffer, count);
312 }
313
314 if (mNextTimeout != LLONG_MAX) {
315 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
316 if (now >= mNextTimeout) {
317#if DEBUG_RAW_EVENTS
318 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
319#endif
320 mNextTimeout = LLONG_MAX;
321 timeoutExpiredLocked(now);
322 }
323 }
324
325 if (oldGeneration != mGeneration) {
326 inputDevicesChanged = true;
327 getInputDevicesLocked(inputDevices);
328 }
329 } // release lock
330
331 // Send out a message that the describes the changed input devices.
332 if (inputDevicesChanged) {
333 mPolicy->notifyInputDevicesChanged(inputDevices);
334 }
335
336 // Flush queued events out to the listener.
337 // This must happen outside of the lock because the listener could potentially call
338 // back into the InputReader's methods, such as getScanCodeState, or become blocked
339 // on another thread similarly waiting to acquire the InputReader lock thereby
340 // resulting in a deadlock. This situation is actually quite plausible because the
341 // listener is actually the input dispatcher, which calls into the window manager,
342 // which occasionally calls into the input reader.
343 mQueuedListener->flush();
344}
345
346void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
347 for (const RawEvent* rawEvent = rawEvents; count;) {
348 int32_t type = rawEvent->type;
349 size_t batchSize = 1;
350 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
351 int32_t deviceId = rawEvent->deviceId;
352 while (batchSize < count) {
353 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
354 || rawEvent[batchSize].deviceId != deviceId) {
355 break;
356 }
357 batchSize += 1;
358 }
359#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700360 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800361#endif
362 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
363 } else {
364 switch (rawEvent->type) {
365 case EventHubInterface::DEVICE_ADDED:
366 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
367 break;
368 case EventHubInterface::DEVICE_REMOVED:
369 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
370 break;
371 case EventHubInterface::FINISHED_DEVICE_SCAN:
372 handleConfigurationChangedLocked(rawEvent->when);
373 break;
374 default:
375 ALOG_ASSERT(false); // can't happen
376 break;
377 }
378 }
379 count -= batchSize;
380 rawEvent += batchSize;
381 }
382}
383
384void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
385 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
386 if (deviceIndex >= 0) {
387 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
388 return;
389 }
390
391 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
392 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
393 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
394
395 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
396 device->configure(when, &mConfig, 0);
397 device->reset(when);
398
399 if (device->isIgnored()) {
400 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100401 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800402 } else {
403 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100404 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 }
406
407 mDevices.add(deviceId, device);
408 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700409
410 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
411 notifyExternalStylusPresenceChanged();
412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413}
414
415void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700416 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
418 if (deviceIndex < 0) {
419 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
420 return;
421 }
422
423 device = mDevices.valueAt(deviceIndex);
424 mDevices.removeItemsAt(deviceIndex, 1);
425 bumpGenerationLocked();
426
427 if (device->isIgnored()) {
428 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100429 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 } else {
431 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100432 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433 }
434
Michael Wright842500e2015-03-13 17:32:02 -0700435 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
436 notifyExternalStylusPresenceChanged();
437 }
438
Michael Wrightd02c5b62014-02-10 15:10:22 -0800439 device->reset(when);
440 delete device;
441}
442
443InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
444 const InputDeviceIdentifier& identifier, uint32_t classes) {
445 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
446 controllerNumber, identifier, classes);
447
448 // External devices.
449 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
450 device->setExternal(true);
451 }
452
Tim Kilbourn063ff532015-04-08 10:26:18 -0700453 // Devices with mics.
454 if (classes & INPUT_DEVICE_CLASS_MIC) {
455 device->setMic(true);
456 }
457
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 // Switch-like devices.
459 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
460 device->addMapper(new SwitchInputMapper(device));
461 }
462
Prashant Malani1941ff52015-08-11 18:29:28 -0700463 // Scroll wheel-like devices.
464 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
465 device->addMapper(new RotaryEncoderInputMapper(device));
466 }
467
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 // Vibrator-like devices.
469 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
470 device->addMapper(new VibratorInputMapper(device));
471 }
472
473 // Keyboard-like devices.
474 uint32_t keyboardSource = 0;
475 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
476 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
477 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
478 }
479 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
480 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
481 }
482 if (classes & INPUT_DEVICE_CLASS_DPAD) {
483 keyboardSource |= AINPUT_SOURCE_DPAD;
484 }
485 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
486 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
487 }
488
489 if (keyboardSource != 0) {
490 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
491 }
492
493 // Cursor-like devices.
494 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
495 device->addMapper(new CursorInputMapper(device));
496 }
497
498 // Touchscreens and touchpad devices.
499 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
500 device->addMapper(new MultiTouchInputMapper(device));
501 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
502 device->addMapper(new SingleTouchInputMapper(device));
503 }
504
505 // Joystick-like devices.
506 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
507 device->addMapper(new JoystickInputMapper(device));
508 }
509
Michael Wright842500e2015-03-13 17:32:02 -0700510 // External stylus-like devices.
511 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
512 device->addMapper(new ExternalStylusInputMapper(device));
513 }
514
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 return device;
516}
517
518void InputReader::processEventsForDeviceLocked(int32_t deviceId,
519 const RawEvent* rawEvents, size_t count) {
520 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
521 if (deviceIndex < 0) {
522 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
523 return;
524 }
525
526 InputDevice* device = mDevices.valueAt(deviceIndex);
527 if (device->isIgnored()) {
528 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
529 return;
530 }
531
532 device->process(rawEvents, count);
533}
534
535void InputReader::timeoutExpiredLocked(nsecs_t when) {
536 for (size_t i = 0; i < mDevices.size(); i++) {
537 InputDevice* device = mDevices.valueAt(i);
538 if (!device->isIgnored()) {
539 device->timeoutExpired(when);
540 }
541 }
542}
543
544void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
545 // Reset global meta state because it depends on the list of all configured devices.
546 updateGlobalMetaStateLocked();
547
548 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800549 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 mQueuedListener->notifyConfigurationChanged(&args);
551}
552
553void InputReader::refreshConfigurationLocked(uint32_t changes) {
554 mPolicy->getReaderConfiguration(&mConfig);
555 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
556
557 if (changes) {
558 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
559 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
560
561 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
562 mEventHub->requestReopenDevices();
563 } else {
564 for (size_t i = 0; i < mDevices.size(); i++) {
565 InputDevice* device = mDevices.valueAt(i);
566 device->configure(now, &mConfig, changes);
567 }
568 }
569 }
570}
571
572void InputReader::updateGlobalMetaStateLocked() {
573 mGlobalMetaState = 0;
574
575 for (size_t i = 0; i < mDevices.size(); i++) {
576 InputDevice* device = mDevices.valueAt(i);
577 mGlobalMetaState |= device->getMetaState();
578 }
579}
580
581int32_t InputReader::getGlobalMetaStateLocked() {
582 return mGlobalMetaState;
583}
584
Michael Wright842500e2015-03-13 17:32:02 -0700585void InputReader::notifyExternalStylusPresenceChanged() {
586 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
587}
588
589void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
590 for (size_t i = 0; i < mDevices.size(); i++) {
591 InputDevice* device = mDevices.valueAt(i);
592 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
593 outDevices.push();
594 device->getDeviceInfo(&outDevices.editTop());
595 }
596 }
597}
598
599void InputReader::dispatchExternalStylusState(const StylusState& state) {
600 for (size_t i = 0; i < mDevices.size(); i++) {
601 InputDevice* device = mDevices.valueAt(i);
602 device->updateExternalStylusState(state);
603 }
604}
605
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
607 mDisableVirtualKeysTimeout = time;
608}
609
610bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
611 InputDevice* device, int32_t keyCode, int32_t scanCode) {
612 if (now < mDisableVirtualKeysTimeout) {
613 ALOGI("Dropping virtual key from device %s because virtual keys are "
614 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100615 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 (mDisableVirtualKeysTimeout - now) * 0.000001,
617 keyCode, scanCode);
618 return true;
619 } else {
620 return false;
621 }
622}
623
624void InputReader::fadePointerLocked() {
625 for (size_t i = 0; i < mDevices.size(); i++) {
626 InputDevice* device = mDevices.valueAt(i);
627 device->fadePointer();
628 }
629}
630
631void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
632 if (when < mNextTimeout) {
633 mNextTimeout = when;
634 mEventHub->wake();
635 }
636}
637
638int32_t InputReader::bumpGenerationLocked() {
639 return ++mGeneration;
640}
641
642void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
643 AutoMutex _l(mLock);
644 getInputDevicesLocked(outInputDevices);
645}
646
647void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
648 outInputDevices.clear();
649
650 size_t numDevices = mDevices.size();
651 for (size_t i = 0; i < numDevices; i++) {
652 InputDevice* device = mDevices.valueAt(i);
653 if (!device->isIgnored()) {
654 outInputDevices.push();
655 device->getDeviceInfo(&outInputDevices.editTop());
656 }
657 }
658}
659
660int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
661 int32_t keyCode) {
662 AutoMutex _l(mLock);
663
664 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
665}
666
667int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
668 int32_t scanCode) {
669 AutoMutex _l(mLock);
670
671 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
672}
673
674int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
675 AutoMutex _l(mLock);
676
677 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
678}
679
680int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
681 GetStateFunc getStateFunc) {
682 int32_t result = AKEY_STATE_UNKNOWN;
683 if (deviceId >= 0) {
684 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
685 if (deviceIndex >= 0) {
686 InputDevice* device = mDevices.valueAt(deviceIndex);
687 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
688 result = (device->*getStateFunc)(sourceMask, code);
689 }
690 }
691 } else {
692 size_t numDevices = mDevices.size();
693 for (size_t i = 0; i < numDevices; i++) {
694 InputDevice* device = mDevices.valueAt(i);
695 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
696 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
697 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
698 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
699 if (currentResult >= AKEY_STATE_DOWN) {
700 return currentResult;
701 } else if (currentResult == AKEY_STATE_UP) {
702 result = currentResult;
703 }
704 }
705 }
706 }
707 return result;
708}
709
Andrii Kulian763a3a42016-03-08 10:46:16 -0800710void InputReader::toggleCapsLockState(int32_t deviceId) {
711 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
712 if (deviceIndex < 0) {
713 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
714 return;
715 }
716
717 InputDevice* device = mDevices.valueAt(deviceIndex);
718 if (device->isIgnored()) {
719 return;
720 }
721
722 device->updateMetaState(AKEYCODE_CAPS_LOCK);
723}
724
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
726 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
727 AutoMutex _l(mLock);
728
729 memset(outFlags, 0, numCodes);
730 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
731}
732
733bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
734 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
735 bool result = false;
736 if (deviceId >= 0) {
737 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
738 if (deviceIndex >= 0) {
739 InputDevice* device = mDevices.valueAt(deviceIndex);
740 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
741 result = device->markSupportedKeyCodes(sourceMask,
742 numCodes, keyCodes, outFlags);
743 }
744 }
745 } else {
746 size_t numDevices = mDevices.size();
747 for (size_t i = 0; i < numDevices; i++) {
748 InputDevice* device = mDevices.valueAt(i);
749 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
750 result |= device->markSupportedKeyCodes(sourceMask,
751 numCodes, keyCodes, outFlags);
752 }
753 }
754 }
755 return result;
756}
757
758void InputReader::requestRefreshConfiguration(uint32_t changes) {
759 AutoMutex _l(mLock);
760
761 if (changes) {
762 bool needWake = !mConfigurationChangesToRefresh;
763 mConfigurationChangesToRefresh |= changes;
764
765 if (needWake) {
766 mEventHub->wake();
767 }
768 }
769}
770
771void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
772 ssize_t repeat, int32_t token) {
773 AutoMutex _l(mLock);
774
775 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
776 if (deviceIndex >= 0) {
777 InputDevice* device = mDevices.valueAt(deviceIndex);
778 device->vibrate(pattern, patternSize, repeat, token);
779 }
780}
781
782void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
783 AutoMutex _l(mLock);
784
785 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
786 if (deviceIndex >= 0) {
787 InputDevice* device = mDevices.valueAt(deviceIndex);
788 device->cancelVibrate(token);
789 }
790}
791
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700792bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
793 AutoMutex _l(mLock);
794
795 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
796 if (deviceIndex >= 0) {
797 InputDevice* device = mDevices.valueAt(deviceIndex);
798 return device->isEnabled();
799 }
800 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
801 return false;
802}
803
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800804void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 AutoMutex _l(mLock);
806
807 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800808 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800810 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811
812 for (size_t i = 0; i < mDevices.size(); i++) {
813 mDevices.valueAt(i)->dump(dump);
814 }
815
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800816 dump += INDENT "Configuration:\n";
817 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
819 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800820 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100822 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800824 dump += "]\n";
825 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 mConfig.virtualKeyQuietTime * 0.000001f);
827
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800828 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
830 mConfig.pointerVelocityControlParameters.scale,
831 mConfig.pointerVelocityControlParameters.lowThreshold,
832 mConfig.pointerVelocityControlParameters.highThreshold,
833 mConfig.pointerVelocityControlParameters.acceleration);
834
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800835 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
837 mConfig.wheelVelocityControlParameters.scale,
838 mConfig.wheelVelocityControlParameters.lowThreshold,
839 mConfig.wheelVelocityControlParameters.highThreshold,
840 mConfig.wheelVelocityControlParameters.acceleration);
841
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800842 dump += StringPrintf(INDENT2 "PointerGesture:\n");
843 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800845 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800847 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800849 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800851 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800853 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800855 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800857 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800859 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800861 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800863 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800865 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700867
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800868 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700869 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870}
871
872void InputReader::monitor() {
873 // Acquire and release the lock to ensure that the reader has not deadlocked.
874 mLock.lock();
875 mEventHub->wake();
876 mReaderIsAliveCondition.wait(mLock);
877 mLock.unlock();
878
879 // Check the EventHub
880 mEventHub->monitor();
881}
882
883
884// --- InputReader::ContextImpl ---
885
886InputReader::ContextImpl::ContextImpl(InputReader* reader) :
887 mReader(reader) {
888}
889
890void InputReader::ContextImpl::updateGlobalMetaState() {
891 // lock is already held by the input loop
892 mReader->updateGlobalMetaStateLocked();
893}
894
895int32_t InputReader::ContextImpl::getGlobalMetaState() {
896 // lock is already held by the input loop
897 return mReader->getGlobalMetaStateLocked();
898}
899
900void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
901 // lock is already held by the input loop
902 mReader->disableVirtualKeysUntilLocked(time);
903}
904
905bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
906 InputDevice* device, int32_t keyCode, int32_t scanCode) {
907 // lock is already held by the input loop
908 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
909}
910
911void InputReader::ContextImpl::fadePointer() {
912 // lock is already held by the input loop
913 mReader->fadePointerLocked();
914}
915
916void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
917 // lock is already held by the input loop
918 mReader->requestTimeoutAtTimeLocked(when);
919}
920
921int32_t InputReader::ContextImpl::bumpGeneration() {
922 // lock is already held by the input loop
923 return mReader->bumpGenerationLocked();
924}
925
Michael Wright842500e2015-03-13 17:32:02 -0700926void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
927 // lock is already held by whatever called refreshConfigurationLocked
928 mReader->getExternalStylusDevicesLocked(outDevices);
929}
930
931void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
932 mReader->dispatchExternalStylusState(state);
933}
934
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
936 return mReader->mPolicy.get();
937}
938
939InputListenerInterface* InputReader::ContextImpl::getListener() {
940 return mReader->mQueuedListener.get();
941}
942
943EventHubInterface* InputReader::ContextImpl::getEventHub() {
944 return mReader->mEventHub.get();
945}
946
Prabir Pradhan42611e02018-11-27 14:04:02 -0800947uint32_t InputReader::ContextImpl::getNextSequenceNum() {
948 return (mReader->mNextSequenceNum)++;
949}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951// --- InputDevice ---
952
953InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
954 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
955 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
956 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700957 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958}
959
960InputDevice::~InputDevice() {
961 size_t numMappers = mMappers.size();
962 for (size_t i = 0; i < numMappers; i++) {
963 delete mMappers[i];
964 }
965 mMappers.clear();
966}
967
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700968bool InputDevice::isEnabled() {
969 return getEventHub()->isDeviceEnabled(mId);
970}
971
972void InputDevice::setEnabled(bool enabled, nsecs_t when) {
973 if (isEnabled() == enabled) {
974 return;
975 }
976
977 if (enabled) {
978 getEventHub()->enableDevice(mId);
979 reset(when);
980 } else {
981 reset(when);
982 getEventHub()->disableDevice(mId);
983 }
984 // Must change generation to flag this device as changed
985 bumpGeneration();
986}
987
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800988void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -0700990 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800992 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100993 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800994 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
995 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -0700996 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
997 if (mAssociatedDisplayPort) {
998 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
999 } else {
1000 dump += "<none>\n";
1001 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001002 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1003 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1004 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005
1006 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1007 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001008 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 for (size_t i = 0; i < ranges.size(); i++) {
1010 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1011 const char* label = getAxisLabel(range.axis);
1012 char name[32];
1013 if (label) {
1014 strncpy(name, label, sizeof(name));
1015 name[sizeof(name) - 1] = '\0';
1016 } else {
1017 snprintf(name, sizeof(name), "%d", range.axis);
1018 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001019 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1021 name, range.source, range.min, range.max, range.flat, range.fuzz,
1022 range.resolution);
1023 }
1024 }
1025
1026 size_t numMappers = mMappers.size();
1027 for (size_t i = 0; i < numMappers; i++) {
1028 InputMapper* mapper = mMappers[i];
1029 mapper->dump(dump);
1030 }
1031}
1032
1033void InputDevice::addMapper(InputMapper* mapper) {
1034 mMappers.add(mapper);
1035}
1036
1037void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1038 mSources = 0;
1039
1040 if (!isIgnored()) {
1041 if (!changes) { // first time only
1042 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1043 }
1044
1045 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1046 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1047 sp<KeyCharacterMap> keyboardLayout =
1048 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1049 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1050 bumpGeneration();
1051 }
1052 }
1053 }
1054
1055 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1056 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001057 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 if (mAlias != alias) {
1059 mAlias = alias;
1060 bumpGeneration();
1061 }
1062 }
1063 }
1064
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001065 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1066 ssize_t index = config->disabledDevices.indexOf(mId);
1067 bool enabled = index < 0;
1068 setEnabled(enabled, when);
1069 }
1070
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001071 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1072 // In most situations, no port will be specified.
1073 mAssociatedDisplayPort = std::nullopt;
1074 // Find the display port that corresponds to the current input port.
1075 const std::string& inputPort = mIdentifier.location;
1076 if (!inputPort.empty()) {
1077 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1078 const auto& displayPort = ports.find(inputPort);
1079 if (displayPort != ports.end()) {
1080 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1081 }
1082 }
1083 }
1084
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 size_t numMappers = mMappers.size();
1086 for (size_t i = 0; i < numMappers; i++) {
1087 InputMapper* mapper = mMappers[i];
1088 mapper->configure(when, config, changes);
1089 mSources |= mapper->getSources();
1090 }
1091 }
1092}
1093
1094void InputDevice::reset(nsecs_t when) {
1095 size_t numMappers = mMappers.size();
1096 for (size_t i = 0; i < numMappers; i++) {
1097 InputMapper* mapper = mMappers[i];
1098 mapper->reset(when);
1099 }
1100
1101 mContext->updateGlobalMetaState();
1102
1103 notifyReset(when);
1104}
1105
1106void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1107 // Process all of the events in order for each mapper.
1108 // We cannot simply ask each mapper to process them in bulk because mappers may
1109 // have side-effects that must be interleaved. For example, joystick movement events and
1110 // gamepad button presses are handled by different mappers but they should be dispatched
1111 // in the order received.
1112 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001113 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001115 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1117 rawEvent->when);
1118#endif
1119
1120 if (mDropUntilNextSync) {
1121 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1122 mDropUntilNextSync = false;
1123#if DEBUG_RAW_EVENTS
1124 ALOGD("Recovered from input event buffer overrun.");
1125#endif
1126 } else {
1127#if DEBUG_RAW_EVENTS
1128 ALOGD("Dropped input event while waiting for next input sync.");
1129#endif
1130 }
1131 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001132 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 mDropUntilNextSync = true;
1134 reset(rawEvent->when);
1135 } else {
1136 for (size_t i = 0; i < numMappers; i++) {
1137 InputMapper* mapper = mMappers[i];
1138 mapper->process(rawEvent);
1139 }
1140 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001141 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 }
1143}
1144
1145void InputDevice::timeoutExpired(nsecs_t when) {
1146 size_t numMappers = mMappers.size();
1147 for (size_t i = 0; i < numMappers; i++) {
1148 InputMapper* mapper = mMappers[i];
1149 mapper->timeoutExpired(when);
1150 }
1151}
1152
Michael Wright842500e2015-03-13 17:32:02 -07001153void InputDevice::updateExternalStylusState(const StylusState& state) {
1154 size_t numMappers = mMappers.size();
1155 for (size_t i = 0; i < numMappers; i++) {
1156 InputMapper* mapper = mMappers[i];
1157 mapper->updateExternalStylusState(state);
1158 }
1159}
1160
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1162 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001163 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 size_t numMappers = mMappers.size();
1165 for (size_t i = 0; i < numMappers; i++) {
1166 InputMapper* mapper = mMappers[i];
1167 mapper->populateDeviceInfo(outDeviceInfo);
1168 }
1169}
1170
1171int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1172 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1173}
1174
1175int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1176 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1177}
1178
1179int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1180 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1181}
1182
1183int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1184 int32_t result = AKEY_STATE_UNKNOWN;
1185 size_t numMappers = mMappers.size();
1186 for (size_t i = 0; i < numMappers; i++) {
1187 InputMapper* mapper = mMappers[i];
1188 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1189 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1190 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1191 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1192 if (currentResult >= AKEY_STATE_DOWN) {
1193 return currentResult;
1194 } else if (currentResult == AKEY_STATE_UP) {
1195 result = currentResult;
1196 }
1197 }
1198 }
1199 return result;
1200}
1201
1202bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1203 const int32_t* keyCodes, uint8_t* outFlags) {
1204 bool result = false;
1205 size_t numMappers = mMappers.size();
1206 for (size_t i = 0; i < numMappers; i++) {
1207 InputMapper* mapper = mMappers[i];
1208 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1209 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1210 }
1211 }
1212 return result;
1213}
1214
1215void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1216 int32_t token) {
1217 size_t numMappers = mMappers.size();
1218 for (size_t i = 0; i < numMappers; i++) {
1219 InputMapper* mapper = mMappers[i];
1220 mapper->vibrate(pattern, patternSize, repeat, token);
1221 }
1222}
1223
1224void InputDevice::cancelVibrate(int32_t token) {
1225 size_t numMappers = mMappers.size();
1226 for (size_t i = 0; i < numMappers; i++) {
1227 InputMapper* mapper = mMappers[i];
1228 mapper->cancelVibrate(token);
1229 }
1230}
1231
Jeff Brownc9aa6282015-02-11 19:03:28 -08001232void InputDevice::cancelTouch(nsecs_t when) {
1233 size_t numMappers = mMappers.size();
1234 for (size_t i = 0; i < numMappers; i++) {
1235 InputMapper* mapper = mMappers[i];
1236 mapper->cancelTouch(when);
1237 }
1238}
1239
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240int32_t InputDevice::getMetaState() {
1241 int32_t result = 0;
1242 size_t numMappers = mMappers.size();
1243 for (size_t i = 0; i < numMappers; i++) {
1244 InputMapper* mapper = mMappers[i];
1245 result |= mapper->getMetaState();
1246 }
1247 return result;
1248}
1249
Andrii Kulian763a3a42016-03-08 10:46:16 -08001250void InputDevice::updateMetaState(int32_t keyCode) {
1251 size_t numMappers = mMappers.size();
1252 for (size_t i = 0; i < numMappers; i++) {
1253 mMappers[i]->updateMetaState(keyCode);
1254 }
1255}
1256
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257void InputDevice::fadePointer() {
1258 size_t numMappers = mMappers.size();
1259 for (size_t i = 0; i < numMappers; i++) {
1260 InputMapper* mapper = mMappers[i];
1261 mapper->fadePointer();
1262 }
1263}
1264
1265void InputDevice::bumpGeneration() {
1266 mGeneration = mContext->bumpGeneration();
1267}
1268
1269void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001270 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 mContext->getListener()->notifyDeviceReset(&args);
1272}
1273
1274
1275// --- CursorButtonAccumulator ---
1276
1277CursorButtonAccumulator::CursorButtonAccumulator() {
1278 clearButtons();
1279}
1280
1281void CursorButtonAccumulator::reset(InputDevice* device) {
1282 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1283 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1284 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1285 mBtnBack = device->isKeyPressed(BTN_BACK);
1286 mBtnSide = device->isKeyPressed(BTN_SIDE);
1287 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1288 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1289 mBtnTask = device->isKeyPressed(BTN_TASK);
1290}
1291
1292void CursorButtonAccumulator::clearButtons() {
1293 mBtnLeft = 0;
1294 mBtnRight = 0;
1295 mBtnMiddle = 0;
1296 mBtnBack = 0;
1297 mBtnSide = 0;
1298 mBtnForward = 0;
1299 mBtnExtra = 0;
1300 mBtnTask = 0;
1301}
1302
1303void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1304 if (rawEvent->type == EV_KEY) {
1305 switch (rawEvent->code) {
1306 case BTN_LEFT:
1307 mBtnLeft = rawEvent->value;
1308 break;
1309 case BTN_RIGHT:
1310 mBtnRight = rawEvent->value;
1311 break;
1312 case BTN_MIDDLE:
1313 mBtnMiddle = rawEvent->value;
1314 break;
1315 case BTN_BACK:
1316 mBtnBack = rawEvent->value;
1317 break;
1318 case BTN_SIDE:
1319 mBtnSide = rawEvent->value;
1320 break;
1321 case BTN_FORWARD:
1322 mBtnForward = rawEvent->value;
1323 break;
1324 case BTN_EXTRA:
1325 mBtnExtra = rawEvent->value;
1326 break;
1327 case BTN_TASK:
1328 mBtnTask = rawEvent->value;
1329 break;
1330 }
1331 }
1332}
1333
1334uint32_t CursorButtonAccumulator::getButtonState() const {
1335 uint32_t result = 0;
1336 if (mBtnLeft) {
1337 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1338 }
1339 if (mBtnRight) {
1340 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1341 }
1342 if (mBtnMiddle) {
1343 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1344 }
1345 if (mBtnBack || mBtnSide) {
1346 result |= AMOTION_EVENT_BUTTON_BACK;
1347 }
1348 if (mBtnForward || mBtnExtra) {
1349 result |= AMOTION_EVENT_BUTTON_FORWARD;
1350 }
1351 return result;
1352}
1353
1354
1355// --- CursorMotionAccumulator ---
1356
1357CursorMotionAccumulator::CursorMotionAccumulator() {
1358 clearRelativeAxes();
1359}
1360
1361void CursorMotionAccumulator::reset(InputDevice* device) {
1362 clearRelativeAxes();
1363}
1364
1365void CursorMotionAccumulator::clearRelativeAxes() {
1366 mRelX = 0;
1367 mRelY = 0;
1368}
1369
1370void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1371 if (rawEvent->type == EV_REL) {
1372 switch (rawEvent->code) {
1373 case REL_X:
1374 mRelX = rawEvent->value;
1375 break;
1376 case REL_Y:
1377 mRelY = rawEvent->value;
1378 break;
1379 }
1380 }
1381}
1382
1383void CursorMotionAccumulator::finishSync() {
1384 clearRelativeAxes();
1385}
1386
1387
1388// --- CursorScrollAccumulator ---
1389
1390CursorScrollAccumulator::CursorScrollAccumulator() :
1391 mHaveRelWheel(false), mHaveRelHWheel(false) {
1392 clearRelativeAxes();
1393}
1394
1395void CursorScrollAccumulator::configure(InputDevice* device) {
1396 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1397 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1398}
1399
1400void CursorScrollAccumulator::reset(InputDevice* device) {
1401 clearRelativeAxes();
1402}
1403
1404void CursorScrollAccumulator::clearRelativeAxes() {
1405 mRelWheel = 0;
1406 mRelHWheel = 0;
1407}
1408
1409void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1410 if (rawEvent->type == EV_REL) {
1411 switch (rawEvent->code) {
1412 case REL_WHEEL:
1413 mRelWheel = rawEvent->value;
1414 break;
1415 case REL_HWHEEL:
1416 mRelHWheel = rawEvent->value;
1417 break;
1418 }
1419 }
1420}
1421
1422void CursorScrollAccumulator::finishSync() {
1423 clearRelativeAxes();
1424}
1425
1426
1427// --- TouchButtonAccumulator ---
1428
1429TouchButtonAccumulator::TouchButtonAccumulator() :
1430 mHaveBtnTouch(false), mHaveStylus(false) {
1431 clearButtons();
1432}
1433
1434void TouchButtonAccumulator::configure(InputDevice* device) {
1435 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1436 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1437 || device->hasKey(BTN_TOOL_RUBBER)
1438 || device->hasKey(BTN_TOOL_BRUSH)
1439 || device->hasKey(BTN_TOOL_PENCIL)
1440 || device->hasKey(BTN_TOOL_AIRBRUSH);
1441}
1442
1443void TouchButtonAccumulator::reset(InputDevice* device) {
1444 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1445 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001446 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1447 mBtnStylus2 =
1448 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1450 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1451 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1452 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1453 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1454 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1455 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1456 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1457 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1458 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1459 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1460}
1461
1462void TouchButtonAccumulator::clearButtons() {
1463 mBtnTouch = 0;
1464 mBtnStylus = 0;
1465 mBtnStylus2 = 0;
1466 mBtnToolFinger = 0;
1467 mBtnToolPen = 0;
1468 mBtnToolRubber = 0;
1469 mBtnToolBrush = 0;
1470 mBtnToolPencil = 0;
1471 mBtnToolAirbrush = 0;
1472 mBtnToolMouse = 0;
1473 mBtnToolLens = 0;
1474 mBtnToolDoubleTap = 0;
1475 mBtnToolTripleTap = 0;
1476 mBtnToolQuadTap = 0;
1477}
1478
1479void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1480 if (rawEvent->type == EV_KEY) {
1481 switch (rawEvent->code) {
1482 case BTN_TOUCH:
1483 mBtnTouch = rawEvent->value;
1484 break;
1485 case BTN_STYLUS:
1486 mBtnStylus = rawEvent->value;
1487 break;
1488 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001489 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 mBtnStylus2 = rawEvent->value;
1491 break;
1492 case BTN_TOOL_FINGER:
1493 mBtnToolFinger = rawEvent->value;
1494 break;
1495 case BTN_TOOL_PEN:
1496 mBtnToolPen = rawEvent->value;
1497 break;
1498 case BTN_TOOL_RUBBER:
1499 mBtnToolRubber = rawEvent->value;
1500 break;
1501 case BTN_TOOL_BRUSH:
1502 mBtnToolBrush = rawEvent->value;
1503 break;
1504 case BTN_TOOL_PENCIL:
1505 mBtnToolPencil = rawEvent->value;
1506 break;
1507 case BTN_TOOL_AIRBRUSH:
1508 mBtnToolAirbrush = rawEvent->value;
1509 break;
1510 case BTN_TOOL_MOUSE:
1511 mBtnToolMouse = rawEvent->value;
1512 break;
1513 case BTN_TOOL_LENS:
1514 mBtnToolLens = rawEvent->value;
1515 break;
1516 case BTN_TOOL_DOUBLETAP:
1517 mBtnToolDoubleTap = rawEvent->value;
1518 break;
1519 case BTN_TOOL_TRIPLETAP:
1520 mBtnToolTripleTap = rawEvent->value;
1521 break;
1522 case BTN_TOOL_QUADTAP:
1523 mBtnToolQuadTap = rawEvent->value;
1524 break;
1525 }
1526 }
1527}
1528
1529uint32_t TouchButtonAccumulator::getButtonState() const {
1530 uint32_t result = 0;
1531 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001532 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
1534 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001535 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 }
1537 return result;
1538}
1539
1540int32_t TouchButtonAccumulator::getToolType() const {
1541 if (mBtnToolMouse || mBtnToolLens) {
1542 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1543 }
1544 if (mBtnToolRubber) {
1545 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1546 }
1547 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1548 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1549 }
1550 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1551 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1552 }
1553 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1554}
1555
1556bool TouchButtonAccumulator::isToolActive() const {
1557 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1558 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1559 || mBtnToolMouse || mBtnToolLens
1560 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1561}
1562
1563bool TouchButtonAccumulator::isHovering() const {
1564 return mHaveBtnTouch && !mBtnTouch;
1565}
1566
1567bool TouchButtonAccumulator::hasStylus() const {
1568 return mHaveStylus;
1569}
1570
1571
1572// --- RawPointerAxes ---
1573
1574RawPointerAxes::RawPointerAxes() {
1575 clear();
1576}
1577
1578void RawPointerAxes::clear() {
1579 x.clear();
1580 y.clear();
1581 pressure.clear();
1582 touchMajor.clear();
1583 touchMinor.clear();
1584 toolMajor.clear();
1585 toolMinor.clear();
1586 orientation.clear();
1587 distance.clear();
1588 tiltX.clear();
1589 tiltY.clear();
1590 trackingId.clear();
1591 slot.clear();
1592}
1593
1594
1595// --- RawPointerData ---
1596
1597RawPointerData::RawPointerData() {
1598 clear();
1599}
1600
1601void RawPointerData::clear() {
1602 pointerCount = 0;
1603 clearIdBits();
1604}
1605
1606void RawPointerData::copyFrom(const RawPointerData& other) {
1607 pointerCount = other.pointerCount;
1608 hoveringIdBits = other.hoveringIdBits;
1609 touchingIdBits = other.touchingIdBits;
1610
1611 for (uint32_t i = 0; i < pointerCount; i++) {
1612 pointers[i] = other.pointers[i];
1613
1614 int id = pointers[i].id;
1615 idToIndex[id] = other.idToIndex[id];
1616 }
1617}
1618
1619void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1620 float x = 0, y = 0;
1621 uint32_t count = touchingIdBits.count();
1622 if (count) {
1623 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1624 uint32_t id = idBits.clearFirstMarkedBit();
1625 const Pointer& pointer = pointerForId(id);
1626 x += pointer.x;
1627 y += pointer.y;
1628 }
1629 x /= count;
1630 y /= count;
1631 }
1632 *outX = x;
1633 *outY = y;
1634}
1635
1636
1637// --- CookedPointerData ---
1638
1639CookedPointerData::CookedPointerData() {
1640 clear();
1641}
1642
1643void CookedPointerData::clear() {
1644 pointerCount = 0;
1645 hoveringIdBits.clear();
1646 touchingIdBits.clear();
1647}
1648
1649void CookedPointerData::copyFrom(const CookedPointerData& other) {
1650 pointerCount = other.pointerCount;
1651 hoveringIdBits = other.hoveringIdBits;
1652 touchingIdBits = other.touchingIdBits;
1653
1654 for (uint32_t i = 0; i < pointerCount; i++) {
1655 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1656 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1657
1658 int id = pointerProperties[i].id;
1659 idToIndex[id] = other.idToIndex[id];
1660 }
1661}
1662
1663
1664// --- SingleTouchMotionAccumulator ---
1665
1666SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1667 clearAbsoluteAxes();
1668}
1669
1670void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1671 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1672 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1673 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1674 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1675 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1676 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1677 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1678}
1679
1680void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1681 mAbsX = 0;
1682 mAbsY = 0;
1683 mAbsPressure = 0;
1684 mAbsToolWidth = 0;
1685 mAbsDistance = 0;
1686 mAbsTiltX = 0;
1687 mAbsTiltY = 0;
1688}
1689
1690void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1691 if (rawEvent->type == EV_ABS) {
1692 switch (rawEvent->code) {
1693 case ABS_X:
1694 mAbsX = rawEvent->value;
1695 break;
1696 case ABS_Y:
1697 mAbsY = rawEvent->value;
1698 break;
1699 case ABS_PRESSURE:
1700 mAbsPressure = rawEvent->value;
1701 break;
1702 case ABS_TOOL_WIDTH:
1703 mAbsToolWidth = rawEvent->value;
1704 break;
1705 case ABS_DISTANCE:
1706 mAbsDistance = rawEvent->value;
1707 break;
1708 case ABS_TILT_X:
1709 mAbsTiltX = rawEvent->value;
1710 break;
1711 case ABS_TILT_Y:
1712 mAbsTiltY = rawEvent->value;
1713 break;
1714 }
1715 }
1716}
1717
1718
1719// --- MultiTouchMotionAccumulator ---
1720
1721MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001722 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001723 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724}
1725
1726MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1727 delete[] mSlots;
1728}
1729
1730void MultiTouchMotionAccumulator::configure(InputDevice* device,
1731 size_t slotCount, bool usingSlotsProtocol) {
1732 mSlotCount = slotCount;
1733 mUsingSlotsProtocol = usingSlotsProtocol;
1734 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1735
1736 delete[] mSlots;
1737 mSlots = new Slot[slotCount];
1738}
1739
1740void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1741 // Unfortunately there is no way to read the initial contents of the slots.
1742 // So when we reset the accumulator, we must assume they are all zeroes.
1743 if (mUsingSlotsProtocol) {
1744 // Query the driver for the current slot index and use it as the initial slot
1745 // before we start reading events from the device. It is possible that the
1746 // current slot index will not be the same as it was when the first event was
1747 // written into the evdev buffer, which means the input mapper could start
1748 // out of sync with the initial state of the events in the evdev buffer.
1749 // In the extremely unlikely case that this happens, the data from
1750 // two slots will be confused until the next ABS_MT_SLOT event is received.
1751 // This can cause the touch point to "jump", but at least there will be
1752 // no stuck touches.
1753 int32_t initialSlot;
1754 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1755 ABS_MT_SLOT, &initialSlot);
1756 if (status) {
1757 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1758 initialSlot = -1;
1759 }
1760 clearSlots(initialSlot);
1761 } else {
1762 clearSlots(-1);
1763 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001764 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765}
1766
1767void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1768 if (mSlots) {
1769 for (size_t i = 0; i < mSlotCount; i++) {
1770 mSlots[i].clear();
1771 }
1772 }
1773 mCurrentSlot = initialSlot;
1774}
1775
1776void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1777 if (rawEvent->type == EV_ABS) {
1778 bool newSlot = false;
1779 if (mUsingSlotsProtocol) {
1780 if (rawEvent->code == ABS_MT_SLOT) {
1781 mCurrentSlot = rawEvent->value;
1782 newSlot = true;
1783 }
1784 } else if (mCurrentSlot < 0) {
1785 mCurrentSlot = 0;
1786 }
1787
1788 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1789#if DEBUG_POINTERS
1790 if (newSlot) {
1791 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001792 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 mCurrentSlot, mSlotCount - 1);
1794 }
1795#endif
1796 } else {
1797 Slot* slot = &mSlots[mCurrentSlot];
1798
1799 switch (rawEvent->code) {
1800 case ABS_MT_POSITION_X:
1801 slot->mInUse = true;
1802 slot->mAbsMTPositionX = rawEvent->value;
1803 break;
1804 case ABS_MT_POSITION_Y:
1805 slot->mInUse = true;
1806 slot->mAbsMTPositionY = rawEvent->value;
1807 break;
1808 case ABS_MT_TOUCH_MAJOR:
1809 slot->mInUse = true;
1810 slot->mAbsMTTouchMajor = rawEvent->value;
1811 break;
1812 case ABS_MT_TOUCH_MINOR:
1813 slot->mInUse = true;
1814 slot->mAbsMTTouchMinor = rawEvent->value;
1815 slot->mHaveAbsMTTouchMinor = true;
1816 break;
1817 case ABS_MT_WIDTH_MAJOR:
1818 slot->mInUse = true;
1819 slot->mAbsMTWidthMajor = rawEvent->value;
1820 break;
1821 case ABS_MT_WIDTH_MINOR:
1822 slot->mInUse = true;
1823 slot->mAbsMTWidthMinor = rawEvent->value;
1824 slot->mHaveAbsMTWidthMinor = true;
1825 break;
1826 case ABS_MT_ORIENTATION:
1827 slot->mInUse = true;
1828 slot->mAbsMTOrientation = rawEvent->value;
1829 break;
1830 case ABS_MT_TRACKING_ID:
1831 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1832 // The slot is no longer in use but it retains its previous contents,
1833 // which may be reused for subsequent touches.
1834 slot->mInUse = false;
1835 } else {
1836 slot->mInUse = true;
1837 slot->mAbsMTTrackingId = rawEvent->value;
1838 }
1839 break;
1840 case ABS_MT_PRESSURE:
1841 slot->mInUse = true;
1842 slot->mAbsMTPressure = rawEvent->value;
1843 break;
1844 case ABS_MT_DISTANCE:
1845 slot->mInUse = true;
1846 slot->mAbsMTDistance = rawEvent->value;
1847 break;
1848 case ABS_MT_TOOL_TYPE:
1849 slot->mInUse = true;
1850 slot->mAbsMTToolType = rawEvent->value;
1851 slot->mHaveAbsMTToolType = true;
1852 break;
1853 }
1854 }
1855 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1856 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1857 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001858 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1859 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 }
1861}
1862
1863void MultiTouchMotionAccumulator::finishSync() {
1864 if (!mUsingSlotsProtocol) {
1865 clearSlots(-1);
1866 }
1867}
1868
1869bool MultiTouchMotionAccumulator::hasStylus() const {
1870 return mHaveStylus;
1871}
1872
1873
1874// --- MultiTouchMotionAccumulator::Slot ---
1875
1876MultiTouchMotionAccumulator::Slot::Slot() {
1877 clear();
1878}
1879
1880void MultiTouchMotionAccumulator::Slot::clear() {
1881 mInUse = false;
1882 mHaveAbsMTTouchMinor = false;
1883 mHaveAbsMTWidthMinor = false;
1884 mHaveAbsMTToolType = false;
1885 mAbsMTPositionX = 0;
1886 mAbsMTPositionY = 0;
1887 mAbsMTTouchMajor = 0;
1888 mAbsMTTouchMinor = 0;
1889 mAbsMTWidthMajor = 0;
1890 mAbsMTWidthMinor = 0;
1891 mAbsMTOrientation = 0;
1892 mAbsMTTrackingId = -1;
1893 mAbsMTPressure = 0;
1894 mAbsMTDistance = 0;
1895 mAbsMTToolType = 0;
1896}
1897
1898int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1899 if (mHaveAbsMTToolType) {
1900 switch (mAbsMTToolType) {
1901 case MT_TOOL_FINGER:
1902 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1903 case MT_TOOL_PEN:
1904 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1905 }
1906 }
1907 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1908}
1909
1910
1911// --- InputMapper ---
1912
1913InputMapper::InputMapper(InputDevice* device) :
1914 mDevice(device), mContext(device->getContext()) {
1915}
1916
1917InputMapper::~InputMapper() {
1918}
1919
1920void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1921 info->addSource(getSources());
1922}
1923
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001924void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925}
1926
1927void InputMapper::configure(nsecs_t when,
1928 const InputReaderConfiguration* config, uint32_t changes) {
1929}
1930
1931void InputMapper::reset(nsecs_t when) {
1932}
1933
1934void InputMapper::timeoutExpired(nsecs_t when) {
1935}
1936
1937int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1938 return AKEY_STATE_UNKNOWN;
1939}
1940
1941int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1942 return AKEY_STATE_UNKNOWN;
1943}
1944
1945int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1946 return AKEY_STATE_UNKNOWN;
1947}
1948
1949bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1950 const int32_t* keyCodes, uint8_t* outFlags) {
1951 return false;
1952}
1953
1954void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1955 int32_t token) {
1956}
1957
1958void InputMapper::cancelVibrate(int32_t token) {
1959}
1960
Jeff Brownc9aa6282015-02-11 19:03:28 -08001961void InputMapper::cancelTouch(nsecs_t when) {
1962}
1963
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964int32_t InputMapper::getMetaState() {
1965 return 0;
1966}
1967
Andrii Kulian763a3a42016-03-08 10:46:16 -08001968void InputMapper::updateMetaState(int32_t keyCode) {
1969}
1970
Michael Wright842500e2015-03-13 17:32:02 -07001971void InputMapper::updateExternalStylusState(const StylusState& state) {
1972
1973}
1974
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975void InputMapper::fadePointer() {
1976}
1977
1978status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1979 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1980}
1981
1982void InputMapper::bumpGeneration() {
1983 mDevice->bumpGeneration();
1984}
1985
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001986void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 const RawAbsoluteAxisInfo& axis, const char* name) {
1988 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001989 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1991 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001992 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 }
1994}
1995
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001996void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
1997 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
1998 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
1999 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2000 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002001}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002
2003// --- SwitchInputMapper ---
2004
2005SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002006 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007}
2008
2009SwitchInputMapper::~SwitchInputMapper() {
2010}
2011
2012uint32_t SwitchInputMapper::getSources() {
2013 return AINPUT_SOURCE_SWITCH;
2014}
2015
2016void SwitchInputMapper::process(const RawEvent* rawEvent) {
2017 switch (rawEvent->type) {
2018 case EV_SW:
2019 processSwitch(rawEvent->code, rawEvent->value);
2020 break;
2021
2022 case EV_SYN:
2023 if (rawEvent->code == SYN_REPORT) {
2024 sync(rawEvent->when);
2025 }
2026 }
2027}
2028
2029void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2030 if (switchCode >= 0 && switchCode < 32) {
2031 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002032 mSwitchValues |= 1 << switchCode;
2033 } else {
2034 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 }
2036 mUpdatedSwitchMask |= 1 << switchCode;
2037 }
2038}
2039
2040void SwitchInputMapper::sync(nsecs_t when) {
2041 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002042 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002043 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2044 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 getListener()->notifySwitch(&args);
2046
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 mUpdatedSwitchMask = 0;
2048 }
2049}
2050
2051int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2052 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2053}
2054
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002055void SwitchInputMapper::dump(std::string& dump) {
2056 dump += INDENT2 "Switch Input Mapper:\n";
2057 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002058}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059
2060// --- VibratorInputMapper ---
2061
2062VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2063 InputMapper(device), mVibrating(false) {
2064}
2065
2066VibratorInputMapper::~VibratorInputMapper() {
2067}
2068
2069uint32_t VibratorInputMapper::getSources() {
2070 return 0;
2071}
2072
2073void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2074 InputMapper::populateDeviceInfo(info);
2075
2076 info->setVibrator(true);
2077}
2078
2079void VibratorInputMapper::process(const RawEvent* rawEvent) {
2080 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2081}
2082
2083void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2084 int32_t token) {
2085#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002086 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 for (size_t i = 0; i < patternSize; i++) {
2088 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002089 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002091 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002093 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002094 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095#endif
2096
2097 mVibrating = true;
2098 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2099 mPatternSize = patternSize;
2100 mRepeat = repeat;
2101 mToken = token;
2102 mIndex = -1;
2103
2104 nextStep();
2105}
2106
2107void VibratorInputMapper::cancelVibrate(int32_t token) {
2108#if DEBUG_VIBRATOR
2109 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2110#endif
2111
2112 if (mVibrating && mToken == token) {
2113 stopVibrating();
2114 }
2115}
2116
2117void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2118 if (mVibrating) {
2119 if (when >= mNextStepTime) {
2120 nextStep();
2121 } else {
2122 getContext()->requestTimeoutAtTime(mNextStepTime);
2123 }
2124 }
2125}
2126
2127void VibratorInputMapper::nextStep() {
2128 mIndex += 1;
2129 if (size_t(mIndex) >= mPatternSize) {
2130 if (mRepeat < 0) {
2131 // We are done.
2132 stopVibrating();
2133 return;
2134 }
2135 mIndex = mRepeat;
2136 }
2137
2138 bool vibratorOn = mIndex & 1;
2139 nsecs_t duration = mPattern[mIndex];
2140 if (vibratorOn) {
2141#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002142 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143#endif
2144 getEventHub()->vibrate(getDeviceId(), duration);
2145 } else {
2146#if DEBUG_VIBRATOR
2147 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2148#endif
2149 getEventHub()->cancelVibrate(getDeviceId());
2150 }
2151 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2152 mNextStepTime = now + duration;
2153 getContext()->requestTimeoutAtTime(mNextStepTime);
2154#if DEBUG_VIBRATOR
2155 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2156#endif
2157}
2158
2159void VibratorInputMapper::stopVibrating() {
2160 mVibrating = false;
2161#if DEBUG_VIBRATOR
2162 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2163#endif
2164 getEventHub()->cancelVibrate(getDeviceId());
2165}
2166
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002167void VibratorInputMapper::dump(std::string& dump) {
2168 dump += INDENT2 "Vibrator Input Mapper:\n";
2169 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170}
2171
2172
2173// --- KeyboardInputMapper ---
2174
2175KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2176 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002177 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178}
2179
2180KeyboardInputMapper::~KeyboardInputMapper() {
2181}
2182
2183uint32_t KeyboardInputMapper::getSources() {
2184 return mSource;
2185}
2186
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002187int32_t KeyboardInputMapper::getOrientation() {
2188 if (mViewport) {
2189 return mViewport->orientation;
2190 }
2191 return DISPLAY_ORIENTATION_0;
2192}
2193
2194int32_t KeyboardInputMapper::getDisplayId() {
2195 if (mViewport) {
2196 return mViewport->displayId;
2197 }
2198 return ADISPLAY_ID_NONE;
2199}
2200
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2202 InputMapper::populateDeviceInfo(info);
2203
2204 info->setKeyboardType(mKeyboardType);
2205 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2206}
2207
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002208void KeyboardInputMapper::dump(std::string& dump) {
2209 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002211 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002212 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002213 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2214 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2215 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216}
2217
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218void KeyboardInputMapper::configure(nsecs_t when,
2219 const InputReaderConfiguration* config, uint32_t changes) {
2220 InputMapper::configure(when, config, changes);
2221
2222 if (!changes) { // first time only
2223 // Configure basic parameters.
2224 configureParameters();
2225 }
2226
2227 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002228 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002229 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231 }
2232}
2233
Ivan Podogovb9afef32017-02-13 15:34:32 +00002234static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2235 int32_t mapped = 0;
2236 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2237 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2238 if (stemKeyRotationMap[i][0] == keyCode) {
2239 stemKeyRotationMap[i][1] = mapped;
2240 return;
2241 }
2242 }
2243 }
2244}
2245
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246void KeyboardInputMapper::configureParameters() {
2247 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002248 const PropertyMap& config = getDevice()->getConfiguration();
2249 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 mParameters.orientationAware);
2251
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002253 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2254 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2255 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2256 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002258
2259 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002260 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002261 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262}
2263
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002264void KeyboardInputMapper::dumpParameters(std::string& dump) {
2265 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002266 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002268 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002269 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270}
2271
2272void KeyboardInputMapper::reset(nsecs_t when) {
2273 mMetaState = AMETA_NONE;
2274 mDownTime = 0;
2275 mKeyDowns.clear();
2276 mCurrentHidUsage = 0;
2277
2278 resetLedState();
2279
2280 InputMapper::reset(when);
2281}
2282
2283void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2284 switch (rawEvent->type) {
2285 case EV_KEY: {
2286 int32_t scanCode = rawEvent->code;
2287 int32_t usageCode = mCurrentHidUsage;
2288 mCurrentHidUsage = 0;
2289
2290 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002291 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 }
2293 break;
2294 }
2295 case EV_MSC: {
2296 if (rawEvent->code == MSC_SCAN) {
2297 mCurrentHidUsage = rawEvent->value;
2298 }
2299 break;
2300 }
2301 case EV_SYN: {
2302 if (rawEvent->code == SYN_REPORT) {
2303 mCurrentHidUsage = 0;
2304 }
2305 }
2306 }
2307}
2308
2309bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2310 return scanCode < BTN_MOUSE
2311 || scanCode >= KEY_OK
2312 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2313 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2314}
2315
Michael Wright58ba9882017-07-26 16:19:11 +01002316bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2317 switch (keyCode) {
2318 case AKEYCODE_MEDIA_PLAY:
2319 case AKEYCODE_MEDIA_PAUSE:
2320 case AKEYCODE_MEDIA_PLAY_PAUSE:
2321 case AKEYCODE_MUTE:
2322 case AKEYCODE_HEADSETHOOK:
2323 case AKEYCODE_MEDIA_STOP:
2324 case AKEYCODE_MEDIA_NEXT:
2325 case AKEYCODE_MEDIA_PREVIOUS:
2326 case AKEYCODE_MEDIA_REWIND:
2327 case AKEYCODE_MEDIA_RECORD:
2328 case AKEYCODE_MEDIA_FAST_FORWARD:
2329 case AKEYCODE_MEDIA_SKIP_FORWARD:
2330 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2331 case AKEYCODE_MEDIA_STEP_FORWARD:
2332 case AKEYCODE_MEDIA_STEP_BACKWARD:
2333 case AKEYCODE_MEDIA_AUDIO_TRACK:
2334 case AKEYCODE_VOLUME_UP:
2335 case AKEYCODE_VOLUME_DOWN:
2336 case AKEYCODE_VOLUME_MUTE:
2337 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2338 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2339 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2340 return true;
2341 }
2342 return false;
2343}
2344
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002345void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2346 int32_t usageCode) {
2347 int32_t keyCode;
2348 int32_t keyMetaState;
2349 uint32_t policyFlags;
2350
2351 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2352 &keyCode, &keyMetaState, &policyFlags)) {
2353 keyCode = AKEYCODE_UNKNOWN;
2354 keyMetaState = mMetaState;
2355 policyFlags = 0;
2356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357
2358 if (down) {
2359 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002360 if (mParameters.orientationAware) {
2361 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 }
2363
2364 // Add key down.
2365 ssize_t keyDownIndex = findKeyDown(scanCode);
2366 if (keyDownIndex >= 0) {
2367 // key repeat, be sure to use same keycode as before in case of rotation
2368 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2369 } else {
2370 // key down
2371 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2372 && mContext->shouldDropVirtualKey(when,
2373 getDevice(), keyCode, scanCode)) {
2374 return;
2375 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002376 if (policyFlags & POLICY_FLAG_GESTURE) {
2377 mDevice->cancelTouch(when);
2378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379
2380 mKeyDowns.push();
2381 KeyDown& keyDown = mKeyDowns.editTop();
2382 keyDown.keyCode = keyCode;
2383 keyDown.scanCode = scanCode;
2384 }
2385
2386 mDownTime = when;
2387 } else {
2388 // Remove key down.
2389 ssize_t keyDownIndex = findKeyDown(scanCode);
2390 if (keyDownIndex >= 0) {
2391 // key up, be sure to use same keycode as before in case of rotation
2392 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2393 mKeyDowns.removeAt(size_t(keyDownIndex));
2394 } else {
2395 // key was not actually down
2396 ALOGI("Dropping key up from device %s because the key was not down. "
2397 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002398 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 return;
2400 }
2401 }
2402
Andrii Kulian763a3a42016-03-08 10:46:16 -08002403 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002404 // If global meta state changed send it along with the key.
2405 // If it has not changed then we'll use what keymap gave us,
2406 // since key replacement logic might temporarily reset a few
2407 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002408 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
2410
2411 nsecs_t downTime = mDownTime;
2412
2413 // Key down on external an keyboard should wake the device.
2414 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2415 // For internal keyboards, the key layout file should specify the policy flags for
2416 // each wake key individually.
2417 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002418 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002419 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 }
2421
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002422 if (mParameters.handlesKeyRepeat) {
2423 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2424 }
2425
Prabir Pradhan42611e02018-11-27 14:04:02 -08002426 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2427 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002428 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 getListener()->notifyKey(&args);
2430}
2431
2432ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2433 size_t n = mKeyDowns.size();
2434 for (size_t i = 0; i < n; i++) {
2435 if (mKeyDowns[i].scanCode == scanCode) {
2436 return i;
2437 }
2438 }
2439 return -1;
2440}
2441
2442int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2443 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2444}
2445
2446int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2447 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2448}
2449
2450bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2451 const int32_t* keyCodes, uint8_t* outFlags) {
2452 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2453}
2454
2455int32_t KeyboardInputMapper::getMetaState() {
2456 return mMetaState;
2457}
2458
Andrii Kulian763a3a42016-03-08 10:46:16 -08002459void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2460 updateMetaStateIfNeeded(keyCode, false);
2461}
2462
2463bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2464 int32_t oldMetaState = mMetaState;
2465 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2466 bool metaStateChanged = oldMetaState != newMetaState;
2467 if (metaStateChanged) {
2468 mMetaState = newMetaState;
2469 updateLedState(false);
2470
2471 getContext()->updateGlobalMetaState();
2472 }
2473
2474 return metaStateChanged;
2475}
2476
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477void KeyboardInputMapper::resetLedState() {
2478 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2479 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2480 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2481
2482 updateLedState(true);
2483}
2484
2485void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2486 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2487 ledState.on = false;
2488}
2489
2490void KeyboardInputMapper::updateLedState(bool reset) {
2491 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2492 AMETA_CAPS_LOCK_ON, reset);
2493 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2494 AMETA_NUM_LOCK_ON, reset);
2495 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2496 AMETA_SCROLL_LOCK_ON, reset);
2497}
2498
2499void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2500 int32_t led, int32_t modifier, bool reset) {
2501 if (ledState.avail) {
2502 bool desiredState = (mMetaState & modifier) != 0;
2503 if (reset || ledState.on != desiredState) {
2504 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2505 ledState.on = desiredState;
2506 }
2507 }
2508}
2509
2510
2511// --- CursorInputMapper ---
2512
2513CursorInputMapper::CursorInputMapper(InputDevice* device) :
2514 InputMapper(device) {
2515}
2516
2517CursorInputMapper::~CursorInputMapper() {
2518}
2519
2520uint32_t CursorInputMapper::getSources() {
2521 return mSource;
2522}
2523
2524void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2525 InputMapper::populateDeviceInfo(info);
2526
2527 if (mParameters.mode == Parameters::MODE_POINTER) {
2528 float minX, minY, maxX, maxY;
2529 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2530 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2531 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2532 }
2533 } else {
2534 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2535 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2536 }
2537 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2538
2539 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2540 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2541 }
2542 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2543 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2544 }
2545}
2546
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002547void CursorInputMapper::dump(std::string& dump) {
2548 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002550 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2551 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2552 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2553 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2554 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002556 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002558 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2559 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2560 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2561 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2562 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2563 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564}
2565
2566void CursorInputMapper::configure(nsecs_t when,
2567 const InputReaderConfiguration* config, uint32_t changes) {
2568 InputMapper::configure(when, config, changes);
2569
2570 if (!changes) { // first time only
2571 mCursorScrollAccumulator.configure(getDevice());
2572
2573 // Configure basic parameters.
2574 configureParameters();
2575
2576 // Configure device mode.
2577 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002578 case Parameters::MODE_POINTER_RELATIVE:
2579 // Should not happen during first time configuration.
2580 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2581 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002582 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 case Parameters::MODE_POINTER:
2584 mSource = AINPUT_SOURCE_MOUSE;
2585 mXPrecision = 1.0f;
2586 mYPrecision = 1.0f;
2587 mXScale = 1.0f;
2588 mYScale = 1.0f;
2589 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2590 break;
2591 case Parameters::MODE_NAVIGATION:
2592 mSource = AINPUT_SOURCE_TRACKBALL;
2593 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2594 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2595 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2596 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2597 break;
2598 }
2599
2600 mVWheelScale = 1.0f;
2601 mHWheelScale = 1.0f;
2602 }
2603
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002604 if ((!changes && config->pointerCapture)
2605 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2606 if (config->pointerCapture) {
2607 if (mParameters.mode == Parameters::MODE_POINTER) {
2608 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2609 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2610 // Keep PointerController around in order to preserve the pointer position.
2611 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2612 } else {
2613 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2614 }
2615 } else {
2616 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2617 mParameters.mode = Parameters::MODE_POINTER;
2618 mSource = AINPUT_SOURCE_MOUSE;
2619 } else {
2620 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2621 }
2622 }
2623 bumpGeneration();
2624 if (changes) {
2625 getDevice()->notifyReset(when);
2626 }
2627 }
2628
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2630 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2631 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2632 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2633 }
2634
2635 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002636 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002638 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002639 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002640 if (internalViewport) {
2641 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002644
2645 // Update the PointerController if viewports changed.
2646 if (mParameters.hasAssociatedDisplay) {
2647 getPolicy()->obtainPointerController(getDeviceId());
2648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 bumpGeneration();
2650 }
2651}
2652
2653void CursorInputMapper::configureParameters() {
2654 mParameters.mode = Parameters::MODE_POINTER;
2655 String8 cursorModeString;
2656 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2657 if (cursorModeString == "navigation") {
2658 mParameters.mode = Parameters::MODE_NAVIGATION;
2659 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2660 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2661 }
2662 }
2663
2664 mParameters.orientationAware = false;
2665 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2666 mParameters.orientationAware);
2667
2668 mParameters.hasAssociatedDisplay = false;
2669 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2670 mParameters.hasAssociatedDisplay = true;
2671 }
2672}
2673
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002674void CursorInputMapper::dumpParameters(std::string& dump) {
2675 dump += INDENT3 "Parameters:\n";
2676 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 toString(mParameters.hasAssociatedDisplay));
2678
2679 switch (mParameters.mode) {
2680 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002681 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002683 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002684 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002685 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002687 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 break;
2689 default:
2690 ALOG_ASSERT(false);
2691 }
2692
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002693 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 toString(mParameters.orientationAware));
2695}
2696
2697void CursorInputMapper::reset(nsecs_t when) {
2698 mButtonState = 0;
2699 mDownTime = 0;
2700
2701 mPointerVelocityControl.reset();
2702 mWheelXVelocityControl.reset();
2703 mWheelYVelocityControl.reset();
2704
2705 mCursorButtonAccumulator.reset(getDevice());
2706 mCursorMotionAccumulator.reset(getDevice());
2707 mCursorScrollAccumulator.reset(getDevice());
2708
2709 InputMapper::reset(when);
2710}
2711
2712void CursorInputMapper::process(const RawEvent* rawEvent) {
2713 mCursorButtonAccumulator.process(rawEvent);
2714 mCursorMotionAccumulator.process(rawEvent);
2715 mCursorScrollAccumulator.process(rawEvent);
2716
2717 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2718 sync(rawEvent->when);
2719 }
2720}
2721
2722void CursorInputMapper::sync(nsecs_t when) {
2723 int32_t lastButtonState = mButtonState;
2724 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2725 mButtonState = currentButtonState;
2726
2727 bool wasDown = isPointerDown(lastButtonState);
2728 bool down = isPointerDown(currentButtonState);
2729 bool downChanged;
2730 if (!wasDown && down) {
2731 mDownTime = when;
2732 downChanged = true;
2733 } else if (wasDown && !down) {
2734 downChanged = true;
2735 } else {
2736 downChanged = false;
2737 }
2738 nsecs_t downTime = mDownTime;
2739 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002740 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2741 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742
2743 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2744 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2745 bool moved = deltaX != 0 || deltaY != 0;
2746
2747 // Rotate delta according to orientation if needed.
2748 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2749 && (deltaX != 0.0f || deltaY != 0.0f)) {
2750 rotateDelta(mOrientation, &deltaX, &deltaY);
2751 }
2752
2753 // Move the pointer.
2754 PointerProperties pointerProperties;
2755 pointerProperties.clear();
2756 pointerProperties.id = 0;
2757 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2758
2759 PointerCoords pointerCoords;
2760 pointerCoords.clear();
2761
2762 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2763 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2764 bool scrolled = vscroll != 0 || hscroll != 0;
2765
Yi Kong9b14ac62018-07-17 13:48:38 -07002766 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2767 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768
2769 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2770
2771 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002772 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 if (moved || scrolled || buttonsChanged) {
2774 mPointerController->setPresentation(
2775 PointerControllerInterface::PRESENTATION_POINTER);
2776
2777 if (moved) {
2778 mPointerController->move(deltaX, deltaY);
2779 }
2780
2781 if (buttonsChanged) {
2782 mPointerController->setButtonState(currentButtonState);
2783 }
2784
2785 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2786 }
2787
2788 float x, y;
2789 mPointerController->getPosition(&x, &y);
2790 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2791 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002792 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2793 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002794 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 } else {
2796 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2797 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2798 displayId = ADISPLAY_ID_NONE;
2799 }
2800
2801 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2802
2803 // Moving an external trackball or mouse should wake the device.
2804 // We don't do this for internal cursor devices to prevent them from waking up
2805 // the device in your pocket.
2806 // TODO: Use the input device configuration to control this behavior more finely.
2807 uint32_t policyFlags = 0;
2808 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002809 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 }
2811
2812 // Synthesize key down from buttons if needed.
2813 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002814 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815
2816 // Send motion event.
2817 if (downChanged || moved || scrolled || buttonsChanged) {
2818 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002819 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 int32_t motionEventAction;
2821 if (downChanged) {
2822 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002823 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2825 } else {
2826 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2827 }
2828
Michael Wright7b159c92015-05-14 14:48:03 +01002829 if (buttonsReleased) {
2830 BitSet32 released(buttonsReleased);
2831 while (!released.isEmpty()) {
2832 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2833 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002834 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2835 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002836 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2837 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002838 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002839 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002840 getListener()->notifyMotion(&releaseArgs);
2841 }
2842 }
2843
Prabir Pradhan42611e02018-11-27 14:04:02 -08002844 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2845 displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
Michael Wright7b159c92015-05-14 14:48:03 +01002846 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002847 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002848 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849 getListener()->notifyMotion(&args);
2850
Michael Wright7b159c92015-05-14 14:48:03 +01002851 if (buttonsPressed) {
2852 BitSet32 pressed(buttonsPressed);
2853 while (!pressed.isEmpty()) {
2854 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2855 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002856 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2857 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2858 actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002859 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002860 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002861 getListener()->notifyMotion(&pressArgs);
2862 }
2863 }
2864
2865 ALOG_ASSERT(buttonState == currentButtonState);
2866
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 // Send hover move after UP to tell the application that the mouse is hovering now.
2868 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002869 && (mSource == AINPUT_SOURCE_MOUSE)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08002870 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2871 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002873 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002874 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 getListener()->notifyMotion(&hoverArgs);
2876 }
2877
2878 // Send scroll events.
2879 if (scrolled) {
2880 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2881 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2882
Prabir Pradhan42611e02018-11-27 14:04:02 -08002883 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2884 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002885 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002887 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002888 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 getListener()->notifyMotion(&scrollArgs);
2890 }
2891 }
2892
2893 // Synthesize key up from buttons if needed.
2894 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002895 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896
2897 mCursorMotionAccumulator.finishSync();
2898 mCursorScrollAccumulator.finishSync();
2899}
2900
2901int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2902 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2903 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2904 } else {
2905 return AKEY_STATE_UNKNOWN;
2906 }
2907}
2908
2909void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002910 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2912 }
2913}
2914
Prashant Malani1941ff52015-08-11 18:29:28 -07002915// --- RotaryEncoderInputMapper ---
2916
2917RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002918 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002919 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2920}
2921
2922RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2923}
2924
2925uint32_t RotaryEncoderInputMapper::getSources() {
2926 return mSource;
2927}
2928
2929void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2930 InputMapper::populateDeviceInfo(info);
2931
2932 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002933 float res = 0.0f;
2934 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2935 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2936 }
2937 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2938 mScalingFactor)) {
2939 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2940 "default to 1.0!\n");
2941 mScalingFactor = 1.0f;
2942 }
2943 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2944 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002945 }
2946}
2947
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002948void RotaryEncoderInputMapper::dump(std::string& dump) {
2949 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2950 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002951 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2952}
2953
2954void RotaryEncoderInputMapper::configure(nsecs_t when,
2955 const InputReaderConfiguration* config, uint32_t changes) {
2956 InputMapper::configure(when, config, changes);
2957 if (!changes) {
2958 mRotaryEncoderScrollAccumulator.configure(getDevice());
2959 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002960 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002961 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002962 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002963 if (internalViewport) {
2964 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002965 } else {
2966 mOrientation = DISPLAY_ORIENTATION_0;
2967 }
2968 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002969}
2970
2971void RotaryEncoderInputMapper::reset(nsecs_t when) {
2972 mRotaryEncoderScrollAccumulator.reset(getDevice());
2973
2974 InputMapper::reset(when);
2975}
2976
2977void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2978 mRotaryEncoderScrollAccumulator.process(rawEvent);
2979
2980 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2981 sync(rawEvent->when);
2982 }
2983}
2984
2985void RotaryEncoderInputMapper::sync(nsecs_t when) {
2986 PointerCoords pointerCoords;
2987 pointerCoords.clear();
2988
2989 PointerProperties pointerProperties;
2990 pointerProperties.clear();
2991 pointerProperties.id = 0;
2992 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2993
2994 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2995 bool scrolled = scroll != 0;
2996
2997 // This is not a pointer, so it's not associated with a display.
2998 int32_t displayId = ADISPLAY_ID_NONE;
2999
3000 // Moving the rotary encoder should wake the device (if specified).
3001 uint32_t policyFlags = 0;
3002 if (scrolled && getDevice()->isExternal()) {
3003 policyFlags |= POLICY_FLAG_WAKE;
3004 }
3005
Ivan Podogovad437252016-09-29 16:29:55 +01003006 if (mOrientation == DISPLAY_ORIENTATION_180) {
3007 scroll = -scroll;
3008 }
3009
Prashant Malani1941ff52015-08-11 18:29:28 -07003010 // Send motion event.
3011 if (scrolled) {
3012 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003013 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003014
Prabir Pradhan42611e02018-11-27 14:04:02 -08003015 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
3016 mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003017 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3018 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003019 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08003020 0, 0, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003021 getListener()->notifyMotion(&scrollArgs);
3022 }
3023
3024 mRotaryEncoderScrollAccumulator.finishSync();
3025}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026
3027// --- TouchInputMapper ---
3028
3029TouchInputMapper::TouchInputMapper(InputDevice* device) :
3030 InputMapper(device),
3031 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3032 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003033 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3035}
3036
3037TouchInputMapper::~TouchInputMapper() {
3038}
3039
3040uint32_t TouchInputMapper::getSources() {
3041 return mSource;
3042}
3043
3044void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3045 InputMapper::populateDeviceInfo(info);
3046
3047 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3048 info->addMotionRange(mOrientedRanges.x);
3049 info->addMotionRange(mOrientedRanges.y);
3050 info->addMotionRange(mOrientedRanges.pressure);
3051
3052 if (mOrientedRanges.haveSize) {
3053 info->addMotionRange(mOrientedRanges.size);
3054 }
3055
3056 if (mOrientedRanges.haveTouchSize) {
3057 info->addMotionRange(mOrientedRanges.touchMajor);
3058 info->addMotionRange(mOrientedRanges.touchMinor);
3059 }
3060
3061 if (mOrientedRanges.haveToolSize) {
3062 info->addMotionRange(mOrientedRanges.toolMajor);
3063 info->addMotionRange(mOrientedRanges.toolMinor);
3064 }
3065
3066 if (mOrientedRanges.haveOrientation) {
3067 info->addMotionRange(mOrientedRanges.orientation);
3068 }
3069
3070 if (mOrientedRanges.haveDistance) {
3071 info->addMotionRange(mOrientedRanges.distance);
3072 }
3073
3074 if (mOrientedRanges.haveTilt) {
3075 info->addMotionRange(mOrientedRanges.tilt);
3076 }
3077
3078 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3079 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3080 0.0f);
3081 }
3082 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3083 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3084 0.0f);
3085 }
3086 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3087 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3088 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3089 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3090 x.fuzz, x.resolution);
3091 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3092 y.fuzz, y.resolution);
3093 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3094 x.fuzz, x.resolution);
3095 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3096 y.fuzz, y.resolution);
3097 }
3098 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3099 }
3100}
3101
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003102void TouchInputMapper::dump(std::string& dump) {
3103 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104 dumpParameters(dump);
3105 dumpVirtualKeys(dump);
3106 dumpRawPointerAxes(dump);
3107 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003108 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 dumpSurface(dump);
3110
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003111 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3112 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3113 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3114 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3115 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3116 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3117 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3118 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3119 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3120 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3121 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3122 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3123 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3124 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3125 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3126 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3127 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003129 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3130 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003131 mLastRawState.rawPointerData.pointerCount);
3132 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3133 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003134 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3136 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3137 "toolType=%d, isHovering=%s\n", i,
3138 pointer.id, pointer.x, pointer.y, pointer.pressure,
3139 pointer.touchMajor, pointer.touchMinor,
3140 pointer.toolMajor, pointer.toolMinor,
3141 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3142 pointer.toolType, toString(pointer.isHovering));
3143 }
3144
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003145 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3146 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003147 mLastCookedState.cookedPointerData.pointerCount);
3148 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3149 const PointerProperties& pointerProperties =
3150 mLastCookedState.cookedPointerData.pointerProperties[i];
3151 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003152 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3154 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3155 "toolType=%d, isHovering=%s\n", i,
3156 pointerProperties.id,
3157 pointerCoords.getX(),
3158 pointerCoords.getY(),
3159 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3160 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3161 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3162 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3163 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3164 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3165 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3166 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3167 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003168 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 }
3170
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003171 dump += INDENT3 "Stylus Fusion:\n";
3172 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003173 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003174 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3175 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003176 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003177 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003178 dumpStylusState(dump, mExternalStylusState);
3179
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003181 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3182 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003184 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003186 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003188 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003190 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 mPointerGestureMaxSwipeWidth);
3192 }
3193}
3194
Santos Cordonfa5cf462017-04-05 10:37:00 -07003195const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3196 switch (deviceMode) {
3197 case DEVICE_MODE_DISABLED:
3198 return "disabled";
3199 case DEVICE_MODE_DIRECT:
3200 return "direct";
3201 case DEVICE_MODE_UNSCALED:
3202 return "unscaled";
3203 case DEVICE_MODE_NAVIGATION:
3204 return "navigation";
3205 case DEVICE_MODE_POINTER:
3206 return "pointer";
3207 }
3208 return "unknown";
3209}
3210
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211void TouchInputMapper::configure(nsecs_t when,
3212 const InputReaderConfiguration* config, uint32_t changes) {
3213 InputMapper::configure(when, config, changes);
3214
3215 mConfig = *config;
3216
3217 if (!changes) { // first time only
3218 // Configure basic parameters.
3219 configureParameters();
3220
3221 // Configure common accumulators.
3222 mCursorScrollAccumulator.configure(getDevice());
3223 mTouchButtonAccumulator.configure(getDevice());
3224
3225 // Configure absolute axis information.
3226 configureRawPointerAxes();
3227
3228 // Prepare input device calibration.
3229 parseCalibration();
3230 resolveCalibration();
3231 }
3232
Michael Wright842500e2015-03-13 17:32:02 -07003233 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003234 // Update location calibration to reflect current settings
3235 updateAffineTransformation();
3236 }
3237
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3239 // Update pointer speed.
3240 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3241 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3242 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3243 }
3244
3245 bool resetNeeded = false;
3246 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3247 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003248 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3249 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 // Configure device sources, surface dimensions, orientation and
3251 // scaling factors.
3252 configureSurface(when, &resetNeeded);
3253 }
3254
3255 if (changes && resetNeeded) {
3256 // Send reset, unless this is the first time the device has been configured,
3257 // in which case the reader will call reset itself after all mappers are ready.
3258 getDevice()->notifyReset(when);
3259 }
3260}
3261
Michael Wright842500e2015-03-13 17:32:02 -07003262void TouchInputMapper::resolveExternalStylusPresence() {
3263 Vector<InputDeviceInfo> devices;
3264 mContext->getExternalStylusDevices(devices);
3265 mExternalStylusConnected = !devices.isEmpty();
3266
3267 if (!mExternalStylusConnected) {
3268 resetExternalStylus();
3269 }
3270}
3271
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272void TouchInputMapper::configureParameters() {
3273 // Use the pointer presentation mode for devices that do not support distinct
3274 // multitouch. The spot-based presentation relies on being able to accurately
3275 // locate two or more fingers on the touch pad.
3276 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003277 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278
3279 String8 gestureModeString;
3280 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3281 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003282 if (gestureModeString == "single-touch") {
3283 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3284 } else if (gestureModeString == "multi-touch") {
3285 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 } else if (gestureModeString != "default") {
3287 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3288 }
3289 }
3290
3291 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3292 // The device is a touch screen.
3293 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3294 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3295 // The device is a pointing device like a track pad.
3296 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3297 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3298 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3299 // The device is a cursor device with a touch pad attached.
3300 // By default don't use the touch pad to move the pointer.
3301 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3302 } else {
3303 // The device is a touch pad of unknown purpose.
3304 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3305 }
3306
3307 mParameters.hasButtonUnderPad=
3308 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3309
3310 String8 deviceTypeString;
3311 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3312 deviceTypeString)) {
3313 if (deviceTypeString == "touchScreen") {
3314 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3315 } else if (deviceTypeString == "touchPad") {
3316 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3317 } else if (deviceTypeString == "touchNavigation") {
3318 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3319 } else if (deviceTypeString == "pointer") {
3320 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3321 } else if (deviceTypeString != "default") {
3322 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3323 }
3324 }
3325
3326 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3327 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3328 mParameters.orientationAware);
3329
3330 mParameters.hasAssociatedDisplay = false;
3331 mParameters.associatedDisplayIsExternal = false;
3332 if (mParameters.orientationAware
3333 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3334 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3335 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003336 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3337 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003338 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003339 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003340 uniqueDisplayId);
3341 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003344 if (getDevice()->getAssociatedDisplayPort()) {
3345 mParameters.hasAssociatedDisplay = true;
3346 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003347
3348 // Initial downs on external touch devices should wake the device.
3349 // Normally we don't do this for internal touch screens to prevent them from waking
3350 // up in your pocket but you can enable it using the input device configuration.
3351 mParameters.wake = getDevice()->isExternal();
3352 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3353 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354}
3355
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003356void TouchInputMapper::dumpParameters(std::string& dump) {
3357 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358
3359 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003360 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003361 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003363 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003364 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 break;
3366 default:
3367 assert(false);
3368 }
3369
3370 switch (mParameters.deviceType) {
3371 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003372 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 break;
3374 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003375 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 break;
3377 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003378 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 break;
3380 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003381 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 break;
3383 default:
3384 ALOG_ASSERT(false);
3385 }
3386
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003387 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003388 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003390 toString(mParameters.associatedDisplayIsExternal),
3391 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003392 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 toString(mParameters.orientationAware));
3394}
3395
3396void TouchInputMapper::configureRawPointerAxes() {
3397 mRawPointerAxes.clear();
3398}
3399
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003400void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3401 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3403 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3404 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3405 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3406 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3407 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3408 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3409 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3410 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3411 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3412 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3413 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3414 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3415}
3416
Michael Wright842500e2015-03-13 17:32:02 -07003417bool TouchInputMapper::hasExternalStylus() const {
3418 return mExternalStylusConnected;
3419}
3420
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003421/**
3422 * Determine which DisplayViewport to use.
3423 * 1. If display port is specified, return the matching viewport. If matching viewport not
3424 * found, then return.
3425 * 2. If a device has associated display, get the matching viewport by either unique id or by
3426 * the display type (internal or external).
3427 * 3. Otherwise, use a non-display viewport.
3428 */
3429std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3430 if (mParameters.hasAssociatedDisplay) {
3431 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3432 if (displayPort) {
3433 // Find the viewport that contains the same port
3434 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3435 if (!v) {
3436 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3437 "but the corresponding viewport is not found.",
3438 getDeviceName().c_str(), *displayPort);
3439 }
3440 return v;
3441 }
3442
3443 if (!mParameters.uniqueDisplayId.empty()) {
3444 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3445 }
3446
3447 ViewportType viewportTypeToUse;
3448 if (mParameters.associatedDisplayIsExternal) {
3449 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3450 } else {
3451 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3452 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003453
3454 std::optional<DisplayViewport> viewport =
3455 mConfig.getDisplayViewportByType(viewportTypeToUse);
3456 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3457 ALOGW("Input device %s should be associated with external display, "
3458 "fallback to internal one for the external viewport is not found.",
3459 getDeviceName().c_str());
3460 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3461 }
3462
3463 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003464 }
3465
3466 DisplayViewport newViewport;
3467 // Raw width and height in the natural orientation.
3468 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3469 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3470 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3471 return std::make_optional(newViewport);
3472}
3473
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3475 int32_t oldDeviceMode = mDeviceMode;
3476
Michael Wright842500e2015-03-13 17:32:02 -07003477 resolveExternalStylusPresence();
3478
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 // Determine device mode.
3480 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3481 && mConfig.pointerGesturesEnabled) {
3482 mSource = AINPUT_SOURCE_MOUSE;
3483 mDeviceMode = DEVICE_MODE_POINTER;
3484 if (hasStylus()) {
3485 mSource |= AINPUT_SOURCE_STYLUS;
3486 }
3487 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3488 && mParameters.hasAssociatedDisplay) {
3489 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3490 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003491 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 mSource |= AINPUT_SOURCE_STYLUS;
3493 }
Michael Wright2f78b682015-06-12 15:25:08 +01003494 if (hasExternalStylus()) {
3495 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3498 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3499 mDeviceMode = DEVICE_MODE_NAVIGATION;
3500 } else {
3501 mSource = AINPUT_SOURCE_TOUCHPAD;
3502 mDeviceMode = DEVICE_MODE_UNSCALED;
3503 }
3504
3505 // Ensure we have valid X and Y axes.
3506 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003507 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003508 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 mDeviceMode = DEVICE_MODE_DISABLED;
3510 return;
3511 }
3512
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003513 // Get associated display dimensions.
3514 std::optional<DisplayViewport> newViewport = findViewport();
3515 if (!newViewport) {
3516 ALOGI("Touch device '%s' could not query the properties of its associated "
3517 "display. The device will be inoperable until the display size "
3518 "becomes available.",
3519 getDeviceName().c_str());
3520 mDeviceMode = DEVICE_MODE_DISABLED;
3521 return;
3522 }
3523
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003525 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3526 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003528 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003530 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531
3532 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3533 // Convert rotated viewport to natural surface coordinates.
3534 int32_t naturalLogicalWidth, naturalLogicalHeight;
3535 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3536 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3537 int32_t naturalDeviceWidth, naturalDeviceHeight;
3538 switch (mViewport.orientation) {
3539 case DISPLAY_ORIENTATION_90:
3540 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3541 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3542 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3543 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3544 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3545 naturalPhysicalTop = mViewport.physicalLeft;
3546 naturalDeviceWidth = mViewport.deviceHeight;
3547 naturalDeviceHeight = mViewport.deviceWidth;
3548 break;
3549 case DISPLAY_ORIENTATION_180:
3550 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3551 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3552 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3553 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3554 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3555 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3556 naturalDeviceWidth = mViewport.deviceWidth;
3557 naturalDeviceHeight = mViewport.deviceHeight;
3558 break;
3559 case DISPLAY_ORIENTATION_270:
3560 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3561 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3562 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3563 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3564 naturalPhysicalLeft = mViewport.physicalTop;
3565 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3566 naturalDeviceWidth = mViewport.deviceHeight;
3567 naturalDeviceHeight = mViewport.deviceWidth;
3568 break;
3569 case DISPLAY_ORIENTATION_0:
3570 default:
3571 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3572 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3573 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3574 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3575 naturalPhysicalLeft = mViewport.physicalLeft;
3576 naturalPhysicalTop = mViewport.physicalTop;
3577 naturalDeviceWidth = mViewport.deviceWidth;
3578 naturalDeviceHeight = mViewport.deviceHeight;
3579 break;
3580 }
3581
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003582 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3583 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3584 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3585 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3586 }
3587
Michael Wright358bcc72018-08-21 04:01:07 +01003588 mPhysicalWidth = naturalPhysicalWidth;
3589 mPhysicalHeight = naturalPhysicalHeight;
3590 mPhysicalLeft = naturalPhysicalLeft;
3591 mPhysicalTop = naturalPhysicalTop;
3592
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3594 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3595 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3596 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3597
3598 mSurfaceOrientation = mParameters.orientationAware ?
3599 mViewport.orientation : DISPLAY_ORIENTATION_0;
3600 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003601 mPhysicalWidth = rawWidth;
3602 mPhysicalHeight = rawHeight;
3603 mPhysicalLeft = 0;
3604 mPhysicalTop = 0;
3605
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 mSurfaceWidth = rawWidth;
3607 mSurfaceHeight = rawHeight;
3608 mSurfaceLeft = 0;
3609 mSurfaceTop = 0;
3610 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3611 }
3612 }
3613
3614 // If moving between pointer modes, need to reset some state.
3615 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3616 if (deviceModeChanged) {
3617 mOrientedRanges.clear();
3618 }
3619
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003620 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 if (mDeviceMode == DEVICE_MODE_POINTER ||
3622 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003623 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3625 }
3626 } else {
3627 mPointerController.clear();
3628 }
3629
3630 if (viewportChanged || deviceModeChanged) {
3631 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3632 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003633 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3635
3636 // Configure X and Y factors.
3637 mXScale = float(mSurfaceWidth) / rawWidth;
3638 mYScale = float(mSurfaceHeight) / rawHeight;
3639 mXTranslate = -mSurfaceLeft;
3640 mYTranslate = -mSurfaceTop;
3641 mXPrecision = 1.0f / mXScale;
3642 mYPrecision = 1.0f / mYScale;
3643
3644 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3645 mOrientedRanges.x.source = mSource;
3646 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3647 mOrientedRanges.y.source = mSource;
3648
3649 configureVirtualKeys();
3650
3651 // Scale factor for terms that are not oriented in a particular axis.
3652 // If the pixels are square then xScale == yScale otherwise we fake it
3653 // by choosing an average.
3654 mGeometricScale = avg(mXScale, mYScale);
3655
3656 // Size of diagonal axis.
3657 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3658
3659 // Size factors.
3660 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3661 if (mRawPointerAxes.touchMajor.valid
3662 && mRawPointerAxes.touchMajor.maxValue != 0) {
3663 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3664 } else if (mRawPointerAxes.toolMajor.valid
3665 && mRawPointerAxes.toolMajor.maxValue != 0) {
3666 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3667 } else {
3668 mSizeScale = 0.0f;
3669 }
3670
3671 mOrientedRanges.haveTouchSize = true;
3672 mOrientedRanges.haveToolSize = true;
3673 mOrientedRanges.haveSize = true;
3674
3675 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3676 mOrientedRanges.touchMajor.source = mSource;
3677 mOrientedRanges.touchMajor.min = 0;
3678 mOrientedRanges.touchMajor.max = diagonalSize;
3679 mOrientedRanges.touchMajor.flat = 0;
3680 mOrientedRanges.touchMajor.fuzz = 0;
3681 mOrientedRanges.touchMajor.resolution = 0;
3682
3683 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3684 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3685
3686 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3687 mOrientedRanges.toolMajor.source = mSource;
3688 mOrientedRanges.toolMajor.min = 0;
3689 mOrientedRanges.toolMajor.max = diagonalSize;
3690 mOrientedRanges.toolMajor.flat = 0;
3691 mOrientedRanges.toolMajor.fuzz = 0;
3692 mOrientedRanges.toolMajor.resolution = 0;
3693
3694 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3695 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3696
3697 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3698 mOrientedRanges.size.source = mSource;
3699 mOrientedRanges.size.min = 0;
3700 mOrientedRanges.size.max = 1.0;
3701 mOrientedRanges.size.flat = 0;
3702 mOrientedRanges.size.fuzz = 0;
3703 mOrientedRanges.size.resolution = 0;
3704 } else {
3705 mSizeScale = 0.0f;
3706 }
3707
3708 // Pressure factors.
3709 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003710 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3712 || mCalibration.pressureCalibration
3713 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3714 if (mCalibration.havePressureScale) {
3715 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003716 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 } else if (mRawPointerAxes.pressure.valid
3718 && mRawPointerAxes.pressure.maxValue != 0) {
3719 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3720 }
3721 }
3722
3723 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3724 mOrientedRanges.pressure.source = mSource;
3725 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003726 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 mOrientedRanges.pressure.flat = 0;
3728 mOrientedRanges.pressure.fuzz = 0;
3729 mOrientedRanges.pressure.resolution = 0;
3730
3731 // Tilt
3732 mTiltXCenter = 0;
3733 mTiltXScale = 0;
3734 mTiltYCenter = 0;
3735 mTiltYScale = 0;
3736 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3737 if (mHaveTilt) {
3738 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3739 mRawPointerAxes.tiltX.maxValue);
3740 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3741 mRawPointerAxes.tiltY.maxValue);
3742 mTiltXScale = M_PI / 180;
3743 mTiltYScale = M_PI / 180;
3744
3745 mOrientedRanges.haveTilt = true;
3746
3747 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3748 mOrientedRanges.tilt.source = mSource;
3749 mOrientedRanges.tilt.min = 0;
3750 mOrientedRanges.tilt.max = M_PI_2;
3751 mOrientedRanges.tilt.flat = 0;
3752 mOrientedRanges.tilt.fuzz = 0;
3753 mOrientedRanges.tilt.resolution = 0;
3754 }
3755
3756 // Orientation
3757 mOrientationScale = 0;
3758 if (mHaveTilt) {
3759 mOrientedRanges.haveOrientation = true;
3760
3761 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3762 mOrientedRanges.orientation.source = mSource;
3763 mOrientedRanges.orientation.min = -M_PI;
3764 mOrientedRanges.orientation.max = M_PI;
3765 mOrientedRanges.orientation.flat = 0;
3766 mOrientedRanges.orientation.fuzz = 0;
3767 mOrientedRanges.orientation.resolution = 0;
3768 } else if (mCalibration.orientationCalibration !=
3769 Calibration::ORIENTATION_CALIBRATION_NONE) {
3770 if (mCalibration.orientationCalibration
3771 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3772 if (mRawPointerAxes.orientation.valid) {
3773 if (mRawPointerAxes.orientation.maxValue > 0) {
3774 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3775 } else if (mRawPointerAxes.orientation.minValue < 0) {
3776 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3777 } else {
3778 mOrientationScale = 0;
3779 }
3780 }
3781 }
3782
3783 mOrientedRanges.haveOrientation = true;
3784
3785 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3786 mOrientedRanges.orientation.source = mSource;
3787 mOrientedRanges.orientation.min = -M_PI_2;
3788 mOrientedRanges.orientation.max = M_PI_2;
3789 mOrientedRanges.orientation.flat = 0;
3790 mOrientedRanges.orientation.fuzz = 0;
3791 mOrientedRanges.orientation.resolution = 0;
3792 }
3793
3794 // Distance
3795 mDistanceScale = 0;
3796 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3797 if (mCalibration.distanceCalibration
3798 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3799 if (mCalibration.haveDistanceScale) {
3800 mDistanceScale = mCalibration.distanceScale;
3801 } else {
3802 mDistanceScale = 1.0f;
3803 }
3804 }
3805
3806 mOrientedRanges.haveDistance = true;
3807
3808 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3809 mOrientedRanges.distance.source = mSource;
3810 mOrientedRanges.distance.min =
3811 mRawPointerAxes.distance.minValue * mDistanceScale;
3812 mOrientedRanges.distance.max =
3813 mRawPointerAxes.distance.maxValue * mDistanceScale;
3814 mOrientedRanges.distance.flat = 0;
3815 mOrientedRanges.distance.fuzz =
3816 mRawPointerAxes.distance.fuzz * mDistanceScale;
3817 mOrientedRanges.distance.resolution = 0;
3818 }
3819
3820 // Compute oriented precision, scales and ranges.
3821 // Note that the maximum value reported is an inclusive maximum value so it is one
3822 // unit less than the total width or height of surface.
3823 switch (mSurfaceOrientation) {
3824 case DISPLAY_ORIENTATION_90:
3825 case DISPLAY_ORIENTATION_270:
3826 mOrientedXPrecision = mYPrecision;
3827 mOrientedYPrecision = mXPrecision;
3828
3829 mOrientedRanges.x.min = mYTranslate;
3830 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3831 mOrientedRanges.x.flat = 0;
3832 mOrientedRanges.x.fuzz = 0;
3833 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3834
3835 mOrientedRanges.y.min = mXTranslate;
3836 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3837 mOrientedRanges.y.flat = 0;
3838 mOrientedRanges.y.fuzz = 0;
3839 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3840 break;
3841
3842 default:
3843 mOrientedXPrecision = mXPrecision;
3844 mOrientedYPrecision = mYPrecision;
3845
3846 mOrientedRanges.x.min = mXTranslate;
3847 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3848 mOrientedRanges.x.flat = 0;
3849 mOrientedRanges.x.fuzz = 0;
3850 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3851
3852 mOrientedRanges.y.min = mYTranslate;
3853 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3854 mOrientedRanges.y.flat = 0;
3855 mOrientedRanges.y.fuzz = 0;
3856 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3857 break;
3858 }
3859
Jason Gerecke71b16e82014-03-10 09:47:59 -07003860 // Location
3861 updateAffineTransformation();
3862
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 if (mDeviceMode == DEVICE_MODE_POINTER) {
3864 // Compute pointer gesture detection parameters.
3865 float rawDiagonal = hypotf(rawWidth, rawHeight);
3866 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3867
3868 // Scale movements such that one whole swipe of the touch pad covers a
3869 // given area relative to the diagonal size of the display when no acceleration
3870 // is applied.
3871 // Assume that the touch pad has a square aspect ratio such that movements in
3872 // X and Y of the same number of raw units cover the same physical distance.
3873 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3874 * displayDiagonal / rawDiagonal;
3875 mPointerYMovementScale = mPointerXMovementScale;
3876
3877 // Scale zooms to cover a smaller range of the display than movements do.
3878 // This value determines the area around the pointer that is affected by freeform
3879 // pointer gestures.
3880 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3881 * displayDiagonal / rawDiagonal;
3882 mPointerYZoomScale = mPointerXZoomScale;
3883
3884 // Max width between pointers to detect a swipe gesture is more than some fraction
3885 // of the diagonal axis of the touch pad. Touches that are wider than this are
3886 // translated into freeform gestures.
3887 mPointerGestureMaxSwipeWidth =
3888 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3889
3890 // Abort current pointer usages because the state has changed.
3891 abortPointerUsage(when, 0 /*policyFlags*/);
3892 }
3893
3894 // Inform the dispatcher about the changes.
3895 *outResetNeeded = true;
3896 bumpGeneration();
3897 }
3898}
3899
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003900void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003901 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003902 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3903 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3904 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3905 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003906 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3907 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3908 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3909 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003910 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911}
3912
3913void TouchInputMapper::configureVirtualKeys() {
3914 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3915 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3916
3917 mVirtualKeys.clear();
3918
3919 if (virtualKeyDefinitions.size() == 0) {
3920 return;
3921 }
3922
3923 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3924
3925 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3926 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003927 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3928 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929
3930 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3931 const VirtualKeyDefinition& virtualKeyDefinition =
3932 virtualKeyDefinitions[i];
3933
3934 mVirtualKeys.add();
3935 VirtualKey& virtualKey = mVirtualKeys.editTop();
3936
3937 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3938 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003939 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003941 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3942 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3944 virtualKey.scanCode);
3945 mVirtualKeys.pop(); // drop the key
3946 continue;
3947 }
3948
3949 virtualKey.keyCode = keyCode;
3950 virtualKey.flags = flags;
3951
3952 // convert the key definition's display coordinates into touch coordinates for a hit box
3953 int32_t halfWidth = virtualKeyDefinition.width / 2;
3954 int32_t halfHeight = virtualKeyDefinition.height / 2;
3955
3956 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3957 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3958 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3959 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3960 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3961 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3962 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3963 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3964 }
3965}
3966
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003967void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003969 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
3971 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3972 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003973 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3975 i, virtualKey.scanCode, virtualKey.keyCode,
3976 virtualKey.hitLeft, virtualKey.hitRight,
3977 virtualKey.hitTop, virtualKey.hitBottom);
3978 }
3979 }
3980}
3981
3982void TouchInputMapper::parseCalibration() {
3983 const PropertyMap& in = getDevice()->getConfiguration();
3984 Calibration& out = mCalibration;
3985
3986 // Size
3987 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3988 String8 sizeCalibrationString;
3989 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3990 if (sizeCalibrationString == "none") {
3991 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3992 } else if (sizeCalibrationString == "geometric") {
3993 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3994 } else if (sizeCalibrationString == "diameter") {
3995 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3996 } else if (sizeCalibrationString == "box") {
3997 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3998 } else if (sizeCalibrationString == "area") {
3999 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4000 } else if (sizeCalibrationString != "default") {
4001 ALOGW("Invalid value for touch.size.calibration: '%s'",
4002 sizeCalibrationString.string());
4003 }
4004 }
4005
4006 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4007 out.sizeScale);
4008 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4009 out.sizeBias);
4010 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4011 out.sizeIsSummed);
4012
4013 // Pressure
4014 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4015 String8 pressureCalibrationString;
4016 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4017 if (pressureCalibrationString == "none") {
4018 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4019 } else if (pressureCalibrationString == "physical") {
4020 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4021 } else if (pressureCalibrationString == "amplitude") {
4022 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4023 } else if (pressureCalibrationString != "default") {
4024 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4025 pressureCalibrationString.string());
4026 }
4027 }
4028
4029 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4030 out.pressureScale);
4031
4032 // Orientation
4033 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4034 String8 orientationCalibrationString;
4035 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4036 if (orientationCalibrationString == "none") {
4037 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4038 } else if (orientationCalibrationString == "interpolated") {
4039 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4040 } else if (orientationCalibrationString == "vector") {
4041 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4042 } else if (orientationCalibrationString != "default") {
4043 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4044 orientationCalibrationString.string());
4045 }
4046 }
4047
4048 // Distance
4049 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4050 String8 distanceCalibrationString;
4051 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4052 if (distanceCalibrationString == "none") {
4053 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4054 } else if (distanceCalibrationString == "scaled") {
4055 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4056 } else if (distanceCalibrationString != "default") {
4057 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4058 distanceCalibrationString.string());
4059 }
4060 }
4061
4062 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4063 out.distanceScale);
4064
4065 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4066 String8 coverageCalibrationString;
4067 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4068 if (coverageCalibrationString == "none") {
4069 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4070 } else if (coverageCalibrationString == "box") {
4071 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4072 } else if (coverageCalibrationString != "default") {
4073 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4074 coverageCalibrationString.string());
4075 }
4076 }
4077}
4078
4079void TouchInputMapper::resolveCalibration() {
4080 // Size
4081 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4082 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4083 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4084 }
4085 } else {
4086 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4087 }
4088
4089 // Pressure
4090 if (mRawPointerAxes.pressure.valid) {
4091 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4092 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4093 }
4094 } else {
4095 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4096 }
4097
4098 // Orientation
4099 if (mRawPointerAxes.orientation.valid) {
4100 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4101 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4102 }
4103 } else {
4104 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4105 }
4106
4107 // Distance
4108 if (mRawPointerAxes.distance.valid) {
4109 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4110 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4111 }
4112 } else {
4113 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4114 }
4115
4116 // Coverage
4117 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4118 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4119 }
4120}
4121
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004122void TouchInputMapper::dumpCalibration(std::string& dump) {
4123 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124
4125 // Size
4126 switch (mCalibration.sizeCalibration) {
4127 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004128 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 break;
4130 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004131 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 break;
4133 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004134 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 break;
4136 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004137 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 break;
4139 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 break;
4142 default:
4143 ALOG_ASSERT(false);
4144 }
4145
4146 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004147 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 mCalibration.sizeScale);
4149 }
4150
4151 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004152 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 mCalibration.sizeBias);
4154 }
4155
4156 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004157 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 toString(mCalibration.sizeIsSummed));
4159 }
4160
4161 // Pressure
4162 switch (mCalibration.pressureCalibration) {
4163 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 break;
4166 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 break;
4169 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004170 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 break;
4172 default:
4173 ALOG_ASSERT(false);
4174 }
4175
4176 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 mCalibration.pressureScale);
4179 }
4180
4181 // Orientation
4182 switch (mCalibration.orientationCalibration) {
4183 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004184 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 break;
4186 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004187 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 break;
4189 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004190 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 break;
4192 default:
4193 ALOG_ASSERT(false);
4194 }
4195
4196 // Distance
4197 switch (mCalibration.distanceCalibration) {
4198 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004199 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 break;
4201 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004202 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 break;
4204 default:
4205 ALOG_ASSERT(false);
4206 }
4207
4208 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004209 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 mCalibration.distanceScale);
4211 }
4212
4213 switch (mCalibration.coverageCalibration) {
4214 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004215 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 break;
4217 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004218 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 break;
4220 default:
4221 ALOG_ASSERT(false);
4222 }
4223}
4224
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4226 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004227
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004228 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4229 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4230 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4231 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4232 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4233 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004234}
4235
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004236void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004237 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4238 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004239}
4240
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241void TouchInputMapper::reset(nsecs_t when) {
4242 mCursorButtonAccumulator.reset(getDevice());
4243 mCursorScrollAccumulator.reset(getDevice());
4244 mTouchButtonAccumulator.reset(getDevice());
4245
4246 mPointerVelocityControl.reset();
4247 mWheelXVelocityControl.reset();
4248 mWheelYVelocityControl.reset();
4249
Michael Wright842500e2015-03-13 17:32:02 -07004250 mRawStatesPending.clear();
4251 mCurrentRawState.clear();
4252 mCurrentCookedState.clear();
4253 mLastRawState.clear();
4254 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 mPointerUsage = POINTER_USAGE_NONE;
4256 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004257 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004258 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 mDownTime = 0;
4260
4261 mCurrentVirtualKey.down = false;
4262
4263 mPointerGesture.reset();
4264 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004265 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
Yi Kong9b14ac62018-07-17 13:48:38 -07004267 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4269 mPointerController->clearSpots();
4270 }
4271
4272 InputMapper::reset(when);
4273}
4274
Michael Wright842500e2015-03-13 17:32:02 -07004275void TouchInputMapper::resetExternalStylus() {
4276 mExternalStylusState.clear();
4277 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004278 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004279 mExternalStylusDataPending = false;
4280}
4281
Michael Wright43fd19f2015-04-21 19:02:58 +01004282void TouchInputMapper::clearStylusDataPendingFlags() {
4283 mExternalStylusDataPending = false;
4284 mExternalStylusFusionTimeout = LLONG_MAX;
4285}
4286
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287void TouchInputMapper::process(const RawEvent* rawEvent) {
4288 mCursorButtonAccumulator.process(rawEvent);
4289 mCursorScrollAccumulator.process(rawEvent);
4290 mTouchButtonAccumulator.process(rawEvent);
4291
4292 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4293 sync(rawEvent->when);
4294 }
4295}
4296
4297void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004298 const RawState* last = mRawStatesPending.isEmpty() ?
4299 &mCurrentRawState : &mRawStatesPending.top();
4300
4301 // Push a new state.
4302 mRawStatesPending.push();
4303 RawState* next = &mRawStatesPending.editTop();
4304 next->clear();
4305 next->when = when;
4306
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004308 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 | mCursorButtonAccumulator.getButtonState();
4310
Michael Wright842500e2015-03-13 17:32:02 -07004311 // Sync scroll
4312 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4313 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 mCursorScrollAccumulator.finishSync();
4315
Michael Wright842500e2015-03-13 17:32:02 -07004316 // Sync touch
4317 syncTouch(when, next);
4318
4319 // Assign pointer ids.
4320 if (!mHavePointerIds) {
4321 assignPointerIds(last, next);
4322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323
4324#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004325 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4326 "hovering ids 0x%08x -> 0x%08x",
4327 last->rawPointerData.pointerCount,
4328 next->rawPointerData.pointerCount,
4329 last->rawPointerData.touchingIdBits.value,
4330 next->rawPointerData.touchingIdBits.value,
4331 last->rawPointerData.hoveringIdBits.value,
4332 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333#endif
4334
Michael Wright842500e2015-03-13 17:32:02 -07004335 processRawTouches(false /*timeout*/);
4336}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337
Michael Wright842500e2015-03-13 17:32:02 -07004338void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4340 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004341 mCurrentRawState.clear();
4342 mRawStatesPending.clear();
4343 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 }
4345
Michael Wright842500e2015-03-13 17:32:02 -07004346 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4347 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4348 // touching the current state will only observe the events that have been dispatched to the
4349 // rest of the pipeline.
4350 const size_t N = mRawStatesPending.size();
4351 size_t count;
4352 for(count = 0; count < N; count++) {
4353 const RawState& next = mRawStatesPending[count];
4354
4355 // A failure to assign the stylus id means that we're waiting on stylus data
4356 // and so should defer the rest of the pipeline.
4357 if (assignExternalStylusId(next, timeout)) {
4358 break;
4359 }
4360
4361 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004362 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004363 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004364 if (mCurrentRawState.when < mLastRawState.when) {
4365 mCurrentRawState.when = mLastRawState.when;
4366 }
Michael Wright842500e2015-03-13 17:32:02 -07004367 cookAndDispatch(mCurrentRawState.when);
4368 }
4369 if (count != 0) {
4370 mRawStatesPending.removeItemsAt(0, count);
4371 }
4372
Michael Wright842500e2015-03-13 17:32:02 -07004373 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004374 if (timeout) {
4375 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4376 clearStylusDataPendingFlags();
4377 mCurrentRawState.copyFrom(mLastRawState);
4378#if DEBUG_STYLUS_FUSION
4379 ALOGD("Timeout expired, synthesizing event with new stylus data");
4380#endif
4381 cookAndDispatch(when);
4382 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4383 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4384 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4385 }
Michael Wright842500e2015-03-13 17:32:02 -07004386 }
4387}
4388
4389void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4390 // Always start with a clean state.
4391 mCurrentCookedState.clear();
4392
4393 // Apply stylus buttons to current raw state.
4394 applyExternalStylusButtonState(when);
4395
4396 // Handle policy on initial down or hover events.
4397 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4398 && mCurrentRawState.rawPointerData.pointerCount != 0;
4399
4400 uint32_t policyFlags = 0;
4401 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4402 if (initialDown || buttonsPressed) {
4403 // If this is a touch screen, hide the pointer on an initial down.
4404 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4405 getContext()->fadePointer();
4406 }
4407
4408 if (mParameters.wake) {
4409 policyFlags |= POLICY_FLAG_WAKE;
4410 }
4411 }
4412
4413 // Consume raw off-screen touches before cooking pointer data.
4414 // If touches are consumed, subsequent code will not receive any pointer data.
4415 if (consumeRawTouches(when, policyFlags)) {
4416 mCurrentRawState.rawPointerData.clear();
4417 }
4418
4419 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4420 // with cooked pointer data that has the same ids and indices as the raw data.
4421 // The following code can use either the raw or cooked data, as needed.
4422 cookPointerData();
4423
4424 // Apply stylus pressure to current cooked state.
4425 applyExternalStylusTouchState(when);
4426
4427 // Synthesize key down from raw buttons if needed.
4428 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004429 mViewport.displayId, policyFlags,
4430 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004431
4432 // Dispatch the touches either directly or by translation through a pointer on screen.
4433 if (mDeviceMode == DEVICE_MODE_POINTER) {
4434 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4435 !idBits.isEmpty(); ) {
4436 uint32_t id = idBits.clearFirstMarkedBit();
4437 const RawPointerData::Pointer& pointer =
4438 mCurrentRawState.rawPointerData.pointerForId(id);
4439 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4440 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4441 mCurrentCookedState.stylusIdBits.markBit(id);
4442 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4443 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4444 mCurrentCookedState.fingerIdBits.markBit(id);
4445 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4446 mCurrentCookedState.mouseIdBits.markBit(id);
4447 }
4448 }
4449 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4450 !idBits.isEmpty(); ) {
4451 uint32_t id = idBits.clearFirstMarkedBit();
4452 const RawPointerData::Pointer& pointer =
4453 mCurrentRawState.rawPointerData.pointerForId(id);
4454 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4455 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4456 mCurrentCookedState.stylusIdBits.markBit(id);
4457 }
4458 }
4459
4460 // Stylus takes precedence over all tools, then mouse, then finger.
4461 PointerUsage pointerUsage = mPointerUsage;
4462 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4463 mCurrentCookedState.mouseIdBits.clear();
4464 mCurrentCookedState.fingerIdBits.clear();
4465 pointerUsage = POINTER_USAGE_STYLUS;
4466 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4467 mCurrentCookedState.fingerIdBits.clear();
4468 pointerUsage = POINTER_USAGE_MOUSE;
4469 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4470 isPointerDown(mCurrentRawState.buttonState)) {
4471 pointerUsage = POINTER_USAGE_GESTURES;
4472 }
4473
4474 dispatchPointerUsage(when, policyFlags, pointerUsage);
4475 } else {
4476 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004477 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004478 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4479 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4480
4481 mPointerController->setButtonState(mCurrentRawState.buttonState);
4482 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4483 mCurrentCookedState.cookedPointerData.idToIndex,
4484 mCurrentCookedState.cookedPointerData.touchingIdBits);
4485 }
4486
Michael Wright8e812822015-06-22 16:18:21 +01004487 if (!mCurrentMotionAborted) {
4488 dispatchButtonRelease(when, policyFlags);
4489 dispatchHoverExit(when, policyFlags);
4490 dispatchTouches(when, policyFlags);
4491 dispatchHoverEnterAndMove(when, policyFlags);
4492 dispatchButtonPress(when, policyFlags);
4493 }
4494
4495 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4496 mCurrentMotionAborted = false;
4497 }
Michael Wright842500e2015-03-13 17:32:02 -07004498 }
4499
4500 // Synthesize key up from raw buttons if needed.
4501 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004502 mViewport.displayId, policyFlags,
4503 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504
4505 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004506 mCurrentRawState.rawVScroll = 0;
4507 mCurrentRawState.rawHScroll = 0;
4508
4509 // Copy current touch to last touch in preparation for the next cycle.
4510 mLastRawState.copyFrom(mCurrentRawState);
4511 mLastCookedState.copyFrom(mCurrentCookedState);
4512}
4513
4514void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004515 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004516 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4517 }
4518}
4519
4520void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004521 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4522 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004523
Michael Wright53dca3a2015-04-23 17:39:53 +01004524 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4525 float pressure = mExternalStylusState.pressure;
4526 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4527 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4528 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4529 }
4530 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4531 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4532
4533 PointerProperties& properties =
4534 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004535 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4536 properties.toolType = mExternalStylusState.toolType;
4537 }
4538 }
4539}
4540
4541bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4542 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4543 return false;
4544 }
4545
4546 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4547 && state.rawPointerData.pointerCount != 0;
4548 if (initialDown) {
4549 if (mExternalStylusState.pressure != 0.0f) {
4550#if DEBUG_STYLUS_FUSION
4551 ALOGD("Have both stylus and touch data, beginning fusion");
4552#endif
4553 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4554 } else if (timeout) {
4555#if DEBUG_STYLUS_FUSION
4556 ALOGD("Timeout expired, assuming touch is not a stylus.");
4557#endif
4558 resetExternalStylus();
4559 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004560 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4561 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004562 }
4563#if DEBUG_STYLUS_FUSION
4564 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004565 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004566#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004567 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004568 return true;
4569 }
4570 }
4571
4572 // Check if the stylus pointer has gone up.
4573 if (mExternalStylusId != -1 &&
4574 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4575#if DEBUG_STYLUS_FUSION
4576 ALOGD("Stylus pointer is going up");
4577#endif
4578 mExternalStylusId = -1;
4579 }
4580
4581 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582}
4583
4584void TouchInputMapper::timeoutExpired(nsecs_t when) {
4585 if (mDeviceMode == DEVICE_MODE_POINTER) {
4586 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4587 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4588 }
Michael Wright842500e2015-03-13 17:32:02 -07004589 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004590 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004591 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004592 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4593 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004594 }
4595 }
4596}
4597
4598void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004599 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004600 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004601 // We're either in the middle of a fused stream of data or we're waiting on data before
4602 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4603 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004604 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004605 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606 }
4607}
4608
4609bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4610 // Check for release of a virtual key.
4611 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004612 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 // Pointer went up while virtual key was down.
4614 mCurrentVirtualKey.down = false;
4615 if (!mCurrentVirtualKey.ignored) {
4616#if DEBUG_VIRTUAL_KEYS
4617 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4618 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4619#endif
4620 dispatchVirtualKey(when, policyFlags,
4621 AKEY_EVENT_ACTION_UP,
4622 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4623 }
4624 return true;
4625 }
4626
Michael Wright842500e2015-03-13 17:32:02 -07004627 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4628 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4629 const RawPointerData::Pointer& pointer =
4630 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4632 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4633 // Pointer is still within the space of the virtual key.
4634 return true;
4635 }
4636 }
4637
4638 // Pointer left virtual key area or another pointer also went down.
4639 // Send key cancellation but do not consume the touch yet.
4640 // This is useful when the user swipes through from the virtual key area
4641 // into the main display surface.
4642 mCurrentVirtualKey.down = false;
4643 if (!mCurrentVirtualKey.ignored) {
4644#if DEBUG_VIRTUAL_KEYS
4645 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4646 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4647#endif
4648 dispatchVirtualKey(when, policyFlags,
4649 AKEY_EVENT_ACTION_UP,
4650 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4651 | AKEY_EVENT_FLAG_CANCELED);
4652 }
4653 }
4654
Michael Wright842500e2015-03-13 17:32:02 -07004655 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4656 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004658 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4659 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4661 // If exactly one pointer went down, check for virtual key hit.
4662 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004663 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4665 if (virtualKey) {
4666 mCurrentVirtualKey.down = true;
4667 mCurrentVirtualKey.downTime = when;
4668 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4669 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4670 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4671 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4672
4673 if (!mCurrentVirtualKey.ignored) {
4674#if DEBUG_VIRTUAL_KEYS
4675 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4676 mCurrentVirtualKey.keyCode,
4677 mCurrentVirtualKey.scanCode);
4678#endif
4679 dispatchVirtualKey(when, policyFlags,
4680 AKEY_EVENT_ACTION_DOWN,
4681 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4682 }
4683 }
4684 }
4685 return true;
4686 }
4687 }
4688
4689 // Disable all virtual key touches that happen within a short time interval of the
4690 // most recent touch within the screen area. The idea is to filter out stray
4691 // virtual key presses when interacting with the touch screen.
4692 //
4693 // Problems we're trying to solve:
4694 //
4695 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4696 // virtual key area that is implemented by a separate touch panel and accidentally
4697 // triggers a virtual key.
4698 //
4699 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4700 // area and accidentally triggers a virtual key. This often happens when virtual keys
4701 // are layed out below the screen near to where the on screen keyboard's space bar
4702 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004703 if (mConfig.virtualKeyQuietTime > 0 &&
4704 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4706 }
4707 return false;
4708}
4709
4710void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4711 int32_t keyEventAction, int32_t keyEventFlags) {
4712 int32_t keyCode = mCurrentVirtualKey.keyCode;
4713 int32_t scanCode = mCurrentVirtualKey.scanCode;
4714 nsecs_t downTime = mCurrentVirtualKey.downTime;
4715 int32_t metaState = mContext->getGlobalMetaState();
4716 policyFlags |= POLICY_FLAG_VIRTUAL;
4717
Prabir Pradhan42611e02018-11-27 14:04:02 -08004718 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4719 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004720 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 getListener()->notifyKey(&args);
4722}
4723
Michael Wright8e812822015-06-22 16:18:21 +01004724void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4725 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4726 if (!currentIdBits.isEmpty()) {
4727 int32_t metaState = getContext()->getGlobalMetaState();
4728 int32_t buttonState = mCurrentCookedState.buttonState;
4729 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4730 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004731 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004732 mCurrentCookedState.cookedPointerData.pointerProperties,
4733 mCurrentCookedState.cookedPointerData.pointerCoords,
4734 mCurrentCookedState.cookedPointerData.idToIndex,
4735 currentIdBits, -1,
4736 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4737 mCurrentMotionAborted = true;
4738 }
4739}
4740
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004742 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4743 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004745 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746
4747 if (currentIdBits == lastIdBits) {
4748 if (!currentIdBits.isEmpty()) {
4749 // No pointer id changes so this is a move event.
4750 // The listener takes care of batching moves so we don't have to deal with that here.
4751 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004752 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004754 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004755 mCurrentCookedState.cookedPointerData.pointerProperties,
4756 mCurrentCookedState.cookedPointerData.pointerCoords,
4757 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 currentIdBits, -1,
4759 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4760 }
4761 } else {
4762 // There may be pointers going up and pointers going down and pointers moving
4763 // all at the same time.
4764 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4765 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4766 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4767 BitSet32 dispatchedIdBits(lastIdBits.value);
4768
4769 // Update last coordinates of pointers that have moved so that we observe the new
4770 // pointer positions at the same time as other pointers that have just gone up.
4771 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004772 mCurrentCookedState.cookedPointerData.pointerProperties,
4773 mCurrentCookedState.cookedPointerData.pointerCoords,
4774 mCurrentCookedState.cookedPointerData.idToIndex,
4775 mLastCookedState.cookedPointerData.pointerProperties,
4776 mLastCookedState.cookedPointerData.pointerCoords,
4777 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004779 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 moveNeeded = true;
4781 }
4782
4783 // Dispatch pointer up events.
4784 while (!upIdBits.isEmpty()) {
4785 uint32_t upId = upIdBits.clearFirstMarkedBit();
4786
4787 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004788 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004789 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004790 mLastCookedState.cookedPointerData.pointerProperties,
4791 mLastCookedState.cookedPointerData.pointerCoords,
4792 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004793 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 dispatchedIdBits.clearBit(upId);
4795 }
4796
4797 // Dispatch move events if any of the remaining pointers moved from their old locations.
4798 // Although applications receive new locations as part of individual pointer up
4799 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004800 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4802 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004803 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004804 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004805 mCurrentCookedState.cookedPointerData.pointerProperties,
4806 mCurrentCookedState.cookedPointerData.pointerCoords,
4807 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004808 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 }
4810
4811 // Dispatch pointer down events using the new pointer locations.
4812 while (!downIdBits.isEmpty()) {
4813 uint32_t downId = downIdBits.clearFirstMarkedBit();
4814 dispatchedIdBits.markBit(downId);
4815
4816 if (dispatchedIdBits.count() == 1) {
4817 // First pointer is going down. Set down time.
4818 mDownTime = when;
4819 }
4820
4821 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004822 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004823 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004824 mCurrentCookedState.cookedPointerData.pointerProperties,
4825 mCurrentCookedState.cookedPointerData.pointerCoords,
4826 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004827 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 }
4829 }
4830}
4831
4832void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4833 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004834 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4835 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 int32_t metaState = getContext()->getGlobalMetaState();
4837 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004838 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004839 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004840 mLastCookedState.cookedPointerData.pointerProperties,
4841 mLastCookedState.cookedPointerData.pointerCoords,
4842 mLastCookedState.cookedPointerData.idToIndex,
4843 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4845 mSentHoverEnter = false;
4846 }
4847}
4848
4849void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004850 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4851 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 int32_t metaState = getContext()->getGlobalMetaState();
4853 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004854 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004855 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004856 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004857 mCurrentCookedState.cookedPointerData.pointerProperties,
4858 mCurrentCookedState.cookedPointerData.pointerCoords,
4859 mCurrentCookedState.cookedPointerData.idToIndex,
4860 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4862 mSentHoverEnter = true;
4863 }
4864
4865 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004866 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004867 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004868 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004869 mCurrentCookedState.cookedPointerData.pointerProperties,
4870 mCurrentCookedState.cookedPointerData.pointerCoords,
4871 mCurrentCookedState.cookedPointerData.idToIndex,
4872 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4874 }
4875}
4876
Michael Wright7b159c92015-05-14 14:48:03 +01004877void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4878 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4879 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4880 const int32_t metaState = getContext()->getGlobalMetaState();
4881 int32_t buttonState = mLastCookedState.buttonState;
4882 while (!releasedButtons.isEmpty()) {
4883 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4884 buttonState &= ~actionButton;
4885 dispatchMotion(when, policyFlags, mSource,
4886 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4887 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004888 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004889 mCurrentCookedState.cookedPointerData.pointerProperties,
4890 mCurrentCookedState.cookedPointerData.pointerCoords,
4891 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4892 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4893 }
4894}
4895
4896void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4897 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4898 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4899 const int32_t metaState = getContext()->getGlobalMetaState();
4900 int32_t buttonState = mLastCookedState.buttonState;
4901 while (!pressedButtons.isEmpty()) {
4902 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4903 buttonState |= actionButton;
4904 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4905 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004906 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004907 mCurrentCookedState.cookedPointerData.pointerProperties,
4908 mCurrentCookedState.cookedPointerData.pointerCoords,
4909 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4910 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4911 }
4912}
4913
4914const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4915 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4916 return cookedPointerData.touchingIdBits;
4917 }
4918 return cookedPointerData.hoveringIdBits;
4919}
4920
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004922 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923
Michael Wright842500e2015-03-13 17:32:02 -07004924 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004925 mCurrentCookedState.deviceTimestamp =
4926 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004927 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4928 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4929 mCurrentRawState.rawPointerData.hoveringIdBits;
4930 mCurrentCookedState.cookedPointerData.touchingIdBits =
4931 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932
Michael Wright7b159c92015-05-14 14:48:03 +01004933 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4934 mCurrentCookedState.buttonState = 0;
4935 } else {
4936 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4937 }
4938
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939 // Walk through the the active pointers and map device coordinates onto
4940 // surface coordinates and adjust for display orientation.
4941 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004942 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943
4944 // Size
4945 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4946 switch (mCalibration.sizeCalibration) {
4947 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4948 case Calibration::SIZE_CALIBRATION_DIAMETER:
4949 case Calibration::SIZE_CALIBRATION_BOX:
4950 case Calibration::SIZE_CALIBRATION_AREA:
4951 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4952 touchMajor = in.touchMajor;
4953 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4954 toolMajor = in.toolMajor;
4955 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4956 size = mRawPointerAxes.touchMinor.valid
4957 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4958 } else if (mRawPointerAxes.touchMajor.valid) {
4959 toolMajor = touchMajor = in.touchMajor;
4960 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4961 ? in.touchMinor : in.touchMajor;
4962 size = mRawPointerAxes.touchMinor.valid
4963 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4964 } else if (mRawPointerAxes.toolMajor.valid) {
4965 touchMajor = toolMajor = in.toolMajor;
4966 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4967 ? in.toolMinor : in.toolMajor;
4968 size = mRawPointerAxes.toolMinor.valid
4969 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4970 } else {
4971 ALOG_ASSERT(false, "No touch or tool axes. "
4972 "Size calibration should have been resolved to NONE.");
4973 touchMajor = 0;
4974 touchMinor = 0;
4975 toolMajor = 0;
4976 toolMinor = 0;
4977 size = 0;
4978 }
4979
4980 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004981 uint32_t touchingCount =
4982 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983 if (touchingCount > 1) {
4984 touchMajor /= touchingCount;
4985 touchMinor /= touchingCount;
4986 toolMajor /= touchingCount;
4987 toolMinor /= touchingCount;
4988 size /= touchingCount;
4989 }
4990 }
4991
4992 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4993 touchMajor *= mGeometricScale;
4994 touchMinor *= mGeometricScale;
4995 toolMajor *= mGeometricScale;
4996 toolMinor *= mGeometricScale;
4997 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4998 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4999 touchMinor = touchMajor;
5000 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5001 toolMinor = toolMajor;
5002 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5003 touchMinor = touchMajor;
5004 toolMinor = toolMajor;
5005 }
5006
5007 mCalibration.applySizeScaleAndBias(&touchMajor);
5008 mCalibration.applySizeScaleAndBias(&touchMinor);
5009 mCalibration.applySizeScaleAndBias(&toolMajor);
5010 mCalibration.applySizeScaleAndBias(&toolMinor);
5011 size *= mSizeScale;
5012 break;
5013 default:
5014 touchMajor = 0;
5015 touchMinor = 0;
5016 toolMajor = 0;
5017 toolMinor = 0;
5018 size = 0;
5019 break;
5020 }
5021
5022 // Pressure
5023 float pressure;
5024 switch (mCalibration.pressureCalibration) {
5025 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5026 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5027 pressure = in.pressure * mPressureScale;
5028 break;
5029 default:
5030 pressure = in.isHovering ? 0 : 1;
5031 break;
5032 }
5033
5034 // Tilt and Orientation
5035 float tilt;
5036 float orientation;
5037 if (mHaveTilt) {
5038 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5039 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5040 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5041 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5042 } else {
5043 tilt = 0;
5044
5045 switch (mCalibration.orientationCalibration) {
5046 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5047 orientation = in.orientation * mOrientationScale;
5048 break;
5049 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5050 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5051 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5052 if (c1 != 0 || c2 != 0) {
5053 orientation = atan2f(c1, c2) * 0.5f;
5054 float confidence = hypotf(c1, c2);
5055 float scale = 1.0f + confidence / 16.0f;
5056 touchMajor *= scale;
5057 touchMinor /= scale;
5058 toolMajor *= scale;
5059 toolMinor /= scale;
5060 } else {
5061 orientation = 0;
5062 }
5063 break;
5064 }
5065 default:
5066 orientation = 0;
5067 }
5068 }
5069
5070 // Distance
5071 float distance;
5072 switch (mCalibration.distanceCalibration) {
5073 case Calibration::DISTANCE_CALIBRATION_SCALED:
5074 distance = in.distance * mDistanceScale;
5075 break;
5076 default:
5077 distance = 0;
5078 }
5079
5080 // Coverage
5081 int32_t rawLeft, rawTop, rawRight, rawBottom;
5082 switch (mCalibration.coverageCalibration) {
5083 case Calibration::COVERAGE_CALIBRATION_BOX:
5084 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5085 rawRight = in.toolMinor & 0x0000ffff;
5086 rawBottom = in.toolMajor & 0x0000ffff;
5087 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5088 break;
5089 default:
5090 rawLeft = rawTop = rawRight = rawBottom = 0;
5091 break;
5092 }
5093
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005094 // Adjust X,Y coords for device calibration
5095 // TODO: Adjust coverage coords?
5096 float xTransformed = in.x, yTransformed = in.y;
5097 mAffineTransform.applyTo(xTransformed, yTransformed);
5098
5099 // Adjust X, Y, and coverage coords for surface orientation.
5100 float x, y;
5101 float left, top, right, bottom;
5102
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 switch (mSurfaceOrientation) {
5104 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005105 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5106 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5108 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5109 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5110 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5111 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005112 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5114 }
5115 break;
5116 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005117 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005118 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005119 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5120 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5122 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5123 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005124 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5126 }
5127 break;
5128 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005129 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005130 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005131 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5132 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5134 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5135 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005136 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5138 }
5139 break;
5140 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005141 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5142 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5144 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5145 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5146 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5147 break;
5148 }
5149
5150 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005151 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 out.clear();
5153 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5154 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5155 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5156 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5157 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5158 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5159 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5160 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5161 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5162 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5163 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5164 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5165 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5166 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5167 } else {
5168 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5169 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5170 }
5171
5172 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005173 PointerProperties& properties =
5174 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 uint32_t id = in.id;
5176 properties.clear();
5177 properties.id = id;
5178 properties.toolType = in.toolType;
5179
5180 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005181 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 }
5183}
5184
5185void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5186 PointerUsage pointerUsage) {
5187 if (pointerUsage != mPointerUsage) {
5188 abortPointerUsage(when, policyFlags);
5189 mPointerUsage = pointerUsage;
5190 }
5191
5192 switch (mPointerUsage) {
5193 case POINTER_USAGE_GESTURES:
5194 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5195 break;
5196 case POINTER_USAGE_STYLUS:
5197 dispatchPointerStylus(when, policyFlags);
5198 break;
5199 case POINTER_USAGE_MOUSE:
5200 dispatchPointerMouse(when, policyFlags);
5201 break;
5202 default:
5203 break;
5204 }
5205}
5206
5207void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5208 switch (mPointerUsage) {
5209 case POINTER_USAGE_GESTURES:
5210 abortPointerGestures(when, policyFlags);
5211 break;
5212 case POINTER_USAGE_STYLUS:
5213 abortPointerStylus(when, policyFlags);
5214 break;
5215 case POINTER_USAGE_MOUSE:
5216 abortPointerMouse(when, policyFlags);
5217 break;
5218 default:
5219 break;
5220 }
5221
5222 mPointerUsage = POINTER_USAGE_NONE;
5223}
5224
5225void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5226 bool isTimeout) {
5227 // Update current gesture coordinates.
5228 bool cancelPreviousGesture, finishPreviousGesture;
5229 bool sendEvents = preparePointerGestures(when,
5230 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5231 if (!sendEvents) {
5232 return;
5233 }
5234 if (finishPreviousGesture) {
5235 cancelPreviousGesture = false;
5236 }
5237
5238 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005239 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5240 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 if (finishPreviousGesture || cancelPreviousGesture) {
5242 mPointerController->clearSpots();
5243 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005244
5245 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5246 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5247 mPointerGesture.currentGestureIdToIndex,
5248 mPointerGesture.currentGestureIdBits);
5249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 } else {
5251 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5252 }
5253
5254 // Show or hide the pointer if needed.
5255 switch (mPointerGesture.currentGestureMode) {
5256 case PointerGesture::NEUTRAL:
5257 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005258 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5259 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 // Remind the user of where the pointer is after finishing a gesture with spots.
5261 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5262 }
5263 break;
5264 case PointerGesture::TAP:
5265 case PointerGesture::TAP_DRAG:
5266 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5267 case PointerGesture::HOVER:
5268 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005269 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270 // Unfade the pointer when the current gesture manipulates the
5271 // area directly under the pointer.
5272 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5273 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 case PointerGesture::FREEFORM:
5275 // Fade the pointer when the current gesture manipulates a different
5276 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005277 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5279 } else {
5280 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5281 }
5282 break;
5283 }
5284
5285 // Send events!
5286 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005287 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288
5289 // Update last coordinates of pointers that have moved so that we observe the new
5290 // pointer positions at the same time as other pointers that have just gone up.
5291 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5292 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5293 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5294 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5295 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5296 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5297 bool moveNeeded = false;
5298 if (down && !cancelPreviousGesture && !finishPreviousGesture
5299 && !mPointerGesture.lastGestureIdBits.isEmpty()
5300 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5301 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5302 & mPointerGesture.lastGestureIdBits.value);
5303 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5304 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5305 mPointerGesture.lastGestureProperties,
5306 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5307 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005308 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 moveNeeded = true;
5310 }
5311 }
5312
5313 // Send motion events for all pointers that went up or were canceled.
5314 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5315 if (!dispatchedGestureIdBits.isEmpty()) {
5316 if (cancelPreviousGesture) {
5317 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005318 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005319 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 mPointerGesture.lastGestureProperties,
5321 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005322 dispatchedGestureIdBits, -1, 0,
5323 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324
5325 dispatchedGestureIdBits.clear();
5326 } else {
5327 BitSet32 upGestureIdBits;
5328 if (finishPreviousGesture) {
5329 upGestureIdBits = dispatchedGestureIdBits;
5330 } else {
5331 upGestureIdBits.value = dispatchedGestureIdBits.value
5332 & ~mPointerGesture.currentGestureIdBits.value;
5333 }
5334 while (!upGestureIdBits.isEmpty()) {
5335 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5336
5337 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005338 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005340 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 mPointerGesture.lastGestureProperties,
5342 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5343 dispatchedGestureIdBits, id,
5344 0, 0, mPointerGesture.downTime);
5345
5346 dispatchedGestureIdBits.clearBit(id);
5347 }
5348 }
5349 }
5350
5351 // Send motion events for all pointers that moved.
5352 if (moveNeeded) {
5353 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005354 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005355 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356 mPointerGesture.currentGestureProperties,
5357 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5358 dispatchedGestureIdBits, -1,
5359 0, 0, mPointerGesture.downTime);
5360 }
5361
5362 // Send motion events for all pointers that went down.
5363 if (down) {
5364 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5365 & ~dispatchedGestureIdBits.value);
5366 while (!downGestureIdBits.isEmpty()) {
5367 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5368 dispatchedGestureIdBits.markBit(id);
5369
5370 if (dispatchedGestureIdBits.count() == 1) {
5371 mPointerGesture.downTime = when;
5372 }
5373
5374 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005375 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005376 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 mPointerGesture.currentGestureProperties,
5378 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5379 dispatchedGestureIdBits, id,
5380 0, 0, mPointerGesture.downTime);
5381 }
5382 }
5383
5384 // Send motion events for hover.
5385 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5386 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005387 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005388 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 mPointerGesture.currentGestureProperties,
5390 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5391 mPointerGesture.currentGestureIdBits, -1,
5392 0, 0, mPointerGesture.downTime);
5393 } else if (dispatchedGestureIdBits.isEmpty()
5394 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5395 // Synthesize a hover move event after all pointers go up to indicate that
5396 // the pointer is hovering again even if the user is not currently touching
5397 // the touch pad. This ensures that a view will receive a fresh hover enter
5398 // event after a tap.
5399 float x, y;
5400 mPointerController->getPosition(&x, &y);
5401
5402 PointerProperties pointerProperties;
5403 pointerProperties.clear();
5404 pointerProperties.id = 0;
5405 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5406
5407 PointerCoords pointerCoords;
5408 pointerCoords.clear();
5409 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5410 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5411
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005412 const int32_t displayId = mPointerController->getDisplayId();
Dan Harmsaca28402018-12-17 13:55:20 -08005413 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005414 mSource, displayId, policyFlags,
Dan Harmsaca28402018-12-17 13:55:20 -08005415 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005417 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08005418 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 getListener()->notifyMotion(&args);
5420 }
5421
5422 // Update state.
5423 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5424 if (!down) {
5425 mPointerGesture.lastGestureIdBits.clear();
5426 } else {
5427 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5428 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5429 uint32_t id = idBits.clearFirstMarkedBit();
5430 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5431 mPointerGesture.lastGestureProperties[index].copyFrom(
5432 mPointerGesture.currentGestureProperties[index]);
5433 mPointerGesture.lastGestureCoords[index].copyFrom(
5434 mPointerGesture.currentGestureCoords[index]);
5435 mPointerGesture.lastGestureIdToIndex[id] = index;
5436 }
5437 }
5438}
5439
5440void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5441 // Cancel previously dispatches pointers.
5442 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5443 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005444 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005446 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005447 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 mPointerGesture.lastGestureProperties,
5449 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5450 mPointerGesture.lastGestureIdBits, -1,
5451 0, 0, mPointerGesture.downTime);
5452 }
5453
5454 // Reset the current pointer gesture.
5455 mPointerGesture.reset();
5456 mPointerVelocityControl.reset();
5457
5458 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005459 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5461 mPointerController->clearSpots();
5462 }
5463}
5464
5465bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5466 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5467 *outCancelPreviousGesture = false;
5468 *outFinishPreviousGesture = false;
5469
5470 // Handle TAP timeout.
5471 if (isTimeout) {
5472#if DEBUG_GESTURES
5473 ALOGD("Gestures: Processing timeout");
5474#endif
5475
5476 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5477 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5478 // The tap/drag timeout has not yet expired.
5479 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5480 + mConfig.pointerGestureTapDragInterval);
5481 } else {
5482 // The tap is finished.
5483#if DEBUG_GESTURES
5484 ALOGD("Gestures: TAP finished");
5485#endif
5486 *outFinishPreviousGesture = true;
5487
5488 mPointerGesture.activeGestureId = -1;
5489 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5490 mPointerGesture.currentGestureIdBits.clear();
5491
5492 mPointerVelocityControl.reset();
5493 return true;
5494 }
5495 }
5496
5497 // We did not handle this timeout.
5498 return false;
5499 }
5500
Michael Wright842500e2015-03-13 17:32:02 -07005501 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5502 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503
5504 // Update the velocity tracker.
5505 {
5506 VelocityTracker::Position positions[MAX_POINTERS];
5507 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005508 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005509 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005510 const RawPointerData::Pointer& pointer =
5511 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 positions[count].x = pointer.x * mPointerXMovementScale;
5513 positions[count].y = pointer.y * mPointerYMovementScale;
5514 }
5515 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005516 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 }
5518
5519 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5520 // to NEUTRAL, then we should not generate tap event.
5521 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5522 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5523 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5524 mPointerGesture.resetTap();
5525 }
5526
5527 // Pick a new active touch id if needed.
5528 // Choose an arbitrary pointer that just went down, if there is one.
5529 // Otherwise choose an arbitrary remaining pointer.
5530 // This guarantees we always have an active touch id when there is at least one pointer.
5531 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5533 int32_t activeTouchId = lastActiveTouchId;
5534 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005535 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005537 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005538 mPointerGesture.firstTouchTime = when;
5539 }
Michael Wright842500e2015-03-13 17:32:02 -07005540 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005541 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005543 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544 } else {
5545 activeTouchId = mPointerGesture.activeTouchId = -1;
5546 }
5547 }
5548
5549 // Determine whether we are in quiet time.
5550 bool isQuietTime = false;
5551 if (activeTouchId < 0) {
5552 mPointerGesture.resetQuietTime();
5553 } else {
5554 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5555 if (!isQuietTime) {
5556 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5557 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5558 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5559 && currentFingerCount < 2) {
5560 // Enter quiet time when exiting swipe or freeform state.
5561 // This is to prevent accidentally entering the hover state and flinging the
5562 // pointer when finishing a swipe and there is still one pointer left onscreen.
5563 isQuietTime = true;
5564 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5565 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005566 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567 // Enter quiet time when releasing the button and there are still two or more
5568 // fingers down. This may indicate that one finger was used to press the button
5569 // but it has not gone up yet.
5570 isQuietTime = true;
5571 }
5572 if (isQuietTime) {
5573 mPointerGesture.quietTime = when;
5574 }
5575 }
5576 }
5577
5578 // Switch states based on button and pointer state.
5579 if (isQuietTime) {
5580 // Case 1: Quiet time. (QUIET)
5581#if DEBUG_GESTURES
5582 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5583 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5584#endif
5585 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5586 *outFinishPreviousGesture = true;
5587 }
5588
5589 mPointerGesture.activeGestureId = -1;
5590 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5591 mPointerGesture.currentGestureIdBits.clear();
5592
5593 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005594 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5596 // The pointer follows the active touch point.
5597 // Emit DOWN, MOVE, UP events at the pointer location.
5598 //
5599 // Only the active touch matters; other fingers are ignored. This policy helps
5600 // to handle the case where the user places a second finger on the touch pad
5601 // to apply the necessary force to depress an integrated button below the surface.
5602 // We don't want the second finger to be delivered to applications.
5603 //
5604 // For this to work well, we need to make sure to track the pointer that is really
5605 // active. If the user first puts one finger down to click then adds another
5606 // finger to drag then the active pointer should switch to the finger that is
5607 // being dragged.
5608#if DEBUG_GESTURES
5609 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5610 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5611#endif
5612 // Reset state when just starting.
5613 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5614 *outFinishPreviousGesture = true;
5615 mPointerGesture.activeGestureId = 0;
5616 }
5617
5618 // Switch pointers if needed.
5619 // Find the fastest pointer and follow it.
5620 if (activeTouchId >= 0 && currentFingerCount > 1) {
5621 int32_t bestId = -1;
5622 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005623 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 uint32_t id = idBits.clearFirstMarkedBit();
5625 float vx, vy;
5626 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5627 float speed = hypotf(vx, vy);
5628 if (speed > bestSpeed) {
5629 bestId = id;
5630 bestSpeed = speed;
5631 }
5632 }
5633 }
5634 if (bestId >= 0 && bestId != activeTouchId) {
5635 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636#if DEBUG_GESTURES
5637 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5638 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5639#endif
5640 }
5641 }
5642
Jun Mukaifa1706a2015-12-03 01:14:46 -08005643 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005644 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005646 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005648 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005649 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5650 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651
5652 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5653 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5654
5655 // Move the pointer using a relative motion.
5656 // When using spots, the click will occur at the position of the anchor
5657 // spot and all other spots will move there.
5658 mPointerController->move(deltaX, deltaY);
5659 } else {
5660 mPointerVelocityControl.reset();
5661 }
5662
5663 float x, y;
5664 mPointerController->getPosition(&x, &y);
5665
5666 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5667 mPointerGesture.currentGestureIdBits.clear();
5668 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5669 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5670 mPointerGesture.currentGestureProperties[0].clear();
5671 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5672 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5673 mPointerGesture.currentGestureCoords[0].clear();
5674 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5675 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5676 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5677 } else if (currentFingerCount == 0) {
5678 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5679 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5680 *outFinishPreviousGesture = true;
5681 }
5682
5683 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5684 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5685 bool tapped = false;
5686 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5687 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5688 && lastFingerCount == 1) {
5689 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5690 float x, y;
5691 mPointerController->getPosition(&x, &y);
5692 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5693 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5694#if DEBUG_GESTURES
5695 ALOGD("Gestures: TAP");
5696#endif
5697
5698 mPointerGesture.tapUpTime = when;
5699 getContext()->requestTimeoutAtTime(when
5700 + mConfig.pointerGestureTapDragInterval);
5701
5702 mPointerGesture.activeGestureId = 0;
5703 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5704 mPointerGesture.currentGestureIdBits.clear();
5705 mPointerGesture.currentGestureIdBits.markBit(
5706 mPointerGesture.activeGestureId);
5707 mPointerGesture.currentGestureIdToIndex[
5708 mPointerGesture.activeGestureId] = 0;
5709 mPointerGesture.currentGestureProperties[0].clear();
5710 mPointerGesture.currentGestureProperties[0].id =
5711 mPointerGesture.activeGestureId;
5712 mPointerGesture.currentGestureProperties[0].toolType =
5713 AMOTION_EVENT_TOOL_TYPE_FINGER;
5714 mPointerGesture.currentGestureCoords[0].clear();
5715 mPointerGesture.currentGestureCoords[0].setAxisValue(
5716 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5717 mPointerGesture.currentGestureCoords[0].setAxisValue(
5718 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5719 mPointerGesture.currentGestureCoords[0].setAxisValue(
5720 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5721
5722 tapped = true;
5723 } else {
5724#if DEBUG_GESTURES
5725 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5726 x - mPointerGesture.tapX,
5727 y - mPointerGesture.tapY);
5728#endif
5729 }
5730 } else {
5731#if DEBUG_GESTURES
5732 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5733 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5734 (when - mPointerGesture.tapDownTime) * 0.000001f);
5735 } else {
5736 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5737 }
5738#endif
5739 }
5740 }
5741
5742 mPointerVelocityControl.reset();
5743
5744 if (!tapped) {
5745#if DEBUG_GESTURES
5746 ALOGD("Gestures: NEUTRAL");
5747#endif
5748 mPointerGesture.activeGestureId = -1;
5749 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5750 mPointerGesture.currentGestureIdBits.clear();
5751 }
5752 } else if (currentFingerCount == 1) {
5753 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5754 // The pointer follows the active touch point.
5755 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5756 // When in TAP_DRAG, emit MOVE events at the pointer location.
5757 ALOG_ASSERT(activeTouchId >= 0);
5758
5759 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5760 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5761 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5762 float x, y;
5763 mPointerController->getPosition(&x, &y);
5764 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5765 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5766 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5767 } else {
5768#if DEBUG_GESTURES
5769 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5770 x - mPointerGesture.tapX,
5771 y - mPointerGesture.tapY);
5772#endif
5773 }
5774 } else {
5775#if DEBUG_GESTURES
5776 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5777 (when - mPointerGesture.tapUpTime) * 0.000001f);
5778#endif
5779 }
5780 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5781 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5782 }
5783
Jun Mukaifa1706a2015-12-03 01:14:46 -08005784 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005785 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005786 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005787 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005789 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005790 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5791 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792
5793 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5794 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5795
5796 // Move the pointer using a relative motion.
5797 // When using spots, the hover or drag will occur at the position of the anchor spot.
5798 mPointerController->move(deltaX, deltaY);
5799 } else {
5800 mPointerVelocityControl.reset();
5801 }
5802
5803 bool down;
5804 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5805#if DEBUG_GESTURES
5806 ALOGD("Gestures: TAP_DRAG");
5807#endif
5808 down = true;
5809 } else {
5810#if DEBUG_GESTURES
5811 ALOGD("Gestures: HOVER");
5812#endif
5813 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5814 *outFinishPreviousGesture = true;
5815 }
5816 mPointerGesture.activeGestureId = 0;
5817 down = false;
5818 }
5819
5820 float x, y;
5821 mPointerController->getPosition(&x, &y);
5822
5823 mPointerGesture.currentGestureIdBits.clear();
5824 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5825 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5826 mPointerGesture.currentGestureProperties[0].clear();
5827 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5828 mPointerGesture.currentGestureProperties[0].toolType =
5829 AMOTION_EVENT_TOOL_TYPE_FINGER;
5830 mPointerGesture.currentGestureCoords[0].clear();
5831 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5832 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5833 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5834 down ? 1.0f : 0.0f);
5835
5836 if (lastFingerCount == 0 && currentFingerCount != 0) {
5837 mPointerGesture.resetTap();
5838 mPointerGesture.tapDownTime = when;
5839 mPointerGesture.tapX = x;
5840 mPointerGesture.tapY = y;
5841 }
5842 } else {
5843 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5844 // We need to provide feedback for each finger that goes down so we cannot wait
5845 // for the fingers to move before deciding what to do.
5846 //
5847 // The ambiguous case is deciding what to do when there are two fingers down but they
5848 // have not moved enough to determine whether they are part of a drag or part of a
5849 // freeform gesture, or just a press or long-press at the pointer location.
5850 //
5851 // When there are two fingers we start with the PRESS hypothesis and we generate a
5852 // down at the pointer location.
5853 //
5854 // When the two fingers move enough or when additional fingers are added, we make
5855 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5856 ALOG_ASSERT(activeTouchId >= 0);
5857
5858 bool settled = when >= mPointerGesture.firstTouchTime
5859 + mConfig.pointerGestureMultitouchSettleInterval;
5860 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5861 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5862 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5863 *outFinishPreviousGesture = true;
5864 } else if (!settled && currentFingerCount > lastFingerCount) {
5865 // Additional pointers have gone down but not yet settled.
5866 // Reset the gesture.
5867#if DEBUG_GESTURES
5868 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5869 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5870 + mConfig.pointerGestureMultitouchSettleInterval - when)
5871 * 0.000001f);
5872#endif
5873 *outCancelPreviousGesture = true;
5874 } else {
5875 // Continue previous gesture.
5876 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5877 }
5878
5879 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5880 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5881 mPointerGesture.activeGestureId = 0;
5882 mPointerGesture.referenceIdBits.clear();
5883 mPointerVelocityControl.reset();
5884
5885 // Use the centroid and pointer location as the reference points for the gesture.
5886#if DEBUG_GESTURES
5887 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5888 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5889 + mConfig.pointerGestureMultitouchSettleInterval - when)
5890 * 0.000001f);
5891#endif
Michael Wright842500e2015-03-13 17:32:02 -07005892 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 &mPointerGesture.referenceTouchX,
5894 &mPointerGesture.referenceTouchY);
5895 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5896 &mPointerGesture.referenceGestureY);
5897 }
5898
5899 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005900 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5902 uint32_t id = idBits.clearFirstMarkedBit();
5903 mPointerGesture.referenceDeltas[id].dx = 0;
5904 mPointerGesture.referenceDeltas[id].dy = 0;
5905 }
Michael Wright842500e2015-03-13 17:32:02 -07005906 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005907
5908 // Add delta for all fingers and calculate a common movement delta.
5909 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005910 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5911 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5913 bool first = (idBits == commonIdBits);
5914 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005915 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5916 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005917 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5918 delta.dx += cpd.x - lpd.x;
5919 delta.dy += cpd.y - lpd.y;
5920
5921 if (first) {
5922 commonDeltaX = delta.dx;
5923 commonDeltaY = delta.dy;
5924 } else {
5925 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5926 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5927 }
5928 }
5929
5930 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5931 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5932 float dist[MAX_POINTER_ID + 1];
5933 int32_t distOverThreshold = 0;
5934 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5935 uint32_t id = idBits.clearFirstMarkedBit();
5936 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5937 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5938 delta.dy * mPointerYZoomScale);
5939 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5940 distOverThreshold += 1;
5941 }
5942 }
5943
5944 // Only transition when at least two pointers have moved further than
5945 // the minimum distance threshold.
5946 if (distOverThreshold >= 2) {
5947 if (currentFingerCount > 2) {
5948 // There are more than two pointers, switch to FREEFORM.
5949#if DEBUG_GESTURES
5950 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5951 currentFingerCount);
5952#endif
5953 *outCancelPreviousGesture = true;
5954 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5955 } else {
5956 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005957 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958 uint32_t id1 = idBits.clearFirstMarkedBit();
5959 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005960 const RawPointerData::Pointer& p1 =
5961 mCurrentRawState.rawPointerData.pointerForId(id1);
5962 const RawPointerData::Pointer& p2 =
5963 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5965 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5966 // There are two pointers but they are too far apart for a SWIPE,
5967 // switch to FREEFORM.
5968#if DEBUG_GESTURES
5969 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5970 mutualDistance, mPointerGestureMaxSwipeWidth);
5971#endif
5972 *outCancelPreviousGesture = true;
5973 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5974 } else {
5975 // There are two pointers. Wait for both pointers to start moving
5976 // before deciding whether this is a SWIPE or FREEFORM gesture.
5977 float dist1 = dist[id1];
5978 float dist2 = dist[id2];
5979 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5980 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5981 // Calculate the dot product of the displacement vectors.
5982 // When the vectors are oriented in approximately the same direction,
5983 // the angle betweeen them is near zero and the cosine of the angle
5984 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5985 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5986 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5987 float dx1 = delta1.dx * mPointerXZoomScale;
5988 float dy1 = delta1.dy * mPointerYZoomScale;
5989 float dx2 = delta2.dx * mPointerXZoomScale;
5990 float dy2 = delta2.dy * mPointerYZoomScale;
5991 float dot = dx1 * dx2 + dy1 * dy2;
5992 float cosine = dot / (dist1 * dist2); // denominator always > 0
5993 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5994 // Pointers are moving in the same direction. Switch to SWIPE.
5995#if DEBUG_GESTURES
5996 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5997 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5998 "cosine %0.3f >= %0.3f",
5999 dist1, mConfig.pointerGestureMultitouchMinDistance,
6000 dist2, mConfig.pointerGestureMultitouchMinDistance,
6001 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6002#endif
6003 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6004 } else {
6005 // Pointers are moving in different directions. Switch to FREEFORM.
6006#if DEBUG_GESTURES
6007 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6008 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6009 "cosine %0.3f < %0.3f",
6010 dist1, mConfig.pointerGestureMultitouchMinDistance,
6011 dist2, mConfig.pointerGestureMultitouchMinDistance,
6012 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6013#endif
6014 *outCancelPreviousGesture = true;
6015 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6016 }
6017 }
6018 }
6019 }
6020 }
6021 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6022 // Switch from SWIPE to FREEFORM if additional pointers go down.
6023 // Cancel previous gesture.
6024 if (currentFingerCount > 2) {
6025#if DEBUG_GESTURES
6026 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6027 currentFingerCount);
6028#endif
6029 *outCancelPreviousGesture = true;
6030 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6031 }
6032 }
6033
6034 // Move the reference points based on the overall group motion of the fingers
6035 // except in PRESS mode while waiting for a transition to occur.
6036 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6037 && (commonDeltaX || commonDeltaY)) {
6038 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6039 uint32_t id = idBits.clearFirstMarkedBit();
6040 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6041 delta.dx = 0;
6042 delta.dy = 0;
6043 }
6044
6045 mPointerGesture.referenceTouchX += commonDeltaX;
6046 mPointerGesture.referenceTouchY += commonDeltaY;
6047
6048 commonDeltaX *= mPointerXMovementScale;
6049 commonDeltaY *= mPointerYMovementScale;
6050
6051 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6052 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6053
6054 mPointerGesture.referenceGestureX += commonDeltaX;
6055 mPointerGesture.referenceGestureY += commonDeltaY;
6056 }
6057
6058 // Report gestures.
6059 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6060 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6061 // PRESS or SWIPE mode.
6062#if DEBUG_GESTURES
6063 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6064 "activeGestureId=%d, currentTouchPointerCount=%d",
6065 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6066#endif
6067 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6068
6069 mPointerGesture.currentGestureIdBits.clear();
6070 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6071 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6072 mPointerGesture.currentGestureProperties[0].clear();
6073 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6074 mPointerGesture.currentGestureProperties[0].toolType =
6075 AMOTION_EVENT_TOOL_TYPE_FINGER;
6076 mPointerGesture.currentGestureCoords[0].clear();
6077 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6078 mPointerGesture.referenceGestureX);
6079 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6080 mPointerGesture.referenceGestureY);
6081 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6082 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6083 // FREEFORM mode.
6084#if DEBUG_GESTURES
6085 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6086 "activeGestureId=%d, currentTouchPointerCount=%d",
6087 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6088#endif
6089 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6090
6091 mPointerGesture.currentGestureIdBits.clear();
6092
6093 BitSet32 mappedTouchIdBits;
6094 BitSet32 usedGestureIdBits;
6095 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6096 // Initially, assign the active gesture id to the active touch point
6097 // if there is one. No other touch id bits are mapped yet.
6098 if (!*outCancelPreviousGesture) {
6099 mappedTouchIdBits.markBit(activeTouchId);
6100 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6101 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6102 mPointerGesture.activeGestureId;
6103 } else {
6104 mPointerGesture.activeGestureId = -1;
6105 }
6106 } else {
6107 // Otherwise, assume we mapped all touches from the previous frame.
6108 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006109 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6110 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6112
6113 // Check whether we need to choose a new active gesture id because the
6114 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006115 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6116 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117 !upTouchIdBits.isEmpty(); ) {
6118 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6119 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6120 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6121 mPointerGesture.activeGestureId = -1;
6122 break;
6123 }
6124 }
6125 }
6126
6127#if DEBUG_GESTURES
6128 ALOGD("Gestures: FREEFORM follow up "
6129 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6130 "activeGestureId=%d",
6131 mappedTouchIdBits.value, usedGestureIdBits.value,
6132 mPointerGesture.activeGestureId);
6133#endif
6134
Michael Wright842500e2015-03-13 17:32:02 -07006135 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136 for (uint32_t i = 0; i < currentFingerCount; i++) {
6137 uint32_t touchId = idBits.clearFirstMarkedBit();
6138 uint32_t gestureId;
6139 if (!mappedTouchIdBits.hasBit(touchId)) {
6140 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6141 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6142#if DEBUG_GESTURES
6143 ALOGD("Gestures: FREEFORM "
6144 "new mapping for touch id %d -> gesture id %d",
6145 touchId, gestureId);
6146#endif
6147 } else {
6148 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6149#if DEBUG_GESTURES
6150 ALOGD("Gestures: FREEFORM "
6151 "existing mapping for touch id %d -> gesture id %d",
6152 touchId, gestureId);
6153#endif
6154 }
6155 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6156 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6157
6158 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006159 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006160 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6161 * mPointerXZoomScale;
6162 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6163 * mPointerYZoomScale;
6164 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6165
6166 mPointerGesture.currentGestureProperties[i].clear();
6167 mPointerGesture.currentGestureProperties[i].id = gestureId;
6168 mPointerGesture.currentGestureProperties[i].toolType =
6169 AMOTION_EVENT_TOOL_TYPE_FINGER;
6170 mPointerGesture.currentGestureCoords[i].clear();
6171 mPointerGesture.currentGestureCoords[i].setAxisValue(
6172 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6173 mPointerGesture.currentGestureCoords[i].setAxisValue(
6174 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6175 mPointerGesture.currentGestureCoords[i].setAxisValue(
6176 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6177 }
6178
6179 if (mPointerGesture.activeGestureId < 0) {
6180 mPointerGesture.activeGestureId =
6181 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6182#if DEBUG_GESTURES
6183 ALOGD("Gestures: FREEFORM new "
6184 "activeGestureId=%d", mPointerGesture.activeGestureId);
6185#endif
6186 }
6187 }
6188 }
6189
Michael Wright842500e2015-03-13 17:32:02 -07006190 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006191
6192#if DEBUG_GESTURES
6193 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6194 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6195 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6196 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6197 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6198 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6199 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6200 uint32_t id = idBits.clearFirstMarkedBit();
6201 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6202 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6203 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6204 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6205 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6206 id, index, properties.toolType,
6207 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6208 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6209 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6210 }
6211 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6212 uint32_t id = idBits.clearFirstMarkedBit();
6213 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6214 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6215 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6216 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6217 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6218 id, index, properties.toolType,
6219 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6220 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6221 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6222 }
6223#endif
6224 return true;
6225}
6226
6227void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6228 mPointerSimple.currentCoords.clear();
6229 mPointerSimple.currentProperties.clear();
6230
6231 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006232 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6233 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6234 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6235 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6236 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237 mPointerController->setPosition(x, y);
6238
Michael Wright842500e2015-03-13 17:32:02 -07006239 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240 down = !hovering;
6241
6242 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006243 mPointerSimple.currentCoords.copyFrom(
6244 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6246 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6247 mPointerSimple.currentProperties.id = 0;
6248 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006249 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006250 } else {
6251 down = false;
6252 hovering = false;
6253 }
6254
6255 dispatchPointerSimple(when, policyFlags, down, hovering);
6256}
6257
6258void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6259 abortPointerSimple(when, policyFlags);
6260}
6261
6262void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6263 mPointerSimple.currentCoords.clear();
6264 mPointerSimple.currentProperties.clear();
6265
6266 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006267 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6268 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6269 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006270 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006271 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6272 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006273 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006274 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006275 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006276 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006277 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 * mPointerYMovementScale;
6279
6280 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6281 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6282
6283 mPointerController->move(deltaX, deltaY);
6284 } else {
6285 mPointerVelocityControl.reset();
6286 }
6287
Michael Wright842500e2015-03-13 17:32:02 -07006288 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006289 hovering = !down;
6290
6291 float x, y;
6292 mPointerController->getPosition(&x, &y);
6293 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006294 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6296 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6297 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6298 hovering ? 0.0f : 1.0f);
6299 mPointerSimple.currentProperties.id = 0;
6300 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006301 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006302 } else {
6303 mPointerVelocityControl.reset();
6304
6305 down = false;
6306 hovering = false;
6307 }
6308
6309 dispatchPointerSimple(when, policyFlags, down, hovering);
6310}
6311
6312void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6313 abortPointerSimple(when, policyFlags);
6314
6315 mPointerVelocityControl.reset();
6316}
6317
6318void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6319 bool down, bool hovering) {
6320 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006321 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006322
Yi Kong9b14ac62018-07-17 13:48:38 -07006323 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006324 if (down || hovering) {
6325 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6326 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006327 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006328 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6329 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6330 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6331 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006332 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006333 }
6334
6335 if (mPointerSimple.down && !down) {
6336 mPointerSimple.down = false;
6337
6338 // Send up.
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006339 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006340 mSource, displayId, policyFlags,
Dan Harmsaca28402018-12-17 13:55:20 -08006341 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
6342 /* deviceTimestamp */ 0,
6343 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6344 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006345 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346 getListener()->notifyMotion(&args);
6347 }
6348
6349 if (mPointerSimple.hovering && !hovering) {
6350 mPointerSimple.hovering = false;
6351
6352 // Send hover exit.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006353 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6354 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006355 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006356 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006357 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6358 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006359 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 getListener()->notifyMotion(&args);
6361 }
6362
6363 if (down) {
6364 if (!mPointerSimple.down) {
6365 mPointerSimple.down = true;
6366 mPointerSimple.downTime = when;
6367
6368 // Send down.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006369 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6370 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006371 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006372 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6374 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006375 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006376 getListener()->notifyMotion(&args);
6377 }
6378
6379 // Send move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006380 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6381 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006382 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006383 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6385 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006386 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387 getListener()->notifyMotion(&args);
6388 }
6389
6390 if (hovering) {
6391 if (!mPointerSimple.hovering) {
6392 mPointerSimple.hovering = true;
6393
6394 // Send hover enter.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006395 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6396 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006397 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006398 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006399 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006400 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6401 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006402 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006403 getListener()->notifyMotion(&args);
6404 }
6405
6406 // Send hover move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006407 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6408 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006409 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006410 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006411 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6413 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006414 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 getListener()->notifyMotion(&args);
6416 }
6417
Michael Wright842500e2015-03-13 17:32:02 -07006418 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6419 float vscroll = mCurrentRawState.rawVScroll;
6420 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006421 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6422 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006423
6424 // Send scroll.
6425 PointerCoords pointerCoords;
6426 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6427 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6428 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6429
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006430 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6431 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006432 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006433 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006434 1, &mPointerSimple.currentProperties, &pointerCoords,
6435 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006436 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006437 getListener()->notifyMotion(&args);
6438 }
6439
6440 // Save state.
6441 if (down || hovering) {
6442 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6443 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6444 } else {
6445 mPointerSimple.reset();
6446 }
6447}
6448
6449void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6450 mPointerSimple.currentCoords.clear();
6451 mPointerSimple.currentProperties.clear();
6452
6453 dispatchPointerSimple(when, policyFlags, false, false);
6454}
6455
6456void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006457 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006458 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006459 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006460 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6461 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006462 PointerCoords pointerCoords[MAX_POINTERS];
6463 PointerProperties pointerProperties[MAX_POINTERS];
6464 uint32_t pointerCount = 0;
6465 while (!idBits.isEmpty()) {
6466 uint32_t id = idBits.clearFirstMarkedBit();
6467 uint32_t index = idToIndex[id];
6468 pointerProperties[pointerCount].copyFrom(properties[index]);
6469 pointerCoords[pointerCount].copyFrom(coords[index]);
6470
6471 if (changedId >= 0 && id == uint32_t(changedId)) {
6472 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6473 }
6474
6475 pointerCount += 1;
6476 }
6477
6478 ALOG_ASSERT(pointerCount != 0);
6479
6480 if (changedId >= 0 && pointerCount == 1) {
6481 // Replace initial down and final up action.
6482 // We can compare the action without masking off the changed pointer index
6483 // because we know the index is 0.
6484 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6485 action = AMOTION_EVENT_ACTION_DOWN;
6486 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6487 action = AMOTION_EVENT_ACTION_UP;
6488 } else {
6489 // Can't happen.
6490 ALOG_ASSERT(false);
6491 }
6492 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006493 const int32_t displayId = mPointerController != nullptr ?
6494 mPointerController->getDisplayId() : mViewport.displayId;
Dan Harmsaca28402018-12-17 13:55:20 -08006495
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006496 const int32_t deviceId = getDeviceId();
6497 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
6498 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006499 source, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006500 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006501 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006502 xPrecision, yPrecision, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006503 getListener()->notifyMotion(&args);
6504}
6505
6506bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6507 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6508 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6509 BitSet32 idBits) const {
6510 bool changed = false;
6511 while (!idBits.isEmpty()) {
6512 uint32_t id = idBits.clearFirstMarkedBit();
6513 uint32_t inIndex = inIdToIndex[id];
6514 uint32_t outIndex = outIdToIndex[id];
6515
6516 const PointerProperties& curInProperties = inProperties[inIndex];
6517 const PointerCoords& curInCoords = inCoords[inIndex];
6518 PointerProperties& curOutProperties = outProperties[outIndex];
6519 PointerCoords& curOutCoords = outCoords[outIndex];
6520
6521 if (curInProperties != curOutProperties) {
6522 curOutProperties.copyFrom(curInProperties);
6523 changed = true;
6524 }
6525
6526 if (curInCoords != curOutCoords) {
6527 curOutCoords.copyFrom(curInCoords);
6528 changed = true;
6529 }
6530 }
6531 return changed;
6532}
6533
6534void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006535 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006536 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6537 }
6538}
6539
Jeff Brownc9aa6282015-02-11 19:03:28 -08006540void TouchInputMapper::cancelTouch(nsecs_t when) {
6541 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006542 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006543}
6544
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006546 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006547 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006549 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6550 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6551 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552}
6553
6554const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6555 int32_t x, int32_t y) {
6556 size_t numVirtualKeys = mVirtualKeys.size();
6557 for (size_t i = 0; i < numVirtualKeys; i++) {
6558 const VirtualKey& virtualKey = mVirtualKeys[i];
6559
6560#if DEBUG_VIRTUAL_KEYS
6561 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6562 "left=%d, top=%d, right=%d, bottom=%d",
6563 x, y,
6564 virtualKey.keyCode, virtualKey.scanCode,
6565 virtualKey.hitLeft, virtualKey.hitTop,
6566 virtualKey.hitRight, virtualKey.hitBottom);
6567#endif
6568
6569 if (virtualKey.isHit(x, y)) {
6570 return & virtualKey;
6571 }
6572 }
6573
Yi Kong9b14ac62018-07-17 13:48:38 -07006574 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575}
6576
Michael Wright842500e2015-03-13 17:32:02 -07006577void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6578 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6579 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580
Michael Wright842500e2015-03-13 17:32:02 -07006581 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006582
6583 if (currentPointerCount == 0) {
6584 // No pointers to assign.
6585 return;
6586 }
6587
6588 if (lastPointerCount == 0) {
6589 // All pointers are new.
6590 for (uint32_t i = 0; i < currentPointerCount; i++) {
6591 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006592 current->rawPointerData.pointers[i].id = id;
6593 current->rawPointerData.idToIndex[id] = i;
6594 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006595 }
6596 return;
6597 }
6598
6599 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006600 && current->rawPointerData.pointers[0].toolType
6601 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006602 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006603 uint32_t id = last->rawPointerData.pointers[0].id;
6604 current->rawPointerData.pointers[0].id = id;
6605 current->rawPointerData.idToIndex[id] = 0;
6606 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006607 return;
6608 }
6609
6610 // General case.
6611 // We build a heap of squared euclidean distances between current and last pointers
6612 // associated with the current and last pointer indices. Then, we find the best
6613 // match (by distance) for each current pointer.
6614 // The pointers must have the same tool type but it is possible for them to
6615 // transition from hovering to touching or vice-versa while retaining the same id.
6616 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6617
6618 uint32_t heapSize = 0;
6619 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6620 currentPointerIndex++) {
6621 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6622 lastPointerIndex++) {
6623 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006624 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006625 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006626 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006627 if (currentPointer.toolType == lastPointer.toolType) {
6628 int64_t deltaX = currentPointer.x - lastPointer.x;
6629 int64_t deltaY = currentPointer.y - lastPointer.y;
6630
6631 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6632
6633 // Insert new element into the heap (sift up).
6634 heap[heapSize].currentPointerIndex = currentPointerIndex;
6635 heap[heapSize].lastPointerIndex = lastPointerIndex;
6636 heap[heapSize].distance = distance;
6637 heapSize += 1;
6638 }
6639 }
6640 }
6641
6642 // Heapify
6643 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6644 startIndex -= 1;
6645 for (uint32_t parentIndex = startIndex; ;) {
6646 uint32_t childIndex = parentIndex * 2 + 1;
6647 if (childIndex >= heapSize) {
6648 break;
6649 }
6650
6651 if (childIndex + 1 < heapSize
6652 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6653 childIndex += 1;
6654 }
6655
6656 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6657 break;
6658 }
6659
6660 swap(heap[parentIndex], heap[childIndex]);
6661 parentIndex = childIndex;
6662 }
6663 }
6664
6665#if DEBUG_POINTER_ASSIGNMENT
6666 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6667 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006668 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006669 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6670 heap[i].distance);
6671 }
6672#endif
6673
6674 // Pull matches out by increasing order of distance.
6675 // To avoid reassigning pointers that have already been matched, the loop keeps track
6676 // of which last and current pointers have been matched using the matchedXXXBits variables.
6677 // It also tracks the used pointer id bits.
6678 BitSet32 matchedLastBits(0);
6679 BitSet32 matchedCurrentBits(0);
6680 BitSet32 usedIdBits(0);
6681 bool first = true;
6682 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6683 while (heapSize > 0) {
6684 if (first) {
6685 // The first time through the loop, we just consume the root element of
6686 // the heap (the one with smallest distance).
6687 first = false;
6688 } else {
6689 // Previous iterations consumed the root element of the heap.
6690 // Pop root element off of the heap (sift down).
6691 heap[0] = heap[heapSize];
6692 for (uint32_t parentIndex = 0; ;) {
6693 uint32_t childIndex = parentIndex * 2 + 1;
6694 if (childIndex >= heapSize) {
6695 break;
6696 }
6697
6698 if (childIndex + 1 < heapSize
6699 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6700 childIndex += 1;
6701 }
6702
6703 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6704 break;
6705 }
6706
6707 swap(heap[parentIndex], heap[childIndex]);
6708 parentIndex = childIndex;
6709 }
6710
6711#if DEBUG_POINTER_ASSIGNMENT
6712 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6713 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006714 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006715 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6716 heap[i].distance);
6717 }
6718#endif
6719 }
6720
6721 heapSize -= 1;
6722
6723 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6724 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6725
6726 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6727 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6728
6729 matchedCurrentBits.markBit(currentPointerIndex);
6730 matchedLastBits.markBit(lastPointerIndex);
6731
Michael Wright842500e2015-03-13 17:32:02 -07006732 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6733 current->rawPointerData.pointers[currentPointerIndex].id = id;
6734 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6735 current->rawPointerData.markIdBit(id,
6736 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006737 usedIdBits.markBit(id);
6738
6739#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006740 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6741 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006742 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6743#endif
6744 break;
6745 }
6746 }
6747
6748 // Assign fresh ids to pointers that were not matched in the process.
6749 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6750 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6751 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6752
Michael Wright842500e2015-03-13 17:32:02 -07006753 current->rawPointerData.pointers[currentPointerIndex].id = id;
6754 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6755 current->rawPointerData.markIdBit(id,
6756 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006757
6758#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006759 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006760#endif
6761 }
6762}
6763
6764int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6765 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6766 return AKEY_STATE_VIRTUAL;
6767 }
6768
6769 size_t numVirtualKeys = mVirtualKeys.size();
6770 for (size_t i = 0; i < numVirtualKeys; i++) {
6771 const VirtualKey& virtualKey = mVirtualKeys[i];
6772 if (virtualKey.keyCode == keyCode) {
6773 return AKEY_STATE_UP;
6774 }
6775 }
6776
6777 return AKEY_STATE_UNKNOWN;
6778}
6779
6780int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6781 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6782 return AKEY_STATE_VIRTUAL;
6783 }
6784
6785 size_t numVirtualKeys = mVirtualKeys.size();
6786 for (size_t i = 0; i < numVirtualKeys; i++) {
6787 const VirtualKey& virtualKey = mVirtualKeys[i];
6788 if (virtualKey.scanCode == scanCode) {
6789 return AKEY_STATE_UP;
6790 }
6791 }
6792
6793 return AKEY_STATE_UNKNOWN;
6794}
6795
6796bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6797 const int32_t* keyCodes, uint8_t* outFlags) {
6798 size_t numVirtualKeys = mVirtualKeys.size();
6799 for (size_t i = 0; i < numVirtualKeys; i++) {
6800 const VirtualKey& virtualKey = mVirtualKeys[i];
6801
6802 for (size_t i = 0; i < numCodes; i++) {
6803 if (virtualKey.keyCode == keyCodes[i]) {
6804 outFlags[i] = 1;
6805 }
6806 }
6807 }
6808
6809 return true;
6810}
6811
6812
6813// --- SingleTouchInputMapper ---
6814
6815SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6816 TouchInputMapper(device) {
6817}
6818
6819SingleTouchInputMapper::~SingleTouchInputMapper() {
6820}
6821
6822void SingleTouchInputMapper::reset(nsecs_t when) {
6823 mSingleTouchMotionAccumulator.reset(getDevice());
6824
6825 TouchInputMapper::reset(when);
6826}
6827
6828void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6829 TouchInputMapper::process(rawEvent);
6830
6831 mSingleTouchMotionAccumulator.process(rawEvent);
6832}
6833
Michael Wright842500e2015-03-13 17:32:02 -07006834void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006835 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006836 outState->rawPointerData.pointerCount = 1;
6837 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006838
6839 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6840 && (mTouchButtonAccumulator.isHovering()
6841 || (mRawPointerAxes.pressure.valid
6842 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006843 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006844
Michael Wright842500e2015-03-13 17:32:02 -07006845 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006846 outPointer.id = 0;
6847 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6848 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6849 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6850 outPointer.touchMajor = 0;
6851 outPointer.touchMinor = 0;
6852 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6853 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6854 outPointer.orientation = 0;
6855 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6856 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6857 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6858 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6859 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6860 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6861 }
6862 outPointer.isHovering = isHovering;
6863 }
6864}
6865
6866void SingleTouchInputMapper::configureRawPointerAxes() {
6867 TouchInputMapper::configureRawPointerAxes();
6868
6869 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6870 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6871 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6872 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6873 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6874 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6875 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6876}
6877
6878bool SingleTouchInputMapper::hasStylus() const {
6879 return mTouchButtonAccumulator.hasStylus();
6880}
6881
6882
6883// --- MultiTouchInputMapper ---
6884
6885MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6886 TouchInputMapper(device) {
6887}
6888
6889MultiTouchInputMapper::~MultiTouchInputMapper() {
6890}
6891
6892void MultiTouchInputMapper::reset(nsecs_t when) {
6893 mMultiTouchMotionAccumulator.reset(getDevice());
6894
6895 mPointerIdBits.clear();
6896
6897 TouchInputMapper::reset(when);
6898}
6899
6900void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6901 TouchInputMapper::process(rawEvent);
6902
6903 mMultiTouchMotionAccumulator.process(rawEvent);
6904}
6905
Michael Wright842500e2015-03-13 17:32:02 -07006906void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006907 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6908 size_t outCount = 0;
6909 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006910 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006911
6912 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6913 const MultiTouchMotionAccumulator::Slot* inSlot =
6914 mMultiTouchMotionAccumulator.getSlot(inIndex);
6915 if (!inSlot->isInUse()) {
6916 continue;
6917 }
6918
6919 if (outCount >= MAX_POINTERS) {
6920#if DEBUG_POINTERS
6921 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6922 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006923 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006924#endif
6925 break; // too many fingers!
6926 }
6927
Michael Wright842500e2015-03-13 17:32:02 -07006928 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006929 outPointer.x = inSlot->getX();
6930 outPointer.y = inSlot->getY();
6931 outPointer.pressure = inSlot->getPressure();
6932 outPointer.touchMajor = inSlot->getTouchMajor();
6933 outPointer.touchMinor = inSlot->getTouchMinor();
6934 outPointer.toolMajor = inSlot->getToolMajor();
6935 outPointer.toolMinor = inSlot->getToolMinor();
6936 outPointer.orientation = inSlot->getOrientation();
6937 outPointer.distance = inSlot->getDistance();
6938 outPointer.tiltX = 0;
6939 outPointer.tiltY = 0;
6940
6941 outPointer.toolType = inSlot->getToolType();
6942 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6943 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6944 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6945 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6946 }
6947 }
6948
6949 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6950 && (mTouchButtonAccumulator.isHovering()
6951 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6952 outPointer.isHovering = isHovering;
6953
6954 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006955 if (mHavePointerIds) {
6956 int32_t trackingId = inSlot->getTrackingId();
6957 int32_t id = -1;
6958 if (trackingId >= 0) {
6959 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6960 uint32_t n = idBits.clearFirstMarkedBit();
6961 if (mPointerTrackingIdMap[n] == trackingId) {
6962 id = n;
6963 }
6964 }
6965
6966 if (id < 0 && !mPointerIdBits.isFull()) {
6967 id = mPointerIdBits.markFirstUnmarkedBit();
6968 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006969 }
Michael Wright842500e2015-03-13 17:32:02 -07006970 }
gaoshang1a632de2016-08-24 10:23:50 +08006971 if (id < 0) {
6972 mHavePointerIds = false;
6973 outState->rawPointerData.clearIdBits();
6974 newPointerIdBits.clear();
6975 } else {
6976 outPointer.id = id;
6977 outState->rawPointerData.idToIndex[id] = outCount;
6978 outState->rawPointerData.markIdBit(id, isHovering);
6979 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006980 }
Michael Wright842500e2015-03-13 17:32:02 -07006981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006982 outCount += 1;
6983 }
6984
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006985 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006986 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006987 mPointerIdBits = newPointerIdBits;
6988
6989 mMultiTouchMotionAccumulator.finishSync();
6990}
6991
6992void MultiTouchInputMapper::configureRawPointerAxes() {
6993 TouchInputMapper::configureRawPointerAxes();
6994
6995 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6996 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6997 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6998 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6999 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7000 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7001 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7002 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7003 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7004 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7005 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7006
7007 if (mRawPointerAxes.trackingId.valid
7008 && mRawPointerAxes.slot.valid
7009 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7010 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7011 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007012 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7013 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007014 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007015 slotCount = MAX_SLOTS;
7016 }
7017 mMultiTouchMotionAccumulator.configure(getDevice(),
7018 slotCount, true /*usingSlotsProtocol*/);
7019 } else {
7020 mMultiTouchMotionAccumulator.configure(getDevice(),
7021 MAX_POINTERS, false /*usingSlotsProtocol*/);
7022 }
7023}
7024
7025bool MultiTouchInputMapper::hasStylus() const {
7026 return mMultiTouchMotionAccumulator.hasStylus()
7027 || mTouchButtonAccumulator.hasStylus();
7028}
7029
Michael Wright842500e2015-03-13 17:32:02 -07007030// --- ExternalStylusInputMapper
7031
7032ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7033 InputMapper(device) {
7034
7035}
7036
7037uint32_t ExternalStylusInputMapper::getSources() {
7038 return AINPUT_SOURCE_STYLUS;
7039}
7040
7041void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7042 InputMapper::populateDeviceInfo(info);
7043 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7044 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7045}
7046
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007047void ExternalStylusInputMapper::dump(std::string& dump) {
7048 dump += INDENT2 "External Stylus Input Mapper:\n";
7049 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007050 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007051 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007052 dumpStylusState(dump, mStylusState);
7053}
7054
7055void ExternalStylusInputMapper::configure(nsecs_t when,
7056 const InputReaderConfiguration* config, uint32_t changes) {
7057 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7058 mTouchButtonAccumulator.configure(getDevice());
7059}
7060
7061void ExternalStylusInputMapper::reset(nsecs_t when) {
7062 InputDevice* device = getDevice();
7063 mSingleTouchMotionAccumulator.reset(device);
7064 mTouchButtonAccumulator.reset(device);
7065 InputMapper::reset(when);
7066}
7067
7068void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7069 mSingleTouchMotionAccumulator.process(rawEvent);
7070 mTouchButtonAccumulator.process(rawEvent);
7071
7072 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7073 sync(rawEvent->when);
7074 }
7075}
7076
7077void ExternalStylusInputMapper::sync(nsecs_t when) {
7078 mStylusState.clear();
7079
7080 mStylusState.when = when;
7081
Michael Wright45ccacf2015-04-21 19:01:58 +01007082 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7083 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7084 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7085 }
7086
Michael Wright842500e2015-03-13 17:32:02 -07007087 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7088 if (mRawPressureAxis.valid) {
7089 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7090 } else if (mTouchButtonAccumulator.isToolActive()) {
7091 mStylusState.pressure = 1.0f;
7092 } else {
7093 mStylusState.pressure = 0.0f;
7094 }
7095
7096 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007097
7098 mContext->dispatchExternalStylusState(mStylusState);
7099}
7100
Michael Wrightd02c5b62014-02-10 15:10:22 -08007101
7102// --- JoystickInputMapper ---
7103
7104JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7105 InputMapper(device) {
7106}
7107
7108JoystickInputMapper::~JoystickInputMapper() {
7109}
7110
7111uint32_t JoystickInputMapper::getSources() {
7112 return AINPUT_SOURCE_JOYSTICK;
7113}
7114
7115void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7116 InputMapper::populateDeviceInfo(info);
7117
7118 for (size_t i = 0; i < mAxes.size(); i++) {
7119 const Axis& axis = mAxes.valueAt(i);
7120 addMotionRange(axis.axisInfo.axis, axis, info);
7121
7122 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7123 addMotionRange(axis.axisInfo.highAxis, axis, info);
7124
7125 }
7126 }
7127}
7128
7129void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7130 InputDeviceInfo* info) {
7131 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7132 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7133 /* In order to ease the transition for developers from using the old axes
7134 * to the newer, more semantically correct axes, we'll continue to register
7135 * the old axes as duplicates of their corresponding new ones. */
7136 int32_t compatAxis = getCompatAxis(axisId);
7137 if (compatAxis >= 0) {
7138 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7139 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7140 }
7141}
7142
7143/* A mapping from axes the joystick actually has to the axes that should be
7144 * artificially created for compatibility purposes.
7145 * Returns -1 if no compatibility axis is needed. */
7146int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7147 switch(axis) {
7148 case AMOTION_EVENT_AXIS_LTRIGGER:
7149 return AMOTION_EVENT_AXIS_BRAKE;
7150 case AMOTION_EVENT_AXIS_RTRIGGER:
7151 return AMOTION_EVENT_AXIS_GAS;
7152 }
7153 return -1;
7154}
7155
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007156void JoystickInputMapper::dump(std::string& dump) {
7157 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007158
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007159 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007160 size_t numAxes = mAxes.size();
7161 for (size_t i = 0; i < numAxes; i++) {
7162 const Axis& axis = mAxes.valueAt(i);
7163 const char* label = getAxisLabel(axis.axisInfo.axis);
7164 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007165 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007166 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007167 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007168 }
7169 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7170 label = getAxisLabel(axis.axisInfo.highAxis);
7171 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007172 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007173 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007174 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007175 axis.axisInfo.splitValue);
7176 }
7177 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007178 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007179 }
7180
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007181 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 -08007182 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007183 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007184 "highScale=%0.5f, highOffset=%0.5f\n",
7185 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007186 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007187 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7188 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7189 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7190 }
7191}
7192
7193void JoystickInputMapper::configure(nsecs_t when,
7194 const InputReaderConfiguration* config, uint32_t changes) {
7195 InputMapper::configure(when, config, changes);
7196
7197 if (!changes) { // first time only
7198 // Collect all axes.
7199 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7200 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7201 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7202 continue; // axis must be claimed by a different device
7203 }
7204
7205 RawAbsoluteAxisInfo rawAxisInfo;
7206 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7207 if (rawAxisInfo.valid) {
7208 // Map axis.
7209 AxisInfo axisInfo;
7210 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7211 if (!explicitlyMapped) {
7212 // Axis is not explicitly mapped, will choose a generic axis later.
7213 axisInfo.mode = AxisInfo::MODE_NORMAL;
7214 axisInfo.axis = -1;
7215 }
7216
7217 // Apply flat override.
7218 int32_t rawFlat = axisInfo.flatOverride < 0
7219 ? rawAxisInfo.flat : axisInfo.flatOverride;
7220
7221 // Calculate scaling factors and limits.
7222 Axis axis;
7223 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7224 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7225 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7226 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7227 scale, 0.0f, highScale, 0.0f,
7228 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7229 rawAxisInfo.resolution * scale);
7230 } else if (isCenteredAxis(axisInfo.axis)) {
7231 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7232 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7233 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7234 scale, offset, scale, offset,
7235 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7236 rawAxisInfo.resolution * scale);
7237 } else {
7238 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7239 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7240 scale, 0.0f, scale, 0.0f,
7241 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7242 rawAxisInfo.resolution * scale);
7243 }
7244
7245 // To eliminate noise while the joystick is at rest, filter out small variations
7246 // in axis values up front.
7247 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7248
7249 mAxes.add(abs, axis);
7250 }
7251 }
7252
7253 // If there are too many axes, start dropping them.
7254 // Prefer to keep explicitly mapped axes.
7255 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007256 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007257 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007258 pruneAxes(true);
7259 pruneAxes(false);
7260 }
7261
7262 // Assign generic axis ids to remaining axes.
7263 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7264 size_t numAxes = mAxes.size();
7265 for (size_t i = 0; i < numAxes; i++) {
7266 Axis& axis = mAxes.editValueAt(i);
7267 if (axis.axisInfo.axis < 0) {
7268 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7269 && haveAxis(nextGenericAxisId)) {
7270 nextGenericAxisId += 1;
7271 }
7272
7273 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7274 axis.axisInfo.axis = nextGenericAxisId;
7275 nextGenericAxisId += 1;
7276 } else {
7277 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7278 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007279 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007280 mAxes.removeItemsAt(i--);
7281 numAxes -= 1;
7282 }
7283 }
7284 }
7285 }
7286}
7287
7288bool JoystickInputMapper::haveAxis(int32_t axisId) {
7289 size_t numAxes = mAxes.size();
7290 for (size_t i = 0; i < numAxes; i++) {
7291 const Axis& axis = mAxes.valueAt(i);
7292 if (axis.axisInfo.axis == axisId
7293 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7294 && axis.axisInfo.highAxis == axisId)) {
7295 return true;
7296 }
7297 }
7298 return false;
7299}
7300
7301void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7302 size_t i = mAxes.size();
7303 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7304 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7305 continue;
7306 }
7307 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007308 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007309 mAxes.removeItemsAt(i);
7310 }
7311}
7312
7313bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7314 switch (axis) {
7315 case AMOTION_EVENT_AXIS_X:
7316 case AMOTION_EVENT_AXIS_Y:
7317 case AMOTION_EVENT_AXIS_Z:
7318 case AMOTION_EVENT_AXIS_RX:
7319 case AMOTION_EVENT_AXIS_RY:
7320 case AMOTION_EVENT_AXIS_RZ:
7321 case AMOTION_EVENT_AXIS_HAT_X:
7322 case AMOTION_EVENT_AXIS_HAT_Y:
7323 case AMOTION_EVENT_AXIS_ORIENTATION:
7324 case AMOTION_EVENT_AXIS_RUDDER:
7325 case AMOTION_EVENT_AXIS_WHEEL:
7326 return true;
7327 default:
7328 return false;
7329 }
7330}
7331
7332void JoystickInputMapper::reset(nsecs_t when) {
7333 // Recenter all axes.
7334 size_t numAxes = mAxes.size();
7335 for (size_t i = 0; i < numAxes; i++) {
7336 Axis& axis = mAxes.editValueAt(i);
7337 axis.resetValue();
7338 }
7339
7340 InputMapper::reset(when);
7341}
7342
7343void JoystickInputMapper::process(const RawEvent* rawEvent) {
7344 switch (rawEvent->type) {
7345 case EV_ABS: {
7346 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7347 if (index >= 0) {
7348 Axis& axis = mAxes.editValueAt(index);
7349 float newValue, highNewValue;
7350 switch (axis.axisInfo.mode) {
7351 case AxisInfo::MODE_INVERT:
7352 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7353 * axis.scale + axis.offset;
7354 highNewValue = 0.0f;
7355 break;
7356 case AxisInfo::MODE_SPLIT:
7357 if (rawEvent->value < axis.axisInfo.splitValue) {
7358 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7359 * axis.scale + axis.offset;
7360 highNewValue = 0.0f;
7361 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7362 newValue = 0.0f;
7363 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7364 * axis.highScale + axis.highOffset;
7365 } else {
7366 newValue = 0.0f;
7367 highNewValue = 0.0f;
7368 }
7369 break;
7370 default:
7371 newValue = rawEvent->value * axis.scale + axis.offset;
7372 highNewValue = 0.0f;
7373 break;
7374 }
7375 axis.newValue = newValue;
7376 axis.highNewValue = highNewValue;
7377 }
7378 break;
7379 }
7380
7381 case EV_SYN:
7382 switch (rawEvent->code) {
7383 case SYN_REPORT:
7384 sync(rawEvent->when, false /*force*/);
7385 break;
7386 }
7387 break;
7388 }
7389}
7390
7391void JoystickInputMapper::sync(nsecs_t when, bool force) {
7392 if (!filterAxes(force)) {
7393 return;
7394 }
7395
7396 int32_t metaState = mContext->getGlobalMetaState();
7397 int32_t buttonState = 0;
7398
7399 PointerProperties pointerProperties;
7400 pointerProperties.clear();
7401 pointerProperties.id = 0;
7402 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7403
7404 PointerCoords pointerCoords;
7405 pointerCoords.clear();
7406
7407 size_t numAxes = mAxes.size();
7408 for (size_t i = 0; i < numAxes; i++) {
7409 const Axis& axis = mAxes.valueAt(i);
7410 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7411 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7412 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7413 axis.highCurrentValue);
7414 }
7415 }
7416
7417 // Moving a joystick axis should not wake the device because joysticks can
7418 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7419 // button will likely wake the device.
7420 // TODO: Use the input device configuration to control this behavior more finely.
7421 uint32_t policyFlags = 0;
7422
Prabir Pradhan42611e02018-11-27 14:04:02 -08007423 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7424 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007425 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007426 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08007427 0, 0, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007428 getListener()->notifyMotion(&args);
7429}
7430
7431void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7432 int32_t axis, float value) {
7433 pointerCoords->setAxisValue(axis, value);
7434 /* In order to ease the transition for developers from using the old axes
7435 * to the newer, more semantically correct axes, we'll continue to produce
7436 * values for the old axes as mirrors of the value of their corresponding
7437 * new axes. */
7438 int32_t compatAxis = getCompatAxis(axis);
7439 if (compatAxis >= 0) {
7440 pointerCoords->setAxisValue(compatAxis, value);
7441 }
7442}
7443
7444bool JoystickInputMapper::filterAxes(bool force) {
7445 bool atLeastOneSignificantChange = force;
7446 size_t numAxes = mAxes.size();
7447 for (size_t i = 0; i < numAxes; i++) {
7448 Axis& axis = mAxes.editValueAt(i);
7449 if (force || hasValueChangedSignificantly(axis.filter,
7450 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7451 axis.currentValue = axis.newValue;
7452 atLeastOneSignificantChange = true;
7453 }
7454 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7455 if (force || hasValueChangedSignificantly(axis.filter,
7456 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7457 axis.highCurrentValue = axis.highNewValue;
7458 atLeastOneSignificantChange = true;
7459 }
7460 }
7461 }
7462 return atLeastOneSignificantChange;
7463}
7464
7465bool JoystickInputMapper::hasValueChangedSignificantly(
7466 float filter, float newValue, float currentValue, float min, float max) {
7467 if (newValue != currentValue) {
7468 // Filter out small changes in value unless the value is converging on the axis
7469 // bounds or center point. This is intended to reduce the amount of information
7470 // sent to applications by particularly noisy joysticks (such as PS3).
7471 if (fabs(newValue - currentValue) > filter
7472 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7473 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7474 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7475 return true;
7476 }
7477 }
7478 return false;
7479}
7480
7481bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7482 float filter, float newValue, float currentValue, float thresholdValue) {
7483 float newDistance = fabs(newValue - thresholdValue);
7484 if (newDistance < filter) {
7485 float oldDistance = fabs(currentValue - thresholdValue);
7486 if (newDistance < oldDistance) {
7487 return true;
7488 }
7489 }
7490 return false;
7491}
7492
7493} // namespace android