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