1 /*
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
42 // Log debug messages about fusing stylus data.
43 #define DEBUG_STYLUS_FUSION 0
44
45 #include "InputReader.h"
46
47 #include <errno.h>
48 #include <inttypes.h>
49 #include <limits.h>
50 #include <math.h>
51 #include <stddef.h>
52 #include <stdlib.h>
53 #include <unistd.h>
54
55 #include <log/log.h>
56
57 #include <android-base/stringprintf.h>
58 #include <input/Keyboard.h>
59 #include <input/VirtualKeyMap.h>
60 #include <statslog.h>
61
62 #define INDENT " "
63 #define INDENT2 " "
64 #define INDENT3 " "
65 #define INDENT4 " "
66 #define INDENT5 " "
67
68 using android::base::StringPrintf;
69
70 namespace android {
71
72 // --- Constants ---
73
74 // Maximum number of slots supported when using the slot-based Multitouch Protocol B.
75 static constexpr size_t MAX_SLOTS = 32;
76
77 // Maximum amount of latency to add to touch events while waiting for data from an
78 // external stylus.
79 static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
80
81 // Maximum amount of time to wait on touch data before pushing out new pressure data.
82 static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
83
84 // Artificial latency on synthetic events created from stylus data without corresponding touch
85 // data.
86 static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
87
88 // How often to report input event statistics
89 static constexpr nsecs_t STATISTICS_REPORT_FREQUENCY = seconds_to_nanoseconds(5 * 60);
90
91 // --- Static Functions ---
92
93 template<typename T>
abs(const T & value)94 inline static T abs(const T& value) {
95 return value < 0 ? - value : value;
96 }
97
98 template<typename T>
min(const T & a,const T & b)99 inline static T min(const T& a, const T& b) {
100 return a < b ? a : b;
101 }
102
103 template<typename T>
swap(T & a,T & b)104 inline static void swap(T& a, T& b) {
105 T temp = a;
106 a = b;
107 b = temp;
108 }
109
avg(float x,float y)110 inline static float avg(float x, float y) {
111 return (x + y) / 2;
112 }
113
distance(float x1,float y1,float x2,float y2)114 inline static float distance(float x1, float y1, float x2, float y2) {
115 return hypotf(x1 - x2, y1 - y2);
116 }
117
signExtendNybble(int32_t value)118 inline static int32_t signExtendNybble(int32_t value) {
119 return value >= 8 ? value - 16 : value;
120 }
121
toString(bool value)122 static inline const char* toString(bool value) {
123 return value ? "true" : "false";
124 }
125
rotateValueUsingRotationMap(int32_t value,int32_t orientation,const int32_t map[][4],size_t mapSize)126 static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
127 const int32_t map[][4], size_t mapSize) {
128 if (orientation != DISPLAY_ORIENTATION_0) {
129 for (size_t i = 0; i < mapSize; i++) {
130 if (value == map[i][0]) {
131 return map[i][orientation];
132 }
133 }
134 }
135 return value;
136 }
137
138 static const int32_t keyCodeRotationMap[][4] = {
139 // key codes enumerated counter-clockwise with the original (unrotated) key first
140 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
141 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
142 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
143 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
144 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
145 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
146 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
147 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
148 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
149 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
150 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
151 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
152 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
153 };
154 static const size_t keyCodeRotationMapSize =
155 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
156
rotateStemKey(int32_t value,int32_t orientation,const int32_t map[][2],size_t mapSize)157 static int32_t rotateStemKey(int32_t value, int32_t orientation,
158 const int32_t map[][2], size_t mapSize) {
159 if (orientation == DISPLAY_ORIENTATION_180) {
160 for (size_t i = 0; i < mapSize; i++) {
161 if (value == map[i][0]) {
162 return map[i][1];
163 }
164 }
165 }
166 return value;
167 }
168
169 // The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
170 static int32_t stemKeyRotationMap[][2] = {
171 // key codes enumerated with the original (unrotated) key first
172 // no rotation, 180 degree rotation
173 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
174 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
175 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
176 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
177 };
178 static const size_t stemKeyRotationMapSize =
179 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
180
rotateKeyCode(int32_t keyCode,int32_t orientation)181 static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
182 keyCode = rotateStemKey(keyCode, orientation,
183 stemKeyRotationMap, stemKeyRotationMapSize);
184 return rotateValueUsingRotationMap(keyCode, orientation,
185 keyCodeRotationMap, keyCodeRotationMapSize);
186 }
187
rotateDelta(int32_t orientation,float * deltaX,float * deltaY)188 static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
189 float temp;
190 switch (orientation) {
191 case DISPLAY_ORIENTATION_90:
192 temp = *deltaX;
193 *deltaX = *deltaY;
194 *deltaY = -temp;
195 break;
196
197 case DISPLAY_ORIENTATION_180:
198 *deltaX = -*deltaX;
199 *deltaY = -*deltaY;
200 break;
201
202 case DISPLAY_ORIENTATION_270:
203 temp = *deltaX;
204 *deltaX = -*deltaY;
205 *deltaY = temp;
206 break;
207 }
208 }
209
sourcesMatchMask(uint32_t sources,uint32_t sourceMask)210 static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
211 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
212 }
213
214 // Returns true if the pointer should be reported as being down given the specified
215 // button states. This determines whether the event is reported as a touch event.
isPointerDown(int32_t buttonState)216 static bool isPointerDown(int32_t buttonState) {
217 return buttonState &
218 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
219 | AMOTION_EVENT_BUTTON_TERTIARY);
220 }
221
calculateCommonVector(float a,float b)222 static float calculateCommonVector(float a, float b) {
223 if (a > 0 && b > 0) {
224 return a < b ? a : b;
225 } else if (a < 0 && b < 0) {
226 return a > b ? a : b;
227 } else {
228 return 0;
229 }
230 }
231
synthesizeButtonKey(InputReaderContext * context,int32_t action,nsecs_t when,int32_t deviceId,uint32_t source,int32_t displayId,uint32_t policyFlags,int32_t lastButtonState,int32_t currentButtonState,int32_t buttonState,int32_t keyCode)232 static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
233 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
234 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
235 int32_t buttonState, int32_t keyCode) {
236 if (
237 (action == AKEY_EVENT_ACTION_DOWN
238 && !(lastButtonState & buttonState)
239 && (currentButtonState & buttonState))
240 || (action == AKEY_EVENT_ACTION_UP
241 && (lastButtonState & buttonState)
242 && !(currentButtonState & buttonState))) {
243 NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
244 policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
245 context->getListener()->notifyKey(&args);
246 }
247 }
248
synthesizeButtonKeys(InputReaderContext * context,int32_t action,nsecs_t when,int32_t deviceId,uint32_t source,int32_t displayId,uint32_t policyFlags,int32_t lastButtonState,int32_t currentButtonState)249 static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
250 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
251 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
252 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
253 lastButtonState, currentButtonState,
254 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
255 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
256 lastButtonState, currentButtonState,
257 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
258 }
259
260
261 // --- InputReader ---
262
InputReader(const sp<EventHubInterface> & eventHub,const sp<InputReaderPolicyInterface> & policy,const sp<InputListenerInterface> & listener)263 InputReader::InputReader(const sp<EventHubInterface>& eventHub,
264 const sp<InputReaderPolicyInterface>& policy,
265 const sp<InputListenerInterface>& listener) :
266 mContext(this), mEventHub(eventHub), mPolicy(policy),
267 mNextSequenceNum(1), mGlobalMetaState(0), mGeneration(1),
268 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
269 mConfigurationChangesToRefresh(0) {
270 mQueuedListener = new QueuedInputListener(listener);
271
272 { // acquire lock
273 AutoMutex _l(mLock);
274
275 refreshConfigurationLocked(0);
276 updateGlobalMetaStateLocked();
277 } // release lock
278 }
279
~InputReader()280 InputReader::~InputReader() {
281 for (size_t i = 0; i < mDevices.size(); i++) {
282 delete mDevices.valueAt(i);
283 }
284 }
285
loopOnce()286 void InputReader::loopOnce() {
287 int32_t oldGeneration;
288 int32_t timeoutMillis;
289 bool inputDevicesChanged = false;
290 std::vector<InputDeviceInfo> inputDevices;
291 { // acquire lock
292 AutoMutex _l(mLock);
293
294 oldGeneration = mGeneration;
295 timeoutMillis = -1;
296
297 uint32_t changes = mConfigurationChangesToRefresh;
298 if (changes) {
299 mConfigurationChangesToRefresh = 0;
300 timeoutMillis = 0;
301 refreshConfigurationLocked(changes);
302 } else if (mNextTimeout != LLONG_MAX) {
303 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
304 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
305 }
306 } // release lock
307
308 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
309
310 { // acquire lock
311 AutoMutex _l(mLock);
312 mReaderIsAliveCondition.broadcast();
313
314 if (count) {
315 processEventsLocked(mEventBuffer, count);
316 }
317
318 if (mNextTimeout != LLONG_MAX) {
319 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
320 if (now >= mNextTimeout) {
321 #if DEBUG_RAW_EVENTS
322 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
323 #endif
324 mNextTimeout = LLONG_MAX;
325 timeoutExpiredLocked(now);
326 }
327 }
328
329 if (oldGeneration != mGeneration) {
330 inputDevicesChanged = true;
331 getInputDevicesLocked(inputDevices);
332 }
333 } // release lock
334
335 // Send out a message that the describes the changed input devices.
336 if (inputDevicesChanged) {
337 mPolicy->notifyInputDevicesChanged(inputDevices);
338 }
339
340 // Flush queued events out to the listener.
341 // This must happen outside of the lock because the listener could potentially call
342 // back into the InputReader's methods, such as getScanCodeState, or become blocked
343 // on another thread similarly waiting to acquire the InputReader lock thereby
344 // resulting in a deadlock. This situation is actually quite plausible because the
345 // listener is actually the input dispatcher, which calls into the window manager,
346 // which occasionally calls into the input reader.
347 mQueuedListener->flush();
348 }
349
processEventsLocked(const RawEvent * rawEvents,size_t count)350 void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
351 for (const RawEvent* rawEvent = rawEvents; count;) {
352 int32_t type = rawEvent->type;
353 size_t batchSize = 1;
354 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
355 int32_t deviceId = rawEvent->deviceId;
356 while (batchSize < count) {
357 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
358 || rawEvent[batchSize].deviceId != deviceId) {
359 break;
360 }
361 batchSize += 1;
362 }
363 #if DEBUG_RAW_EVENTS
364 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
365 #endif
366 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
367 } else {
368 switch (rawEvent->type) {
369 case EventHubInterface::DEVICE_ADDED:
370 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
371 break;
372 case EventHubInterface::DEVICE_REMOVED:
373 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
374 break;
375 case EventHubInterface::FINISHED_DEVICE_SCAN:
376 handleConfigurationChangedLocked(rawEvent->when);
377 break;
378 default:
379 ALOG_ASSERT(false); // can't happen
380 break;
381 }
382 }
383 count -= batchSize;
384 rawEvent += batchSize;
385 }
386 }
387
addDeviceLocked(nsecs_t when,int32_t deviceId)388 void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
389 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
390 if (deviceIndex >= 0) {
391 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
392 return;
393 }
394
395 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
396 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
397 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
398
399 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
400 device->configure(when, &mConfig, 0);
401 device->reset(when);
402
403 if (device->isIgnored()) {
404 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
405 identifier.name.c_str());
406 } else {
407 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
408 identifier.name.c_str(), device->getSources());
409 }
410
411 mDevices.add(deviceId, device);
412 bumpGenerationLocked();
413
414 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
415 notifyExternalStylusPresenceChanged();
416 }
417 }
418
removeDeviceLocked(nsecs_t when,int32_t deviceId)419 void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
420 InputDevice* device = nullptr;
421 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
422 if (deviceIndex < 0) {
423 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
424 return;
425 }
426
427 device = mDevices.valueAt(deviceIndex);
428 mDevices.removeItemsAt(deviceIndex, 1);
429 bumpGenerationLocked();
430
431 if (device->isIgnored()) {
432 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
433 device->getId(), device->getName().c_str());
434 } else {
435 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
436 device->getId(), device->getName().c_str(), device->getSources());
437 }
438
439 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
440 notifyExternalStylusPresenceChanged();
441 }
442
443 device->reset(when);
444 delete device;
445 }
446
createDeviceLocked(int32_t deviceId,int32_t controllerNumber,const InputDeviceIdentifier & identifier,uint32_t classes)447 InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
448 const InputDeviceIdentifier& identifier, uint32_t classes) {
449 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
450 controllerNumber, identifier, classes);
451
452 // External devices.
453 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
454 device->setExternal(true);
455 }
456
457 // Devices with mics.
458 if (classes & INPUT_DEVICE_CLASS_MIC) {
459 device->setMic(true);
460 }
461
462 // Switch-like devices.
463 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
464 device->addMapper(new SwitchInputMapper(device));
465 }
466
467 // Scroll wheel-like devices.
468 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
469 device->addMapper(new RotaryEncoderInputMapper(device));
470 }
471
472 // Vibrator-like devices.
473 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
474 device->addMapper(new VibratorInputMapper(device));
475 }
476
477 // Keyboard-like devices.
478 uint32_t keyboardSource = 0;
479 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
480 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
481 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
482 }
483 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
484 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
485 }
486 if (classes & INPUT_DEVICE_CLASS_DPAD) {
487 keyboardSource |= AINPUT_SOURCE_DPAD;
488 }
489 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
490 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
491 }
492
493 if (keyboardSource != 0) {
494 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
495 }
496
497 // Cursor-like devices.
498 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
499 device->addMapper(new CursorInputMapper(device));
500 }
501
502 // Touchscreens and touchpad devices.
503 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
504 device->addMapper(new MultiTouchInputMapper(device));
505 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
506 device->addMapper(new SingleTouchInputMapper(device));
507 }
508
509 // Joystick-like devices.
510 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
511 device->addMapper(new JoystickInputMapper(device));
512 }
513
514 // External stylus-like devices.
515 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
516 device->addMapper(new ExternalStylusInputMapper(device));
517 }
518
519 return device;
520 }
521
processEventsForDeviceLocked(int32_t deviceId,const RawEvent * rawEvents,size_t count)522 void InputReader::processEventsForDeviceLocked(int32_t deviceId,
523 const RawEvent* rawEvents, size_t count) {
524 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
525 if (deviceIndex < 0) {
526 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
527 return;
528 }
529
530 InputDevice* device = mDevices.valueAt(deviceIndex);
531 if (device->isIgnored()) {
532 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
533 return;
534 }
535
536 device->process(rawEvents, count);
537 }
538
timeoutExpiredLocked(nsecs_t when)539 void InputReader::timeoutExpiredLocked(nsecs_t when) {
540 for (size_t i = 0; i < mDevices.size(); i++) {
541 InputDevice* device = mDevices.valueAt(i);
542 if (!device->isIgnored()) {
543 device->timeoutExpired(when);
544 }
545 }
546 }
547
handleConfigurationChangedLocked(nsecs_t when)548 void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
549 // Reset global meta state because it depends on the list of all configured devices.
550 updateGlobalMetaStateLocked();
551
552 // Enqueue configuration changed.
553 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
554 mQueuedListener->notifyConfigurationChanged(&args);
555 }
556
refreshConfigurationLocked(uint32_t changes)557 void InputReader::refreshConfigurationLocked(uint32_t changes) {
558 mPolicy->getReaderConfiguration(&mConfig);
559 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
560
561 if (changes) {
562 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
563 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
564
565 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
566 mEventHub->requestReopenDevices();
567 } else {
568 for (size_t i = 0; i < mDevices.size(); i++) {
569 InputDevice* device = mDevices.valueAt(i);
570 device->configure(now, &mConfig, changes);
571 }
572 }
573 }
574 }
575
updateGlobalMetaStateLocked()576 void InputReader::updateGlobalMetaStateLocked() {
577 mGlobalMetaState = 0;
578
579 for (size_t i = 0; i < mDevices.size(); i++) {
580 InputDevice* device = mDevices.valueAt(i);
581 mGlobalMetaState |= device->getMetaState();
582 }
583 }
584
getGlobalMetaStateLocked()585 int32_t InputReader::getGlobalMetaStateLocked() {
586 return mGlobalMetaState;
587 }
588
notifyExternalStylusPresenceChanged()589 void InputReader::notifyExternalStylusPresenceChanged() {
590 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
591 }
592
getExternalStylusDevicesLocked(std::vector<InputDeviceInfo> & outDevices)593 void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
594 for (size_t i = 0; i < mDevices.size(); i++) {
595 InputDevice* device = mDevices.valueAt(i);
596 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
597 InputDeviceInfo info;
598 device->getDeviceInfo(&info);
599 outDevices.push_back(info);
600 }
601 }
602 }
603
dispatchExternalStylusState(const StylusState & state)604 void InputReader::dispatchExternalStylusState(const StylusState& state) {
605 for (size_t i = 0; i < mDevices.size(); i++) {
606 InputDevice* device = mDevices.valueAt(i);
607 device->updateExternalStylusState(state);
608 }
609 }
610
disableVirtualKeysUntilLocked(nsecs_t time)611 void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
612 mDisableVirtualKeysTimeout = time;
613 }
614
shouldDropVirtualKeyLocked(nsecs_t now,InputDevice * device,int32_t keyCode,int32_t scanCode)615 bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
616 InputDevice* device, int32_t keyCode, int32_t scanCode) {
617 if (now < mDisableVirtualKeysTimeout) {
618 ALOGI("Dropping virtual key from device %s because virtual keys are "
619 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
620 device->getName().c_str(),
621 (mDisableVirtualKeysTimeout - now) * 0.000001,
622 keyCode, scanCode);
623 return true;
624 } else {
625 return false;
626 }
627 }
628
fadePointerLocked()629 void InputReader::fadePointerLocked() {
630 for (size_t i = 0; i < mDevices.size(); i++) {
631 InputDevice* device = mDevices.valueAt(i);
632 device->fadePointer();
633 }
634 }
635
requestTimeoutAtTimeLocked(nsecs_t when)636 void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
637 if (when < mNextTimeout) {
638 mNextTimeout = when;
639 mEventHub->wake();
640 }
641 }
642
bumpGenerationLocked()643 int32_t InputReader::bumpGenerationLocked() {
644 return ++mGeneration;
645 }
646
getInputDevices(std::vector<InputDeviceInfo> & outInputDevices)647 void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
648 AutoMutex _l(mLock);
649 getInputDevicesLocked(outInputDevices);
650 }
651
getInputDevicesLocked(std::vector<InputDeviceInfo> & outInputDevices)652 void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
653 outInputDevices.clear();
654
655 size_t numDevices = mDevices.size();
656 for (size_t i = 0; i < numDevices; i++) {
657 InputDevice* device = mDevices.valueAt(i);
658 if (!device->isIgnored()) {
659 InputDeviceInfo info;
660 device->getDeviceInfo(&info);
661 outInputDevices.push_back(info);
662 }
663 }
664 }
665
getKeyCodeState(int32_t deviceId,uint32_t sourceMask,int32_t keyCode)666 int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
667 int32_t keyCode) {
668 AutoMutex _l(mLock);
669
670 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
671 }
672
getScanCodeState(int32_t deviceId,uint32_t sourceMask,int32_t scanCode)673 int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
674 int32_t scanCode) {
675 AutoMutex _l(mLock);
676
677 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
678 }
679
getSwitchState(int32_t deviceId,uint32_t sourceMask,int32_t switchCode)680 int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
681 AutoMutex _l(mLock);
682
683 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
684 }
685
getStateLocked(int32_t deviceId,uint32_t sourceMask,int32_t code,GetStateFunc getStateFunc)686 int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
687 GetStateFunc getStateFunc) {
688 int32_t result = AKEY_STATE_UNKNOWN;
689 if (deviceId >= 0) {
690 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
691 if (deviceIndex >= 0) {
692 InputDevice* device = mDevices.valueAt(deviceIndex);
693 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
694 result = (device->*getStateFunc)(sourceMask, code);
695 }
696 }
697 } else {
698 size_t numDevices = mDevices.size();
699 for (size_t i = 0; i < numDevices; i++) {
700 InputDevice* device = mDevices.valueAt(i);
701 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
702 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
703 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
704 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
705 if (currentResult >= AKEY_STATE_DOWN) {
706 return currentResult;
707 } else if (currentResult == AKEY_STATE_UP) {
708 result = currentResult;
709 }
710 }
711 }
712 }
713 return result;
714 }
715
toggleCapsLockState(int32_t deviceId)716 void InputReader::toggleCapsLockState(int32_t deviceId) {
717 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
718 if (deviceIndex < 0) {
719 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
720 return;
721 }
722
723 InputDevice* device = mDevices.valueAt(deviceIndex);
724 if (device->isIgnored()) {
725 return;
726 }
727
728 device->updateMetaState(AKEYCODE_CAPS_LOCK);
729 }
730
hasKeys(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)731 bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
732 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
733 AutoMutex _l(mLock);
734
735 memset(outFlags, 0, numCodes);
736 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
737 }
738
markSupportedKeyCodesLocked(int32_t deviceId,uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)739 bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
740 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
741 bool result = false;
742 if (deviceId >= 0) {
743 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
744 if (deviceIndex >= 0) {
745 InputDevice* device = mDevices.valueAt(deviceIndex);
746 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
747 result = device->markSupportedKeyCodes(sourceMask,
748 numCodes, keyCodes, outFlags);
749 }
750 }
751 } else {
752 size_t numDevices = mDevices.size();
753 for (size_t i = 0; i < numDevices; i++) {
754 InputDevice* device = mDevices.valueAt(i);
755 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
756 result |= device->markSupportedKeyCodes(sourceMask,
757 numCodes, keyCodes, outFlags);
758 }
759 }
760 }
761 return result;
762 }
763
requestRefreshConfiguration(uint32_t changes)764 void InputReader::requestRefreshConfiguration(uint32_t changes) {
765 AutoMutex _l(mLock);
766
767 if (changes) {
768 bool needWake = !mConfigurationChangesToRefresh;
769 mConfigurationChangesToRefresh |= changes;
770
771 if (needWake) {
772 mEventHub->wake();
773 }
774 }
775 }
776
vibrate(int32_t deviceId,const nsecs_t * pattern,size_t patternSize,ssize_t repeat,int32_t token)777 void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
778 ssize_t repeat, int32_t token) {
779 AutoMutex _l(mLock);
780
781 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
782 if (deviceIndex >= 0) {
783 InputDevice* device = mDevices.valueAt(deviceIndex);
784 device->vibrate(pattern, patternSize, repeat, token);
785 }
786 }
787
cancelVibrate(int32_t deviceId,int32_t token)788 void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
789 AutoMutex _l(mLock);
790
791 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
792 if (deviceIndex >= 0) {
793 InputDevice* device = mDevices.valueAt(deviceIndex);
794 device->cancelVibrate(token);
795 }
796 }
797
isInputDeviceEnabled(int32_t deviceId)798 bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
799 AutoMutex _l(mLock);
800
801 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
802 if (deviceIndex >= 0) {
803 InputDevice* device = mDevices.valueAt(deviceIndex);
804 return device->isEnabled();
805 }
806 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
807 return false;
808 }
809
canDispatchToDisplay(int32_t deviceId,int32_t displayId)810 bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
811 AutoMutex _l(mLock);
812
813 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
814 if (deviceIndex < 0) {
815 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
816 return false;
817 }
818
819 InputDevice* device = mDevices.valueAt(deviceIndex);
820 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplay();
821 // No associated display. By default, can dispatch to all displays.
822 if (!associatedDisplayId) {
823 return true;
824 }
825
826 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
827 ALOGW("Device has associated, but no associated display id.");
828 return true;
829 }
830
831 return *associatedDisplayId == displayId;
832 }
833
dump(std::string & dump)834 void InputReader::dump(std::string& dump) {
835 AutoMutex _l(mLock);
836
837 mEventHub->dump(dump);
838 dump += "\n";
839
840 dump += "Input Reader State:\n";
841
842 for (size_t i = 0; i < mDevices.size(); i++) {
843 mDevices.valueAt(i)->dump(dump);
844 }
845
846 dump += INDENT "Configuration:\n";
847 dump += INDENT2 "ExcludedDeviceNames: [";
848 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
849 if (i != 0) {
850 dump += ", ";
851 }
852 dump += mConfig.excludedDeviceNames[i];
853 }
854 dump += "]\n";
855 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
856 mConfig.virtualKeyQuietTime * 0.000001f);
857
858 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
859 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
860 mConfig.pointerVelocityControlParameters.scale,
861 mConfig.pointerVelocityControlParameters.lowThreshold,
862 mConfig.pointerVelocityControlParameters.highThreshold,
863 mConfig.pointerVelocityControlParameters.acceleration);
864
865 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
866 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
867 mConfig.wheelVelocityControlParameters.scale,
868 mConfig.wheelVelocityControlParameters.lowThreshold,
869 mConfig.wheelVelocityControlParameters.highThreshold,
870 mConfig.wheelVelocityControlParameters.acceleration);
871
872 dump += StringPrintf(INDENT2 "PointerGesture:\n");
873 dump += StringPrintf(INDENT3 "Enabled: %s\n",
874 toString(mConfig.pointerGesturesEnabled));
875 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
876 mConfig.pointerGestureQuietInterval * 0.000001f);
877 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
878 mConfig.pointerGestureDragMinSwitchSpeed);
879 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
880 mConfig.pointerGestureTapInterval * 0.000001f);
881 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
882 mConfig.pointerGestureTapDragInterval * 0.000001f);
883 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
884 mConfig.pointerGestureTapSlop);
885 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
886 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
887 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
888 mConfig.pointerGestureMultitouchMinDistance);
889 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
890 mConfig.pointerGestureSwipeTransitionAngleCosine);
891 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
892 mConfig.pointerGestureSwipeMaxWidthRatio);
893 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
894 mConfig.pointerGestureMovementSpeedRatio);
895 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
896 mConfig.pointerGestureZoomSpeedRatio);
897
898 dump += INDENT3 "Viewports:\n";
899 mConfig.dump(dump);
900 }
901
monitor()902 void InputReader::monitor() {
903 // Acquire and release the lock to ensure that the reader has not deadlocked.
904 mLock.lock();
905 mEventHub->wake();
906 mReaderIsAliveCondition.wait(mLock);
907 mLock.unlock();
908
909 // Check the EventHub
910 mEventHub->monitor();
911 }
912
913
914 // --- InputReader::ContextImpl ---
915
ContextImpl(InputReader * reader)916 InputReader::ContextImpl::ContextImpl(InputReader* reader) :
917 mReader(reader) {
918 }
919
updateGlobalMetaState()920 void InputReader::ContextImpl::updateGlobalMetaState() {
921 // lock is already held by the input loop
922 mReader->updateGlobalMetaStateLocked();
923 }
924
getGlobalMetaState()925 int32_t InputReader::ContextImpl::getGlobalMetaState() {
926 // lock is already held by the input loop
927 return mReader->getGlobalMetaStateLocked();
928 }
929
disableVirtualKeysUntil(nsecs_t time)930 void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
931 // lock is already held by the input loop
932 mReader->disableVirtualKeysUntilLocked(time);
933 }
934
shouldDropVirtualKey(nsecs_t now,InputDevice * device,int32_t keyCode,int32_t scanCode)935 bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
936 InputDevice* device, int32_t keyCode, int32_t scanCode) {
937 // lock is already held by the input loop
938 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
939 }
940
fadePointer()941 void InputReader::ContextImpl::fadePointer() {
942 // lock is already held by the input loop
943 mReader->fadePointerLocked();
944 }
945
requestTimeoutAtTime(nsecs_t when)946 void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
947 // lock is already held by the input loop
948 mReader->requestTimeoutAtTimeLocked(when);
949 }
950
bumpGeneration()951 int32_t InputReader::ContextImpl::bumpGeneration() {
952 // lock is already held by the input loop
953 return mReader->bumpGenerationLocked();
954 }
955
getExternalStylusDevices(std::vector<InputDeviceInfo> & outDevices)956 void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
957 // lock is already held by whatever called refreshConfigurationLocked
958 mReader->getExternalStylusDevicesLocked(outDevices);
959 }
960
dispatchExternalStylusState(const StylusState & state)961 void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
962 mReader->dispatchExternalStylusState(state);
963 }
964
getPolicy()965 InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
966 return mReader->mPolicy.get();
967 }
968
getListener()969 InputListenerInterface* InputReader::ContextImpl::getListener() {
970 return mReader->mQueuedListener.get();
971 }
972
getEventHub()973 EventHubInterface* InputReader::ContextImpl::getEventHub() {
974 return mReader->mEventHub.get();
975 }
976
getNextSequenceNum()977 uint32_t InputReader::ContextImpl::getNextSequenceNum() {
978 return (mReader->mNextSequenceNum)++;
979 }
980
981 // --- InputDevice ---
982
InputDevice(InputReaderContext * context,int32_t id,int32_t generation,int32_t controllerNumber,const InputDeviceIdentifier & identifier,uint32_t classes)983 InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
984 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
985 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
986 mIdentifier(identifier), mClasses(classes),
987 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
988 }
989
~InputDevice()990 InputDevice::~InputDevice() {
991 size_t numMappers = mMappers.size();
992 for (size_t i = 0; i < numMappers; i++) {
993 delete mMappers[i];
994 }
995 mMappers.clear();
996 }
997
isEnabled()998 bool InputDevice::isEnabled() {
999 return getEventHub()->isDeviceEnabled(mId);
1000 }
1001
setEnabled(bool enabled,nsecs_t when)1002 void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1003 if (isEnabled() == enabled) {
1004 return;
1005 }
1006
1007 if (enabled) {
1008 getEventHub()->enableDevice(mId);
1009 reset(when);
1010 } else {
1011 reset(when);
1012 getEventHub()->disableDevice(mId);
1013 }
1014 // Must change generation to flag this device as changed
1015 bumpGeneration();
1016 }
1017
dump(std::string & dump)1018 void InputDevice::dump(std::string& dump) {
1019 InputDeviceInfo deviceInfo;
1020 getDeviceInfo(&deviceInfo);
1021
1022 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
1023 deviceInfo.getDisplayName().c_str());
1024 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1025 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
1026 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1027 if (mAssociatedDisplayPort) {
1028 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1029 } else {
1030 dump += "<none>\n";
1031 }
1032 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1033 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1034 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
1035
1036 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1037 if (!ranges.empty()) {
1038 dump += INDENT2 "Motion Ranges:\n";
1039 for (size_t i = 0; i < ranges.size(); i++) {
1040 const InputDeviceInfo::MotionRange& range = ranges[i];
1041 const char* label = getAxisLabel(range.axis);
1042 char name[32];
1043 if (label) {
1044 strncpy(name, label, sizeof(name));
1045 name[sizeof(name) - 1] = '\0';
1046 } else {
1047 snprintf(name, sizeof(name), "%d", range.axis);
1048 }
1049 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
1050 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1051 name, range.source, range.min, range.max, range.flat, range.fuzz,
1052 range.resolution);
1053 }
1054 }
1055
1056 size_t numMappers = mMappers.size();
1057 for (size_t i = 0; i < numMappers; i++) {
1058 InputMapper* mapper = mMappers[i];
1059 mapper->dump(dump);
1060 }
1061 }
1062
addMapper(InputMapper * mapper)1063 void InputDevice::addMapper(InputMapper* mapper) {
1064 mMappers.push_back(mapper);
1065 }
1066
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)1067 void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1068 mSources = 0;
1069
1070 if (!isIgnored()) {
1071 if (!changes) { // first time only
1072 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1073 }
1074
1075 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1076 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1077 sp<KeyCharacterMap> keyboardLayout =
1078 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1079 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1080 bumpGeneration();
1081 }
1082 }
1083 }
1084
1085 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1086 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1087 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
1088 if (mAlias != alias) {
1089 mAlias = alias;
1090 bumpGeneration();
1091 }
1092 }
1093 }
1094
1095 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1096 ssize_t index = config->disabledDevices.indexOf(mId);
1097 bool enabled = index < 0;
1098 setEnabled(enabled, when);
1099 }
1100
1101 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1102 // In most situations, no port will be specified.
1103 mAssociatedDisplayPort = std::nullopt;
1104 // Find the display port that corresponds to the current input port.
1105 const std::string& inputPort = mIdentifier.location;
1106 if (!inputPort.empty()) {
1107 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1108 const auto& displayPort = ports.find(inputPort);
1109 if (displayPort != ports.end()) {
1110 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1111 }
1112 }
1113 }
1114
1115 for (InputMapper* mapper : mMappers) {
1116 mapper->configure(when, config, changes);
1117 mSources |= mapper->getSources();
1118 }
1119 }
1120 }
1121
reset(nsecs_t when)1122 void InputDevice::reset(nsecs_t when) {
1123 for (InputMapper* mapper : mMappers) {
1124 mapper->reset(when);
1125 }
1126
1127 mContext->updateGlobalMetaState();
1128
1129 notifyReset(when);
1130 }
1131
process(const RawEvent * rawEvents,size_t count)1132 void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1133 // Process all of the events in order for each mapper.
1134 // We cannot simply ask each mapper to process them in bulk because mappers may
1135 // have side-effects that must be interleaved. For example, joystick movement events and
1136 // gamepad button presses are handled by different mappers but they should be dispatched
1137 // in the order received.
1138 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
1139 #if DEBUG_RAW_EVENTS
1140 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
1141 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1142 rawEvent->when);
1143 #endif
1144
1145 if (mDropUntilNextSync) {
1146 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1147 mDropUntilNextSync = false;
1148 #if DEBUG_RAW_EVENTS
1149 ALOGD("Recovered from input event buffer overrun.");
1150 #endif
1151 } else {
1152 #if DEBUG_RAW_EVENTS
1153 ALOGD("Dropped input event while waiting for next input sync.");
1154 #endif
1155 }
1156 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
1157 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
1158 mDropUntilNextSync = true;
1159 reset(rawEvent->when);
1160 } else {
1161 for (InputMapper* mapper : mMappers) {
1162 mapper->process(rawEvent);
1163 }
1164 }
1165 --count;
1166 }
1167 }
1168
timeoutExpired(nsecs_t when)1169 void InputDevice::timeoutExpired(nsecs_t when) {
1170 for (InputMapper* mapper : mMappers) {
1171 mapper->timeoutExpired(when);
1172 }
1173 }
1174
updateExternalStylusState(const StylusState & state)1175 void InputDevice::updateExternalStylusState(const StylusState& state) {
1176 for (InputMapper* mapper : mMappers) {
1177 mapper->updateExternalStylusState(state);
1178 }
1179 }
1180
getDeviceInfo(InputDeviceInfo * outDeviceInfo)1181 void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1182 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
1183 mIsExternal, mHasMic);
1184 for (InputMapper* mapper : mMappers) {
1185 mapper->populateDeviceInfo(outDeviceInfo);
1186 }
1187 }
1188
getKeyCodeState(uint32_t sourceMask,int32_t keyCode)1189 int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1190 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1191 }
1192
getScanCodeState(uint32_t sourceMask,int32_t scanCode)1193 int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1194 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1195 }
1196
getSwitchState(uint32_t sourceMask,int32_t switchCode)1197 int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1198 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1199 }
1200
getState(uint32_t sourceMask,int32_t code,GetStateFunc getStateFunc)1201 int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1202 int32_t result = AKEY_STATE_UNKNOWN;
1203 for (InputMapper* mapper : mMappers) {
1204 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1205 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1206 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1207 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1208 if (currentResult >= AKEY_STATE_DOWN) {
1209 return currentResult;
1210 } else if (currentResult == AKEY_STATE_UP) {
1211 result = currentResult;
1212 }
1213 }
1214 }
1215 return result;
1216 }
1217
markSupportedKeyCodes(uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)1218 bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1219 const int32_t* keyCodes, uint8_t* outFlags) {
1220 bool result = false;
1221 for (InputMapper* mapper : mMappers) {
1222 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1223 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1224 }
1225 }
1226 return result;
1227 }
1228
vibrate(const nsecs_t * pattern,size_t patternSize,ssize_t repeat,int32_t token)1229 void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1230 int32_t token) {
1231 for (InputMapper* mapper : mMappers) {
1232 mapper->vibrate(pattern, patternSize, repeat, token);
1233 }
1234 }
1235
cancelVibrate(int32_t token)1236 void InputDevice::cancelVibrate(int32_t token) {
1237 for (InputMapper* mapper : mMappers) {
1238 mapper->cancelVibrate(token);
1239 }
1240 }
1241
cancelTouch(nsecs_t when)1242 void InputDevice::cancelTouch(nsecs_t when) {
1243 for (InputMapper* mapper : mMappers) {
1244 mapper->cancelTouch(when);
1245 }
1246 }
1247
getMetaState()1248 int32_t InputDevice::getMetaState() {
1249 int32_t result = 0;
1250 for (InputMapper* mapper : mMappers) {
1251 result |= mapper->getMetaState();
1252 }
1253 return result;
1254 }
1255
updateMetaState(int32_t keyCode)1256 void InputDevice::updateMetaState(int32_t keyCode) {
1257 for (InputMapper* mapper : mMappers) {
1258 mapper->updateMetaState(keyCode);
1259 }
1260 }
1261
fadePointer()1262 void InputDevice::fadePointer() {
1263 for (InputMapper* mapper : mMappers) {
1264 mapper->fadePointer();
1265 }
1266 }
1267
bumpGeneration()1268 void InputDevice::bumpGeneration() {
1269 mGeneration = mContext->bumpGeneration();
1270 }
1271
notifyReset(nsecs_t when)1272 void InputDevice::notifyReset(nsecs_t when) {
1273 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
1274 mContext->getListener()->notifyDeviceReset(&args);
1275 }
1276
getAssociatedDisplay()1277 std::optional<int32_t> InputDevice::getAssociatedDisplay() {
1278 for (InputMapper* mapper : mMappers) {
1279 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplay();
1280 if (associatedDisplayId) {
1281 return associatedDisplayId;
1282 }
1283 }
1284
1285 return std::nullopt;
1286 }
1287
1288 // --- CursorButtonAccumulator ---
1289
CursorButtonAccumulator()1290 CursorButtonAccumulator::CursorButtonAccumulator() {
1291 clearButtons();
1292 }
1293
reset(InputDevice * device)1294 void CursorButtonAccumulator::reset(InputDevice* device) {
1295 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1296 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1297 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1298 mBtnBack = device->isKeyPressed(BTN_BACK);
1299 mBtnSide = device->isKeyPressed(BTN_SIDE);
1300 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1301 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1302 mBtnTask = device->isKeyPressed(BTN_TASK);
1303 }
1304
clearButtons()1305 void CursorButtonAccumulator::clearButtons() {
1306 mBtnLeft = 0;
1307 mBtnRight = 0;
1308 mBtnMiddle = 0;
1309 mBtnBack = 0;
1310 mBtnSide = 0;
1311 mBtnForward = 0;
1312 mBtnExtra = 0;
1313 mBtnTask = 0;
1314 }
1315
process(const RawEvent * rawEvent)1316 void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1317 if (rawEvent->type == EV_KEY) {
1318 switch (rawEvent->code) {
1319 case BTN_LEFT:
1320 mBtnLeft = rawEvent->value;
1321 break;
1322 case BTN_RIGHT:
1323 mBtnRight = rawEvent->value;
1324 break;
1325 case BTN_MIDDLE:
1326 mBtnMiddle = rawEvent->value;
1327 break;
1328 case BTN_BACK:
1329 mBtnBack = rawEvent->value;
1330 break;
1331 case BTN_SIDE:
1332 mBtnSide = rawEvent->value;
1333 break;
1334 case BTN_FORWARD:
1335 mBtnForward = rawEvent->value;
1336 break;
1337 case BTN_EXTRA:
1338 mBtnExtra = rawEvent->value;
1339 break;
1340 case BTN_TASK:
1341 mBtnTask = rawEvent->value;
1342 break;
1343 }
1344 }
1345 }
1346
getButtonState() const1347 uint32_t CursorButtonAccumulator::getButtonState() const {
1348 uint32_t result = 0;
1349 if (mBtnLeft) {
1350 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1351 }
1352 if (mBtnRight) {
1353 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1354 }
1355 if (mBtnMiddle) {
1356 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1357 }
1358 if (mBtnBack || mBtnSide) {
1359 result |= AMOTION_EVENT_BUTTON_BACK;
1360 }
1361 if (mBtnForward || mBtnExtra) {
1362 result |= AMOTION_EVENT_BUTTON_FORWARD;
1363 }
1364 return result;
1365 }
1366
1367
1368 // --- CursorMotionAccumulator ---
1369
CursorMotionAccumulator()1370 CursorMotionAccumulator::CursorMotionAccumulator() {
1371 clearRelativeAxes();
1372 }
1373
reset(InputDevice * device)1374 void CursorMotionAccumulator::reset(InputDevice* device) {
1375 clearRelativeAxes();
1376 }
1377
clearRelativeAxes()1378 void CursorMotionAccumulator::clearRelativeAxes() {
1379 mRelX = 0;
1380 mRelY = 0;
1381 }
1382
process(const RawEvent * rawEvent)1383 void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1384 if (rawEvent->type == EV_REL) {
1385 switch (rawEvent->code) {
1386 case REL_X:
1387 mRelX = rawEvent->value;
1388 break;
1389 case REL_Y:
1390 mRelY = rawEvent->value;
1391 break;
1392 }
1393 }
1394 }
1395
finishSync()1396 void CursorMotionAccumulator::finishSync() {
1397 clearRelativeAxes();
1398 }
1399
1400
1401 // --- CursorScrollAccumulator ---
1402
CursorScrollAccumulator()1403 CursorScrollAccumulator::CursorScrollAccumulator() :
1404 mHaveRelWheel(false), mHaveRelHWheel(false) {
1405 clearRelativeAxes();
1406 }
1407
configure(InputDevice * device)1408 void CursorScrollAccumulator::configure(InputDevice* device) {
1409 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1410 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1411 }
1412
reset(InputDevice * device)1413 void CursorScrollAccumulator::reset(InputDevice* device) {
1414 clearRelativeAxes();
1415 }
1416
clearRelativeAxes()1417 void CursorScrollAccumulator::clearRelativeAxes() {
1418 mRelWheel = 0;
1419 mRelHWheel = 0;
1420 }
1421
process(const RawEvent * rawEvent)1422 void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1423 if (rawEvent->type == EV_REL) {
1424 switch (rawEvent->code) {
1425 case REL_WHEEL:
1426 mRelWheel = rawEvent->value;
1427 break;
1428 case REL_HWHEEL:
1429 mRelHWheel = rawEvent->value;
1430 break;
1431 }
1432 }
1433 }
1434
finishSync()1435 void CursorScrollAccumulator::finishSync() {
1436 clearRelativeAxes();
1437 }
1438
1439
1440 // --- TouchButtonAccumulator ---
1441
TouchButtonAccumulator()1442 TouchButtonAccumulator::TouchButtonAccumulator() :
1443 mHaveBtnTouch(false), mHaveStylus(false) {
1444 clearButtons();
1445 }
1446
configure(InputDevice * device)1447 void TouchButtonAccumulator::configure(InputDevice* device) {
1448 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1449 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1450 || device->hasKey(BTN_TOOL_RUBBER)
1451 || device->hasKey(BTN_TOOL_BRUSH)
1452 || device->hasKey(BTN_TOOL_PENCIL)
1453 || device->hasKey(BTN_TOOL_AIRBRUSH);
1454 }
1455
reset(InputDevice * device)1456 void TouchButtonAccumulator::reset(InputDevice* device) {
1457 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1458 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
1459 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1460 mBtnStylus2 =
1461 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
1462 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1463 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1464 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1465 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1466 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1467 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1468 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1469 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1470 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1471 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1472 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1473 }
1474
clearButtons()1475 void TouchButtonAccumulator::clearButtons() {
1476 mBtnTouch = 0;
1477 mBtnStylus = 0;
1478 mBtnStylus2 = 0;
1479 mBtnToolFinger = 0;
1480 mBtnToolPen = 0;
1481 mBtnToolRubber = 0;
1482 mBtnToolBrush = 0;
1483 mBtnToolPencil = 0;
1484 mBtnToolAirbrush = 0;
1485 mBtnToolMouse = 0;
1486 mBtnToolLens = 0;
1487 mBtnToolDoubleTap = 0;
1488 mBtnToolTripleTap = 0;
1489 mBtnToolQuadTap = 0;
1490 }
1491
process(const RawEvent * rawEvent)1492 void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1493 if (rawEvent->type == EV_KEY) {
1494 switch (rawEvent->code) {
1495 case BTN_TOUCH:
1496 mBtnTouch = rawEvent->value;
1497 break;
1498 case BTN_STYLUS:
1499 mBtnStylus = rawEvent->value;
1500 break;
1501 case BTN_STYLUS2:
1502 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1503 mBtnStylus2 = rawEvent->value;
1504 break;
1505 case BTN_TOOL_FINGER:
1506 mBtnToolFinger = rawEvent->value;
1507 break;
1508 case BTN_TOOL_PEN:
1509 mBtnToolPen = rawEvent->value;
1510 break;
1511 case BTN_TOOL_RUBBER:
1512 mBtnToolRubber = rawEvent->value;
1513 break;
1514 case BTN_TOOL_BRUSH:
1515 mBtnToolBrush = rawEvent->value;
1516 break;
1517 case BTN_TOOL_PENCIL:
1518 mBtnToolPencil = rawEvent->value;
1519 break;
1520 case BTN_TOOL_AIRBRUSH:
1521 mBtnToolAirbrush = rawEvent->value;
1522 break;
1523 case BTN_TOOL_MOUSE:
1524 mBtnToolMouse = rawEvent->value;
1525 break;
1526 case BTN_TOOL_LENS:
1527 mBtnToolLens = rawEvent->value;
1528 break;
1529 case BTN_TOOL_DOUBLETAP:
1530 mBtnToolDoubleTap = rawEvent->value;
1531 break;
1532 case BTN_TOOL_TRIPLETAP:
1533 mBtnToolTripleTap = rawEvent->value;
1534 break;
1535 case BTN_TOOL_QUADTAP:
1536 mBtnToolQuadTap = rawEvent->value;
1537 break;
1538 }
1539 }
1540 }
1541
getButtonState() const1542 uint32_t TouchButtonAccumulator::getButtonState() const {
1543 uint32_t result = 0;
1544 if (mBtnStylus) {
1545 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
1546 }
1547 if (mBtnStylus2) {
1548 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
1549 }
1550 return result;
1551 }
1552
getToolType() const1553 int32_t TouchButtonAccumulator::getToolType() const {
1554 if (mBtnToolMouse || mBtnToolLens) {
1555 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1556 }
1557 if (mBtnToolRubber) {
1558 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1559 }
1560 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1561 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1562 }
1563 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1564 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1565 }
1566 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1567 }
1568
isToolActive() const1569 bool TouchButtonAccumulator::isToolActive() const {
1570 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1571 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1572 || mBtnToolMouse || mBtnToolLens
1573 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1574 }
1575
isHovering() const1576 bool TouchButtonAccumulator::isHovering() const {
1577 return mHaveBtnTouch && !mBtnTouch;
1578 }
1579
hasStylus() const1580 bool TouchButtonAccumulator::hasStylus() const {
1581 return mHaveStylus;
1582 }
1583
1584
1585 // --- RawPointerAxes ---
1586
RawPointerAxes()1587 RawPointerAxes::RawPointerAxes() {
1588 clear();
1589 }
1590
clear()1591 void RawPointerAxes::clear() {
1592 x.clear();
1593 y.clear();
1594 pressure.clear();
1595 touchMajor.clear();
1596 touchMinor.clear();
1597 toolMajor.clear();
1598 toolMinor.clear();
1599 orientation.clear();
1600 distance.clear();
1601 tiltX.clear();
1602 tiltY.clear();
1603 trackingId.clear();
1604 slot.clear();
1605 }
1606
1607
1608 // --- RawPointerData ---
1609
RawPointerData()1610 RawPointerData::RawPointerData() {
1611 clear();
1612 }
1613
clear()1614 void RawPointerData::clear() {
1615 pointerCount = 0;
1616 clearIdBits();
1617 }
1618
copyFrom(const RawPointerData & other)1619 void RawPointerData::copyFrom(const RawPointerData& other) {
1620 pointerCount = other.pointerCount;
1621 hoveringIdBits = other.hoveringIdBits;
1622 touchingIdBits = other.touchingIdBits;
1623
1624 for (uint32_t i = 0; i < pointerCount; i++) {
1625 pointers[i] = other.pointers[i];
1626
1627 int id = pointers[i].id;
1628 idToIndex[id] = other.idToIndex[id];
1629 }
1630 }
1631
getCentroidOfTouchingPointers(float * outX,float * outY) const1632 void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1633 float x = 0, y = 0;
1634 uint32_t count = touchingIdBits.count();
1635 if (count) {
1636 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1637 uint32_t id = idBits.clearFirstMarkedBit();
1638 const Pointer& pointer = pointerForId(id);
1639 x += pointer.x;
1640 y += pointer.y;
1641 }
1642 x /= count;
1643 y /= count;
1644 }
1645 *outX = x;
1646 *outY = y;
1647 }
1648
1649
1650 // --- CookedPointerData ---
1651
CookedPointerData()1652 CookedPointerData::CookedPointerData() {
1653 clear();
1654 }
1655
clear()1656 void CookedPointerData::clear() {
1657 pointerCount = 0;
1658 hoveringIdBits.clear();
1659 touchingIdBits.clear();
1660 }
1661
copyFrom(const CookedPointerData & other)1662 void CookedPointerData::copyFrom(const CookedPointerData& other) {
1663 pointerCount = other.pointerCount;
1664 hoveringIdBits = other.hoveringIdBits;
1665 touchingIdBits = other.touchingIdBits;
1666
1667 for (uint32_t i = 0; i < pointerCount; i++) {
1668 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1669 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1670
1671 int id = pointerProperties[i].id;
1672 idToIndex[id] = other.idToIndex[id];
1673 }
1674 }
1675
1676
1677 // --- SingleTouchMotionAccumulator ---
1678
SingleTouchMotionAccumulator()1679 SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1680 clearAbsoluteAxes();
1681 }
1682
reset(InputDevice * device)1683 void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1684 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1685 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1686 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1687 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1688 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1689 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1690 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1691 }
1692
clearAbsoluteAxes()1693 void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1694 mAbsX = 0;
1695 mAbsY = 0;
1696 mAbsPressure = 0;
1697 mAbsToolWidth = 0;
1698 mAbsDistance = 0;
1699 mAbsTiltX = 0;
1700 mAbsTiltY = 0;
1701 }
1702
process(const RawEvent * rawEvent)1703 void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1704 if (rawEvent->type == EV_ABS) {
1705 switch (rawEvent->code) {
1706 case ABS_X:
1707 mAbsX = rawEvent->value;
1708 break;
1709 case ABS_Y:
1710 mAbsY = rawEvent->value;
1711 break;
1712 case ABS_PRESSURE:
1713 mAbsPressure = rawEvent->value;
1714 break;
1715 case ABS_TOOL_WIDTH:
1716 mAbsToolWidth = rawEvent->value;
1717 break;
1718 case ABS_DISTANCE:
1719 mAbsDistance = rawEvent->value;
1720 break;
1721 case ABS_TILT_X:
1722 mAbsTiltX = rawEvent->value;
1723 break;
1724 case ABS_TILT_Y:
1725 mAbsTiltY = rawEvent->value;
1726 break;
1727 }
1728 }
1729 }
1730
1731
1732 // --- MultiTouchMotionAccumulator ---
1733
MultiTouchMotionAccumulator()1734 MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1735 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
1736 mHaveStylus(false), mDeviceTimestamp(0) {
1737 }
1738
~MultiTouchMotionAccumulator()1739 MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1740 delete[] mSlots;
1741 }
1742
configure(InputDevice * device,size_t slotCount,bool usingSlotsProtocol)1743 void MultiTouchMotionAccumulator::configure(InputDevice* device,
1744 size_t slotCount, bool usingSlotsProtocol) {
1745 mSlotCount = slotCount;
1746 mUsingSlotsProtocol = usingSlotsProtocol;
1747 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1748
1749 delete[] mSlots;
1750 mSlots = new Slot[slotCount];
1751 }
1752
reset(InputDevice * device)1753 void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1754 // Unfortunately there is no way to read the initial contents of the slots.
1755 // So when we reset the accumulator, we must assume they are all zeroes.
1756 if (mUsingSlotsProtocol) {
1757 // Query the driver for the current slot index and use it as the initial slot
1758 // before we start reading events from the device. It is possible that the
1759 // current slot index will not be the same as it was when the first event was
1760 // written into the evdev buffer, which means the input mapper could start
1761 // out of sync with the initial state of the events in the evdev buffer.
1762 // In the extremely unlikely case that this happens, the data from
1763 // two slots will be confused until the next ABS_MT_SLOT event is received.
1764 // This can cause the touch point to "jump", but at least there will be
1765 // no stuck touches.
1766 int32_t initialSlot;
1767 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1768 ABS_MT_SLOT, &initialSlot);
1769 if (status) {
1770 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1771 initialSlot = -1;
1772 }
1773 clearSlots(initialSlot);
1774 } else {
1775 clearSlots(-1);
1776 }
1777 mDeviceTimestamp = 0;
1778 }
1779
clearSlots(int32_t initialSlot)1780 void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1781 if (mSlots) {
1782 for (size_t i = 0; i < mSlotCount; i++) {
1783 mSlots[i].clear();
1784 }
1785 }
1786 mCurrentSlot = initialSlot;
1787 }
1788
process(const RawEvent * rawEvent)1789 void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1790 if (rawEvent->type == EV_ABS) {
1791 bool newSlot = false;
1792 if (mUsingSlotsProtocol) {
1793 if (rawEvent->code == ABS_MT_SLOT) {
1794 mCurrentSlot = rawEvent->value;
1795 newSlot = true;
1796 }
1797 } else if (mCurrentSlot < 0) {
1798 mCurrentSlot = 0;
1799 }
1800
1801 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1802 #if DEBUG_POINTERS
1803 if (newSlot) {
1804 ALOGW("MultiTouch device emitted invalid slot index %d but it "
1805 "should be between 0 and %zd; ignoring this slot.",
1806 mCurrentSlot, mSlotCount - 1);
1807 }
1808 #endif
1809 } else {
1810 Slot* slot = &mSlots[mCurrentSlot];
1811
1812 switch (rawEvent->code) {
1813 case ABS_MT_POSITION_X:
1814 slot->mInUse = true;
1815 slot->mAbsMTPositionX = rawEvent->value;
1816 break;
1817 case ABS_MT_POSITION_Y:
1818 slot->mInUse = true;
1819 slot->mAbsMTPositionY = rawEvent->value;
1820 break;
1821 case ABS_MT_TOUCH_MAJOR:
1822 slot->mInUse = true;
1823 slot->mAbsMTTouchMajor = rawEvent->value;
1824 break;
1825 case ABS_MT_TOUCH_MINOR:
1826 slot->mInUse = true;
1827 slot->mAbsMTTouchMinor = rawEvent->value;
1828 slot->mHaveAbsMTTouchMinor = true;
1829 break;
1830 case ABS_MT_WIDTH_MAJOR:
1831 slot->mInUse = true;
1832 slot->mAbsMTWidthMajor = rawEvent->value;
1833 break;
1834 case ABS_MT_WIDTH_MINOR:
1835 slot->mInUse = true;
1836 slot->mAbsMTWidthMinor = rawEvent->value;
1837 slot->mHaveAbsMTWidthMinor = true;
1838 break;
1839 case ABS_MT_ORIENTATION:
1840 slot->mInUse = true;
1841 slot->mAbsMTOrientation = rawEvent->value;
1842 break;
1843 case ABS_MT_TRACKING_ID:
1844 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1845 // The slot is no longer in use but it retains its previous contents,
1846 // which may be reused for subsequent touches.
1847 slot->mInUse = false;
1848 } else {
1849 slot->mInUse = true;
1850 slot->mAbsMTTrackingId = rawEvent->value;
1851 }
1852 break;
1853 case ABS_MT_PRESSURE:
1854 slot->mInUse = true;
1855 slot->mAbsMTPressure = rawEvent->value;
1856 break;
1857 case ABS_MT_DISTANCE:
1858 slot->mInUse = true;
1859 slot->mAbsMTDistance = rawEvent->value;
1860 break;
1861 case ABS_MT_TOOL_TYPE:
1862 slot->mInUse = true;
1863 slot->mAbsMTToolType = rawEvent->value;
1864 slot->mHaveAbsMTToolType = true;
1865 break;
1866 }
1867 }
1868 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1869 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1870 mCurrentSlot += 1;
1871 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1872 mDeviceTimestamp = rawEvent->value;
1873 }
1874 }
1875
finishSync()1876 void MultiTouchMotionAccumulator::finishSync() {
1877 if (!mUsingSlotsProtocol) {
1878 clearSlots(-1);
1879 }
1880 }
1881
hasStylus() const1882 bool MultiTouchMotionAccumulator::hasStylus() const {
1883 return mHaveStylus;
1884 }
1885
1886
1887 // --- MultiTouchMotionAccumulator::Slot ---
1888
Slot()1889 MultiTouchMotionAccumulator::Slot::Slot() {
1890 clear();
1891 }
1892
clear()1893 void MultiTouchMotionAccumulator::Slot::clear() {
1894 mInUse = false;
1895 mHaveAbsMTTouchMinor = false;
1896 mHaveAbsMTWidthMinor = false;
1897 mHaveAbsMTToolType = false;
1898 mAbsMTPositionX = 0;
1899 mAbsMTPositionY = 0;
1900 mAbsMTTouchMajor = 0;
1901 mAbsMTTouchMinor = 0;
1902 mAbsMTWidthMajor = 0;
1903 mAbsMTWidthMinor = 0;
1904 mAbsMTOrientation = 0;
1905 mAbsMTTrackingId = -1;
1906 mAbsMTPressure = 0;
1907 mAbsMTDistance = 0;
1908 mAbsMTToolType = 0;
1909 }
1910
getToolType() const1911 int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1912 if (mHaveAbsMTToolType) {
1913 switch (mAbsMTToolType) {
1914 case MT_TOOL_FINGER:
1915 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1916 case MT_TOOL_PEN:
1917 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1918 }
1919 }
1920 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1921 }
1922
1923
1924 // --- InputMapper ---
1925
InputMapper(InputDevice * device)1926 InputMapper::InputMapper(InputDevice* device) :
1927 mDevice(device), mContext(device->getContext()) {
1928 }
1929
~InputMapper()1930 InputMapper::~InputMapper() {
1931 }
1932
populateDeviceInfo(InputDeviceInfo * info)1933 void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1934 info->addSource(getSources());
1935 }
1936
dump(std::string & dump)1937 void InputMapper::dump(std::string& dump) {
1938 }
1939
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)1940 void InputMapper::configure(nsecs_t when,
1941 const InputReaderConfiguration* config, uint32_t changes) {
1942 }
1943
reset(nsecs_t when)1944 void InputMapper::reset(nsecs_t when) {
1945 }
1946
timeoutExpired(nsecs_t when)1947 void InputMapper::timeoutExpired(nsecs_t when) {
1948 }
1949
getKeyCodeState(uint32_t sourceMask,int32_t keyCode)1950 int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1951 return AKEY_STATE_UNKNOWN;
1952 }
1953
getScanCodeState(uint32_t sourceMask,int32_t scanCode)1954 int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1955 return AKEY_STATE_UNKNOWN;
1956 }
1957
getSwitchState(uint32_t sourceMask,int32_t switchCode)1958 int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1959 return AKEY_STATE_UNKNOWN;
1960 }
1961
markSupportedKeyCodes(uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)1962 bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1963 const int32_t* keyCodes, uint8_t* outFlags) {
1964 return false;
1965 }
1966
vibrate(const nsecs_t * pattern,size_t patternSize,ssize_t repeat,int32_t token)1967 void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1968 int32_t token) {
1969 }
1970
cancelVibrate(int32_t token)1971 void InputMapper::cancelVibrate(int32_t token) {
1972 }
1973
cancelTouch(nsecs_t when)1974 void InputMapper::cancelTouch(nsecs_t when) {
1975 }
1976
getMetaState()1977 int32_t InputMapper::getMetaState() {
1978 return 0;
1979 }
1980
updateMetaState(int32_t keyCode)1981 void InputMapper::updateMetaState(int32_t keyCode) {
1982 }
1983
updateExternalStylusState(const StylusState & state)1984 void InputMapper::updateExternalStylusState(const StylusState& state) {
1985
1986 }
1987
fadePointer()1988 void InputMapper::fadePointer() {
1989 }
1990
getAbsoluteAxisInfo(int32_t axis,RawAbsoluteAxisInfo * axisInfo)1991 status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1992 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1993 }
1994
bumpGeneration()1995 void InputMapper::bumpGeneration() {
1996 mDevice->bumpGeneration();
1997 }
1998
dumpRawAbsoluteAxisInfo(std::string & dump,const RawAbsoluteAxisInfo & axis,const char * name)1999 void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
2000 const RawAbsoluteAxisInfo& axis, const char* name) {
2001 if (axis.valid) {
2002 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
2003 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2004 } else {
2005 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
2006 }
2007 }
2008
dumpStylusState(std::string & dump,const StylusState & state)2009 void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2010 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2011 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2012 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2013 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
2014 }
2015
2016 // --- SwitchInputMapper ---
2017
SwitchInputMapper(InputDevice * device)2018 SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
2019 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
2020 }
2021
~SwitchInputMapper()2022 SwitchInputMapper::~SwitchInputMapper() {
2023 }
2024
getSources()2025 uint32_t SwitchInputMapper::getSources() {
2026 return AINPUT_SOURCE_SWITCH;
2027 }
2028
process(const RawEvent * rawEvent)2029 void SwitchInputMapper::process(const RawEvent* rawEvent) {
2030 switch (rawEvent->type) {
2031 case EV_SW:
2032 processSwitch(rawEvent->code, rawEvent->value);
2033 break;
2034
2035 case EV_SYN:
2036 if (rawEvent->code == SYN_REPORT) {
2037 sync(rawEvent->when);
2038 }
2039 }
2040 }
2041
processSwitch(int32_t switchCode,int32_t switchValue)2042 void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2043 if (switchCode >= 0 && switchCode < 32) {
2044 if (switchValue) {
2045 mSwitchValues |= 1 << switchCode;
2046 } else {
2047 mSwitchValues &= ~(1 << switchCode);
2048 }
2049 mUpdatedSwitchMask |= 1 << switchCode;
2050 }
2051 }
2052
sync(nsecs_t when)2053 void SwitchInputMapper::sync(nsecs_t when) {
2054 if (mUpdatedSwitchMask) {
2055 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
2056 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2057 mUpdatedSwitchMask);
2058 getListener()->notifySwitch(&args);
2059
2060 mUpdatedSwitchMask = 0;
2061 }
2062 }
2063
getSwitchState(uint32_t sourceMask,int32_t switchCode)2064 int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2065 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2066 }
2067
dump(std::string & dump)2068 void SwitchInputMapper::dump(std::string& dump) {
2069 dump += INDENT2 "Switch Input Mapper:\n";
2070 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
2071 }
2072
2073 // --- VibratorInputMapper ---
2074
VibratorInputMapper(InputDevice * device)2075 VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2076 InputMapper(device), mVibrating(false) {
2077 }
2078
~VibratorInputMapper()2079 VibratorInputMapper::~VibratorInputMapper() {
2080 }
2081
getSources()2082 uint32_t VibratorInputMapper::getSources() {
2083 return 0;
2084 }
2085
populateDeviceInfo(InputDeviceInfo * info)2086 void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2087 InputMapper::populateDeviceInfo(info);
2088
2089 info->setVibrator(true);
2090 }
2091
process(const RawEvent * rawEvent)2092 void VibratorInputMapper::process(const RawEvent* rawEvent) {
2093 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2094 }
2095
vibrate(const nsecs_t * pattern,size_t patternSize,ssize_t repeat,int32_t token)2096 void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2097 int32_t token) {
2098 #if DEBUG_VIBRATOR
2099 std::string patternStr;
2100 for (size_t i = 0; i < patternSize; i++) {
2101 if (i != 0) {
2102 patternStr += ", ";
2103 }
2104 patternStr += StringPrintf("%" PRId64, pattern[i]);
2105 }
2106 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
2107 getDeviceId(), patternStr.c_str(), repeat, token);
2108 #endif
2109
2110 mVibrating = true;
2111 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2112 mPatternSize = patternSize;
2113 mRepeat = repeat;
2114 mToken = token;
2115 mIndex = -1;
2116
2117 nextStep();
2118 }
2119
cancelVibrate(int32_t token)2120 void VibratorInputMapper::cancelVibrate(int32_t token) {
2121 #if DEBUG_VIBRATOR
2122 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2123 #endif
2124
2125 if (mVibrating && mToken == token) {
2126 stopVibrating();
2127 }
2128 }
2129
timeoutExpired(nsecs_t when)2130 void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2131 if (mVibrating) {
2132 if (when >= mNextStepTime) {
2133 nextStep();
2134 } else {
2135 getContext()->requestTimeoutAtTime(mNextStepTime);
2136 }
2137 }
2138 }
2139
nextStep()2140 void VibratorInputMapper::nextStep() {
2141 mIndex += 1;
2142 if (size_t(mIndex) >= mPatternSize) {
2143 if (mRepeat < 0) {
2144 // We are done.
2145 stopVibrating();
2146 return;
2147 }
2148 mIndex = mRepeat;
2149 }
2150
2151 bool vibratorOn = mIndex & 1;
2152 nsecs_t duration = mPattern[mIndex];
2153 if (vibratorOn) {
2154 #if DEBUG_VIBRATOR
2155 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
2156 #endif
2157 getEventHub()->vibrate(getDeviceId(), duration);
2158 } else {
2159 #if DEBUG_VIBRATOR
2160 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2161 #endif
2162 getEventHub()->cancelVibrate(getDeviceId());
2163 }
2164 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2165 mNextStepTime = now + duration;
2166 getContext()->requestTimeoutAtTime(mNextStepTime);
2167 #if DEBUG_VIBRATOR
2168 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2169 #endif
2170 }
2171
stopVibrating()2172 void VibratorInputMapper::stopVibrating() {
2173 mVibrating = false;
2174 #if DEBUG_VIBRATOR
2175 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2176 #endif
2177 getEventHub()->cancelVibrate(getDeviceId());
2178 }
2179
dump(std::string & dump)2180 void VibratorInputMapper::dump(std::string& dump) {
2181 dump += INDENT2 "Vibrator Input Mapper:\n";
2182 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2183 }
2184
2185
2186 // --- KeyboardInputMapper ---
2187
KeyboardInputMapper(InputDevice * device,uint32_t source,int32_t keyboardType)2188 KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2189 uint32_t source, int32_t keyboardType) :
2190 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
2191 }
2192
~KeyboardInputMapper()2193 KeyboardInputMapper::~KeyboardInputMapper() {
2194 }
2195
getSources()2196 uint32_t KeyboardInputMapper::getSources() {
2197 return mSource;
2198 }
2199
getOrientation()2200 int32_t KeyboardInputMapper::getOrientation() {
2201 if (mViewport) {
2202 return mViewport->orientation;
2203 }
2204 return DISPLAY_ORIENTATION_0;
2205 }
2206
getDisplayId()2207 int32_t KeyboardInputMapper::getDisplayId() {
2208 if (mViewport) {
2209 return mViewport->displayId;
2210 }
2211 return ADISPLAY_ID_NONE;
2212 }
2213
populateDeviceInfo(InputDeviceInfo * info)2214 void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2215 InputMapper::populateDeviceInfo(info);
2216
2217 info->setKeyboardType(mKeyboardType);
2218 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2219 }
2220
dump(std::string & dump)2221 void KeyboardInputMapper::dump(std::string& dump) {
2222 dump += INDENT2 "Keyboard Input Mapper:\n";
2223 dumpParameters(dump);
2224 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2225 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
2226 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2227 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2228 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
2229 }
2230
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)2231 void KeyboardInputMapper::configure(nsecs_t when,
2232 const InputReaderConfiguration* config, uint32_t changes) {
2233 InputMapper::configure(when, config, changes);
2234
2235 if (!changes) { // first time only
2236 // Configure basic parameters.
2237 configureParameters();
2238 }
2239
2240 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2241 if (mParameters.orientationAware) {
2242 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
2243 }
2244 }
2245 }
2246
mapStemKey(int32_t keyCode,const PropertyMap & config,char const * property)2247 static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2248 int32_t mapped = 0;
2249 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2250 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2251 if (stemKeyRotationMap[i][0] == keyCode) {
2252 stemKeyRotationMap[i][1] = mapped;
2253 return;
2254 }
2255 }
2256 }
2257 }
2258
configureParameters()2259 void KeyboardInputMapper::configureParameters() {
2260 mParameters.orientationAware = false;
2261 const PropertyMap& config = getDevice()->getConfiguration();
2262 config.tryGetProperty(String8("keyboard.orientationAware"),
2263 mParameters.orientationAware);
2264
2265 if (mParameters.orientationAware) {
2266 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2267 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2268 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2269 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
2270 }
2271
2272 mParameters.handlesKeyRepeat = false;
2273 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
2274 mParameters.handlesKeyRepeat);
2275 }
2276
dumpParameters(std::string & dump)2277 void KeyboardInputMapper::dumpParameters(std::string& dump) {
2278 dump += INDENT3 "Parameters:\n";
2279 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
2280 toString(mParameters.orientationAware));
2281 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
2282 toString(mParameters.handlesKeyRepeat));
2283 }
2284
reset(nsecs_t when)2285 void KeyboardInputMapper::reset(nsecs_t when) {
2286 mMetaState = AMETA_NONE;
2287 mDownTime = 0;
2288 mKeyDowns.clear();
2289 mCurrentHidUsage = 0;
2290
2291 resetLedState();
2292
2293 InputMapper::reset(when);
2294 }
2295
process(const RawEvent * rawEvent)2296 void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2297 switch (rawEvent->type) {
2298 case EV_KEY: {
2299 int32_t scanCode = rawEvent->code;
2300 int32_t usageCode = mCurrentHidUsage;
2301 mCurrentHidUsage = 0;
2302
2303 if (isKeyboardOrGamepadKey(scanCode)) {
2304 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
2305 }
2306 break;
2307 }
2308 case EV_MSC: {
2309 if (rawEvent->code == MSC_SCAN) {
2310 mCurrentHidUsage = rawEvent->value;
2311 }
2312 break;
2313 }
2314 case EV_SYN: {
2315 if (rawEvent->code == SYN_REPORT) {
2316 mCurrentHidUsage = 0;
2317 }
2318 }
2319 }
2320 }
2321
isKeyboardOrGamepadKey(int32_t scanCode)2322 bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2323 return scanCode < BTN_MOUSE
2324 || scanCode >= KEY_OK
2325 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2326 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2327 }
2328
isMediaKey(int32_t keyCode)2329 bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2330 switch (keyCode) {
2331 case AKEYCODE_MEDIA_PLAY:
2332 case AKEYCODE_MEDIA_PAUSE:
2333 case AKEYCODE_MEDIA_PLAY_PAUSE:
2334 case AKEYCODE_MUTE:
2335 case AKEYCODE_HEADSETHOOK:
2336 case AKEYCODE_MEDIA_STOP:
2337 case AKEYCODE_MEDIA_NEXT:
2338 case AKEYCODE_MEDIA_PREVIOUS:
2339 case AKEYCODE_MEDIA_REWIND:
2340 case AKEYCODE_MEDIA_RECORD:
2341 case AKEYCODE_MEDIA_FAST_FORWARD:
2342 case AKEYCODE_MEDIA_SKIP_FORWARD:
2343 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2344 case AKEYCODE_MEDIA_STEP_FORWARD:
2345 case AKEYCODE_MEDIA_STEP_BACKWARD:
2346 case AKEYCODE_MEDIA_AUDIO_TRACK:
2347 case AKEYCODE_VOLUME_UP:
2348 case AKEYCODE_VOLUME_DOWN:
2349 case AKEYCODE_VOLUME_MUTE:
2350 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2351 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2352 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2353 return true;
2354 }
2355 return false;
2356 }
2357
processKey(nsecs_t when,bool down,int32_t scanCode,int32_t usageCode)2358 void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2359 int32_t usageCode) {
2360 int32_t keyCode;
2361 int32_t keyMetaState;
2362 uint32_t policyFlags;
2363
2364 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2365 &keyCode, &keyMetaState, &policyFlags)) {
2366 keyCode = AKEYCODE_UNKNOWN;
2367 keyMetaState = mMetaState;
2368 policyFlags = 0;
2369 }
2370
2371 if (down) {
2372 // Rotate key codes according to orientation if needed.
2373 if (mParameters.orientationAware) {
2374 keyCode = rotateKeyCode(keyCode, getOrientation());
2375 }
2376
2377 // Add key down.
2378 ssize_t keyDownIndex = findKeyDown(scanCode);
2379 if (keyDownIndex >= 0) {
2380 // key repeat, be sure to use same keycode as before in case of rotation
2381 keyCode = mKeyDowns[keyDownIndex].keyCode;
2382 } else {
2383 // key down
2384 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2385 && mContext->shouldDropVirtualKey(when,
2386 getDevice(), keyCode, scanCode)) {
2387 return;
2388 }
2389 if (policyFlags & POLICY_FLAG_GESTURE) {
2390 mDevice->cancelTouch(when);
2391 }
2392
2393 KeyDown keyDown;
2394 keyDown.keyCode = keyCode;
2395 keyDown.scanCode = scanCode;
2396 mKeyDowns.push_back(keyDown);
2397 }
2398
2399 mDownTime = when;
2400 } else {
2401 // Remove key down.
2402 ssize_t keyDownIndex = findKeyDown(scanCode);
2403 if (keyDownIndex >= 0) {
2404 // key up, be sure to use same keycode as before in case of rotation
2405 keyCode = mKeyDowns[keyDownIndex].keyCode;
2406 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
2407 } else {
2408 // key was not actually down
2409 ALOGI("Dropping key up from device %s because the key was not down. "
2410 "keyCode=%d, scanCode=%d",
2411 getDeviceName().c_str(), keyCode, scanCode);
2412 return;
2413 }
2414 }
2415
2416 if (updateMetaStateIfNeeded(keyCode, down)) {
2417 // If global meta state changed send it along with the key.
2418 // If it has not changed then we'll use what keymap gave us,
2419 // since key replacement logic might temporarily reset a few
2420 // meta bits for given key.
2421 keyMetaState = mMetaState;
2422 }
2423
2424 nsecs_t downTime = mDownTime;
2425
2426 // Key down on external an keyboard should wake the device.
2427 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2428 // For internal keyboards, the key layout file should specify the policy flags for
2429 // each wake key individually.
2430 // TODO: Use the input device configuration to control this behavior more finely.
2431 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
2432 policyFlags |= POLICY_FLAG_WAKE;
2433 }
2434
2435 if (mParameters.handlesKeyRepeat) {
2436 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2437 }
2438
2439 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2440 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
2441 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
2442 getListener()->notifyKey(&args);
2443 }
2444
findKeyDown(int32_t scanCode)2445 ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2446 size_t n = mKeyDowns.size();
2447 for (size_t i = 0; i < n; i++) {
2448 if (mKeyDowns[i].scanCode == scanCode) {
2449 return i;
2450 }
2451 }
2452 return -1;
2453 }
2454
getKeyCodeState(uint32_t sourceMask,int32_t keyCode)2455 int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2456 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2457 }
2458
getScanCodeState(uint32_t sourceMask,int32_t scanCode)2459 int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2460 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2461 }
2462
markSupportedKeyCodes(uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)2463 bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2464 const int32_t* keyCodes, uint8_t* outFlags) {
2465 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2466 }
2467
getMetaState()2468 int32_t KeyboardInputMapper::getMetaState() {
2469 return mMetaState;
2470 }
2471
updateMetaState(int32_t keyCode)2472 void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2473 updateMetaStateIfNeeded(keyCode, false);
2474 }
2475
updateMetaStateIfNeeded(int32_t keyCode,bool down)2476 bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2477 int32_t oldMetaState = mMetaState;
2478 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2479 bool metaStateChanged = oldMetaState != newMetaState;
2480 if (metaStateChanged) {
2481 mMetaState = newMetaState;
2482 updateLedState(false);
2483
2484 getContext()->updateGlobalMetaState();
2485 }
2486
2487 return metaStateChanged;
2488 }
2489
resetLedState()2490 void KeyboardInputMapper::resetLedState() {
2491 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2492 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2493 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2494
2495 updateLedState(true);
2496 }
2497
initializeLedState(LedState & ledState,int32_t led)2498 void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2499 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2500 ledState.on = false;
2501 }
2502
updateLedState(bool reset)2503 void KeyboardInputMapper::updateLedState(bool reset) {
2504 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2505 AMETA_CAPS_LOCK_ON, reset);
2506 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2507 AMETA_NUM_LOCK_ON, reset);
2508 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2509 AMETA_SCROLL_LOCK_ON, reset);
2510 }
2511
updateLedStateForModifier(LedState & ledState,int32_t led,int32_t modifier,bool reset)2512 void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2513 int32_t led, int32_t modifier, bool reset) {
2514 if (ledState.avail) {
2515 bool desiredState = (mMetaState & modifier) != 0;
2516 if (reset || ledState.on != desiredState) {
2517 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2518 ledState.on = desiredState;
2519 }
2520 }
2521 }
2522
2523
2524 // --- CursorInputMapper ---
2525
CursorInputMapper(InputDevice * device)2526 CursorInputMapper::CursorInputMapper(InputDevice* device) :
2527 InputMapper(device) {
2528 }
2529
~CursorInputMapper()2530 CursorInputMapper::~CursorInputMapper() {
2531 }
2532
getSources()2533 uint32_t CursorInputMapper::getSources() {
2534 return mSource;
2535 }
2536
populateDeviceInfo(InputDeviceInfo * info)2537 void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2538 InputMapper::populateDeviceInfo(info);
2539
2540 if (mParameters.mode == Parameters::MODE_POINTER) {
2541 float minX, minY, maxX, maxY;
2542 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2543 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2544 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2545 }
2546 } else {
2547 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2548 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2549 }
2550 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2551
2552 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2553 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2554 }
2555 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2556 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2557 }
2558 }
2559
dump(std::string & dump)2560 void CursorInputMapper::dump(std::string& dump) {
2561 dump += INDENT2 "Cursor Input Mapper:\n";
2562 dumpParameters(dump);
2563 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2564 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2565 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2566 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2567 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
2568 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2569 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
2570 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2571 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2572 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2573 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2574 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2575 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2576 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
2577 }
2578
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)2579 void CursorInputMapper::configure(nsecs_t when,
2580 const InputReaderConfiguration* config, uint32_t changes) {
2581 InputMapper::configure(when, config, changes);
2582
2583 if (!changes) { // first time only
2584 mCursorScrollAccumulator.configure(getDevice());
2585
2586 // Configure basic parameters.
2587 configureParameters();
2588
2589 // Configure device mode.
2590 switch (mParameters.mode) {
2591 case Parameters::MODE_POINTER_RELATIVE:
2592 // Should not happen during first time configuration.
2593 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2594 mParameters.mode = Parameters::MODE_POINTER;
2595 [[fallthrough]];
2596 case Parameters::MODE_POINTER:
2597 mSource = AINPUT_SOURCE_MOUSE;
2598 mXPrecision = 1.0f;
2599 mYPrecision = 1.0f;
2600 mXScale = 1.0f;
2601 mYScale = 1.0f;
2602 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2603 break;
2604 case Parameters::MODE_NAVIGATION:
2605 mSource = AINPUT_SOURCE_TRACKBALL;
2606 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2607 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2608 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2609 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2610 break;
2611 }
2612
2613 mVWheelScale = 1.0f;
2614 mHWheelScale = 1.0f;
2615 }
2616
2617 if ((!changes && config->pointerCapture)
2618 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2619 if (config->pointerCapture) {
2620 if (mParameters.mode == Parameters::MODE_POINTER) {
2621 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2622 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2623 // Keep PointerController around in order to preserve the pointer position.
2624 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2625 } else {
2626 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2627 }
2628 } else {
2629 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2630 mParameters.mode = Parameters::MODE_POINTER;
2631 mSource = AINPUT_SOURCE_MOUSE;
2632 } else {
2633 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2634 }
2635 }
2636 bumpGeneration();
2637 if (changes) {
2638 getDevice()->notifyReset(when);
2639 }
2640 }
2641
2642 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2643 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2644 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2645 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2646 }
2647
2648 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2649 mOrientation = DISPLAY_ORIENTATION_0;
2650 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2651 std::optional<DisplayViewport> internalViewport =
2652 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
2653 if (internalViewport) {
2654 mOrientation = internalViewport->orientation;
2655 }
2656 }
2657
2658 // Update the PointerController if viewports changed.
2659 if (mParameters.mode == Parameters::MODE_POINTER) {
2660 getPolicy()->obtainPointerController(getDeviceId());
2661 }
2662 bumpGeneration();
2663 }
2664 }
2665
configureParameters()2666 void CursorInputMapper::configureParameters() {
2667 mParameters.mode = Parameters::MODE_POINTER;
2668 String8 cursorModeString;
2669 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2670 if (cursorModeString == "navigation") {
2671 mParameters.mode = Parameters::MODE_NAVIGATION;
2672 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2673 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2674 }
2675 }
2676
2677 mParameters.orientationAware = false;
2678 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2679 mParameters.orientationAware);
2680
2681 mParameters.hasAssociatedDisplay = false;
2682 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2683 mParameters.hasAssociatedDisplay = true;
2684 }
2685 }
2686
dumpParameters(std::string & dump)2687 void CursorInputMapper::dumpParameters(std::string& dump) {
2688 dump += INDENT3 "Parameters:\n";
2689 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
2690 toString(mParameters.hasAssociatedDisplay));
2691
2692 switch (mParameters.mode) {
2693 case Parameters::MODE_POINTER:
2694 dump += INDENT4 "Mode: pointer\n";
2695 break;
2696 case Parameters::MODE_POINTER_RELATIVE:
2697 dump += INDENT4 "Mode: relative pointer\n";
2698 break;
2699 case Parameters::MODE_NAVIGATION:
2700 dump += INDENT4 "Mode: navigation\n";
2701 break;
2702 default:
2703 ALOG_ASSERT(false);
2704 }
2705
2706 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
2707 toString(mParameters.orientationAware));
2708 }
2709
reset(nsecs_t when)2710 void CursorInputMapper::reset(nsecs_t when) {
2711 mButtonState = 0;
2712 mDownTime = 0;
2713
2714 mPointerVelocityControl.reset();
2715 mWheelXVelocityControl.reset();
2716 mWheelYVelocityControl.reset();
2717
2718 mCursorButtonAccumulator.reset(getDevice());
2719 mCursorMotionAccumulator.reset(getDevice());
2720 mCursorScrollAccumulator.reset(getDevice());
2721
2722 InputMapper::reset(when);
2723 }
2724
process(const RawEvent * rawEvent)2725 void CursorInputMapper::process(const RawEvent* rawEvent) {
2726 mCursorButtonAccumulator.process(rawEvent);
2727 mCursorMotionAccumulator.process(rawEvent);
2728 mCursorScrollAccumulator.process(rawEvent);
2729
2730 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2731 sync(rawEvent->when);
2732 }
2733 }
2734
sync(nsecs_t when)2735 void CursorInputMapper::sync(nsecs_t when) {
2736 int32_t lastButtonState = mButtonState;
2737 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2738 mButtonState = currentButtonState;
2739
2740 bool wasDown = isPointerDown(lastButtonState);
2741 bool down = isPointerDown(currentButtonState);
2742 bool downChanged;
2743 if (!wasDown && down) {
2744 mDownTime = when;
2745 downChanged = true;
2746 } else if (wasDown && !down) {
2747 downChanged = true;
2748 } else {
2749 downChanged = false;
2750 }
2751 nsecs_t downTime = mDownTime;
2752 bool buttonsChanged = currentButtonState != lastButtonState;
2753 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2754 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
2755
2756 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2757 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2758 bool moved = deltaX != 0 || deltaY != 0;
2759
2760 // Rotate delta according to orientation if needed.
2761 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2762 && (deltaX != 0.0f || deltaY != 0.0f)) {
2763 rotateDelta(mOrientation, &deltaX, &deltaY);
2764 }
2765
2766 // Move the pointer.
2767 PointerProperties pointerProperties;
2768 pointerProperties.clear();
2769 pointerProperties.id = 0;
2770 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2771
2772 PointerCoords pointerCoords;
2773 pointerCoords.clear();
2774
2775 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2776 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2777 bool scrolled = vscroll != 0 || hscroll != 0;
2778
2779 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2780 mWheelXVelocityControl.move(when, &hscroll, nullptr);
2781
2782 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2783
2784 int32_t displayId;
2785 if (mSource == AINPUT_SOURCE_MOUSE) {
2786 if (moved || scrolled || buttonsChanged) {
2787 mPointerController->setPresentation(
2788 PointerControllerInterface::PRESENTATION_POINTER);
2789
2790 if (moved) {
2791 mPointerController->move(deltaX, deltaY);
2792 }
2793
2794 if (buttonsChanged) {
2795 mPointerController->setButtonState(currentButtonState);
2796 }
2797
2798 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2799 }
2800
2801 float x, y;
2802 mPointerController->getPosition(&x, &y);
2803 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2804 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2805 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2806 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
2807 displayId = mPointerController->getDisplayId();
2808 } else {
2809 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2810 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2811 displayId = ADISPLAY_ID_NONE;
2812 }
2813
2814 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2815
2816 // Moving an external trackball or mouse should wake the device.
2817 // We don't do this for internal cursor devices to prevent them from waking up
2818 // the device in your pocket.
2819 // TODO: Use the input device configuration to control this behavior more finely.
2820 uint32_t policyFlags = 0;
2821 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
2822 policyFlags |= POLICY_FLAG_WAKE;
2823 }
2824
2825 // Synthesize key down from buttons if needed.
2826 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2827 displayId, policyFlags, lastButtonState, currentButtonState);
2828
2829 // Send motion event.
2830 if (downChanged || moved || scrolled || buttonsChanged) {
2831 int32_t metaState = mContext->getGlobalMetaState();
2832 int32_t buttonState = lastButtonState;
2833 int32_t motionEventAction;
2834 if (downChanged) {
2835 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2836 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
2837 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2838 } else {
2839 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2840 }
2841
2842 if (buttonsReleased) {
2843 BitSet32 released(buttonsReleased);
2844 while (!released.isEmpty()) {
2845 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2846 buttonState &= ~actionButton;
2847 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2848 mSource, displayId, policyFlags,
2849 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2850 metaState, buttonState,
2851 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2852 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
2853 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
2854 getListener()->notifyMotion(&releaseArgs);
2855 }
2856 }
2857
2858 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2859 displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
2860 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2861 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
2862 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
2863 getListener()->notifyMotion(&args);
2864
2865 if (buttonsPressed) {
2866 BitSet32 pressed(buttonsPressed);
2867 while (!pressed.isEmpty()) {
2868 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2869 buttonState |= actionButton;
2870 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2871 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2872 actionButton, 0, metaState, buttonState,
2873 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2874 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
2875 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
2876 getListener()->notifyMotion(&pressArgs);
2877 }
2878 }
2879
2880 ALOG_ASSERT(buttonState == currentButtonState);
2881
2882 // Send hover move after UP to tell the application that the mouse is hovering now.
2883 if (motionEventAction == AMOTION_EVENT_ACTION_UP
2884 && (mSource == AINPUT_SOURCE_MOUSE)) {
2885 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2886 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2887 metaState, currentButtonState,
2888 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2889 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
2890 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
2891 getListener()->notifyMotion(&hoverArgs);
2892 }
2893
2894 // Send scroll events.
2895 if (scrolled) {
2896 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2897 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2898
2899 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2900 mSource, displayId, policyFlags,
2901 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
2902 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2903 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
2904 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
2905 getListener()->notifyMotion(&scrollArgs);
2906 }
2907 }
2908
2909 // Synthesize key up from buttons if needed.
2910 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2911 displayId, policyFlags, lastButtonState, currentButtonState);
2912
2913 mCursorMotionAccumulator.finishSync();
2914 mCursorScrollAccumulator.finishSync();
2915 }
2916
getScanCodeState(uint32_t sourceMask,int32_t scanCode)2917 int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2918 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2919 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2920 } else {
2921 return AKEY_STATE_UNKNOWN;
2922 }
2923 }
2924
fadePointer()2925 void CursorInputMapper::fadePointer() {
2926 if (mPointerController != nullptr) {
2927 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2928 }
2929 }
2930
getAssociatedDisplay()2931 std::optional<int32_t> CursorInputMapper::getAssociatedDisplay() {
2932 if (mParameters.hasAssociatedDisplay) {
2933 if (mParameters.mode == Parameters::MODE_POINTER) {
2934 return std::make_optional(mPointerController->getDisplayId());
2935 } else {
2936 // If the device is orientationAware and not a mouse,
2937 // it expects to dispatch events to any display
2938 return std::make_optional(ADISPLAY_ID_NONE);
2939 }
2940 }
2941 return std::nullopt;
2942 }
2943
2944 // --- RotaryEncoderInputMapper ---
2945
RotaryEncoderInputMapper(InputDevice * device)2946 RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
2947 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
2948 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2949 }
2950
~RotaryEncoderInputMapper()2951 RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2952 }
2953
getSources()2954 uint32_t RotaryEncoderInputMapper::getSources() {
2955 return mSource;
2956 }
2957
populateDeviceInfo(InputDeviceInfo * info)2958 void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2959 InputMapper::populateDeviceInfo(info);
2960
2961 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
2962 float res = 0.0f;
2963 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2964 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2965 }
2966 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2967 mScalingFactor)) {
2968 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2969 "default to 1.0!\n");
2970 mScalingFactor = 1.0f;
2971 }
2972 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2973 res * mScalingFactor);
2974 }
2975 }
2976
dump(std::string & dump)2977 void RotaryEncoderInputMapper::dump(std::string& dump) {
2978 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2979 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
2980 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2981 }
2982
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)2983 void RotaryEncoderInputMapper::configure(nsecs_t when,
2984 const InputReaderConfiguration* config, uint32_t changes) {
2985 InputMapper::configure(when, config, changes);
2986 if (!changes) {
2987 mRotaryEncoderScrollAccumulator.configure(getDevice());
2988 }
2989 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2990 std::optional<DisplayViewport> internalViewport =
2991 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
2992 if (internalViewport) {
2993 mOrientation = internalViewport->orientation;
2994 } else {
2995 mOrientation = DISPLAY_ORIENTATION_0;
2996 }
2997 }
2998 }
2999
reset(nsecs_t when)3000 void RotaryEncoderInputMapper::reset(nsecs_t when) {
3001 mRotaryEncoderScrollAccumulator.reset(getDevice());
3002
3003 InputMapper::reset(when);
3004 }
3005
process(const RawEvent * rawEvent)3006 void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3007 mRotaryEncoderScrollAccumulator.process(rawEvent);
3008
3009 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3010 sync(rawEvent->when);
3011 }
3012 }
3013
sync(nsecs_t when)3014 void RotaryEncoderInputMapper::sync(nsecs_t when) {
3015 PointerCoords pointerCoords;
3016 pointerCoords.clear();
3017
3018 PointerProperties pointerProperties;
3019 pointerProperties.clear();
3020 pointerProperties.id = 0;
3021 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3022
3023 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3024 bool scrolled = scroll != 0;
3025
3026 // This is not a pointer, so it's not associated with a display.
3027 int32_t displayId = ADISPLAY_ID_NONE;
3028
3029 // Moving the rotary encoder should wake the device (if specified).
3030 uint32_t policyFlags = 0;
3031 if (scrolled && getDevice()->isExternal()) {
3032 policyFlags |= POLICY_FLAG_WAKE;
3033 }
3034
3035 if (mOrientation == DISPLAY_ORIENTATION_180) {
3036 scroll = -scroll;
3037 }
3038
3039 // Send motion event.
3040 if (scrolled) {
3041 int32_t metaState = mContext->getGlobalMetaState();
3042 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
3043
3044 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
3045 mSource, displayId, policyFlags,
3046 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, /* buttonState */ 0,
3047 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
3048 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
3049 0, 0, 0, /* videoFrames */ {});
3050 getListener()->notifyMotion(&scrollArgs);
3051 }
3052
3053 mRotaryEncoderScrollAccumulator.finishSync();
3054 }
3055
3056 // --- TouchInputMapper ---
3057
TouchInputMapper(InputDevice * device)3058 TouchInputMapper::TouchInputMapper(InputDevice* device) :
3059 InputMapper(device),
3060 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3061 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3062 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
3063 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3064 }
3065
~TouchInputMapper()3066 TouchInputMapper::~TouchInputMapper() {
3067 }
3068
getSources()3069 uint32_t TouchInputMapper::getSources() {
3070 return mSource;
3071 }
3072
populateDeviceInfo(InputDeviceInfo * info)3073 void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3074 InputMapper::populateDeviceInfo(info);
3075
3076 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3077 info->addMotionRange(mOrientedRanges.x);
3078 info->addMotionRange(mOrientedRanges.y);
3079 info->addMotionRange(mOrientedRanges.pressure);
3080
3081 if (mOrientedRanges.haveSize) {
3082 info->addMotionRange(mOrientedRanges.size);
3083 }
3084
3085 if (mOrientedRanges.haveTouchSize) {
3086 info->addMotionRange(mOrientedRanges.touchMajor);
3087 info->addMotionRange(mOrientedRanges.touchMinor);
3088 }
3089
3090 if (mOrientedRanges.haveToolSize) {
3091 info->addMotionRange(mOrientedRanges.toolMajor);
3092 info->addMotionRange(mOrientedRanges.toolMinor);
3093 }
3094
3095 if (mOrientedRanges.haveOrientation) {
3096 info->addMotionRange(mOrientedRanges.orientation);
3097 }
3098
3099 if (mOrientedRanges.haveDistance) {
3100 info->addMotionRange(mOrientedRanges.distance);
3101 }
3102
3103 if (mOrientedRanges.haveTilt) {
3104 info->addMotionRange(mOrientedRanges.tilt);
3105 }
3106
3107 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3108 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3109 0.0f);
3110 }
3111 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3112 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3113 0.0f);
3114 }
3115 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3116 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3117 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3118 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3119 x.fuzz, x.resolution);
3120 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3121 y.fuzz, y.resolution);
3122 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3123 x.fuzz, x.resolution);
3124 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3125 y.fuzz, y.resolution);
3126 }
3127 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3128 }
3129 }
3130
dump(std::string & dump)3131 void TouchInputMapper::dump(std::string& dump) {
3132 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
3133 dumpParameters(dump);
3134 dumpVirtualKeys(dump);
3135 dumpRawPointerAxes(dump);
3136 dumpCalibration(dump);
3137 dumpAffineTransformation(dump);
3138 dumpSurface(dump);
3139
3140 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3141 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3142 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3143 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3144 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3145 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3146 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3147 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3148 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3149 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3150 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3151 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3152 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3153 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3154 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3155 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3156 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3157
3158 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3159 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
3160 mLastRawState.rawPointerData.pointerCount);
3161 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3162 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
3163 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3164 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3165 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3166 "toolType=%d, isHovering=%s\n", i,
3167 pointer.id, pointer.x, pointer.y, pointer.pressure,
3168 pointer.touchMajor, pointer.touchMinor,
3169 pointer.toolMajor, pointer.toolMinor,
3170 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3171 pointer.toolType, toString(pointer.isHovering));
3172 }
3173
3174 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3175 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
3176 mLastCookedState.cookedPointerData.pointerCount);
3177 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3178 const PointerProperties& pointerProperties =
3179 mLastCookedState.cookedPointerData.pointerProperties[i];
3180 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
3181 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3182 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3183 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3184 "toolType=%d, isHovering=%s\n", i,
3185 pointerProperties.id,
3186 pointerCoords.getX(),
3187 pointerCoords.getY(),
3188 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3189 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3190 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3191 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3192 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3193 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3194 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3195 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3196 pointerProperties.toolType,
3197 toString(mLastCookedState.cookedPointerData.isHovering(i)));
3198 }
3199
3200 dump += INDENT3 "Stylus Fusion:\n";
3201 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
3202 toString(mExternalStylusConnected));
3203 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3204 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
3205 mExternalStylusFusionTimeout);
3206 dump += INDENT3 "External Stylus State:\n";
3207 dumpStylusState(dump, mExternalStylusState);
3208
3209 if (mDeviceMode == DEVICE_MODE_POINTER) {
3210 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3211 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
3212 mPointerXMovementScale);
3213 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
3214 mPointerYMovementScale);
3215 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
3216 mPointerXZoomScale);
3217 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
3218 mPointerYZoomScale);
3219 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
3220 mPointerGestureMaxSwipeWidth);
3221 }
3222 }
3223
modeToString(DeviceMode deviceMode)3224 const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3225 switch (deviceMode) {
3226 case DEVICE_MODE_DISABLED:
3227 return "disabled";
3228 case DEVICE_MODE_DIRECT:
3229 return "direct";
3230 case DEVICE_MODE_UNSCALED:
3231 return "unscaled";
3232 case DEVICE_MODE_NAVIGATION:
3233 return "navigation";
3234 case DEVICE_MODE_POINTER:
3235 return "pointer";
3236 }
3237 return "unknown";
3238 }
3239
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)3240 void TouchInputMapper::configure(nsecs_t when,
3241 const InputReaderConfiguration* config, uint32_t changes) {
3242 InputMapper::configure(when, config, changes);
3243
3244 mConfig = *config;
3245
3246 if (!changes) { // first time only
3247 // Configure basic parameters.
3248 configureParameters();
3249
3250 // Configure common accumulators.
3251 mCursorScrollAccumulator.configure(getDevice());
3252 mTouchButtonAccumulator.configure(getDevice());
3253
3254 // Configure absolute axis information.
3255 configureRawPointerAxes();
3256
3257 // Prepare input device calibration.
3258 parseCalibration();
3259 resolveCalibration();
3260 }
3261
3262 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
3263 // Update location calibration to reflect current settings
3264 updateAffineTransformation();
3265 }
3266
3267 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3268 // Update pointer speed.
3269 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3270 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3271 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3272 }
3273
3274 bool resetNeeded = false;
3275 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3276 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
3277 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3278 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
3279 // Configure device sources, surface dimensions, orientation and
3280 // scaling factors.
3281 configureSurface(when, &resetNeeded);
3282 }
3283
3284 if (changes && resetNeeded) {
3285 // Send reset, unless this is the first time the device has been configured,
3286 // in which case the reader will call reset itself after all mappers are ready.
3287 getDevice()->notifyReset(when);
3288 }
3289 }
3290
resolveExternalStylusPresence()3291 void TouchInputMapper::resolveExternalStylusPresence() {
3292 std::vector<InputDeviceInfo> devices;
3293 mContext->getExternalStylusDevices(devices);
3294 mExternalStylusConnected = !devices.empty();
3295
3296 if (!mExternalStylusConnected) {
3297 resetExternalStylus();
3298 }
3299 }
3300
configureParameters()3301 void TouchInputMapper::configureParameters() {
3302 // Use the pointer presentation mode for devices that do not support distinct
3303 // multitouch. The spot-based presentation relies on being able to accurately
3304 // locate two or more fingers on the touch pad.
3305 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
3306 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
3307
3308 String8 gestureModeString;
3309 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3310 gestureModeString)) {
3311 if (gestureModeString == "single-touch") {
3312 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3313 } else if (gestureModeString == "multi-touch") {
3314 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
3315 } else if (gestureModeString != "default") {
3316 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3317 }
3318 }
3319
3320 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3321 // The device is a touch screen.
3322 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3323 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3324 // The device is a pointing device like a track pad.
3325 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3326 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3327 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3328 // The device is a cursor device with a touch pad attached.
3329 // By default don't use the touch pad to move the pointer.
3330 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3331 } else {
3332 // The device is a touch pad of unknown purpose.
3333 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3334 }
3335
3336 mParameters.hasButtonUnderPad=
3337 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3338
3339 String8 deviceTypeString;
3340 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3341 deviceTypeString)) {
3342 if (deviceTypeString == "touchScreen") {
3343 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3344 } else if (deviceTypeString == "touchPad") {
3345 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3346 } else if (deviceTypeString == "touchNavigation") {
3347 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3348 } else if (deviceTypeString == "pointer") {
3349 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3350 } else if (deviceTypeString != "default") {
3351 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3352 }
3353 }
3354
3355 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3356 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3357 mParameters.orientationAware);
3358
3359 mParameters.hasAssociatedDisplay = false;
3360 mParameters.associatedDisplayIsExternal = false;
3361 if (mParameters.orientationAware
3362 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3363 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3364 mParameters.hasAssociatedDisplay = true;
3365 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3366 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3367 String8 uniqueDisplayId;
3368 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3369 uniqueDisplayId);
3370 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
3371 }
3372 }
3373 if (getDevice()->getAssociatedDisplayPort()) {
3374 mParameters.hasAssociatedDisplay = true;
3375 }
3376
3377 // Initial downs on external touch devices should wake the device.
3378 // Normally we don't do this for internal touch screens to prevent them from waking
3379 // up in your pocket but you can enable it using the input device configuration.
3380 mParameters.wake = getDevice()->isExternal();
3381 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3382 mParameters.wake);
3383 }
3384
dumpParameters(std::string & dump)3385 void TouchInputMapper::dumpParameters(std::string& dump) {
3386 dump += INDENT3 "Parameters:\n";
3387
3388 switch (mParameters.gestureMode) {
3389 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3390 dump += INDENT4 "GestureMode: single-touch\n";
3391 break;
3392 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3393 dump += INDENT4 "GestureMode: multi-touch\n";
3394 break;
3395 default:
3396 assert(false);
3397 }
3398
3399 switch (mParameters.deviceType) {
3400 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3401 dump += INDENT4 "DeviceType: touchScreen\n";
3402 break;
3403 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3404 dump += INDENT4 "DeviceType: touchPad\n";
3405 break;
3406 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3407 dump += INDENT4 "DeviceType: touchNavigation\n";
3408 break;
3409 case Parameters::DEVICE_TYPE_POINTER:
3410 dump += INDENT4 "DeviceType: pointer\n";
3411 break;
3412 default:
3413 ALOG_ASSERT(false);
3414 }
3415
3416 dump += StringPrintf(
3417 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
3418 toString(mParameters.hasAssociatedDisplay),
3419 toString(mParameters.associatedDisplayIsExternal),
3420 mParameters.uniqueDisplayId.c_str());
3421 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
3422 toString(mParameters.orientationAware));
3423 }
3424
configureRawPointerAxes()3425 void TouchInputMapper::configureRawPointerAxes() {
3426 mRawPointerAxes.clear();
3427 }
3428
dumpRawPointerAxes(std::string & dump)3429 void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3430 dump += INDENT3 "Raw Touch Axes:\n";
3431 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3432 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3433 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3434 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3435 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3436 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3437 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3438 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3439 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3440 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3441 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3442 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3443 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3444 }
3445
hasExternalStylus() const3446 bool TouchInputMapper::hasExternalStylus() const {
3447 return mExternalStylusConnected;
3448 }
3449
3450 /**
3451 * Determine which DisplayViewport to use.
3452 * 1. If display port is specified, return the matching viewport. If matching viewport not
3453 * found, then return.
3454 * 2. If a device has associated display, get the matching viewport by either unique id or by
3455 * the display type (internal or external).
3456 * 3. Otherwise, use a non-display viewport.
3457 */
findViewport()3458 std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3459 if (mParameters.hasAssociatedDisplay) {
3460 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3461 if (displayPort) {
3462 // Find the viewport that contains the same port
3463 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3464 if (!v) {
3465 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3466 "but the corresponding viewport is not found.",
3467 getDeviceName().c_str(), *displayPort);
3468 }
3469 return v;
3470 }
3471
3472 if (!mParameters.uniqueDisplayId.empty()) {
3473 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3474 }
3475
3476 ViewportType viewportTypeToUse;
3477 if (mParameters.associatedDisplayIsExternal) {
3478 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3479 } else {
3480 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3481 }
3482
3483 std::optional<DisplayViewport> viewport =
3484 mConfig.getDisplayViewportByType(viewportTypeToUse);
3485 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3486 ALOGW("Input device %s should be associated with external display, "
3487 "fallback to internal one for the external viewport is not found.",
3488 getDeviceName().c_str());
3489 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3490 }
3491
3492 return viewport;
3493 }
3494
3495 DisplayViewport newViewport;
3496 // Raw width and height in the natural orientation.
3497 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3498 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3499 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3500 return std::make_optional(newViewport);
3501 }
3502
configureSurface(nsecs_t when,bool * outResetNeeded)3503 void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3504 int32_t oldDeviceMode = mDeviceMode;
3505
3506 resolveExternalStylusPresence();
3507
3508 // Determine device mode.
3509 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3510 && mConfig.pointerGesturesEnabled) {
3511 mSource = AINPUT_SOURCE_MOUSE;
3512 mDeviceMode = DEVICE_MODE_POINTER;
3513 if (hasStylus()) {
3514 mSource |= AINPUT_SOURCE_STYLUS;
3515 }
3516 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3517 && mParameters.hasAssociatedDisplay) {
3518 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3519 mDeviceMode = DEVICE_MODE_DIRECT;
3520 if (hasStylus()) {
3521 mSource |= AINPUT_SOURCE_STYLUS;
3522 }
3523 if (hasExternalStylus()) {
3524 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3525 }
3526 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3527 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3528 mDeviceMode = DEVICE_MODE_NAVIGATION;
3529 } else {
3530 mSource = AINPUT_SOURCE_TOUCHPAD;
3531 mDeviceMode = DEVICE_MODE_UNSCALED;
3532 }
3533
3534 // Ensure we have valid X and Y axes.
3535 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3536 ALOGW("Touch device '%s' did not report support for X or Y axis! "
3537 "The device will be inoperable.", getDeviceName().c_str());
3538 mDeviceMode = DEVICE_MODE_DISABLED;
3539 return;
3540 }
3541
3542 // Get associated display dimensions.
3543 std::optional<DisplayViewport> newViewport = findViewport();
3544 if (!newViewport) {
3545 ALOGI("Touch device '%s' could not query the properties of its associated "
3546 "display. The device will be inoperable until the display size "
3547 "becomes available.",
3548 getDeviceName().c_str());
3549 mDeviceMode = DEVICE_MODE_DISABLED;
3550 return;
3551 }
3552
3553 // Raw width and height in the natural orientation.
3554 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3555 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3556
3557 bool viewportChanged = mViewport != *newViewport;
3558 if (viewportChanged) {
3559 mViewport = *newViewport;
3560
3561 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3562 // Convert rotated viewport to natural surface coordinates.
3563 int32_t naturalLogicalWidth, naturalLogicalHeight;
3564 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3565 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3566 int32_t naturalDeviceWidth, naturalDeviceHeight;
3567 switch (mViewport.orientation) {
3568 case DISPLAY_ORIENTATION_90:
3569 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3570 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3571 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3572 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3573 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3574 naturalPhysicalTop = mViewport.physicalLeft;
3575 naturalDeviceWidth = mViewport.deviceHeight;
3576 naturalDeviceHeight = mViewport.deviceWidth;
3577 break;
3578 case DISPLAY_ORIENTATION_180:
3579 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3580 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3581 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3582 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3583 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3584 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3585 naturalDeviceWidth = mViewport.deviceWidth;
3586 naturalDeviceHeight = mViewport.deviceHeight;
3587 break;
3588 case DISPLAY_ORIENTATION_270:
3589 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3590 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3591 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3592 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3593 naturalPhysicalLeft = mViewport.physicalTop;
3594 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3595 naturalDeviceWidth = mViewport.deviceHeight;
3596 naturalDeviceHeight = mViewport.deviceWidth;
3597 break;
3598 case DISPLAY_ORIENTATION_0:
3599 default:
3600 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3601 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3602 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3603 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3604 naturalPhysicalLeft = mViewport.physicalLeft;
3605 naturalPhysicalTop = mViewport.physicalTop;
3606 naturalDeviceWidth = mViewport.deviceWidth;
3607 naturalDeviceHeight = mViewport.deviceHeight;
3608 break;
3609 }
3610
3611 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3612 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3613 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3614 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3615 }
3616
3617 mPhysicalWidth = naturalPhysicalWidth;
3618 mPhysicalHeight = naturalPhysicalHeight;
3619 mPhysicalLeft = naturalPhysicalLeft;
3620 mPhysicalTop = naturalPhysicalTop;
3621
3622 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3623 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3624 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3625 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3626
3627 mSurfaceOrientation = mParameters.orientationAware ?
3628 mViewport.orientation : DISPLAY_ORIENTATION_0;
3629 } else {
3630 mPhysicalWidth = rawWidth;
3631 mPhysicalHeight = rawHeight;
3632 mPhysicalLeft = 0;
3633 mPhysicalTop = 0;
3634
3635 mSurfaceWidth = rawWidth;
3636 mSurfaceHeight = rawHeight;
3637 mSurfaceLeft = 0;
3638 mSurfaceTop = 0;
3639 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3640 }
3641 }
3642
3643 // If moving between pointer modes, need to reset some state.
3644 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3645 if (deviceModeChanged) {
3646 mOrientedRanges.clear();
3647 }
3648
3649 // Create or update pointer controller if needed.
3650 if (mDeviceMode == DEVICE_MODE_POINTER ||
3651 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3652 if (mPointerController == nullptr || viewportChanged) {
3653 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3654 }
3655 } else {
3656 mPointerController.clear();
3657 }
3658
3659 if (viewportChanged || deviceModeChanged) {
3660 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3661 "display id %d",
3662 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
3663 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3664
3665 // Configure X and Y factors.
3666 mXScale = float(mSurfaceWidth) / rawWidth;
3667 mYScale = float(mSurfaceHeight) / rawHeight;
3668 mXTranslate = -mSurfaceLeft;
3669 mYTranslate = -mSurfaceTop;
3670 mXPrecision = 1.0f / mXScale;
3671 mYPrecision = 1.0f / mYScale;
3672
3673 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3674 mOrientedRanges.x.source = mSource;
3675 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3676 mOrientedRanges.y.source = mSource;
3677
3678 configureVirtualKeys();
3679
3680 // Scale factor for terms that are not oriented in a particular axis.
3681 // If the pixels are square then xScale == yScale otherwise we fake it
3682 // by choosing an average.
3683 mGeometricScale = avg(mXScale, mYScale);
3684
3685 // Size of diagonal axis.
3686 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3687
3688 // Size factors.
3689 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3690 if (mRawPointerAxes.touchMajor.valid
3691 && mRawPointerAxes.touchMajor.maxValue != 0) {
3692 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3693 } else if (mRawPointerAxes.toolMajor.valid
3694 && mRawPointerAxes.toolMajor.maxValue != 0) {
3695 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3696 } else {
3697 mSizeScale = 0.0f;
3698 }
3699
3700 mOrientedRanges.haveTouchSize = true;
3701 mOrientedRanges.haveToolSize = true;
3702 mOrientedRanges.haveSize = true;
3703
3704 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3705 mOrientedRanges.touchMajor.source = mSource;
3706 mOrientedRanges.touchMajor.min = 0;
3707 mOrientedRanges.touchMajor.max = diagonalSize;
3708 mOrientedRanges.touchMajor.flat = 0;
3709 mOrientedRanges.touchMajor.fuzz = 0;
3710 mOrientedRanges.touchMajor.resolution = 0;
3711
3712 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3713 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3714
3715 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3716 mOrientedRanges.toolMajor.source = mSource;
3717 mOrientedRanges.toolMajor.min = 0;
3718 mOrientedRanges.toolMajor.max = diagonalSize;
3719 mOrientedRanges.toolMajor.flat = 0;
3720 mOrientedRanges.toolMajor.fuzz = 0;
3721 mOrientedRanges.toolMajor.resolution = 0;
3722
3723 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3724 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3725
3726 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3727 mOrientedRanges.size.source = mSource;
3728 mOrientedRanges.size.min = 0;
3729 mOrientedRanges.size.max = 1.0;
3730 mOrientedRanges.size.flat = 0;
3731 mOrientedRanges.size.fuzz = 0;
3732 mOrientedRanges.size.resolution = 0;
3733 } else {
3734 mSizeScale = 0.0f;
3735 }
3736
3737 // Pressure factors.
3738 mPressureScale = 0;
3739 float pressureMax = 1.0;
3740 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3741 || mCalibration.pressureCalibration
3742 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3743 if (mCalibration.havePressureScale) {
3744 mPressureScale = mCalibration.pressureScale;
3745 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
3746 } else if (mRawPointerAxes.pressure.valid
3747 && mRawPointerAxes.pressure.maxValue != 0) {
3748 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3749 }
3750 }
3751
3752 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3753 mOrientedRanges.pressure.source = mSource;
3754 mOrientedRanges.pressure.min = 0;
3755 mOrientedRanges.pressure.max = pressureMax;
3756 mOrientedRanges.pressure.flat = 0;
3757 mOrientedRanges.pressure.fuzz = 0;
3758 mOrientedRanges.pressure.resolution = 0;
3759
3760 // Tilt
3761 mTiltXCenter = 0;
3762 mTiltXScale = 0;
3763 mTiltYCenter = 0;
3764 mTiltYScale = 0;
3765 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3766 if (mHaveTilt) {
3767 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3768 mRawPointerAxes.tiltX.maxValue);
3769 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3770 mRawPointerAxes.tiltY.maxValue);
3771 mTiltXScale = M_PI / 180;
3772 mTiltYScale = M_PI / 180;
3773
3774 mOrientedRanges.haveTilt = true;
3775
3776 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3777 mOrientedRanges.tilt.source = mSource;
3778 mOrientedRanges.tilt.min = 0;
3779 mOrientedRanges.tilt.max = M_PI_2;
3780 mOrientedRanges.tilt.flat = 0;
3781 mOrientedRanges.tilt.fuzz = 0;
3782 mOrientedRanges.tilt.resolution = 0;
3783 }
3784
3785 // Orientation
3786 mOrientationScale = 0;
3787 if (mHaveTilt) {
3788 mOrientedRanges.haveOrientation = true;
3789
3790 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3791 mOrientedRanges.orientation.source = mSource;
3792 mOrientedRanges.orientation.min = -M_PI;
3793 mOrientedRanges.orientation.max = M_PI;
3794 mOrientedRanges.orientation.flat = 0;
3795 mOrientedRanges.orientation.fuzz = 0;
3796 mOrientedRanges.orientation.resolution = 0;
3797 } else if (mCalibration.orientationCalibration !=
3798 Calibration::ORIENTATION_CALIBRATION_NONE) {
3799 if (mCalibration.orientationCalibration
3800 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3801 if (mRawPointerAxes.orientation.valid) {
3802 if (mRawPointerAxes.orientation.maxValue > 0) {
3803 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3804 } else if (mRawPointerAxes.orientation.minValue < 0) {
3805 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3806 } else {
3807 mOrientationScale = 0;
3808 }
3809 }
3810 }
3811
3812 mOrientedRanges.haveOrientation = true;
3813
3814 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3815 mOrientedRanges.orientation.source = mSource;
3816 mOrientedRanges.orientation.min = -M_PI_2;
3817 mOrientedRanges.orientation.max = M_PI_2;
3818 mOrientedRanges.orientation.flat = 0;
3819 mOrientedRanges.orientation.fuzz = 0;
3820 mOrientedRanges.orientation.resolution = 0;
3821 }
3822
3823 // Distance
3824 mDistanceScale = 0;
3825 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3826 if (mCalibration.distanceCalibration
3827 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3828 if (mCalibration.haveDistanceScale) {
3829 mDistanceScale = mCalibration.distanceScale;
3830 } else {
3831 mDistanceScale = 1.0f;
3832 }
3833 }
3834
3835 mOrientedRanges.haveDistance = true;
3836
3837 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3838 mOrientedRanges.distance.source = mSource;
3839 mOrientedRanges.distance.min =
3840 mRawPointerAxes.distance.minValue * mDistanceScale;
3841 mOrientedRanges.distance.max =
3842 mRawPointerAxes.distance.maxValue * mDistanceScale;
3843 mOrientedRanges.distance.flat = 0;
3844 mOrientedRanges.distance.fuzz =
3845 mRawPointerAxes.distance.fuzz * mDistanceScale;
3846 mOrientedRanges.distance.resolution = 0;
3847 }
3848
3849 // Compute oriented precision, scales and ranges.
3850 // Note that the maximum value reported is an inclusive maximum value so it is one
3851 // unit less than the total width or height of surface.
3852 switch (mSurfaceOrientation) {
3853 case DISPLAY_ORIENTATION_90:
3854 case DISPLAY_ORIENTATION_270:
3855 mOrientedXPrecision = mYPrecision;
3856 mOrientedYPrecision = mXPrecision;
3857
3858 mOrientedRanges.x.min = mYTranslate;
3859 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3860 mOrientedRanges.x.flat = 0;
3861 mOrientedRanges.x.fuzz = 0;
3862 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3863
3864 mOrientedRanges.y.min = mXTranslate;
3865 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3866 mOrientedRanges.y.flat = 0;
3867 mOrientedRanges.y.fuzz = 0;
3868 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3869 break;
3870
3871 default:
3872 mOrientedXPrecision = mXPrecision;
3873 mOrientedYPrecision = mYPrecision;
3874
3875 mOrientedRanges.x.min = mXTranslate;
3876 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3877 mOrientedRanges.x.flat = 0;
3878 mOrientedRanges.x.fuzz = 0;
3879 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3880
3881 mOrientedRanges.y.min = mYTranslate;
3882 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3883 mOrientedRanges.y.flat = 0;
3884 mOrientedRanges.y.fuzz = 0;
3885 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3886 break;
3887 }
3888
3889 // Location
3890 updateAffineTransformation();
3891
3892 if (mDeviceMode == DEVICE_MODE_POINTER) {
3893 // Compute pointer gesture detection parameters.
3894 float rawDiagonal = hypotf(rawWidth, rawHeight);
3895 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3896
3897 // Scale movements such that one whole swipe of the touch pad covers a
3898 // given area relative to the diagonal size of the display when no acceleration
3899 // is applied.
3900 // Assume that the touch pad has a square aspect ratio such that movements in
3901 // X and Y of the same number of raw units cover the same physical distance.
3902 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3903 * displayDiagonal / rawDiagonal;
3904 mPointerYMovementScale = mPointerXMovementScale;
3905
3906 // Scale zooms to cover a smaller range of the display than movements do.
3907 // This value determines the area around the pointer that is affected by freeform
3908 // pointer gestures.
3909 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3910 * displayDiagonal / rawDiagonal;
3911 mPointerYZoomScale = mPointerXZoomScale;
3912
3913 // Max width between pointers to detect a swipe gesture is more than some fraction
3914 // of the diagonal axis of the touch pad. Touches that are wider than this are
3915 // translated into freeform gestures.
3916 mPointerGestureMaxSwipeWidth =
3917 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3918
3919 // Abort current pointer usages because the state has changed.
3920 abortPointerUsage(when, 0 /*policyFlags*/);
3921 }
3922
3923 // Inform the dispatcher about the changes.
3924 *outResetNeeded = true;
3925 bumpGeneration();
3926 }
3927 }
3928
dumpSurface(std::string & dump)3929 void TouchInputMapper::dumpSurface(std::string& dump) {
3930 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
3931 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3932 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3933 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3934 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3935 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3936 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3937 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3938 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
3939 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3940 }
3941
configureVirtualKeys()3942 void TouchInputMapper::configureVirtualKeys() {
3943 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
3944 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3945
3946 mVirtualKeys.clear();
3947
3948 if (virtualKeyDefinitions.size() == 0) {
3949 return;
3950 }
3951
3952 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3953 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3954 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3955 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
3956
3957 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
3958 VirtualKey virtualKey;
3959
3960 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3961 int32_t keyCode;
3962 int32_t dummyKeyMetaState;
3963 uint32_t flags;
3964 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3965 &keyCode, &dummyKeyMetaState, &flags)) {
3966 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3967 virtualKey.scanCode);
3968 continue; // drop the key
3969 }
3970
3971 virtualKey.keyCode = keyCode;
3972 virtualKey.flags = flags;
3973
3974 // convert the key definition's display coordinates into touch coordinates for a hit box
3975 int32_t halfWidth = virtualKeyDefinition.width / 2;
3976 int32_t halfHeight = virtualKeyDefinition.height / 2;
3977
3978 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3979 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3980 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3981 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3982 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3983 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3984 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3985 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3986 mVirtualKeys.push_back(virtualKey);
3987 }
3988 }
3989
dumpVirtualKeys(std::string & dump)3990 void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
3991 if (!mVirtualKeys.empty()) {
3992 dump += INDENT3 "Virtual Keys:\n";
3993
3994 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3995 const VirtualKey& virtualKey = mVirtualKeys[i];
3996 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
3997 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3998 i, virtualKey.scanCode, virtualKey.keyCode,
3999 virtualKey.hitLeft, virtualKey.hitRight,
4000 virtualKey.hitTop, virtualKey.hitBottom);
4001 }
4002 }
4003 }
4004
parseCalibration()4005 void TouchInputMapper::parseCalibration() {
4006 const PropertyMap& in = getDevice()->getConfiguration();
4007 Calibration& out = mCalibration;
4008
4009 // Size
4010 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4011 String8 sizeCalibrationString;
4012 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4013 if (sizeCalibrationString == "none") {
4014 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4015 } else if (sizeCalibrationString == "geometric") {
4016 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4017 } else if (sizeCalibrationString == "diameter") {
4018 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4019 } else if (sizeCalibrationString == "box") {
4020 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4021 } else if (sizeCalibrationString == "area") {
4022 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4023 } else if (sizeCalibrationString != "default") {
4024 ALOGW("Invalid value for touch.size.calibration: '%s'",
4025 sizeCalibrationString.string());
4026 }
4027 }
4028
4029 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4030 out.sizeScale);
4031 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4032 out.sizeBias);
4033 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4034 out.sizeIsSummed);
4035
4036 // Pressure
4037 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4038 String8 pressureCalibrationString;
4039 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4040 if (pressureCalibrationString == "none") {
4041 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4042 } else if (pressureCalibrationString == "physical") {
4043 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4044 } else if (pressureCalibrationString == "amplitude") {
4045 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4046 } else if (pressureCalibrationString != "default") {
4047 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4048 pressureCalibrationString.string());
4049 }
4050 }
4051
4052 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4053 out.pressureScale);
4054
4055 // Orientation
4056 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4057 String8 orientationCalibrationString;
4058 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4059 if (orientationCalibrationString == "none") {
4060 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4061 } else if (orientationCalibrationString == "interpolated") {
4062 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4063 } else if (orientationCalibrationString == "vector") {
4064 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4065 } else if (orientationCalibrationString != "default") {
4066 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4067 orientationCalibrationString.string());
4068 }
4069 }
4070
4071 // Distance
4072 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4073 String8 distanceCalibrationString;
4074 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4075 if (distanceCalibrationString == "none") {
4076 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4077 } else if (distanceCalibrationString == "scaled") {
4078 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4079 } else if (distanceCalibrationString != "default") {
4080 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4081 distanceCalibrationString.string());
4082 }
4083 }
4084
4085 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4086 out.distanceScale);
4087
4088 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4089 String8 coverageCalibrationString;
4090 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4091 if (coverageCalibrationString == "none") {
4092 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4093 } else if (coverageCalibrationString == "box") {
4094 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4095 } else if (coverageCalibrationString != "default") {
4096 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4097 coverageCalibrationString.string());
4098 }
4099 }
4100 }
4101
resolveCalibration()4102 void TouchInputMapper::resolveCalibration() {
4103 // Size
4104 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4105 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4106 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4107 }
4108 } else {
4109 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4110 }
4111
4112 // Pressure
4113 if (mRawPointerAxes.pressure.valid) {
4114 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4115 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4116 }
4117 } else {
4118 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4119 }
4120
4121 // Orientation
4122 if (mRawPointerAxes.orientation.valid) {
4123 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4124 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4125 }
4126 } else {
4127 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4128 }
4129
4130 // Distance
4131 if (mRawPointerAxes.distance.valid) {
4132 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4133 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4134 }
4135 } else {
4136 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4137 }
4138
4139 // Coverage
4140 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4141 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4142 }
4143 }
4144
dumpCalibration(std::string & dump)4145 void TouchInputMapper::dumpCalibration(std::string& dump) {
4146 dump += INDENT3 "Calibration:\n";
4147
4148 // Size
4149 switch (mCalibration.sizeCalibration) {
4150 case Calibration::SIZE_CALIBRATION_NONE:
4151 dump += INDENT4 "touch.size.calibration: none\n";
4152 break;
4153 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4154 dump += INDENT4 "touch.size.calibration: geometric\n";
4155 break;
4156 case Calibration::SIZE_CALIBRATION_DIAMETER:
4157 dump += INDENT4 "touch.size.calibration: diameter\n";
4158 break;
4159 case Calibration::SIZE_CALIBRATION_BOX:
4160 dump += INDENT4 "touch.size.calibration: box\n";
4161 break;
4162 case Calibration::SIZE_CALIBRATION_AREA:
4163 dump += INDENT4 "touch.size.calibration: area\n";
4164 break;
4165 default:
4166 ALOG_ASSERT(false);
4167 }
4168
4169 if (mCalibration.haveSizeScale) {
4170 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
4171 mCalibration.sizeScale);
4172 }
4173
4174 if (mCalibration.haveSizeBias) {
4175 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
4176 mCalibration.sizeBias);
4177 }
4178
4179 if (mCalibration.haveSizeIsSummed) {
4180 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
4181 toString(mCalibration.sizeIsSummed));
4182 }
4183
4184 // Pressure
4185 switch (mCalibration.pressureCalibration) {
4186 case Calibration::PRESSURE_CALIBRATION_NONE:
4187 dump += INDENT4 "touch.pressure.calibration: none\n";
4188 break;
4189 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4190 dump += INDENT4 "touch.pressure.calibration: physical\n";
4191 break;
4192 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4193 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
4194 break;
4195 default:
4196 ALOG_ASSERT(false);
4197 }
4198
4199 if (mCalibration.havePressureScale) {
4200 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
4201 mCalibration.pressureScale);
4202 }
4203
4204 // Orientation
4205 switch (mCalibration.orientationCalibration) {
4206 case Calibration::ORIENTATION_CALIBRATION_NONE:
4207 dump += INDENT4 "touch.orientation.calibration: none\n";
4208 break;
4209 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4210 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
4211 break;
4212 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4213 dump += INDENT4 "touch.orientation.calibration: vector\n";
4214 break;
4215 default:
4216 ALOG_ASSERT(false);
4217 }
4218
4219 // Distance
4220 switch (mCalibration.distanceCalibration) {
4221 case Calibration::DISTANCE_CALIBRATION_NONE:
4222 dump += INDENT4 "touch.distance.calibration: none\n";
4223 break;
4224 case Calibration::DISTANCE_CALIBRATION_SCALED:
4225 dump += INDENT4 "touch.distance.calibration: scaled\n";
4226 break;
4227 default:
4228 ALOG_ASSERT(false);
4229 }
4230
4231 if (mCalibration.haveDistanceScale) {
4232 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
4233 mCalibration.distanceScale);
4234 }
4235
4236 switch (mCalibration.coverageCalibration) {
4237 case Calibration::COVERAGE_CALIBRATION_NONE:
4238 dump += INDENT4 "touch.coverage.calibration: none\n";
4239 break;
4240 case Calibration::COVERAGE_CALIBRATION_BOX:
4241 dump += INDENT4 "touch.coverage.calibration: box\n";
4242 break;
4243 default:
4244 ALOG_ASSERT(false);
4245 }
4246 }
4247
dumpAffineTransformation(std::string & dump)4248 void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4249 dump += INDENT3 "Affine Transformation:\n";
4250
4251 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4252 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4253 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4254 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4255 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4256 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4257 }
4258
updateAffineTransformation()4259 void TouchInputMapper::updateAffineTransformation() {
4260 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4261 mSurfaceOrientation);
4262 }
4263
reset(nsecs_t when)4264 void TouchInputMapper::reset(nsecs_t when) {
4265 mCursorButtonAccumulator.reset(getDevice());
4266 mCursorScrollAccumulator.reset(getDevice());
4267 mTouchButtonAccumulator.reset(getDevice());
4268
4269 mPointerVelocityControl.reset();
4270 mWheelXVelocityControl.reset();
4271 mWheelYVelocityControl.reset();
4272
4273 mRawStatesPending.clear();
4274 mCurrentRawState.clear();
4275 mCurrentCookedState.clear();
4276 mLastRawState.clear();
4277 mLastCookedState.clear();
4278 mPointerUsage = POINTER_USAGE_NONE;
4279 mSentHoverEnter = false;
4280 mHavePointerIds = false;
4281 mCurrentMotionAborted = false;
4282 mDownTime = 0;
4283
4284 mCurrentVirtualKey.down = false;
4285
4286 mPointerGesture.reset();
4287 mPointerSimple.reset();
4288 resetExternalStylus();
4289
4290 if (mPointerController != nullptr) {
4291 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4292 mPointerController->clearSpots();
4293 }
4294
4295 InputMapper::reset(when);
4296 }
4297
resetExternalStylus()4298 void TouchInputMapper::resetExternalStylus() {
4299 mExternalStylusState.clear();
4300 mExternalStylusId = -1;
4301 mExternalStylusFusionTimeout = LLONG_MAX;
4302 mExternalStylusDataPending = false;
4303 }
4304
clearStylusDataPendingFlags()4305 void TouchInputMapper::clearStylusDataPendingFlags() {
4306 mExternalStylusDataPending = false;
4307 mExternalStylusFusionTimeout = LLONG_MAX;
4308 }
4309
reportEventForStatistics(nsecs_t evdevTime)4310 void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4311 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4312 nsecs_t latency = now - evdevTime;
4313 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4314 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4315 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
4316 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED,
4317 mStatistics.min, mStatistics.max,
4318 mStatistics.mean(), mStatistics.stdev(), mStatistics.count);
4319 mStatistics.reset(now);
4320 }
4321 }
4322
process(const RawEvent * rawEvent)4323 void TouchInputMapper::process(const RawEvent* rawEvent) {
4324 mCursorButtonAccumulator.process(rawEvent);
4325 mCursorScrollAccumulator.process(rawEvent);
4326 mTouchButtonAccumulator.process(rawEvent);
4327
4328 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4329 reportEventForStatistics(rawEvent->when);
4330 sync(rawEvent->when);
4331 }
4332 }
4333
sync(nsecs_t when)4334 void TouchInputMapper::sync(nsecs_t when) {
4335 const RawState* last = mRawStatesPending.empty() ?
4336 &mCurrentRawState : &mRawStatesPending.back();
4337
4338 // Push a new state.
4339 mRawStatesPending.emplace_back();
4340
4341 RawState* next = &mRawStatesPending.back();
4342 next->clear();
4343 next->when = when;
4344
4345 // Sync button state.
4346 next->buttonState = mTouchButtonAccumulator.getButtonState()
4347 | mCursorButtonAccumulator.getButtonState();
4348
4349 // Sync scroll
4350 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4351 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
4352 mCursorScrollAccumulator.finishSync();
4353
4354 // Sync touch
4355 syncTouch(when, next);
4356
4357 // Assign pointer ids.
4358 if (!mHavePointerIds) {
4359 assignPointerIds(last, next);
4360 }
4361
4362 #if DEBUG_RAW_EVENTS
4363 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4364 "hovering ids 0x%08x -> 0x%08x",
4365 last->rawPointerData.pointerCount,
4366 next->rawPointerData.pointerCount,
4367 last->rawPointerData.touchingIdBits.value,
4368 next->rawPointerData.touchingIdBits.value,
4369 last->rawPointerData.hoveringIdBits.value,
4370 next->rawPointerData.hoveringIdBits.value);
4371 #endif
4372
4373 processRawTouches(false /*timeout*/);
4374 }
4375
processRawTouches(bool timeout)4376 void TouchInputMapper::processRawTouches(bool timeout) {
4377 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4378 // Drop all input if the device is disabled.
4379 mCurrentRawState.clear();
4380 mRawStatesPending.clear();
4381 return;
4382 }
4383
4384 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4385 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4386 // touching the current state will only observe the events that have been dispatched to the
4387 // rest of the pipeline.
4388 const size_t N = mRawStatesPending.size();
4389 size_t count;
4390 for(count = 0; count < N; count++) {
4391 const RawState& next = mRawStatesPending[count];
4392
4393 // A failure to assign the stylus id means that we're waiting on stylus data
4394 // and so should defer the rest of the pipeline.
4395 if (assignExternalStylusId(next, timeout)) {
4396 break;
4397 }
4398
4399 // All ready to go.
4400 clearStylusDataPendingFlags();
4401 mCurrentRawState.copyFrom(next);
4402 if (mCurrentRawState.when < mLastRawState.when) {
4403 mCurrentRawState.when = mLastRawState.when;
4404 }
4405 cookAndDispatch(mCurrentRawState.when);
4406 }
4407 if (count != 0) {
4408 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
4409 }
4410
4411 if (mExternalStylusDataPending) {
4412 if (timeout) {
4413 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4414 clearStylusDataPendingFlags();
4415 mCurrentRawState.copyFrom(mLastRawState);
4416 #if DEBUG_STYLUS_FUSION
4417 ALOGD("Timeout expired, synthesizing event with new stylus data");
4418 #endif
4419 cookAndDispatch(when);
4420 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4421 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4422 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4423 }
4424 }
4425 }
4426
cookAndDispatch(nsecs_t when)4427 void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4428 // Always start with a clean state.
4429 mCurrentCookedState.clear();
4430
4431 // Apply stylus buttons to current raw state.
4432 applyExternalStylusButtonState(when);
4433
4434 // Handle policy on initial down or hover events.
4435 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4436 && mCurrentRawState.rawPointerData.pointerCount != 0;
4437
4438 uint32_t policyFlags = 0;
4439 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4440 if (initialDown || buttonsPressed) {
4441 // If this is a touch screen, hide the pointer on an initial down.
4442 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4443 getContext()->fadePointer();
4444 }
4445
4446 if (mParameters.wake) {
4447 policyFlags |= POLICY_FLAG_WAKE;
4448 }
4449 }
4450
4451 // Consume raw off-screen touches before cooking pointer data.
4452 // If touches are consumed, subsequent code will not receive any pointer data.
4453 if (consumeRawTouches(when, policyFlags)) {
4454 mCurrentRawState.rawPointerData.clear();
4455 }
4456
4457 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4458 // with cooked pointer data that has the same ids and indices as the raw data.
4459 // The following code can use either the raw or cooked data, as needed.
4460 cookPointerData();
4461
4462 // Apply stylus pressure to current cooked state.
4463 applyExternalStylusTouchState(when);
4464
4465 // Synthesize key down from raw buttons if needed.
4466 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
4467 mViewport.displayId, policyFlags,
4468 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
4469
4470 // Dispatch the touches either directly or by translation through a pointer on screen.
4471 if (mDeviceMode == DEVICE_MODE_POINTER) {
4472 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4473 !idBits.isEmpty(); ) {
4474 uint32_t id = idBits.clearFirstMarkedBit();
4475 const RawPointerData::Pointer& pointer =
4476 mCurrentRawState.rawPointerData.pointerForId(id);
4477 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4478 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4479 mCurrentCookedState.stylusIdBits.markBit(id);
4480 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4481 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4482 mCurrentCookedState.fingerIdBits.markBit(id);
4483 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4484 mCurrentCookedState.mouseIdBits.markBit(id);
4485 }
4486 }
4487 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4488 !idBits.isEmpty(); ) {
4489 uint32_t id = idBits.clearFirstMarkedBit();
4490 const RawPointerData::Pointer& pointer =
4491 mCurrentRawState.rawPointerData.pointerForId(id);
4492 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4493 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4494 mCurrentCookedState.stylusIdBits.markBit(id);
4495 }
4496 }
4497
4498 // Stylus takes precedence over all tools, then mouse, then finger.
4499 PointerUsage pointerUsage = mPointerUsage;
4500 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4501 mCurrentCookedState.mouseIdBits.clear();
4502 mCurrentCookedState.fingerIdBits.clear();
4503 pointerUsage = POINTER_USAGE_STYLUS;
4504 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4505 mCurrentCookedState.fingerIdBits.clear();
4506 pointerUsage = POINTER_USAGE_MOUSE;
4507 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4508 isPointerDown(mCurrentRawState.buttonState)) {
4509 pointerUsage = POINTER_USAGE_GESTURES;
4510 }
4511
4512 dispatchPointerUsage(when, policyFlags, pointerUsage);
4513 } else {
4514 if (mDeviceMode == DEVICE_MODE_DIRECT
4515 && mConfig.showTouches && mPointerController != nullptr) {
4516 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4517 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4518
4519 mPointerController->setButtonState(mCurrentRawState.buttonState);
4520 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4521 mCurrentCookedState.cookedPointerData.idToIndex,
4522 mCurrentCookedState.cookedPointerData.touchingIdBits,
4523 mViewport.displayId);
4524 }
4525
4526 if (!mCurrentMotionAborted) {
4527 dispatchButtonRelease(when, policyFlags);
4528 dispatchHoverExit(when, policyFlags);
4529 dispatchTouches(when, policyFlags);
4530 dispatchHoverEnterAndMove(when, policyFlags);
4531 dispatchButtonPress(when, policyFlags);
4532 }
4533
4534 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4535 mCurrentMotionAborted = false;
4536 }
4537 }
4538
4539 // Synthesize key up from raw buttons if needed.
4540 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
4541 mViewport.displayId, policyFlags,
4542 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
4543
4544 // Clear some transient state.
4545 mCurrentRawState.rawVScroll = 0;
4546 mCurrentRawState.rawHScroll = 0;
4547
4548 // Copy current touch to last touch in preparation for the next cycle.
4549 mLastRawState.copyFrom(mCurrentRawState);
4550 mLastCookedState.copyFrom(mCurrentCookedState);
4551 }
4552
applyExternalStylusButtonState(nsecs_t when)4553 void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
4554 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
4555 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4556 }
4557 }
4558
applyExternalStylusTouchState(nsecs_t when)4559 void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
4560 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4561 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
4562
4563 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4564 float pressure = mExternalStylusState.pressure;
4565 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4566 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4567 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4568 }
4569 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4570 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4571
4572 PointerProperties& properties =
4573 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
4574 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4575 properties.toolType = mExternalStylusState.toolType;
4576 }
4577 }
4578 }
4579
assignExternalStylusId(const RawState & state,bool timeout)4580 bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4581 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4582 return false;
4583 }
4584
4585 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4586 && state.rawPointerData.pointerCount != 0;
4587 if (initialDown) {
4588 if (mExternalStylusState.pressure != 0.0f) {
4589 #if DEBUG_STYLUS_FUSION
4590 ALOGD("Have both stylus and touch data, beginning fusion");
4591 #endif
4592 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4593 } else if (timeout) {
4594 #if DEBUG_STYLUS_FUSION
4595 ALOGD("Timeout expired, assuming touch is not a stylus.");
4596 #endif
4597 resetExternalStylus();
4598 } else {
4599 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4600 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
4601 }
4602 #if DEBUG_STYLUS_FUSION
4603 ALOGD("No stylus data but stylus is connected, requesting timeout "
4604 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
4605 #endif
4606 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4607 return true;
4608 }
4609 }
4610
4611 // Check if the stylus pointer has gone up.
4612 if (mExternalStylusId != -1 &&
4613 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4614 #if DEBUG_STYLUS_FUSION
4615 ALOGD("Stylus pointer is going up");
4616 #endif
4617 mExternalStylusId = -1;
4618 }
4619
4620 return false;
4621 }
4622
timeoutExpired(nsecs_t when)4623 void TouchInputMapper::timeoutExpired(nsecs_t when) {
4624 if (mDeviceMode == DEVICE_MODE_POINTER) {
4625 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4626 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4627 }
4628 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
4629 if (mExternalStylusFusionTimeout < when) {
4630 processRawTouches(true /*timeout*/);
4631 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4632 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4633 }
4634 }
4635 }
4636
updateExternalStylusState(const StylusState & state)4637 void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
4638 mExternalStylusState.copyFrom(state);
4639 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
4640 // We're either in the middle of a fused stream of data or we're waiting on data before
4641 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4642 // data.
4643 mExternalStylusDataPending = true;
4644 processRawTouches(false /*timeout*/);
4645 }
4646 }
4647
consumeRawTouches(nsecs_t when,uint32_t policyFlags)4648 bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4649 // Check for release of a virtual key.
4650 if (mCurrentVirtualKey.down) {
4651 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
4652 // Pointer went up while virtual key was down.
4653 mCurrentVirtualKey.down = false;
4654 if (!mCurrentVirtualKey.ignored) {
4655 #if DEBUG_VIRTUAL_KEYS
4656 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4657 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4658 #endif
4659 dispatchVirtualKey(when, policyFlags,
4660 AKEY_EVENT_ACTION_UP,
4661 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4662 }
4663 return true;
4664 }
4665
4666 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4667 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4668 const RawPointerData::Pointer& pointer =
4669 mCurrentRawState.rawPointerData.pointerForId(id);
4670 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4671 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4672 // Pointer is still within the space of the virtual key.
4673 return true;
4674 }
4675 }
4676
4677 // Pointer left virtual key area or another pointer also went down.
4678 // Send key cancellation but do not consume the touch yet.
4679 // This is useful when the user swipes through from the virtual key area
4680 // into the main display surface.
4681 mCurrentVirtualKey.down = false;
4682 if (!mCurrentVirtualKey.ignored) {
4683 #if DEBUG_VIRTUAL_KEYS
4684 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4685 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4686 #endif
4687 dispatchVirtualKey(when, policyFlags,
4688 AKEY_EVENT_ACTION_UP,
4689 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4690 | AKEY_EVENT_FLAG_CANCELED);
4691 }
4692 }
4693
4694 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4695 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
4696 // Pointer just went down. Check for virtual key press or off-screen touches.
4697 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4698 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
4699 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4700 // If exactly one pointer went down, check for virtual key hit.
4701 // Otherwise we will drop the entire stroke.
4702 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4703 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4704 if (virtualKey) {
4705 mCurrentVirtualKey.down = true;
4706 mCurrentVirtualKey.downTime = when;
4707 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4708 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4709 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4710 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4711
4712 if (!mCurrentVirtualKey.ignored) {
4713 #if DEBUG_VIRTUAL_KEYS
4714 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4715 mCurrentVirtualKey.keyCode,
4716 mCurrentVirtualKey.scanCode);
4717 #endif
4718 dispatchVirtualKey(when, policyFlags,
4719 AKEY_EVENT_ACTION_DOWN,
4720 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4721 }
4722 }
4723 }
4724 return true;
4725 }
4726 }
4727
4728 // Disable all virtual key touches that happen within a short time interval of the
4729 // most recent touch within the screen area. The idea is to filter out stray
4730 // virtual key presses when interacting with the touch screen.
4731 //
4732 // Problems we're trying to solve:
4733 //
4734 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4735 // virtual key area that is implemented by a separate touch panel and accidentally
4736 // triggers a virtual key.
4737 //
4738 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4739 // area and accidentally triggers a virtual key. This often happens when virtual keys
4740 // are layed out below the screen near to where the on screen keyboard's space bar
4741 // is displayed.
4742 if (mConfig.virtualKeyQuietTime > 0 &&
4743 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
4744 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4745 }
4746 return false;
4747 }
4748
dispatchVirtualKey(nsecs_t when,uint32_t policyFlags,int32_t keyEventAction,int32_t keyEventFlags)4749 void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4750 int32_t keyEventAction, int32_t keyEventFlags) {
4751 int32_t keyCode = mCurrentVirtualKey.keyCode;
4752 int32_t scanCode = mCurrentVirtualKey.scanCode;
4753 nsecs_t downTime = mCurrentVirtualKey.downTime;
4754 int32_t metaState = mContext->getGlobalMetaState();
4755 policyFlags |= POLICY_FLAG_VIRTUAL;
4756
4757 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4758 mViewport.displayId,
4759 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4760 getListener()->notifyKey(&args);
4761 }
4762
abortTouches(nsecs_t when,uint32_t policyFlags)4763 void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4764 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4765 if (!currentIdBits.isEmpty()) {
4766 int32_t metaState = getContext()->getGlobalMetaState();
4767 int32_t buttonState = mCurrentCookedState.buttonState;
4768 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4769 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4770 mCurrentCookedState.deviceTimestamp,
4771 mCurrentCookedState.cookedPointerData.pointerProperties,
4772 mCurrentCookedState.cookedPointerData.pointerCoords,
4773 mCurrentCookedState.cookedPointerData.idToIndex,
4774 currentIdBits, -1,
4775 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4776 mCurrentMotionAborted = true;
4777 }
4778 }
4779
dispatchTouches(nsecs_t when,uint32_t policyFlags)4780 void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
4781 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4782 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
4783 int32_t metaState = getContext()->getGlobalMetaState();
4784 int32_t buttonState = mCurrentCookedState.buttonState;
4785
4786 if (currentIdBits == lastIdBits) {
4787 if (!currentIdBits.isEmpty()) {
4788 // No pointer id changes so this is a move event.
4789 // The listener takes care of batching moves so we don't have to deal with that here.
4790 dispatchMotion(when, policyFlags, mSource,
4791 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
4792 AMOTION_EVENT_EDGE_FLAG_NONE,
4793 mCurrentCookedState.deviceTimestamp,
4794 mCurrentCookedState.cookedPointerData.pointerProperties,
4795 mCurrentCookedState.cookedPointerData.pointerCoords,
4796 mCurrentCookedState.cookedPointerData.idToIndex,
4797 currentIdBits, -1,
4798 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4799 }
4800 } else {
4801 // There may be pointers going up and pointers going down and pointers moving
4802 // all at the same time.
4803 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4804 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4805 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4806 BitSet32 dispatchedIdBits(lastIdBits.value);
4807
4808 // Update last coordinates of pointers that have moved so that we observe the new
4809 // pointer positions at the same time as other pointers that have just gone up.
4810 bool moveNeeded = updateMovedPointers(
4811 mCurrentCookedState.cookedPointerData.pointerProperties,
4812 mCurrentCookedState.cookedPointerData.pointerCoords,
4813 mCurrentCookedState.cookedPointerData.idToIndex,
4814 mLastCookedState.cookedPointerData.pointerProperties,
4815 mLastCookedState.cookedPointerData.pointerCoords,
4816 mLastCookedState.cookedPointerData.idToIndex,
4817 moveIdBits);
4818 if (buttonState != mLastCookedState.buttonState) {
4819 moveNeeded = true;
4820 }
4821
4822 // Dispatch pointer up events.
4823 while (!upIdBits.isEmpty()) {
4824 uint32_t upId = upIdBits.clearFirstMarkedBit();
4825
4826 dispatchMotion(when, policyFlags, mSource,
4827 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
4828 mCurrentCookedState.deviceTimestamp,
4829 mLastCookedState.cookedPointerData.pointerProperties,
4830 mLastCookedState.cookedPointerData.pointerCoords,
4831 mLastCookedState.cookedPointerData.idToIndex,
4832 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4833 dispatchedIdBits.clearBit(upId);
4834 }
4835
4836 // Dispatch move events if any of the remaining pointers moved from their old locations.
4837 // Although applications receive new locations as part of individual pointer up
4838 // events, they do not generally handle them except when presented in a move event.
4839 if (moveNeeded && !moveIdBits.isEmpty()) {
4840 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4841 dispatchMotion(when, policyFlags, mSource,
4842 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
4843 mCurrentCookedState.deviceTimestamp,
4844 mCurrentCookedState.cookedPointerData.pointerProperties,
4845 mCurrentCookedState.cookedPointerData.pointerCoords,
4846 mCurrentCookedState.cookedPointerData.idToIndex,
4847 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4848 }
4849
4850 // Dispatch pointer down events using the new pointer locations.
4851 while (!downIdBits.isEmpty()) {
4852 uint32_t downId = downIdBits.clearFirstMarkedBit();
4853 dispatchedIdBits.markBit(downId);
4854
4855 if (dispatchedIdBits.count() == 1) {
4856 // First pointer is going down. Set down time.
4857 mDownTime = when;
4858 }
4859
4860 dispatchMotion(when, policyFlags, mSource,
4861 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
4862 mCurrentCookedState.deviceTimestamp,
4863 mCurrentCookedState.cookedPointerData.pointerProperties,
4864 mCurrentCookedState.cookedPointerData.pointerCoords,
4865 mCurrentCookedState.cookedPointerData.idToIndex,
4866 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4867 }
4868 }
4869 }
4870
dispatchHoverExit(nsecs_t when,uint32_t policyFlags)4871 void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4872 if (mSentHoverEnter &&
4873 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4874 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
4875 int32_t metaState = getContext()->getGlobalMetaState();
4876 dispatchMotion(when, policyFlags, mSource,
4877 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
4878 mLastCookedState.deviceTimestamp,
4879 mLastCookedState.cookedPointerData.pointerProperties,
4880 mLastCookedState.cookedPointerData.pointerCoords,
4881 mLastCookedState.cookedPointerData.idToIndex,
4882 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
4883 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4884 mSentHoverEnter = false;
4885 }
4886 }
4887
dispatchHoverEnterAndMove(nsecs_t when,uint32_t policyFlags)4888 void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
4889 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4890 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
4891 int32_t metaState = getContext()->getGlobalMetaState();
4892 if (!mSentHoverEnter) {
4893 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
4894 0, 0, metaState, mCurrentRawState.buttonState, 0,
4895 mCurrentCookedState.deviceTimestamp,
4896 mCurrentCookedState.cookedPointerData.pointerProperties,
4897 mCurrentCookedState.cookedPointerData.pointerCoords,
4898 mCurrentCookedState.cookedPointerData.idToIndex,
4899 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
4900 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4901 mSentHoverEnter = true;
4902 }
4903
4904 dispatchMotion(when, policyFlags, mSource,
4905 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
4906 mCurrentRawState.buttonState, 0,
4907 mCurrentCookedState.deviceTimestamp,
4908 mCurrentCookedState.cookedPointerData.pointerProperties,
4909 mCurrentCookedState.cookedPointerData.pointerCoords,
4910 mCurrentCookedState.cookedPointerData.idToIndex,
4911 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
4912 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4913 }
4914 }
4915
dispatchButtonRelease(nsecs_t when,uint32_t policyFlags)4916 void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4917 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4918 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4919 const int32_t metaState = getContext()->getGlobalMetaState();
4920 int32_t buttonState = mLastCookedState.buttonState;
4921 while (!releasedButtons.isEmpty()) {
4922 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4923 buttonState &= ~actionButton;
4924 dispatchMotion(when, policyFlags, mSource,
4925 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4926 0, metaState, buttonState, 0,
4927 mCurrentCookedState.deviceTimestamp,
4928 mCurrentCookedState.cookedPointerData.pointerProperties,
4929 mCurrentCookedState.cookedPointerData.pointerCoords,
4930 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4931 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4932 }
4933 }
4934
dispatchButtonPress(nsecs_t when,uint32_t policyFlags)4935 void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4936 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4937 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4938 const int32_t metaState = getContext()->getGlobalMetaState();
4939 int32_t buttonState = mLastCookedState.buttonState;
4940 while (!pressedButtons.isEmpty()) {
4941 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4942 buttonState |= actionButton;
4943 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4944 0, metaState, buttonState, 0,
4945 mCurrentCookedState.deviceTimestamp,
4946 mCurrentCookedState.cookedPointerData.pointerProperties,
4947 mCurrentCookedState.cookedPointerData.pointerCoords,
4948 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4949 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4950 }
4951 }
4952
findActiveIdBits(const CookedPointerData & cookedPointerData)4953 const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4954 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4955 return cookedPointerData.touchingIdBits;
4956 }
4957 return cookedPointerData.hoveringIdBits;
4958 }
4959
cookPointerData()4960 void TouchInputMapper::cookPointerData() {
4961 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
4962
4963 mCurrentCookedState.cookedPointerData.clear();
4964 mCurrentCookedState.deviceTimestamp =
4965 mCurrentRawState.deviceTimestamp;
4966 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4967 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4968 mCurrentRawState.rawPointerData.hoveringIdBits;
4969 mCurrentCookedState.cookedPointerData.touchingIdBits =
4970 mCurrentRawState.rawPointerData.touchingIdBits;
4971
4972 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4973 mCurrentCookedState.buttonState = 0;
4974 } else {
4975 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4976 }
4977
4978 // Walk through the the active pointers and map device coordinates onto
4979 // surface coordinates and adjust for display orientation.
4980 for (uint32_t i = 0; i < currentPointerCount; i++) {
4981 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
4982
4983 // Size
4984 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4985 switch (mCalibration.sizeCalibration) {
4986 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4987 case Calibration::SIZE_CALIBRATION_DIAMETER:
4988 case Calibration::SIZE_CALIBRATION_BOX:
4989 case Calibration::SIZE_CALIBRATION_AREA:
4990 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4991 touchMajor = in.touchMajor;
4992 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4993 toolMajor = in.toolMajor;
4994 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4995 size = mRawPointerAxes.touchMinor.valid
4996 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4997 } else if (mRawPointerAxes.touchMajor.valid) {
4998 toolMajor = touchMajor = in.touchMajor;
4999 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
5000 ? in.touchMinor : in.touchMajor;
5001 size = mRawPointerAxes.touchMinor.valid
5002 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5003 } else if (mRawPointerAxes.toolMajor.valid) {
5004 touchMajor = toolMajor = in.toolMajor;
5005 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
5006 ? in.toolMinor : in.toolMajor;
5007 size = mRawPointerAxes.toolMinor.valid
5008 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5009 } else {
5010 ALOG_ASSERT(false, "No touch or tool axes. "
5011 "Size calibration should have been resolved to NONE.");
5012 touchMajor = 0;
5013 touchMinor = 0;
5014 toolMajor = 0;
5015 toolMinor = 0;
5016 size = 0;
5017 }
5018
5019 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
5020 uint32_t touchingCount =
5021 mCurrentRawState.rawPointerData.touchingIdBits.count();
5022 if (touchingCount > 1) {
5023 touchMajor /= touchingCount;
5024 touchMinor /= touchingCount;
5025 toolMajor /= touchingCount;
5026 toolMinor /= touchingCount;
5027 size /= touchingCount;
5028 }
5029 }
5030
5031 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5032 touchMajor *= mGeometricScale;
5033 touchMinor *= mGeometricScale;
5034 toolMajor *= mGeometricScale;
5035 toolMinor *= mGeometricScale;
5036 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5037 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5038 touchMinor = touchMajor;
5039 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5040 toolMinor = toolMajor;
5041 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5042 touchMinor = touchMajor;
5043 toolMinor = toolMajor;
5044 }
5045
5046 mCalibration.applySizeScaleAndBias(&touchMajor);
5047 mCalibration.applySizeScaleAndBias(&touchMinor);
5048 mCalibration.applySizeScaleAndBias(&toolMajor);
5049 mCalibration.applySizeScaleAndBias(&toolMinor);
5050 size *= mSizeScale;
5051 break;
5052 default:
5053 touchMajor = 0;
5054 touchMinor = 0;
5055 toolMajor = 0;
5056 toolMinor = 0;
5057 size = 0;
5058 break;
5059 }
5060
5061 // Pressure
5062 float pressure;
5063 switch (mCalibration.pressureCalibration) {
5064 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5065 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5066 pressure = in.pressure * mPressureScale;
5067 break;
5068 default:
5069 pressure = in.isHovering ? 0 : 1;
5070 break;
5071 }
5072
5073 // Tilt and Orientation
5074 float tilt;
5075 float orientation;
5076 if (mHaveTilt) {
5077 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5078 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5079 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5080 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5081 } else {
5082 tilt = 0;
5083
5084 switch (mCalibration.orientationCalibration) {
5085 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5086 orientation = in.orientation * mOrientationScale;
5087 break;
5088 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5089 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5090 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5091 if (c1 != 0 || c2 != 0) {
5092 orientation = atan2f(c1, c2) * 0.5f;
5093 float confidence = hypotf(c1, c2);
5094 float scale = 1.0f + confidence / 16.0f;
5095 touchMajor *= scale;
5096 touchMinor /= scale;
5097 toolMajor *= scale;
5098 toolMinor /= scale;
5099 } else {
5100 orientation = 0;
5101 }
5102 break;
5103 }
5104 default:
5105 orientation = 0;
5106 }
5107 }
5108
5109 // Distance
5110 float distance;
5111 switch (mCalibration.distanceCalibration) {
5112 case Calibration::DISTANCE_CALIBRATION_SCALED:
5113 distance = in.distance * mDistanceScale;
5114 break;
5115 default:
5116 distance = 0;
5117 }
5118
5119 // Coverage
5120 int32_t rawLeft, rawTop, rawRight, rawBottom;
5121 switch (mCalibration.coverageCalibration) {
5122 case Calibration::COVERAGE_CALIBRATION_BOX:
5123 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5124 rawRight = in.toolMinor & 0x0000ffff;
5125 rawBottom = in.toolMajor & 0x0000ffff;
5126 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5127 break;
5128 default:
5129 rawLeft = rawTop = rawRight = rawBottom = 0;
5130 break;
5131 }
5132
5133 // Adjust X,Y coords for device calibration
5134 // TODO: Adjust coverage coords?
5135 float xTransformed = in.x, yTransformed = in.y;
5136 mAffineTransform.applyTo(xTransformed, yTransformed);
5137
5138 // Adjust X, Y, and coverage coords for surface orientation.
5139 float x, y;
5140 float left, top, right, bottom;
5141
5142 switch (mSurfaceOrientation) {
5143 case DISPLAY_ORIENTATION_90:
5144 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5145 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5146 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5147 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5148 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5149 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5150 orientation -= M_PI_2;
5151 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
5152 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5153 }
5154 break;
5155 case DISPLAY_ORIENTATION_180:
5156 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
5157 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5158 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5159 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
5160 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5161 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5162 orientation -= M_PI;
5163 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
5164 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5165 }
5166 break;
5167 case DISPLAY_ORIENTATION_270:
5168 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
5169 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5170 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5171 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
5172 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5173 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5174 orientation += M_PI_2;
5175 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
5176 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5177 }
5178 break;
5179 default:
5180 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5181 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5182 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5183 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5184 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5185 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5186 break;
5187 }
5188
5189 // Write output coords.
5190 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
5191 out.clear();
5192 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5193 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5194 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5195 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5196 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5197 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5198 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5199 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5200 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5201 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5202 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5203 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5204 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5205 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5206 } else {
5207 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5208 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5209 }
5210
5211 // Write output properties.
5212 PointerProperties& properties =
5213 mCurrentCookedState.cookedPointerData.pointerProperties[i];
5214 uint32_t id = in.id;
5215 properties.clear();
5216 properties.id = id;
5217 properties.toolType = in.toolType;
5218
5219 // Write id index.
5220 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
5221 }
5222 }
5223
dispatchPointerUsage(nsecs_t when,uint32_t policyFlags,PointerUsage pointerUsage)5224 void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5225 PointerUsage pointerUsage) {
5226 if (pointerUsage != mPointerUsage) {
5227 abortPointerUsage(when, policyFlags);
5228 mPointerUsage = pointerUsage;
5229 }
5230
5231 switch (mPointerUsage) {
5232 case POINTER_USAGE_GESTURES:
5233 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5234 break;
5235 case POINTER_USAGE_STYLUS:
5236 dispatchPointerStylus(when, policyFlags);
5237 break;
5238 case POINTER_USAGE_MOUSE:
5239 dispatchPointerMouse(when, policyFlags);
5240 break;
5241 default:
5242 break;
5243 }
5244 }
5245
abortPointerUsage(nsecs_t when,uint32_t policyFlags)5246 void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5247 switch (mPointerUsage) {
5248 case POINTER_USAGE_GESTURES:
5249 abortPointerGestures(when, policyFlags);
5250 break;
5251 case POINTER_USAGE_STYLUS:
5252 abortPointerStylus(when, policyFlags);
5253 break;
5254 case POINTER_USAGE_MOUSE:
5255 abortPointerMouse(when, policyFlags);
5256 break;
5257 default:
5258 break;
5259 }
5260
5261 mPointerUsage = POINTER_USAGE_NONE;
5262 }
5263
dispatchPointerGestures(nsecs_t when,uint32_t policyFlags,bool isTimeout)5264 void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5265 bool isTimeout) {
5266 // Update current gesture coordinates.
5267 bool cancelPreviousGesture, finishPreviousGesture;
5268 bool sendEvents = preparePointerGestures(when,
5269 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5270 if (!sendEvents) {
5271 return;
5272 }
5273 if (finishPreviousGesture) {
5274 cancelPreviousGesture = false;
5275 }
5276
5277 // Update the pointer presentation and spots.
5278 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5279 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5280 if (finishPreviousGesture || cancelPreviousGesture) {
5281 mPointerController->clearSpots();
5282 }
5283
5284 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5285 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5286 mPointerGesture.currentGestureIdToIndex,
5287 mPointerGesture.currentGestureIdBits,
5288 mPointerController->getDisplayId());
5289 }
5290 } else {
5291 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5292 }
5293
5294 // Show or hide the pointer if needed.
5295 switch (mPointerGesture.currentGestureMode) {
5296 case PointerGesture::NEUTRAL:
5297 case PointerGesture::QUIET:
5298 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5299 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
5300 // Remind the user of where the pointer is after finishing a gesture with spots.
5301 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5302 }
5303 break;
5304 case PointerGesture::TAP:
5305 case PointerGesture::TAP_DRAG:
5306 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5307 case PointerGesture::HOVER:
5308 case PointerGesture::PRESS:
5309 case PointerGesture::SWIPE:
5310 // Unfade the pointer when the current gesture manipulates the
5311 // area directly under the pointer.
5312 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5313 break;
5314 case PointerGesture::FREEFORM:
5315 // Fade the pointer when the current gesture manipulates a different
5316 // area and there are spots to guide the user experience.
5317 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5318 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5319 } else {
5320 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5321 }
5322 break;
5323 }
5324
5325 // Send events!
5326 int32_t metaState = getContext()->getGlobalMetaState();
5327 int32_t buttonState = mCurrentCookedState.buttonState;
5328
5329 // Update last coordinates of pointers that have moved so that we observe the new
5330 // pointer positions at the same time as other pointers that have just gone up.
5331 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5332 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5333 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5334 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5335 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5336 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5337 bool moveNeeded = false;
5338 if (down && !cancelPreviousGesture && !finishPreviousGesture
5339 && !mPointerGesture.lastGestureIdBits.isEmpty()
5340 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5341 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5342 & mPointerGesture.lastGestureIdBits.value);
5343 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5344 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5345 mPointerGesture.lastGestureProperties,
5346 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5347 movedGestureIdBits);
5348 if (buttonState != mLastCookedState.buttonState) {
5349 moveNeeded = true;
5350 }
5351 }
5352
5353 // Send motion events for all pointers that went up or were canceled.
5354 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5355 if (!dispatchedGestureIdBits.isEmpty()) {
5356 if (cancelPreviousGesture) {
5357 dispatchMotion(when, policyFlags, mSource,
5358 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
5359 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
5360 mPointerGesture.lastGestureProperties,
5361 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5362 dispatchedGestureIdBits, -1, 0,
5363 0, mPointerGesture.downTime);
5364
5365 dispatchedGestureIdBits.clear();
5366 } else {
5367 BitSet32 upGestureIdBits;
5368 if (finishPreviousGesture) {
5369 upGestureIdBits = dispatchedGestureIdBits;
5370 } else {
5371 upGestureIdBits.value = dispatchedGestureIdBits.value
5372 & ~mPointerGesture.currentGestureIdBits.value;
5373 }
5374 while (!upGestureIdBits.isEmpty()) {
5375 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5376
5377 dispatchMotion(when, policyFlags, mSource,
5378 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
5379 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5380 /* deviceTimestamp */ 0,
5381 mPointerGesture.lastGestureProperties,
5382 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5383 dispatchedGestureIdBits, id,
5384 0, 0, mPointerGesture.downTime);
5385
5386 dispatchedGestureIdBits.clearBit(id);
5387 }
5388 }
5389 }
5390
5391 // Send motion events for all pointers that moved.
5392 if (moveNeeded) {
5393 dispatchMotion(when, policyFlags, mSource,
5394 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5395 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
5396 mPointerGesture.currentGestureProperties,
5397 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5398 dispatchedGestureIdBits, -1,
5399 0, 0, mPointerGesture.downTime);
5400 }
5401
5402 // Send motion events for all pointers that went down.
5403 if (down) {
5404 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5405 & ~dispatchedGestureIdBits.value);
5406 while (!downGestureIdBits.isEmpty()) {
5407 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5408 dispatchedGestureIdBits.markBit(id);
5409
5410 if (dispatchedGestureIdBits.count() == 1) {
5411 mPointerGesture.downTime = when;
5412 }
5413
5414 dispatchMotion(when, policyFlags, mSource,
5415 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
5416 /* deviceTimestamp */ 0,
5417 mPointerGesture.currentGestureProperties,
5418 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5419 dispatchedGestureIdBits, id,
5420 0, 0, mPointerGesture.downTime);
5421 }
5422 }
5423
5424 // Send motion events for hover.
5425 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5426 dispatchMotion(when, policyFlags, mSource,
5427 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5428 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
5429 mPointerGesture.currentGestureProperties,
5430 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5431 mPointerGesture.currentGestureIdBits, -1,
5432 0, 0, mPointerGesture.downTime);
5433 } else if (dispatchedGestureIdBits.isEmpty()
5434 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5435 // Synthesize a hover move event after all pointers go up to indicate that
5436 // the pointer is hovering again even if the user is not currently touching
5437 // the touch pad. This ensures that a view will receive a fresh hover enter
5438 // event after a tap.
5439 float x, y;
5440 mPointerController->getPosition(&x, &y);
5441
5442 PointerProperties pointerProperties;
5443 pointerProperties.clear();
5444 pointerProperties.id = 0;
5445 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5446
5447 PointerCoords pointerCoords;
5448 pointerCoords.clear();
5449 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5450 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5451
5452 const int32_t displayId = mPointerController->getDisplayId();
5453 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
5454 mSource, displayId, policyFlags,
5455 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5456 metaState, buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
5457 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
5458 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
5459 getListener()->notifyMotion(&args);
5460 }
5461
5462 // Update state.
5463 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5464 if (!down) {
5465 mPointerGesture.lastGestureIdBits.clear();
5466 } else {
5467 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5468 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5469 uint32_t id = idBits.clearFirstMarkedBit();
5470 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5471 mPointerGesture.lastGestureProperties[index].copyFrom(
5472 mPointerGesture.currentGestureProperties[index]);
5473 mPointerGesture.lastGestureCoords[index].copyFrom(
5474 mPointerGesture.currentGestureCoords[index]);
5475 mPointerGesture.lastGestureIdToIndex[id] = index;
5476 }
5477 }
5478 }
5479
abortPointerGestures(nsecs_t when,uint32_t policyFlags)5480 void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5481 // Cancel previously dispatches pointers.
5482 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5483 int32_t metaState = getContext()->getGlobalMetaState();
5484 int32_t buttonState = mCurrentRawState.buttonState;
5485 dispatchMotion(when, policyFlags, mSource,
5486 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
5487 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
5488 mPointerGesture.lastGestureProperties,
5489 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5490 mPointerGesture.lastGestureIdBits, -1,
5491 0, 0, mPointerGesture.downTime);
5492 }
5493
5494 // Reset the current pointer gesture.
5495 mPointerGesture.reset();
5496 mPointerVelocityControl.reset();
5497
5498 // Remove any current spots.
5499 if (mPointerController != nullptr) {
5500 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5501 mPointerController->clearSpots();
5502 }
5503 }
5504
preparePointerGestures(nsecs_t when,bool * outCancelPreviousGesture,bool * outFinishPreviousGesture,bool isTimeout)5505 bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5506 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5507 *outCancelPreviousGesture = false;
5508 *outFinishPreviousGesture = false;
5509
5510 // Handle TAP timeout.
5511 if (isTimeout) {
5512 #if DEBUG_GESTURES
5513 ALOGD("Gestures: Processing timeout");
5514 #endif
5515
5516 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5517 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5518 // The tap/drag timeout has not yet expired.
5519 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5520 + mConfig.pointerGestureTapDragInterval);
5521 } else {
5522 // The tap is finished.
5523 #if DEBUG_GESTURES
5524 ALOGD("Gestures: TAP finished");
5525 #endif
5526 *outFinishPreviousGesture = true;
5527
5528 mPointerGesture.activeGestureId = -1;
5529 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5530 mPointerGesture.currentGestureIdBits.clear();
5531
5532 mPointerVelocityControl.reset();
5533 return true;
5534 }
5535 }
5536
5537 // We did not handle this timeout.
5538 return false;
5539 }
5540
5541 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5542 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
5543
5544 // Update the velocity tracker.
5545 {
5546 VelocityTracker::Position positions[MAX_POINTERS];
5547 uint32_t count = 0;
5548 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
5549 uint32_t id = idBits.clearFirstMarkedBit();
5550 const RawPointerData::Pointer& pointer =
5551 mCurrentRawState.rawPointerData.pointerForId(id);
5552 positions[count].x = pointer.x * mPointerXMovementScale;
5553 positions[count].y = pointer.y * mPointerYMovementScale;
5554 }
5555 mPointerGesture.velocityTracker.addMovement(when,
5556 mCurrentCookedState.fingerIdBits, positions);
5557 }
5558
5559 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5560 // to NEUTRAL, then we should not generate tap event.
5561 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5562 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5563 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5564 mPointerGesture.resetTap();
5565 }
5566
5567 // Pick a new active touch id if needed.
5568 // Choose an arbitrary pointer that just went down, if there is one.
5569 // Otherwise choose an arbitrary remaining pointer.
5570 // This guarantees we always have an active touch id when there is at least one pointer.
5571 // We keep the same active touch id for as long as possible.
5572 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5573 int32_t activeTouchId = lastActiveTouchId;
5574 if (activeTouchId < 0) {
5575 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
5576 activeTouchId = mPointerGesture.activeTouchId =
5577 mCurrentCookedState.fingerIdBits.firstMarkedBit();
5578 mPointerGesture.firstTouchTime = when;
5579 }
5580 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
5581 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
5582 activeTouchId = mPointerGesture.activeTouchId =
5583 mCurrentCookedState.fingerIdBits.firstMarkedBit();
5584 } else {
5585 activeTouchId = mPointerGesture.activeTouchId = -1;
5586 }
5587 }
5588
5589 // Determine whether we are in quiet time.
5590 bool isQuietTime = false;
5591 if (activeTouchId < 0) {
5592 mPointerGesture.resetQuietTime();
5593 } else {
5594 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5595 if (!isQuietTime) {
5596 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5597 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5598 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5599 && currentFingerCount < 2) {
5600 // Enter quiet time when exiting swipe or freeform state.
5601 // This is to prevent accidentally entering the hover state and flinging the
5602 // pointer when finishing a swipe and there is still one pointer left onscreen.
5603 isQuietTime = true;
5604 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5605 && currentFingerCount >= 2
5606 && !isPointerDown(mCurrentRawState.buttonState)) {
5607 // Enter quiet time when releasing the button and there are still two or more
5608 // fingers down. This may indicate that one finger was used to press the button
5609 // but it has not gone up yet.
5610 isQuietTime = true;
5611 }
5612 if (isQuietTime) {
5613 mPointerGesture.quietTime = when;
5614 }
5615 }
5616 }
5617
5618 // Switch states based on button and pointer state.
5619 if (isQuietTime) {
5620 // Case 1: Quiet time. (QUIET)
5621 #if DEBUG_GESTURES
5622 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5623 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5624 #endif
5625 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5626 *outFinishPreviousGesture = true;
5627 }
5628
5629 mPointerGesture.activeGestureId = -1;
5630 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5631 mPointerGesture.currentGestureIdBits.clear();
5632
5633 mPointerVelocityControl.reset();
5634 } else if (isPointerDown(mCurrentRawState.buttonState)) {
5635 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5636 // The pointer follows the active touch point.
5637 // Emit DOWN, MOVE, UP events at the pointer location.
5638 //
5639 // Only the active touch matters; other fingers are ignored. This policy helps
5640 // to handle the case where the user places a second finger on the touch pad
5641 // to apply the necessary force to depress an integrated button below the surface.
5642 // We don't want the second finger to be delivered to applications.
5643 //
5644 // For this to work well, we need to make sure to track the pointer that is really
5645 // active. If the user first puts one finger down to click then adds another
5646 // finger to drag then the active pointer should switch to the finger that is
5647 // being dragged.
5648 #if DEBUG_GESTURES
5649 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5650 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5651 #endif
5652 // Reset state when just starting.
5653 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5654 *outFinishPreviousGesture = true;
5655 mPointerGesture.activeGestureId = 0;
5656 }
5657
5658 // Switch pointers if needed.
5659 // Find the fastest pointer and follow it.
5660 if (activeTouchId >= 0 && currentFingerCount > 1) {
5661 int32_t bestId = -1;
5662 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
5663 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
5664 uint32_t id = idBits.clearFirstMarkedBit();
5665 float vx, vy;
5666 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5667 float speed = hypotf(vx, vy);
5668 if (speed > bestSpeed) {
5669 bestId = id;
5670 bestSpeed = speed;
5671 }
5672 }
5673 }
5674 if (bestId >= 0 && bestId != activeTouchId) {
5675 mPointerGesture.activeTouchId = activeTouchId = bestId;
5676 #if DEBUG_GESTURES
5677 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5678 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5679 #endif
5680 }
5681 }
5682
5683 float deltaX = 0, deltaY = 0;
5684 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
5685 const RawPointerData::Pointer& currentPointer =
5686 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
5687 const RawPointerData::Pointer& lastPointer =
5688 mLastRawState.rawPointerData.pointerForId(activeTouchId);
5689 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5690 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
5691
5692 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5693 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5694
5695 // Move the pointer using a relative motion.
5696 // When using spots, the click will occur at the position of the anchor
5697 // spot and all other spots will move there.
5698 mPointerController->move(deltaX, deltaY);
5699 } else {
5700 mPointerVelocityControl.reset();
5701 }
5702
5703 float x, y;
5704 mPointerController->getPosition(&x, &y);
5705
5706 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5707 mPointerGesture.currentGestureIdBits.clear();
5708 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5709 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5710 mPointerGesture.currentGestureProperties[0].clear();
5711 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5712 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5713 mPointerGesture.currentGestureCoords[0].clear();
5714 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5715 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5716 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5717 } else if (currentFingerCount == 0) {
5718 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5719 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5720 *outFinishPreviousGesture = true;
5721 }
5722
5723 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5724 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5725 bool tapped = false;
5726 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5727 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5728 && lastFingerCount == 1) {
5729 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5730 float x, y;
5731 mPointerController->getPosition(&x, &y);
5732 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5733 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5734 #if DEBUG_GESTURES
5735 ALOGD("Gestures: TAP");
5736 #endif
5737
5738 mPointerGesture.tapUpTime = when;
5739 getContext()->requestTimeoutAtTime(when
5740 + mConfig.pointerGestureTapDragInterval);
5741
5742 mPointerGesture.activeGestureId = 0;
5743 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5744 mPointerGesture.currentGestureIdBits.clear();
5745 mPointerGesture.currentGestureIdBits.markBit(
5746 mPointerGesture.activeGestureId);
5747 mPointerGesture.currentGestureIdToIndex[
5748 mPointerGesture.activeGestureId] = 0;
5749 mPointerGesture.currentGestureProperties[0].clear();
5750 mPointerGesture.currentGestureProperties[0].id =
5751 mPointerGesture.activeGestureId;
5752 mPointerGesture.currentGestureProperties[0].toolType =
5753 AMOTION_EVENT_TOOL_TYPE_FINGER;
5754 mPointerGesture.currentGestureCoords[0].clear();
5755 mPointerGesture.currentGestureCoords[0].setAxisValue(
5756 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5757 mPointerGesture.currentGestureCoords[0].setAxisValue(
5758 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5759 mPointerGesture.currentGestureCoords[0].setAxisValue(
5760 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5761
5762 tapped = true;
5763 } else {
5764 #if DEBUG_GESTURES
5765 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5766 x - mPointerGesture.tapX,
5767 y - mPointerGesture.tapY);
5768 #endif
5769 }
5770 } else {
5771 #if DEBUG_GESTURES
5772 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5773 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5774 (when - mPointerGesture.tapDownTime) * 0.000001f);
5775 } else {
5776 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5777 }
5778 #endif
5779 }
5780 }
5781
5782 mPointerVelocityControl.reset();
5783
5784 if (!tapped) {
5785 #if DEBUG_GESTURES
5786 ALOGD("Gestures: NEUTRAL");
5787 #endif
5788 mPointerGesture.activeGestureId = -1;
5789 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5790 mPointerGesture.currentGestureIdBits.clear();
5791 }
5792 } else if (currentFingerCount == 1) {
5793 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5794 // The pointer follows the active touch point.
5795 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5796 // When in TAP_DRAG, emit MOVE events at the pointer location.
5797 ALOG_ASSERT(activeTouchId >= 0);
5798
5799 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5800 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5801 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5802 float x, y;
5803 mPointerController->getPosition(&x, &y);
5804 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5805 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5806 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5807 } else {
5808 #if DEBUG_GESTURES
5809 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5810 x - mPointerGesture.tapX,
5811 y - mPointerGesture.tapY);
5812 #endif
5813 }
5814 } else {
5815 #if DEBUG_GESTURES
5816 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5817 (when - mPointerGesture.tapUpTime) * 0.000001f);
5818 #endif
5819 }
5820 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5821 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5822 }
5823
5824 float deltaX = 0, deltaY = 0;
5825 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
5826 const RawPointerData::Pointer& currentPointer =
5827 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
5828 const RawPointerData::Pointer& lastPointer =
5829 mLastRawState.rawPointerData.pointerForId(activeTouchId);
5830 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5831 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
5832
5833 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5834 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5835
5836 // Move the pointer using a relative motion.
5837 // When using spots, the hover or drag will occur at the position of the anchor spot.
5838 mPointerController->move(deltaX, deltaY);
5839 } else {
5840 mPointerVelocityControl.reset();
5841 }
5842
5843 bool down;
5844 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5845 #if DEBUG_GESTURES
5846 ALOGD("Gestures: TAP_DRAG");
5847 #endif
5848 down = true;
5849 } else {
5850 #if DEBUG_GESTURES
5851 ALOGD("Gestures: HOVER");
5852 #endif
5853 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5854 *outFinishPreviousGesture = true;
5855 }
5856 mPointerGesture.activeGestureId = 0;
5857 down = false;
5858 }
5859
5860 float x, y;
5861 mPointerController->getPosition(&x, &y);
5862
5863 mPointerGesture.currentGestureIdBits.clear();
5864 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5865 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5866 mPointerGesture.currentGestureProperties[0].clear();
5867 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5868 mPointerGesture.currentGestureProperties[0].toolType =
5869 AMOTION_EVENT_TOOL_TYPE_FINGER;
5870 mPointerGesture.currentGestureCoords[0].clear();
5871 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5872 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5873 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5874 down ? 1.0f : 0.0f);
5875
5876 if (lastFingerCount == 0 && currentFingerCount != 0) {
5877 mPointerGesture.resetTap();
5878 mPointerGesture.tapDownTime = when;
5879 mPointerGesture.tapX = x;
5880 mPointerGesture.tapY = y;
5881 }
5882 } else {
5883 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5884 // We need to provide feedback for each finger that goes down so we cannot wait
5885 // for the fingers to move before deciding what to do.
5886 //
5887 // The ambiguous case is deciding what to do when there are two fingers down but they
5888 // have not moved enough to determine whether they are part of a drag or part of a
5889 // freeform gesture, or just a press or long-press at the pointer location.
5890 //
5891 // When there are two fingers we start with the PRESS hypothesis and we generate a
5892 // down at the pointer location.
5893 //
5894 // When the two fingers move enough or when additional fingers are added, we make
5895 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5896 ALOG_ASSERT(activeTouchId >= 0);
5897
5898 bool settled = when >= mPointerGesture.firstTouchTime
5899 + mConfig.pointerGestureMultitouchSettleInterval;
5900 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5901 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5902 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5903 *outFinishPreviousGesture = true;
5904 } else if (!settled && currentFingerCount > lastFingerCount) {
5905 // Additional pointers have gone down but not yet settled.
5906 // Reset the gesture.
5907 #if DEBUG_GESTURES
5908 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5909 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5910 + mConfig.pointerGestureMultitouchSettleInterval - when)
5911 * 0.000001f);
5912 #endif
5913 *outCancelPreviousGesture = true;
5914 } else {
5915 // Continue previous gesture.
5916 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5917 }
5918
5919 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5920 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5921 mPointerGesture.activeGestureId = 0;
5922 mPointerGesture.referenceIdBits.clear();
5923 mPointerVelocityControl.reset();
5924
5925 // Use the centroid and pointer location as the reference points for the gesture.
5926 #if DEBUG_GESTURES
5927 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5928 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5929 + mConfig.pointerGestureMultitouchSettleInterval - when)
5930 * 0.000001f);
5931 #endif
5932 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
5933 &mPointerGesture.referenceTouchX,
5934 &mPointerGesture.referenceTouchY);
5935 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5936 &mPointerGesture.referenceGestureY);
5937 }
5938
5939 // Clear the reference deltas for fingers not yet included in the reference calculation.
5940 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
5941 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5942 uint32_t id = idBits.clearFirstMarkedBit();
5943 mPointerGesture.referenceDeltas[id].dx = 0;
5944 mPointerGesture.referenceDeltas[id].dy = 0;
5945 }
5946 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
5947
5948 // Add delta for all fingers and calculate a common movement delta.
5949 float commonDeltaX = 0, commonDeltaY = 0;
5950 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5951 & mCurrentCookedState.fingerIdBits.value);
5952 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5953 bool first = (idBits == commonIdBits);
5954 uint32_t id = idBits.clearFirstMarkedBit();
5955 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5956 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
5957 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5958 delta.dx += cpd.x - lpd.x;
5959 delta.dy += cpd.y - lpd.y;
5960
5961 if (first) {
5962 commonDeltaX = delta.dx;
5963 commonDeltaY = delta.dy;
5964 } else {
5965 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5966 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5967 }
5968 }
5969
5970 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5971 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5972 float dist[MAX_POINTER_ID + 1];
5973 int32_t distOverThreshold = 0;
5974 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5975 uint32_t id = idBits.clearFirstMarkedBit();
5976 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5977 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5978 delta.dy * mPointerYZoomScale);
5979 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5980 distOverThreshold += 1;
5981 }
5982 }
5983
5984 // Only transition when at least two pointers have moved further than
5985 // the minimum distance threshold.
5986 if (distOverThreshold >= 2) {
5987 if (currentFingerCount > 2) {
5988 // There are more than two pointers, switch to FREEFORM.
5989 #if DEBUG_GESTURES
5990 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5991 currentFingerCount);
5992 #endif
5993 *outCancelPreviousGesture = true;
5994 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5995 } else {
5996 // There are exactly two pointers.
5997 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
5998 uint32_t id1 = idBits.clearFirstMarkedBit();
5999 uint32_t id2 = idBits.firstMarkedBit();
6000 const RawPointerData::Pointer& p1 =
6001 mCurrentRawState.rawPointerData.pointerForId(id1);
6002 const RawPointerData::Pointer& p2 =
6003 mCurrentRawState.rawPointerData.pointerForId(id2);
6004 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
6005 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
6006 // There are two pointers but they are too far apart for a SWIPE,
6007 // switch to FREEFORM.
6008 #if DEBUG_GESTURES
6009 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
6010 mutualDistance, mPointerGestureMaxSwipeWidth);
6011 #endif
6012 *outCancelPreviousGesture = true;
6013 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6014 } else {
6015 // There are two pointers. Wait for both pointers to start moving
6016 // before deciding whether this is a SWIPE or FREEFORM gesture.
6017 float dist1 = dist[id1];
6018 float dist2 = dist[id2];
6019 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6020 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6021 // Calculate the dot product of the displacement vectors.
6022 // When the vectors are oriented in approximately the same direction,
6023 // the angle betweeen them is near zero and the cosine of the angle
6024 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6025 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6026 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6027 float dx1 = delta1.dx * mPointerXZoomScale;
6028 float dy1 = delta1.dy * mPointerYZoomScale;
6029 float dx2 = delta2.dx * mPointerXZoomScale;
6030 float dy2 = delta2.dy * mPointerYZoomScale;
6031 float dot = dx1 * dx2 + dy1 * dy2;
6032 float cosine = dot / (dist1 * dist2); // denominator always > 0
6033 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6034 // Pointers are moving in the same direction. Switch to SWIPE.
6035 #if DEBUG_GESTURES
6036 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6037 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6038 "cosine %0.3f >= %0.3f",
6039 dist1, mConfig.pointerGestureMultitouchMinDistance,
6040 dist2, mConfig.pointerGestureMultitouchMinDistance,
6041 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6042 #endif
6043 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6044 } else {
6045 // Pointers are moving in different directions. Switch to FREEFORM.
6046 #if DEBUG_GESTURES
6047 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6048 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6049 "cosine %0.3f < %0.3f",
6050 dist1, mConfig.pointerGestureMultitouchMinDistance,
6051 dist2, mConfig.pointerGestureMultitouchMinDistance,
6052 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6053 #endif
6054 *outCancelPreviousGesture = true;
6055 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6056 }
6057 }
6058 }
6059 }
6060 }
6061 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6062 // Switch from SWIPE to FREEFORM if additional pointers go down.
6063 // Cancel previous gesture.
6064 if (currentFingerCount > 2) {
6065 #if DEBUG_GESTURES
6066 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6067 currentFingerCount);
6068 #endif
6069 *outCancelPreviousGesture = true;
6070 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6071 }
6072 }
6073
6074 // Move the reference points based on the overall group motion of the fingers
6075 // except in PRESS mode while waiting for a transition to occur.
6076 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6077 && (commonDeltaX || commonDeltaY)) {
6078 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6079 uint32_t id = idBits.clearFirstMarkedBit();
6080 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6081 delta.dx = 0;
6082 delta.dy = 0;
6083 }
6084
6085 mPointerGesture.referenceTouchX += commonDeltaX;
6086 mPointerGesture.referenceTouchY += commonDeltaY;
6087
6088 commonDeltaX *= mPointerXMovementScale;
6089 commonDeltaY *= mPointerYMovementScale;
6090
6091 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6092 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6093
6094 mPointerGesture.referenceGestureX += commonDeltaX;
6095 mPointerGesture.referenceGestureY += commonDeltaY;
6096 }
6097
6098 // Report gestures.
6099 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6100 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6101 // PRESS or SWIPE mode.
6102 #if DEBUG_GESTURES
6103 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6104 "activeGestureId=%d, currentTouchPointerCount=%d",
6105 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6106 #endif
6107 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6108
6109 mPointerGesture.currentGestureIdBits.clear();
6110 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6111 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6112 mPointerGesture.currentGestureProperties[0].clear();
6113 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6114 mPointerGesture.currentGestureProperties[0].toolType =
6115 AMOTION_EVENT_TOOL_TYPE_FINGER;
6116 mPointerGesture.currentGestureCoords[0].clear();
6117 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6118 mPointerGesture.referenceGestureX);
6119 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6120 mPointerGesture.referenceGestureY);
6121 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6122 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6123 // FREEFORM mode.
6124 #if DEBUG_GESTURES
6125 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6126 "activeGestureId=%d, currentTouchPointerCount=%d",
6127 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6128 #endif
6129 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6130
6131 mPointerGesture.currentGestureIdBits.clear();
6132
6133 BitSet32 mappedTouchIdBits;
6134 BitSet32 usedGestureIdBits;
6135 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6136 // Initially, assign the active gesture id to the active touch point
6137 // if there is one. No other touch id bits are mapped yet.
6138 if (!*outCancelPreviousGesture) {
6139 mappedTouchIdBits.markBit(activeTouchId);
6140 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6141 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6142 mPointerGesture.activeGestureId;
6143 } else {
6144 mPointerGesture.activeGestureId = -1;
6145 }
6146 } else {
6147 // Otherwise, assume we mapped all touches from the previous frame.
6148 // Reuse all mappings that are still applicable.
6149 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6150 & mCurrentCookedState.fingerIdBits.value;
6151 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6152
6153 // Check whether we need to choose a new active gesture id because the
6154 // current went went up.
6155 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6156 & ~mCurrentCookedState.fingerIdBits.value);
6157 !upTouchIdBits.isEmpty(); ) {
6158 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6159 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6160 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6161 mPointerGesture.activeGestureId = -1;
6162 break;
6163 }
6164 }
6165 }
6166
6167 #if DEBUG_GESTURES
6168 ALOGD("Gestures: FREEFORM follow up "
6169 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6170 "activeGestureId=%d",
6171 mappedTouchIdBits.value, usedGestureIdBits.value,
6172 mPointerGesture.activeGestureId);
6173 #endif
6174
6175 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
6176 for (uint32_t i = 0; i < currentFingerCount; i++) {
6177 uint32_t touchId = idBits.clearFirstMarkedBit();
6178 uint32_t gestureId;
6179 if (!mappedTouchIdBits.hasBit(touchId)) {
6180 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6181 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6182 #if DEBUG_GESTURES
6183 ALOGD("Gestures: FREEFORM "
6184 "new mapping for touch id %d -> gesture id %d",
6185 touchId, gestureId);
6186 #endif
6187 } else {
6188 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6189 #if DEBUG_GESTURES
6190 ALOGD("Gestures: FREEFORM "
6191 "existing mapping for touch id %d -> gesture id %d",
6192 touchId, gestureId);
6193 #endif
6194 }
6195 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6196 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6197
6198 const RawPointerData::Pointer& pointer =
6199 mCurrentRawState.rawPointerData.pointerForId(touchId);
6200 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6201 * mPointerXZoomScale;
6202 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6203 * mPointerYZoomScale;
6204 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6205
6206 mPointerGesture.currentGestureProperties[i].clear();
6207 mPointerGesture.currentGestureProperties[i].id = gestureId;
6208 mPointerGesture.currentGestureProperties[i].toolType =
6209 AMOTION_EVENT_TOOL_TYPE_FINGER;
6210 mPointerGesture.currentGestureCoords[i].clear();
6211 mPointerGesture.currentGestureCoords[i].setAxisValue(
6212 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6213 mPointerGesture.currentGestureCoords[i].setAxisValue(
6214 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6215 mPointerGesture.currentGestureCoords[i].setAxisValue(
6216 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6217 }
6218
6219 if (mPointerGesture.activeGestureId < 0) {
6220 mPointerGesture.activeGestureId =
6221 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6222 #if DEBUG_GESTURES
6223 ALOGD("Gestures: FREEFORM new "
6224 "activeGestureId=%d", mPointerGesture.activeGestureId);
6225 #endif
6226 }
6227 }
6228 }
6229
6230 mPointerController->setButtonState(mCurrentRawState.buttonState);
6231
6232 #if DEBUG_GESTURES
6233 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6234 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6235 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6236 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6237 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6238 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6239 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6240 uint32_t id = idBits.clearFirstMarkedBit();
6241 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6242 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6243 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6244 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6245 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6246 id, index, properties.toolType,
6247 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6248 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6249 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6250 }
6251 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6252 uint32_t id = idBits.clearFirstMarkedBit();
6253 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6254 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6255 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6256 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6257 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6258 id, index, properties.toolType,
6259 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6260 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6261 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6262 }
6263 #endif
6264 return true;
6265 }
6266
dispatchPointerStylus(nsecs_t when,uint32_t policyFlags)6267 void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6268 mPointerSimple.currentCoords.clear();
6269 mPointerSimple.currentProperties.clear();
6270
6271 bool down, hovering;
6272 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6273 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6274 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6275 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6276 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
6277 mPointerController->setPosition(x, y);
6278
6279 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
6280 down = !hovering;
6281
6282 mPointerController->getPosition(&x, &y);
6283 mPointerSimple.currentCoords.copyFrom(
6284 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
6285 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6286 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6287 mPointerSimple.currentProperties.id = 0;
6288 mPointerSimple.currentProperties.toolType =
6289 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
6290 } else {
6291 down = false;
6292 hovering = false;
6293 }
6294
6295 dispatchPointerSimple(when, policyFlags, down, hovering);
6296 }
6297
abortPointerStylus(nsecs_t when,uint32_t policyFlags)6298 void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6299 abortPointerSimple(when, policyFlags);
6300 }
6301
dispatchPointerMouse(nsecs_t when,uint32_t policyFlags)6302 void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6303 mPointerSimple.currentCoords.clear();
6304 mPointerSimple.currentProperties.clear();
6305
6306 bool down, hovering;
6307 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6308 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6309 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
6310 float deltaX = 0, deltaY = 0;
6311 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6312 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
6313 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
6314 - mLastRawState.rawPointerData.pointers[lastIndex].x)
6315 * mPointerXMovementScale;
6316 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
6317 - mLastRawState.rawPointerData.pointers[lastIndex].y)
6318 * mPointerYMovementScale;
6319
6320 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6321 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6322
6323 mPointerController->move(deltaX, deltaY);
6324 } else {
6325 mPointerVelocityControl.reset();
6326 }
6327
6328 down = isPointerDown(mCurrentRawState.buttonState);
6329 hovering = !down;
6330
6331 float x, y;
6332 mPointerController->getPosition(&x, &y);
6333 mPointerSimple.currentCoords.copyFrom(
6334 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
6335 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6336 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6337 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6338 hovering ? 0.0f : 1.0f);
6339 mPointerSimple.currentProperties.id = 0;
6340 mPointerSimple.currentProperties.toolType =
6341 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
6342 } else {
6343 mPointerVelocityControl.reset();
6344
6345 down = false;
6346 hovering = false;
6347 }
6348
6349 dispatchPointerSimple(when, policyFlags, down, hovering);
6350 }
6351
abortPointerMouse(nsecs_t when,uint32_t policyFlags)6352 void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6353 abortPointerSimple(when, policyFlags);
6354
6355 mPointerVelocityControl.reset();
6356 }
6357
dispatchPointerSimple(nsecs_t when,uint32_t policyFlags,bool down,bool hovering)6358 void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6359 bool down, bool hovering) {
6360 int32_t metaState = getContext()->getGlobalMetaState();
6361 int32_t displayId = mViewport.displayId;
6362
6363 if (mPointerController != nullptr) {
6364 if (down || hovering) {
6365 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6366 mPointerController->clearSpots();
6367 mPointerController->setButtonState(mCurrentRawState.buttonState);
6368 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6369 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6370 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6371 }
6372 displayId = mPointerController->getDisplayId();
6373 }
6374
6375 if (mPointerSimple.down && !down) {
6376 mPointerSimple.down = false;
6377
6378 // Send up.
6379 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6380 mSource, displayId, policyFlags,
6381 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState,
6382 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
6383 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6384 mOrientedXPrecision, mOrientedYPrecision,
6385 mPointerSimple.downTime, /* videoFrames */ {});
6386 getListener()->notifyMotion(&args);
6387 }
6388
6389 if (mPointerSimple.hovering && !hovering) {
6390 mPointerSimple.hovering = false;
6391
6392 // Send hover exit.
6393 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6394 mSource, displayId, policyFlags,
6395 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState,
6396 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
6397 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6398 mOrientedXPrecision, mOrientedYPrecision,
6399 mPointerSimple.downTime, /* videoFrames */ {});
6400 getListener()->notifyMotion(&args);
6401 }
6402
6403 if (down) {
6404 if (!mPointerSimple.down) {
6405 mPointerSimple.down = true;
6406 mPointerSimple.downTime = when;
6407
6408 // Send down.
6409 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6410 mSource, displayId, policyFlags,
6411 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState,
6412 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
6413 /* deviceTimestamp */ 0,
6414 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6415 mOrientedXPrecision, mOrientedYPrecision,
6416 mPointerSimple.downTime, /* videoFrames */ {});
6417 getListener()->notifyMotion(&args);
6418 }
6419
6420 // Send move.
6421 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6422 mSource, displayId, policyFlags,
6423 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState,
6424 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
6425 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6426 mOrientedXPrecision, mOrientedYPrecision,
6427 mPointerSimple.downTime, /* videoFrames */ {});
6428 getListener()->notifyMotion(&args);
6429 }
6430
6431 if (hovering) {
6432 if (!mPointerSimple.hovering) {
6433 mPointerSimple.hovering = true;
6434
6435 // Send hover enter.
6436 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6437 mSource, displayId, policyFlags,
6438 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
6439 mCurrentRawState.buttonState, MotionClassification::NONE,
6440 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
6441 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6442 mOrientedXPrecision, mOrientedYPrecision,
6443 mPointerSimple.downTime, /* videoFrames */ {});
6444 getListener()->notifyMotion(&args);
6445 }
6446
6447 // Send hover move.
6448 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6449 mSource, displayId, policyFlags,
6450 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
6451 mCurrentRawState.buttonState, MotionClassification::NONE,
6452 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
6453 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6454 mOrientedXPrecision, mOrientedYPrecision,
6455 mPointerSimple.downTime, /* videoFrames */ {});
6456 getListener()->notifyMotion(&args);
6457 }
6458
6459 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6460 float vscroll = mCurrentRawState.rawVScroll;
6461 float hscroll = mCurrentRawState.rawHScroll;
6462 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6463 mWheelXVelocityControl.move(when, &hscroll, nullptr);
6464
6465 // Send scroll.
6466 PointerCoords pointerCoords;
6467 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6468 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6469 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6470
6471 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6472 mSource, displayId, policyFlags,
6473 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState,
6474 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
6475 1, &mPointerSimple.currentProperties, &pointerCoords,
6476 mOrientedXPrecision, mOrientedYPrecision,
6477 mPointerSimple.downTime, /* videoFrames */ {});
6478 getListener()->notifyMotion(&args);
6479 }
6480
6481 // Save state.
6482 if (down || hovering) {
6483 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6484 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6485 } else {
6486 mPointerSimple.reset();
6487 }
6488 }
6489
abortPointerSimple(nsecs_t when,uint32_t policyFlags)6490 void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6491 mPointerSimple.currentCoords.clear();
6492 mPointerSimple.currentProperties.clear();
6493
6494 dispatchPointerSimple(when, policyFlags, false, false);
6495 }
6496
dispatchMotion(nsecs_t when,uint32_t policyFlags,uint32_t source,int32_t action,int32_t actionButton,int32_t flags,int32_t metaState,int32_t buttonState,int32_t edgeFlags,uint32_t deviceTimestamp,const PointerProperties * properties,const PointerCoords * coords,const uint32_t * idToIndex,BitSet32 idBits,int32_t changedId,float xPrecision,float yPrecision,nsecs_t downTime)6497 void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
6498 int32_t action, int32_t actionButton, int32_t flags,
6499 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
6500 const PointerProperties* properties, const PointerCoords* coords,
6501 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6502 float xPrecision, float yPrecision, nsecs_t downTime) {
6503 PointerCoords pointerCoords[MAX_POINTERS];
6504 PointerProperties pointerProperties[MAX_POINTERS];
6505 uint32_t pointerCount = 0;
6506 while (!idBits.isEmpty()) {
6507 uint32_t id = idBits.clearFirstMarkedBit();
6508 uint32_t index = idToIndex[id];
6509 pointerProperties[pointerCount].copyFrom(properties[index]);
6510 pointerCoords[pointerCount].copyFrom(coords[index]);
6511
6512 if (changedId >= 0 && id == uint32_t(changedId)) {
6513 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6514 }
6515
6516 pointerCount += 1;
6517 }
6518
6519 ALOG_ASSERT(pointerCount != 0);
6520
6521 if (changedId >= 0 && pointerCount == 1) {
6522 // Replace initial down and final up action.
6523 // We can compare the action without masking off the changed pointer index
6524 // because we know the index is 0.
6525 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6526 action = AMOTION_EVENT_ACTION_DOWN;
6527 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6528 action = AMOTION_EVENT_ACTION_UP;
6529 } else {
6530 // Can't happen.
6531 ALOG_ASSERT(false);
6532 }
6533 }
6534 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
6535 const int32_t deviceId = getDeviceId();
6536 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
6537 std::for_each(frames.begin(), frames.end(),
6538 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
6539 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
6540 source, displayId, policyFlags,
6541 action, actionButton, flags, metaState, buttonState, MotionClassification::NONE,
6542 edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
6543 xPrecision, yPrecision, downTime, std::move(frames));
6544 getListener()->notifyMotion(&args);
6545 }
6546
updateMovedPointers(const PointerProperties * inProperties,const PointerCoords * inCoords,const uint32_t * inIdToIndex,PointerProperties * outProperties,PointerCoords * outCoords,const uint32_t * outIdToIndex,BitSet32 idBits) const6547 bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6548 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6549 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6550 BitSet32 idBits) const {
6551 bool changed = false;
6552 while (!idBits.isEmpty()) {
6553 uint32_t id = idBits.clearFirstMarkedBit();
6554 uint32_t inIndex = inIdToIndex[id];
6555 uint32_t outIndex = outIdToIndex[id];
6556
6557 const PointerProperties& curInProperties = inProperties[inIndex];
6558 const PointerCoords& curInCoords = inCoords[inIndex];
6559 PointerProperties& curOutProperties = outProperties[outIndex];
6560 PointerCoords& curOutCoords = outCoords[outIndex];
6561
6562 if (curInProperties != curOutProperties) {
6563 curOutProperties.copyFrom(curInProperties);
6564 changed = true;
6565 }
6566
6567 if (curInCoords != curOutCoords) {
6568 curOutCoords.copyFrom(curInCoords);
6569 changed = true;
6570 }
6571 }
6572 return changed;
6573 }
6574
fadePointer()6575 void TouchInputMapper::fadePointer() {
6576 if (mPointerController != nullptr) {
6577 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6578 }
6579 }
6580
cancelTouch(nsecs_t when)6581 void TouchInputMapper::cancelTouch(nsecs_t when) {
6582 abortPointerUsage(when, 0 /*policyFlags*/);
6583 abortTouches(when, 0 /* policyFlags*/);
6584 }
6585
isPointInsideSurface(int32_t x,int32_t y)6586 bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6587 const float scaledX = x * mXScale;
6588 const float scaledY = y * mYScale;
6589 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6590 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6591 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6592 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
6593 }
6594
findVirtualKeyHit(int32_t x,int32_t y)6595 const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
6596
6597 for (const VirtualKey& virtualKey: mVirtualKeys) {
6598 #if DEBUG_VIRTUAL_KEYS
6599 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6600 "left=%d, top=%d, right=%d, bottom=%d",
6601 x, y,
6602 virtualKey.keyCode, virtualKey.scanCode,
6603 virtualKey.hitLeft, virtualKey.hitTop,
6604 virtualKey.hitRight, virtualKey.hitBottom);
6605 #endif
6606
6607 if (virtualKey.isHit(x, y)) {
6608 return & virtualKey;
6609 }
6610 }
6611
6612 return nullptr;
6613 }
6614
assignPointerIds(const RawState * last,RawState * current)6615 void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6616 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6617 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
6618
6619 current->rawPointerData.clearIdBits();
6620
6621 if (currentPointerCount == 0) {
6622 // No pointers to assign.
6623 return;
6624 }
6625
6626 if (lastPointerCount == 0) {
6627 // All pointers are new.
6628 for (uint32_t i = 0; i < currentPointerCount; i++) {
6629 uint32_t id = i;
6630 current->rawPointerData.pointers[i].id = id;
6631 current->rawPointerData.idToIndex[id] = i;
6632 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
6633 }
6634 return;
6635 }
6636
6637 if (currentPointerCount == 1 && lastPointerCount == 1
6638 && current->rawPointerData.pointers[0].toolType
6639 == last->rawPointerData.pointers[0].toolType) {
6640 // Only one pointer and no change in count so it must have the same id as before.
6641 uint32_t id = last->rawPointerData.pointers[0].id;
6642 current->rawPointerData.pointers[0].id = id;
6643 current->rawPointerData.idToIndex[id] = 0;
6644 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
6645 return;
6646 }
6647
6648 // General case.
6649 // We build a heap of squared euclidean distances between current and last pointers
6650 // associated with the current and last pointer indices. Then, we find the best
6651 // match (by distance) for each current pointer.
6652 // The pointers must have the same tool type but it is possible for them to
6653 // transition from hovering to touching or vice-versa while retaining the same id.
6654 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6655
6656 uint32_t heapSize = 0;
6657 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6658 currentPointerIndex++) {
6659 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6660 lastPointerIndex++) {
6661 const RawPointerData::Pointer& currentPointer =
6662 current->rawPointerData.pointers[currentPointerIndex];
6663 const RawPointerData::Pointer& lastPointer =
6664 last->rawPointerData.pointers[lastPointerIndex];
6665 if (currentPointer.toolType == lastPointer.toolType) {
6666 int64_t deltaX = currentPointer.x - lastPointer.x;
6667 int64_t deltaY = currentPointer.y - lastPointer.y;
6668
6669 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6670
6671 // Insert new element into the heap (sift up).
6672 heap[heapSize].currentPointerIndex = currentPointerIndex;
6673 heap[heapSize].lastPointerIndex = lastPointerIndex;
6674 heap[heapSize].distance = distance;
6675 heapSize += 1;
6676 }
6677 }
6678 }
6679
6680 // Heapify
6681 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6682 startIndex -= 1;
6683 for (uint32_t parentIndex = startIndex; ;) {
6684 uint32_t childIndex = parentIndex * 2 + 1;
6685 if (childIndex >= heapSize) {
6686 break;
6687 }
6688
6689 if (childIndex + 1 < heapSize
6690 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6691 childIndex += 1;
6692 }
6693
6694 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6695 break;
6696 }
6697
6698 swap(heap[parentIndex], heap[childIndex]);
6699 parentIndex = childIndex;
6700 }
6701 }
6702
6703 #if DEBUG_POINTER_ASSIGNMENT
6704 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6705 for (size_t i = 0; i < heapSize; i++) {
6706 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
6707 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6708 heap[i].distance);
6709 }
6710 #endif
6711
6712 // Pull matches out by increasing order of distance.
6713 // To avoid reassigning pointers that have already been matched, the loop keeps track
6714 // of which last and current pointers have been matched using the matchedXXXBits variables.
6715 // It also tracks the used pointer id bits.
6716 BitSet32 matchedLastBits(0);
6717 BitSet32 matchedCurrentBits(0);
6718 BitSet32 usedIdBits(0);
6719 bool first = true;
6720 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6721 while (heapSize > 0) {
6722 if (first) {
6723 // The first time through the loop, we just consume the root element of
6724 // the heap (the one with smallest distance).
6725 first = false;
6726 } else {
6727 // Previous iterations consumed the root element of the heap.
6728 // Pop root element off of the heap (sift down).
6729 heap[0] = heap[heapSize];
6730 for (uint32_t parentIndex = 0; ;) {
6731 uint32_t childIndex = parentIndex * 2 + 1;
6732 if (childIndex >= heapSize) {
6733 break;
6734 }
6735
6736 if (childIndex + 1 < heapSize
6737 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6738 childIndex += 1;
6739 }
6740
6741 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6742 break;
6743 }
6744
6745 swap(heap[parentIndex], heap[childIndex]);
6746 parentIndex = childIndex;
6747 }
6748
6749 #if DEBUG_POINTER_ASSIGNMENT
6750 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6751 for (size_t i = 0; i < heapSize; i++) {
6752 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
6753 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6754 heap[i].distance);
6755 }
6756 #endif
6757 }
6758
6759 heapSize -= 1;
6760
6761 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6762 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6763
6764 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6765 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6766
6767 matchedCurrentBits.markBit(currentPointerIndex);
6768 matchedLastBits.markBit(lastPointerIndex);
6769
6770 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6771 current->rawPointerData.pointers[currentPointerIndex].id = id;
6772 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6773 current->rawPointerData.markIdBit(id,
6774 current->rawPointerData.isHovering(currentPointerIndex));
6775 usedIdBits.markBit(id);
6776
6777 #if DEBUG_POINTER_ASSIGNMENT
6778 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6779 ", id=%" PRIu32 ", distance=%" PRIu64,
6780 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6781 #endif
6782 break;
6783 }
6784 }
6785
6786 // Assign fresh ids to pointers that were not matched in the process.
6787 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6788 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6789 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6790
6791 current->rawPointerData.pointers[currentPointerIndex].id = id;
6792 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6793 current->rawPointerData.markIdBit(id,
6794 current->rawPointerData.isHovering(currentPointerIndex));
6795
6796 #if DEBUG_POINTER_ASSIGNMENT
6797 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
6798 #endif
6799 }
6800 }
6801
getKeyCodeState(uint32_t sourceMask,int32_t keyCode)6802 int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6803 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6804 return AKEY_STATE_VIRTUAL;
6805 }
6806
6807 for (const VirtualKey& virtualKey : mVirtualKeys) {
6808 if (virtualKey.keyCode == keyCode) {
6809 return AKEY_STATE_UP;
6810 }
6811 }
6812
6813 return AKEY_STATE_UNKNOWN;
6814 }
6815
getScanCodeState(uint32_t sourceMask,int32_t scanCode)6816 int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6817 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6818 return AKEY_STATE_VIRTUAL;
6819 }
6820
6821 for (const VirtualKey& virtualKey : mVirtualKeys) {
6822 if (virtualKey.scanCode == scanCode) {
6823 return AKEY_STATE_UP;
6824 }
6825 }
6826
6827 return AKEY_STATE_UNKNOWN;
6828 }
6829
markSupportedKeyCodes(uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)6830 bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6831 const int32_t* keyCodes, uint8_t* outFlags) {
6832 for (const VirtualKey& virtualKey : mVirtualKeys) {
6833 for (size_t i = 0; i < numCodes; i++) {
6834 if (virtualKey.keyCode == keyCodes[i]) {
6835 outFlags[i] = 1;
6836 }
6837 }
6838 }
6839
6840 return true;
6841 }
6842
getAssociatedDisplay()6843 std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6844 if (mParameters.hasAssociatedDisplay) {
6845 if (mDeviceMode == DEVICE_MODE_POINTER) {
6846 return std::make_optional(mPointerController->getDisplayId());
6847 } else {
6848 return std::make_optional(mViewport.displayId);
6849 }
6850 }
6851 return std::nullopt;
6852 }
6853
6854 // --- SingleTouchInputMapper ---
6855
SingleTouchInputMapper(InputDevice * device)6856 SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6857 TouchInputMapper(device) {
6858 }
6859
~SingleTouchInputMapper()6860 SingleTouchInputMapper::~SingleTouchInputMapper() {
6861 }
6862
reset(nsecs_t when)6863 void SingleTouchInputMapper::reset(nsecs_t when) {
6864 mSingleTouchMotionAccumulator.reset(getDevice());
6865
6866 TouchInputMapper::reset(when);
6867 }
6868
process(const RawEvent * rawEvent)6869 void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6870 TouchInputMapper::process(rawEvent);
6871
6872 mSingleTouchMotionAccumulator.process(rawEvent);
6873 }
6874
syncTouch(nsecs_t when,RawState * outState)6875 void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
6876 if (mTouchButtonAccumulator.isToolActive()) {
6877 outState->rawPointerData.pointerCount = 1;
6878 outState->rawPointerData.idToIndex[0] = 0;
6879
6880 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6881 && (mTouchButtonAccumulator.isHovering()
6882 || (mRawPointerAxes.pressure.valid
6883 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
6884 outState->rawPointerData.markIdBit(0, isHovering);
6885
6886 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
6887 outPointer.id = 0;
6888 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6889 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6890 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6891 outPointer.touchMajor = 0;
6892 outPointer.touchMinor = 0;
6893 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6894 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6895 outPointer.orientation = 0;
6896 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6897 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6898 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6899 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6900 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6901 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6902 }
6903 outPointer.isHovering = isHovering;
6904 }
6905 }
6906
configureRawPointerAxes()6907 void SingleTouchInputMapper::configureRawPointerAxes() {
6908 TouchInputMapper::configureRawPointerAxes();
6909
6910 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6911 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6912 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6913 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6914 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6915 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6916 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6917 }
6918
hasStylus() const6919 bool SingleTouchInputMapper::hasStylus() const {
6920 return mTouchButtonAccumulator.hasStylus();
6921 }
6922
6923
6924 // --- MultiTouchInputMapper ---
6925
MultiTouchInputMapper(InputDevice * device)6926 MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6927 TouchInputMapper(device) {
6928 }
6929
~MultiTouchInputMapper()6930 MultiTouchInputMapper::~MultiTouchInputMapper() {
6931 }
6932
reset(nsecs_t when)6933 void MultiTouchInputMapper::reset(nsecs_t when) {
6934 mMultiTouchMotionAccumulator.reset(getDevice());
6935
6936 mPointerIdBits.clear();
6937
6938 TouchInputMapper::reset(when);
6939 }
6940
process(const RawEvent * rawEvent)6941 void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6942 TouchInputMapper::process(rawEvent);
6943
6944 mMultiTouchMotionAccumulator.process(rawEvent);
6945 }
6946
syncTouch(nsecs_t when,RawState * outState)6947 void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
6948 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6949 size_t outCount = 0;
6950 BitSet32 newPointerIdBits;
6951 mHavePointerIds = true;
6952
6953 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6954 const MultiTouchMotionAccumulator::Slot* inSlot =
6955 mMultiTouchMotionAccumulator.getSlot(inIndex);
6956 if (!inSlot->isInUse()) {
6957 continue;
6958 }
6959
6960 if (outCount >= MAX_POINTERS) {
6961 #if DEBUG_POINTERS
6962 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6963 "ignoring the rest.",
6964 getDeviceName().c_str(), MAX_POINTERS);
6965 #endif
6966 break; // too many fingers!
6967 }
6968
6969 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
6970 outPointer.x = inSlot->getX();
6971 outPointer.y = inSlot->getY();
6972 outPointer.pressure = inSlot->getPressure();
6973 outPointer.touchMajor = inSlot->getTouchMajor();
6974 outPointer.touchMinor = inSlot->getTouchMinor();
6975 outPointer.toolMajor = inSlot->getToolMajor();
6976 outPointer.toolMinor = inSlot->getToolMinor();
6977 outPointer.orientation = inSlot->getOrientation();
6978 outPointer.distance = inSlot->getDistance();
6979 outPointer.tiltX = 0;
6980 outPointer.tiltY = 0;
6981
6982 outPointer.toolType = inSlot->getToolType();
6983 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6984 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6985 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6986 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6987 }
6988 }
6989
6990 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6991 && (mTouchButtonAccumulator.isHovering()
6992 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6993 outPointer.isHovering = isHovering;
6994
6995 // Assign pointer id using tracking id if available.
6996 if (mHavePointerIds) {
6997 int32_t trackingId = inSlot->getTrackingId();
6998 int32_t id = -1;
6999 if (trackingId >= 0) {
7000 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
7001 uint32_t n = idBits.clearFirstMarkedBit();
7002 if (mPointerTrackingIdMap[n] == trackingId) {
7003 id = n;
7004 }
7005 }
7006
7007 if (id < 0 && !mPointerIdBits.isFull()) {
7008 id = mPointerIdBits.markFirstUnmarkedBit();
7009 mPointerTrackingIdMap[id] = trackingId;
7010 }
7011 }
7012 if (id < 0) {
7013 mHavePointerIds = false;
7014 outState->rawPointerData.clearIdBits();
7015 newPointerIdBits.clear();
7016 } else {
7017 outPointer.id = id;
7018 outState->rawPointerData.idToIndex[id] = outCount;
7019 outState->rawPointerData.markIdBit(id, isHovering);
7020 newPointerIdBits.markBit(id);
7021 }
7022 }
7023 outCount += 1;
7024 }
7025
7026 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
7027 outState->rawPointerData.pointerCount = outCount;
7028 mPointerIdBits = newPointerIdBits;
7029
7030 mMultiTouchMotionAccumulator.finishSync();
7031 }
7032
configureRawPointerAxes()7033 void MultiTouchInputMapper::configureRawPointerAxes() {
7034 TouchInputMapper::configureRawPointerAxes();
7035
7036 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7037 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7038 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7039 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7040 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7041 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7042 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7043 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7044 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7045 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7046 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7047
7048 if (mRawPointerAxes.trackingId.valid
7049 && mRawPointerAxes.slot.valid
7050 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7051 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7052 if (slotCount > MAX_SLOTS) {
7053 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7054 "only supports a maximum of %zu slots at this time.",
7055 getDeviceName().c_str(), slotCount, MAX_SLOTS);
7056 slotCount = MAX_SLOTS;
7057 }
7058 mMultiTouchMotionAccumulator.configure(getDevice(),
7059 slotCount, true /*usingSlotsProtocol*/);
7060 } else {
7061 mMultiTouchMotionAccumulator.configure(getDevice(),
7062 MAX_POINTERS, false /*usingSlotsProtocol*/);
7063 }
7064 }
7065
hasStylus() const7066 bool MultiTouchInputMapper::hasStylus() const {
7067 return mMultiTouchMotionAccumulator.hasStylus()
7068 || mTouchButtonAccumulator.hasStylus();
7069 }
7070
7071 // --- ExternalStylusInputMapper
7072
ExternalStylusInputMapper(InputDevice * device)7073 ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7074 InputMapper(device) {
7075
7076 }
7077
getSources()7078 uint32_t ExternalStylusInputMapper::getSources() {
7079 return AINPUT_SOURCE_STYLUS;
7080 }
7081
populateDeviceInfo(InputDeviceInfo * info)7082 void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7083 InputMapper::populateDeviceInfo(info);
7084 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7085 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7086 }
7087
dump(std::string & dump)7088 void ExternalStylusInputMapper::dump(std::string& dump) {
7089 dump += INDENT2 "External Stylus Input Mapper:\n";
7090 dump += INDENT3 "Raw Stylus Axes:\n";
7091 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
7092 dump += INDENT3 "Stylus State:\n";
7093 dumpStylusState(dump, mStylusState);
7094 }
7095
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)7096 void ExternalStylusInputMapper::configure(nsecs_t when,
7097 const InputReaderConfiguration* config, uint32_t changes) {
7098 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7099 mTouchButtonAccumulator.configure(getDevice());
7100 }
7101
reset(nsecs_t when)7102 void ExternalStylusInputMapper::reset(nsecs_t when) {
7103 InputDevice* device = getDevice();
7104 mSingleTouchMotionAccumulator.reset(device);
7105 mTouchButtonAccumulator.reset(device);
7106 InputMapper::reset(when);
7107 }
7108
process(const RawEvent * rawEvent)7109 void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7110 mSingleTouchMotionAccumulator.process(rawEvent);
7111 mTouchButtonAccumulator.process(rawEvent);
7112
7113 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7114 sync(rawEvent->when);
7115 }
7116 }
7117
sync(nsecs_t when)7118 void ExternalStylusInputMapper::sync(nsecs_t when) {
7119 mStylusState.clear();
7120
7121 mStylusState.when = when;
7122
7123 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7124 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7125 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7126 }
7127
7128 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7129 if (mRawPressureAxis.valid) {
7130 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7131 } else if (mTouchButtonAccumulator.isToolActive()) {
7132 mStylusState.pressure = 1.0f;
7133 } else {
7134 mStylusState.pressure = 0.0f;
7135 }
7136
7137 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
7138
7139 mContext->dispatchExternalStylusState(mStylusState);
7140 }
7141
7142
7143 // --- JoystickInputMapper ---
7144
JoystickInputMapper(InputDevice * device)7145 JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7146 InputMapper(device) {
7147 }
7148
~JoystickInputMapper()7149 JoystickInputMapper::~JoystickInputMapper() {
7150 }
7151
getSources()7152 uint32_t JoystickInputMapper::getSources() {
7153 return AINPUT_SOURCE_JOYSTICK;
7154 }
7155
populateDeviceInfo(InputDeviceInfo * info)7156 void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7157 InputMapper::populateDeviceInfo(info);
7158
7159 for (size_t i = 0; i < mAxes.size(); i++) {
7160 const Axis& axis = mAxes.valueAt(i);
7161 addMotionRange(axis.axisInfo.axis, axis, info);
7162
7163 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7164 addMotionRange(axis.axisInfo.highAxis, axis, info);
7165
7166 }
7167 }
7168 }
7169
addMotionRange(int32_t axisId,const Axis & axis,InputDeviceInfo * info)7170 void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7171 InputDeviceInfo* info) {
7172 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7173 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7174 /* In order to ease the transition for developers from using the old axes
7175 * to the newer, more semantically correct axes, we'll continue to register
7176 * the old axes as duplicates of their corresponding new ones. */
7177 int32_t compatAxis = getCompatAxis(axisId);
7178 if (compatAxis >= 0) {
7179 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7180 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7181 }
7182 }
7183
7184 /* A mapping from axes the joystick actually has to the axes that should be
7185 * artificially created for compatibility purposes.
7186 * Returns -1 if no compatibility axis is needed. */
getCompatAxis(int32_t axis)7187 int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7188 switch(axis) {
7189 case AMOTION_EVENT_AXIS_LTRIGGER:
7190 return AMOTION_EVENT_AXIS_BRAKE;
7191 case AMOTION_EVENT_AXIS_RTRIGGER:
7192 return AMOTION_EVENT_AXIS_GAS;
7193 }
7194 return -1;
7195 }
7196
dump(std::string & dump)7197 void JoystickInputMapper::dump(std::string& dump) {
7198 dump += INDENT2 "Joystick Input Mapper:\n";
7199
7200 dump += INDENT3 "Axes:\n";
7201 size_t numAxes = mAxes.size();
7202 for (size_t i = 0; i < numAxes; i++) {
7203 const Axis& axis = mAxes.valueAt(i);
7204 const char* label = getAxisLabel(axis.axisInfo.axis);
7205 if (label) {
7206 dump += StringPrintf(INDENT4 "%s", label);
7207 } else {
7208 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
7209 }
7210 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7211 label = getAxisLabel(axis.axisInfo.highAxis);
7212 if (label) {
7213 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
7214 } else {
7215 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
7216 axis.axisInfo.splitValue);
7217 }
7218 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
7219 dump += " (invert)";
7220 }
7221
7222 dump += StringPrintf(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
7223 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7224 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
7225 "highScale=%0.5f, highOffset=%0.5f\n",
7226 axis.scale, axis.offset, axis.highScale, axis.highOffset);
7227 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
7228 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7229 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7230 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7231 }
7232 }
7233
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)7234 void JoystickInputMapper::configure(nsecs_t when,
7235 const InputReaderConfiguration* config, uint32_t changes) {
7236 InputMapper::configure(when, config, changes);
7237
7238 if (!changes) { // first time only
7239 // Collect all axes.
7240 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7241 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7242 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7243 continue; // axis must be claimed by a different device
7244 }
7245
7246 RawAbsoluteAxisInfo rawAxisInfo;
7247 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7248 if (rawAxisInfo.valid) {
7249 // Map axis.
7250 AxisInfo axisInfo;
7251 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7252 if (!explicitlyMapped) {
7253 // Axis is not explicitly mapped, will choose a generic axis later.
7254 axisInfo.mode = AxisInfo::MODE_NORMAL;
7255 axisInfo.axis = -1;
7256 }
7257
7258 // Apply flat override.
7259 int32_t rawFlat = axisInfo.flatOverride < 0
7260 ? rawAxisInfo.flat : axisInfo.flatOverride;
7261
7262 // Calculate scaling factors and limits.
7263 Axis axis;
7264 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7265 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7266 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7267 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7268 scale, 0.0f, highScale, 0.0f,
7269 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7270 rawAxisInfo.resolution * scale);
7271 } else if (isCenteredAxis(axisInfo.axis)) {
7272 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7273 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7274 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7275 scale, offset, scale, offset,
7276 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7277 rawAxisInfo.resolution * scale);
7278 } else {
7279 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7280 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7281 scale, 0.0f, scale, 0.0f,
7282 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7283 rawAxisInfo.resolution * scale);
7284 }
7285
7286 // To eliminate noise while the joystick is at rest, filter out small variations
7287 // in axis values up front.
7288 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7289
7290 mAxes.add(abs, axis);
7291 }
7292 }
7293
7294 // If there are too many axes, start dropping them.
7295 // Prefer to keep explicitly mapped axes.
7296 if (mAxes.size() > PointerCoords::MAX_AXES) {
7297 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
7298 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
7299 pruneAxes(true);
7300 pruneAxes(false);
7301 }
7302
7303 // Assign generic axis ids to remaining axes.
7304 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7305 size_t numAxes = mAxes.size();
7306 for (size_t i = 0; i < numAxes; i++) {
7307 Axis& axis = mAxes.editValueAt(i);
7308 if (axis.axisInfo.axis < 0) {
7309 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7310 && haveAxis(nextGenericAxisId)) {
7311 nextGenericAxisId += 1;
7312 }
7313
7314 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7315 axis.axisInfo.axis = nextGenericAxisId;
7316 nextGenericAxisId += 1;
7317 } else {
7318 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7319 "have already been assigned to other axes.",
7320 getDeviceName().c_str(), mAxes.keyAt(i));
7321 mAxes.removeItemsAt(i--);
7322 numAxes -= 1;
7323 }
7324 }
7325 }
7326 }
7327 }
7328
haveAxis(int32_t axisId)7329 bool JoystickInputMapper::haveAxis(int32_t axisId) {
7330 size_t numAxes = mAxes.size();
7331 for (size_t i = 0; i < numAxes; i++) {
7332 const Axis& axis = mAxes.valueAt(i);
7333 if (axis.axisInfo.axis == axisId
7334 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7335 && axis.axisInfo.highAxis == axisId)) {
7336 return true;
7337 }
7338 }
7339 return false;
7340 }
7341
pruneAxes(bool ignoreExplicitlyMappedAxes)7342 void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7343 size_t i = mAxes.size();
7344 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7345 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7346 continue;
7347 }
7348 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7349 getDeviceName().c_str(), mAxes.keyAt(i));
7350 mAxes.removeItemsAt(i);
7351 }
7352 }
7353
isCenteredAxis(int32_t axis)7354 bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7355 switch (axis) {
7356 case AMOTION_EVENT_AXIS_X:
7357 case AMOTION_EVENT_AXIS_Y:
7358 case AMOTION_EVENT_AXIS_Z:
7359 case AMOTION_EVENT_AXIS_RX:
7360 case AMOTION_EVENT_AXIS_RY:
7361 case AMOTION_EVENT_AXIS_RZ:
7362 case AMOTION_EVENT_AXIS_HAT_X:
7363 case AMOTION_EVENT_AXIS_HAT_Y:
7364 case AMOTION_EVENT_AXIS_ORIENTATION:
7365 case AMOTION_EVENT_AXIS_RUDDER:
7366 case AMOTION_EVENT_AXIS_WHEEL:
7367 return true;
7368 default:
7369 return false;
7370 }
7371 }
7372
reset(nsecs_t when)7373 void JoystickInputMapper::reset(nsecs_t when) {
7374 // Recenter all axes.
7375 size_t numAxes = mAxes.size();
7376 for (size_t i = 0; i < numAxes; i++) {
7377 Axis& axis = mAxes.editValueAt(i);
7378 axis.resetValue();
7379 }
7380
7381 InputMapper::reset(when);
7382 }
7383
process(const RawEvent * rawEvent)7384 void JoystickInputMapper::process(const RawEvent* rawEvent) {
7385 switch (rawEvent->type) {
7386 case EV_ABS: {
7387 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7388 if (index >= 0) {
7389 Axis& axis = mAxes.editValueAt(index);
7390 float newValue, highNewValue;
7391 switch (axis.axisInfo.mode) {
7392 case AxisInfo::MODE_INVERT:
7393 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7394 * axis.scale + axis.offset;
7395 highNewValue = 0.0f;
7396 break;
7397 case AxisInfo::MODE_SPLIT:
7398 if (rawEvent->value < axis.axisInfo.splitValue) {
7399 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7400 * axis.scale + axis.offset;
7401 highNewValue = 0.0f;
7402 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7403 newValue = 0.0f;
7404 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7405 * axis.highScale + axis.highOffset;
7406 } else {
7407 newValue = 0.0f;
7408 highNewValue = 0.0f;
7409 }
7410 break;
7411 default:
7412 newValue = rawEvent->value * axis.scale + axis.offset;
7413 highNewValue = 0.0f;
7414 break;
7415 }
7416 axis.newValue = newValue;
7417 axis.highNewValue = highNewValue;
7418 }
7419 break;
7420 }
7421
7422 case EV_SYN:
7423 switch (rawEvent->code) {
7424 case SYN_REPORT:
7425 sync(rawEvent->when, false /*force*/);
7426 break;
7427 }
7428 break;
7429 }
7430 }
7431
sync(nsecs_t when,bool force)7432 void JoystickInputMapper::sync(nsecs_t when, bool force) {
7433 if (!filterAxes(force)) {
7434 return;
7435 }
7436
7437 int32_t metaState = mContext->getGlobalMetaState();
7438 int32_t buttonState = 0;
7439
7440 PointerProperties pointerProperties;
7441 pointerProperties.clear();
7442 pointerProperties.id = 0;
7443 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7444
7445 PointerCoords pointerCoords;
7446 pointerCoords.clear();
7447
7448 size_t numAxes = mAxes.size();
7449 for (size_t i = 0; i < numAxes; i++) {
7450 const Axis& axis = mAxes.valueAt(i);
7451 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7452 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7453 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7454 axis.highCurrentValue);
7455 }
7456 }
7457
7458 // Moving a joystick axis should not wake the device because joysticks can
7459 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7460 // button will likely wake the device.
7461 // TODO: Use the input device configuration to control this behavior more finely.
7462 uint32_t policyFlags = 0;
7463
7464 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7465 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
7466 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, MotionClassification::NONE,
7467 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
7468 &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {});
7469 getListener()->notifyMotion(&args);
7470 }
7471
setPointerCoordsAxisValue(PointerCoords * pointerCoords,int32_t axis,float value)7472 void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7473 int32_t axis, float value) {
7474 pointerCoords->setAxisValue(axis, value);
7475 /* In order to ease the transition for developers from using the old axes
7476 * to the newer, more semantically correct axes, we'll continue to produce
7477 * values for the old axes as mirrors of the value of their corresponding
7478 * new axes. */
7479 int32_t compatAxis = getCompatAxis(axis);
7480 if (compatAxis >= 0) {
7481 pointerCoords->setAxisValue(compatAxis, value);
7482 }
7483 }
7484
filterAxes(bool force)7485 bool JoystickInputMapper::filterAxes(bool force) {
7486 bool atLeastOneSignificantChange = force;
7487 size_t numAxes = mAxes.size();
7488 for (size_t i = 0; i < numAxes; i++) {
7489 Axis& axis = mAxes.editValueAt(i);
7490 if (force || hasValueChangedSignificantly(axis.filter,
7491 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7492 axis.currentValue = axis.newValue;
7493 atLeastOneSignificantChange = true;
7494 }
7495 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7496 if (force || hasValueChangedSignificantly(axis.filter,
7497 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7498 axis.highCurrentValue = axis.highNewValue;
7499 atLeastOneSignificantChange = true;
7500 }
7501 }
7502 }
7503 return atLeastOneSignificantChange;
7504 }
7505
hasValueChangedSignificantly(float filter,float newValue,float currentValue,float min,float max)7506 bool JoystickInputMapper::hasValueChangedSignificantly(
7507 float filter, float newValue, float currentValue, float min, float max) {
7508 if (newValue != currentValue) {
7509 // Filter out small changes in value unless the value is converging on the axis
7510 // bounds or center point. This is intended to reduce the amount of information
7511 // sent to applications by particularly noisy joysticks (such as PS3).
7512 if (fabs(newValue - currentValue) > filter
7513 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7514 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7515 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7516 return true;
7517 }
7518 }
7519 return false;
7520 }
7521
hasMovedNearerToValueWithinFilteredRange(float filter,float newValue,float currentValue,float thresholdValue)7522 bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7523 float filter, float newValue, float currentValue, float thresholdValue) {
7524 float newDistance = fabs(newValue - thresholdValue);
7525 if (newDistance < filter) {
7526 float oldDistance = fabs(currentValue - thresholdValue);
7527 if (newDistance < oldDistance) {
7528 return true;
7529 }
7530 }
7531 return false;
7532 }
7533
7534 } // namespace android
7535