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