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