PageRenderTime 138ms CodeModel.GetById 12ms app.highlight 105ms RepoModel.GetById 2ms app.codeStats 2ms

/services/input/InputReader.cpp

https://github.com/aizuzi/platform_frameworks_base
C++ | 6530 lines | 5241 code | 841 blank | 448 comment | 1189 complexity | 19fa9db18105ec4a4b7b381c61b853b7 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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 <input/Keyboard.h>
  46#include <input/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
  61namespace android {
  62
  63// --- Constants ---
  64
  65// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
  66static const size_t MAX_SLOTS = 32;
  67
  68// --- Static Functions ---
  69
  70template<typename T>
  71inline static T abs(const T& value) {
  72    return value < 0 ? - value : value;
  73}
  74
  75template<typename T>
  76inline static T min(const T& a, const T& b) {
  77    return a < b ? a : b;
  78}
  79
  80template<typename T>
  81inline static void swap(T& a, T& b) {
  82    T temp = a;
  83    a = b;
  84    b = temp;
  85}
  86
  87inline static float avg(float x, float y) {
  88    return (x + y) / 2;
  89}
  90
  91inline static float distance(float x1, float y1, float x2, float y2) {
  92    return hypotf(x1 - x2, y1 - y2);
  93}
  94
  95inline static int32_t signExtendNybble(int32_t value) {
  96    return value >= 8 ? value - 16 : value;
  97}
  98
  99static inline const char* toString(bool value) {
 100    return value ? "true" : "false";
 101}
 102
 103static 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
 115static 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};
 123static const size_t keyCodeRotationMapSize =
 124        sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
 125
 126static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
 127    return rotateValueUsingRotationMap(keyCode, orientation,
 128            keyCodeRotationMap, keyCodeRotationMapSize);
 129}
 130
 131static 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
 153static 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.
 159static bool isPointerDown(int32_t buttonState) {
 160    return buttonState &
 161            (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
 162                    | AMOTION_EVENT_BUTTON_TERTIARY);
 163}
 164
 165static 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
 175static 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
 192static 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
 206bool InputReaderConfiguration::getDisplayInfo(bool external, DisplayViewport* outViewport) const {
 207    const DisplayViewport& viewport = external ? mExternalDisplay : mInternalDisplay;
 208    if (viewport.displayId >= 0) {
 209        *outViewport = viewport;
 210        return true;
 211    }
 212    return false;
 213}
 214
 215void InputReaderConfiguration::setDisplayInfo(bool external, const DisplayViewport& viewport) {
 216    DisplayViewport& v = external ? mExternalDisplay : mInternalDisplay;
 217    v = viewport;
 218}
 219
 220
 221// --- InputReader ---
 222
 223InputReader::InputReader(const sp<EventHubInterface>& eventHub,
 224        const sp<InputReaderPolicyInterface>& policy,
 225        const sp<InputListenerInterface>& listener) :
 226        mContext(this), mEventHub(eventHub), mPolicy(policy),
 227        mGlobalMetaState(0), mGeneration(1),
 228        mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
 229        mConfigurationChangesToRefresh(0) {
 230    mQueuedListener = new QueuedInputListener(listener);
 231
 232    { // acquire lock
 233        AutoMutex _l(mLock);
 234
 235        refreshConfigurationLocked(0);
 236        updateGlobalMetaStateLocked();
 237    } // release lock
 238}
 239
 240InputReader::~InputReader() {
 241    for (size_t i = 0; i < mDevices.size(); i++) {
 242        delete mDevices.valueAt(i);
 243    }
 244}
 245
 246void InputReader::loopOnce() {
 247    int32_t oldGeneration;
 248    int32_t timeoutMillis;
 249    bool inputDevicesChanged = false;
 250    Vector<InputDeviceInfo> inputDevices;
 251    { // acquire lock
 252        AutoMutex _l(mLock);
 253
 254        oldGeneration = mGeneration;
 255        timeoutMillis = -1;
 256
 257        uint32_t changes = mConfigurationChangesToRefresh;
 258        if (changes) {
 259            mConfigurationChangesToRefresh = 0;
 260            timeoutMillis = 0;
 261            refreshConfigurationLocked(changes);
 262        } else if (mNextTimeout != LLONG_MAX) {
 263            nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
 264            timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
 265        }
 266    } // release lock
 267
 268    size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
 269
 270    { // acquire lock
 271        AutoMutex _l(mLock);
 272        mReaderIsAliveCondition.broadcast();
 273
 274        if (count) {
 275            processEventsLocked(mEventBuffer, count);
 276        }
 277
 278        if (mNextTimeout != LLONG_MAX) {
 279            nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
 280            if (now >= mNextTimeout) {
 281#if DEBUG_RAW_EVENTS
 282                ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
 283#endif
 284                mNextTimeout = LLONG_MAX;
 285                timeoutExpiredLocked(now);
 286            }
 287        }
 288
 289        if (oldGeneration != mGeneration) {
 290            inputDevicesChanged = true;
 291            getInputDevicesLocked(inputDevices);
 292        }
 293    } // release lock
 294
 295    // Send out a message that the describes the changed input devices.
 296    if (inputDevicesChanged) {
 297        mPolicy->notifyInputDevicesChanged(inputDevices);
 298    }
 299
 300    // Flush queued events out to the listener.
 301    // This must happen outside of the lock because the listener could potentially call
 302    // back into the InputReader's methods, such as getScanCodeState, or become blocked
 303    // on another thread similarly waiting to acquire the InputReader lock thereby
 304    // resulting in a deadlock.  This situation is actually quite plausible because the
 305    // listener is actually the input dispatcher, which calls into the window manager,
 306    // which occasionally calls into the input reader.
 307    mQueuedListener->flush();
 308}
 309
 310void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
 311    for (const RawEvent* rawEvent = rawEvents; count;) {
 312        int32_t type = rawEvent->type;
 313        size_t batchSize = 1;
 314        if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
 315            int32_t deviceId = rawEvent->deviceId;
 316            while (batchSize < count) {
 317                if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
 318                        || rawEvent[batchSize].deviceId != deviceId) {
 319                    break;
 320                }
 321                batchSize += 1;
 322            }
 323#if DEBUG_RAW_EVENTS
 324            ALOGD("BatchSize: %d Count: %d", batchSize, count);
 325#endif
 326            processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
 327        } else {
 328            switch (rawEvent->type) {
 329            case EventHubInterface::DEVICE_ADDED:
 330                addDeviceLocked(rawEvent->when, rawEvent->deviceId);
 331                break;
 332            case EventHubInterface::DEVICE_REMOVED:
 333                removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
 334                break;
 335            case EventHubInterface::FINISHED_DEVICE_SCAN:
 336                handleConfigurationChangedLocked(rawEvent->when);
 337                break;
 338            default:
 339                ALOG_ASSERT(false); // can't happen
 340                break;
 341            }
 342        }
 343        count -= batchSize;
 344        rawEvent += batchSize;
 345    }
 346}
 347
 348void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
 349    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
 350    if (deviceIndex >= 0) {
 351        ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
 352        return;
 353    }
 354
 355    InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
 356    uint32_t classes = mEventHub->getDeviceClasses(deviceId);
 357    int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
 358
 359    InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
 360    device->configure(when, &mConfig, 0);
 361    device->reset(when);
 362
 363    if (device->isIgnored()) {
 364        ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
 365                identifier.name.string());
 366    } else {
 367        ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
 368                identifier.name.string(), device->getSources());
 369    }
 370
 371    mDevices.add(deviceId, device);
 372    bumpGenerationLocked();
 373}
 374
 375void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
 376    InputDevice* device = NULL;
 377    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
 378    if (deviceIndex < 0) {
 379        ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
 380        return;
 381    }
 382
 383    device = mDevices.valueAt(deviceIndex);
 384    mDevices.removeItemsAt(deviceIndex, 1);
 385    bumpGenerationLocked();
 386
 387    if (device->isIgnored()) {
 388        ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
 389                device->getId(), device->getName().string());
 390    } else {
 391        ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
 392                device->getId(), device->getName().string(), device->getSources());
 393    }
 394
 395    device->reset(when);
 396    delete device;
 397}
 398
 399InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
 400        const InputDeviceIdentifier& identifier, uint32_t classes) {
 401    InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
 402            controllerNumber, identifier, classes);
 403
 404    // External devices.
 405    if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
 406        device->setExternal(true);
 407    }
 408
 409    // Switch-like devices.
 410    if (classes & INPUT_DEVICE_CLASS_SWITCH) {
 411        device->addMapper(new SwitchInputMapper(device));
 412    }
 413
 414    // Vibrator-like devices.
 415    if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
 416        device->addMapper(new VibratorInputMapper(device));
 417    }
 418
 419    // Keyboard-like devices.
 420    uint32_t keyboardSource = 0;
 421    int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
 422    if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
 423        keyboardSource |= AINPUT_SOURCE_KEYBOARD;
 424    }
 425    if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
 426        keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
 427    }
 428    if (classes & INPUT_DEVICE_CLASS_DPAD) {
 429        keyboardSource |= AINPUT_SOURCE_DPAD;
 430    }
 431    if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
 432        keyboardSource |= AINPUT_SOURCE_GAMEPAD;
 433    }
 434
 435    if (keyboardSource != 0) {
 436        device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
 437    }
 438
 439    // Cursor-like devices.
 440    if (classes & INPUT_DEVICE_CLASS_CURSOR) {
 441        device->addMapper(new CursorInputMapper(device));
 442    }
 443
 444    // Touchscreens and touchpad devices.
 445    if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
 446        device->addMapper(new MultiTouchInputMapper(device));
 447    } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
 448        device->addMapper(new SingleTouchInputMapper(device));
 449    }
 450
 451    // Joystick-like devices.
 452    if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
 453        device->addMapper(new JoystickInputMapper(device));
 454    }
 455
 456    return device;
 457}
 458
 459void InputReader::processEventsForDeviceLocked(int32_t deviceId,
 460        const RawEvent* rawEvents, size_t count) {
 461    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
 462    if (deviceIndex < 0) {
 463        ALOGW("Discarding event for unknown deviceId %d.", deviceId);
 464        return;
 465    }
 466
 467    InputDevice* device = mDevices.valueAt(deviceIndex);
 468    if (device->isIgnored()) {
 469        //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
 470        return;
 471    }
 472
 473    device->process(rawEvents, count);
 474}
 475
 476void InputReader::timeoutExpiredLocked(nsecs_t when) {
 477    for (size_t i = 0; i < mDevices.size(); i++) {
 478        InputDevice* device = mDevices.valueAt(i);
 479        if (!device->isIgnored()) {
 480            device->timeoutExpired(when);
 481        }
 482    }
 483}
 484
 485void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
 486    // Reset global meta state because it depends on the list of all configured devices.
 487    updateGlobalMetaStateLocked();
 488
 489    // Enqueue configuration changed.
 490    NotifyConfigurationChangedArgs args(when);
 491    mQueuedListener->notifyConfigurationChanged(&args);
 492}
 493
 494void InputReader::refreshConfigurationLocked(uint32_t changes) {
 495    mPolicy->getReaderConfiguration(&mConfig);
 496    mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
 497
 498    if (changes) {
 499        ALOGI("Reconfiguring input devices.  changes=0x%08x", changes);
 500        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
 501
 502        if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
 503            mEventHub->requestReopenDevices();
 504        } else {
 505            for (size_t i = 0; i < mDevices.size(); i++) {
 506                InputDevice* device = mDevices.valueAt(i);
 507                device->configure(now, &mConfig, changes);
 508            }
 509        }
 510    }
 511}
 512
 513void InputReader::updateGlobalMetaStateLocked() {
 514    mGlobalMetaState = 0;
 515
 516    for (size_t i = 0; i < mDevices.size(); i++) {
 517        InputDevice* device = mDevices.valueAt(i);
 518        mGlobalMetaState |= device->getMetaState();
 519    }
 520}
 521
 522int32_t InputReader::getGlobalMetaStateLocked() {
 523    return mGlobalMetaState;
 524}
 525
 526void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
 527    mDisableVirtualKeysTimeout = time;
 528}
 529
 530bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
 531        InputDevice* device, int32_t keyCode, int32_t scanCode) {
 532    if (now < mDisableVirtualKeysTimeout) {
 533        ALOGI("Dropping virtual key from device %s because virtual keys are "
 534                "temporarily disabled for the next %0.3fms.  keyCode=%d, scanCode=%d",
 535                device->getName().string(),
 536                (mDisableVirtualKeysTimeout - now) * 0.000001,
 537                keyCode, scanCode);
 538        return true;
 539    } else {
 540        return false;
 541    }
 542}
 543
 544void InputReader::fadePointerLocked() {
 545    for (size_t i = 0; i < mDevices.size(); i++) {
 546        InputDevice* device = mDevices.valueAt(i);
 547        device->fadePointer();
 548    }
 549}
 550
 551void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
 552    if (when < mNextTimeout) {
 553        mNextTimeout = when;
 554        mEventHub->wake();
 555    }
 556}
 557
 558int32_t InputReader::bumpGenerationLocked() {
 559    return ++mGeneration;
 560}
 561
 562void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
 563    AutoMutex _l(mLock);
 564    getInputDevicesLocked(outInputDevices);
 565}
 566
 567void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
 568    outInputDevices.clear();
 569
 570    size_t numDevices = mDevices.size();
 571    for (size_t i = 0; i < numDevices; i++) {
 572        InputDevice* device = mDevices.valueAt(i);
 573        if (!device->isIgnored()) {
 574            outInputDevices.push();
 575            device->getDeviceInfo(&outInputDevices.editTop());
 576        }
 577    }
 578}
 579
 580int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
 581        int32_t keyCode) {
 582    AutoMutex _l(mLock);
 583
 584    return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
 585}
 586
 587int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
 588        int32_t scanCode) {
 589    AutoMutex _l(mLock);
 590
 591    return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
 592}
 593
 594int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
 595    AutoMutex _l(mLock);
 596
 597    return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
 598}
 599
 600int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
 601        GetStateFunc getStateFunc) {
 602    int32_t result = AKEY_STATE_UNKNOWN;
 603    if (deviceId >= 0) {
 604        ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
 605        if (deviceIndex >= 0) {
 606            InputDevice* device = mDevices.valueAt(deviceIndex);
 607            if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
 608                result = (device->*getStateFunc)(sourceMask, code);
 609            }
 610        }
 611    } else {
 612        size_t numDevices = mDevices.size();
 613        for (size_t i = 0; i < numDevices; i++) {
 614            InputDevice* device = mDevices.valueAt(i);
 615            if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
 616                // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
 617                // value.  Otherwise, return AKEY_STATE_UP as long as one device reports it.
 618                int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
 619                if (currentResult >= AKEY_STATE_DOWN) {
 620                    return currentResult;
 621                } else if (currentResult == AKEY_STATE_UP) {
 622                    result = currentResult;
 623                }
 624            }
 625        }
 626    }
 627    return result;
 628}
 629
 630bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
 631        size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
 632    AutoMutex _l(mLock);
 633
 634    memset(outFlags, 0, numCodes);
 635    return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
 636}
 637
 638bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
 639        size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
 640    bool result = false;
 641    if (deviceId >= 0) {
 642        ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
 643        if (deviceIndex >= 0) {
 644            InputDevice* device = mDevices.valueAt(deviceIndex);
 645            if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
 646                result = device->markSupportedKeyCodes(sourceMask,
 647                        numCodes, keyCodes, outFlags);
 648            }
 649        }
 650    } else {
 651        size_t numDevices = mDevices.size();
 652        for (size_t i = 0; i < numDevices; i++) {
 653            InputDevice* device = mDevices.valueAt(i);
 654            if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
 655                result |= device->markSupportedKeyCodes(sourceMask,
 656                        numCodes, keyCodes, outFlags);
 657            }
 658        }
 659    }
 660    return result;
 661}
 662
 663void InputReader::requestRefreshConfiguration(uint32_t changes) {
 664    AutoMutex _l(mLock);
 665
 666    if (changes) {
 667        bool needWake = !mConfigurationChangesToRefresh;
 668        mConfigurationChangesToRefresh |= changes;
 669
 670        if (needWake) {
 671            mEventHub->wake();
 672        }
 673    }
 674}
 675
 676void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
 677        ssize_t repeat, int32_t token) {
 678    AutoMutex _l(mLock);
 679
 680    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
 681    if (deviceIndex >= 0) {
 682        InputDevice* device = mDevices.valueAt(deviceIndex);
 683        device->vibrate(pattern, patternSize, repeat, token);
 684    }
 685}
 686
 687void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
 688    AutoMutex _l(mLock);
 689
 690    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
 691    if (deviceIndex >= 0) {
 692        InputDevice* device = mDevices.valueAt(deviceIndex);
 693        device->cancelVibrate(token);
 694    }
 695}
 696
 697void InputReader::dump(String8& dump) {
 698    AutoMutex _l(mLock);
 699
 700    mEventHub->dump(dump);
 701    dump.append("\n");
 702
 703    dump.append("Input Reader State:\n");
 704
 705    for (size_t i = 0; i < mDevices.size(); i++) {
 706        mDevices.valueAt(i)->dump(dump);
 707    }
 708
 709    dump.append(INDENT "Configuration:\n");
 710    dump.append(INDENT2 "ExcludedDeviceNames: [");
 711    for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
 712        if (i != 0) {
 713            dump.append(", ");
 714        }
 715        dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
 716    }
 717    dump.append("]\n");
 718    dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
 719            mConfig.virtualKeyQuietTime * 0.000001f);
 720
 721    dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
 722            "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
 723            mConfig.pointerVelocityControlParameters.scale,
 724            mConfig.pointerVelocityControlParameters.lowThreshold,
 725            mConfig.pointerVelocityControlParameters.highThreshold,
 726            mConfig.pointerVelocityControlParameters.acceleration);
 727
 728    dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
 729            "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
 730            mConfig.wheelVelocityControlParameters.scale,
 731            mConfig.wheelVelocityControlParameters.lowThreshold,
 732            mConfig.wheelVelocityControlParameters.highThreshold,
 733            mConfig.wheelVelocityControlParameters.acceleration);
 734
 735    dump.appendFormat(INDENT2 "PointerGesture:\n");
 736    dump.appendFormat(INDENT3 "Enabled: %s\n",
 737            toString(mConfig.pointerGesturesEnabled));
 738    dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
 739            mConfig.pointerGestureQuietInterval * 0.000001f);
 740    dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
 741            mConfig.pointerGestureDragMinSwitchSpeed);
 742    dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
 743            mConfig.pointerGestureTapInterval * 0.000001f);
 744    dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
 745            mConfig.pointerGestureTapDragInterval * 0.000001f);
 746    dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
 747            mConfig.pointerGestureTapSlop);
 748    dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
 749            mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
 750    dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
 751            mConfig.pointerGestureMultitouchMinDistance);
 752    dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
 753            mConfig.pointerGestureSwipeTransitionAngleCosine);
 754    dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
 755            mConfig.pointerGestureSwipeMaxWidthRatio);
 756    dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
 757            mConfig.pointerGestureMovementSpeedRatio);
 758    dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
 759            mConfig.pointerGestureZoomSpeedRatio);
 760}
 761
 762void InputReader::monitor() {
 763    // Acquire and release the lock to ensure that the reader has not deadlocked.
 764    mLock.lock();
 765    mEventHub->wake();
 766    mReaderIsAliveCondition.wait(mLock);
 767    mLock.unlock();
 768
 769    // Check the EventHub
 770    mEventHub->monitor();
 771}
 772
 773
 774// --- InputReader::ContextImpl ---
 775
 776InputReader::ContextImpl::ContextImpl(InputReader* reader) :
 777        mReader(reader) {
 778}
 779
 780void InputReader::ContextImpl::updateGlobalMetaState() {
 781    // lock is already held by the input loop
 782    mReader->updateGlobalMetaStateLocked();
 783}
 784
 785int32_t InputReader::ContextImpl::getGlobalMetaState() {
 786    // lock is already held by the input loop
 787    return mReader->getGlobalMetaStateLocked();
 788}
 789
 790void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
 791    // lock is already held by the input loop
 792    mReader->disableVirtualKeysUntilLocked(time);
 793}
 794
 795bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
 796        InputDevice* device, int32_t keyCode, int32_t scanCode) {
 797    // lock is already held by the input loop
 798    return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
 799}
 800
 801void InputReader::ContextImpl::fadePointer() {
 802    // lock is already held by the input loop
 803    mReader->fadePointerLocked();
 804}
 805
 806void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
 807    // lock is already held by the input loop
 808    mReader->requestTimeoutAtTimeLocked(when);
 809}
 810
 811int32_t InputReader::ContextImpl::bumpGeneration() {
 812    // lock is already held by the input loop
 813    return mReader->bumpGenerationLocked();
 814}
 815
 816InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
 817    return mReader->mPolicy.get();
 818}
 819
 820InputListenerInterface* InputReader::ContextImpl::getListener() {
 821    return mReader->mQueuedListener.get();
 822}
 823
 824EventHubInterface* InputReader::ContextImpl::getEventHub() {
 825    return mReader->mEventHub.get();
 826}
 827
 828
 829// --- InputReaderThread ---
 830
 831InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
 832        Thread(/*canCallJava*/ true), mReader(reader) {
 833}
 834
 835InputReaderThread::~InputReaderThread() {
 836}
 837
 838bool InputReaderThread::threadLoop() {
 839    mReader->loopOnce();
 840    return true;
 841}
 842
 843
 844// --- InputDevice ---
 845
 846InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
 847        int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
 848        mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
 849        mIdentifier(identifier), mClasses(classes),
 850        mSources(0), mIsExternal(false), mDropUntilNextSync(false) {
 851}
 852
 853InputDevice::~InputDevice() {
 854    size_t numMappers = mMappers.size();
 855    for (size_t i = 0; i < numMappers; i++) {
 856        delete mMappers[i];
 857    }
 858    mMappers.clear();
 859}
 860
 861void InputDevice::dump(String8& dump) {
 862    InputDeviceInfo deviceInfo;
 863    getDeviceInfo(& deviceInfo);
 864
 865    dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
 866            deviceInfo.getDisplayName().string());
 867    dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
 868    dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
 869    dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
 870    dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
 871
 872    const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
 873    if (!ranges.isEmpty()) {
 874        dump.append(INDENT2 "Motion Ranges:\n");
 875        for (size_t i = 0; i < ranges.size(); i++) {
 876            const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
 877            const char* label = getAxisLabel(range.axis);
 878            char name[32];
 879            if (label) {
 880                strncpy(name, label, sizeof(name));
 881                name[sizeof(name) - 1] = '\0';
 882            } else {
 883                snprintf(name, sizeof(name), "%d", range.axis);
 884            }
 885            dump.appendFormat(INDENT3 "%s: source=0x%08x, "
 886                    "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
 887                    name, range.source, range.min, range.max, range.flat, range.fuzz,
 888                    range.resolution);
 889        }
 890    }
 891
 892    size_t numMappers = mMappers.size();
 893    for (size_t i = 0; i < numMappers; i++) {
 894        InputMapper* mapper = mMappers[i];
 895        mapper->dump(dump);
 896    }
 897}
 898
 899void InputDevice::addMapper(InputMapper* mapper) {
 900    mMappers.add(mapper);
 901}
 902
 903void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
 904    mSources = 0;
 905
 906    if (!isIgnored()) {
 907        if (!changes) { // first time only
 908            mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
 909        }
 910
 911        if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
 912            if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
 913                sp<KeyCharacterMap> keyboardLayout =
 914                        mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier.descriptor);
 915                if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
 916                    bumpGeneration();
 917                }
 918            }
 919        }
 920
 921        if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
 922            if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
 923                String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
 924                if (mAlias != alias) {
 925                    mAlias = alias;
 926                    bumpGeneration();
 927                }
 928            }
 929        }
 930
 931        size_t numMappers = mMappers.size();
 932        for (size_t i = 0; i < numMappers; i++) {
 933            InputMapper* mapper = mMappers[i];
 934            mapper->configure(when, config, changes);
 935            mSources |= mapper->getSources();
 936        }
 937    }
 938}
 939
 940void InputDevice::reset(nsecs_t when) {
 941    size_t numMappers = mMappers.size();
 942    for (size_t i = 0; i < numMappers; i++) {
 943        InputMapper* mapper = mMappers[i];
 944        mapper->reset(when);
 945    }
 946
 947    mContext->updateGlobalMetaState();
 948
 949    notifyReset(when);
 950}
 951
 952void InputDevice::process(const RawEvent* rawEvents, size_t count) {
 953    // Process all of the events in order for each mapper.
 954    // We cannot simply ask each mapper to process them in bulk because mappers may
 955    // have side-effects that must be interleaved.  For example, joystick movement events and
 956    // gamepad button presses are handled by different mappers but they should be dispatched
 957    // in the order received.
 958    size_t numMappers = mMappers.size();
 959    for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
 960#if DEBUG_RAW_EVENTS
 961        ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
 962                rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
 963                rawEvent->when);
 964#endif
 965
 966        if (mDropUntilNextSync) {
 967            if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
 968                mDropUntilNextSync = false;
 969#if DEBUG_RAW_EVENTS
 970                ALOGD("Recovered from input event buffer overrun.");
 971#endif
 972            } else {
 973#if DEBUG_RAW_EVENTS
 974                ALOGD("Dropped input event while waiting for next input sync.");
 975#endif
 976            }
 977        } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
 978            ALOGI("Detected input event buffer overrun for device %s.", getName().string());
 979            mDropUntilNextSync = true;
 980            reset(rawEvent->when);
 981        } else {
 982            for (size_t i = 0; i < numMappers; i++) {
 983                InputMapper* mapper = mMappers[i];
 984                mapper->process(rawEvent);
 985            }
 986        }
 987    }
 988}
 989
 990void InputDevice::timeoutExpired(nsecs_t when) {
 991    size_t numMappers = mMappers.size();
 992    for (size_t i = 0; i < numMappers; i++) {
 993        InputMapper* mapper = mMappers[i];
 994        mapper->timeoutExpired(when);
 995    }
 996}
 997
 998void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
 999    outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
1000            mIsExternal);
1001
1002    size_t numMappers = mMappers.size();
1003    for (size_t i = 0; i < numMappers; i++) {
1004        InputMapper* mapper = mMappers[i];
1005        mapper->populateDeviceInfo(outDeviceInfo);
1006    }
1007}
1008
1009int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1010    return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1011}
1012
1013int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1014    return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1015}
1016
1017int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1018    return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1019}
1020
1021int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1022    int32_t result = AKEY_STATE_UNKNOWN;
1023    size_t numMappers = mMappers.size();
1024    for (size_t i = 0; i < numMappers; i++) {
1025        InputMapper* mapper = mMappers[i];
1026        if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1027            // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1028            // value.  Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1029            int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1030            if (currentResult >= AKEY_STATE_DOWN) {
1031                return currentResult;
1032            } else if (currentResult == AKEY_STATE_UP) {
1033                result = currentResult;
1034            }
1035        }
1036    }
1037    return result;
1038}
1039
1040bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1041        const int32_t* keyCodes, uint8_t* outFlags) {
1042    bool result = false;
1043    size_t numMappers = mMappers.size();
1044    for (size_t i = 0; i < numMappers; i++) {
1045        InputMapper* mapper = mMappers[i];
1046        if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1047            result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1048        }
1049    }
1050    return result;
1051}
1052
1053void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1054        int32_t token) {
1055    size_t numMappers = mMappers.size();
1056    for (size_t i = 0; i < numMappers; i++) {
1057        InputMapper* mapper = mMappers[i];
1058        mapper->vibrate(pattern, patternSize, repeat, token);
1059    }
1060}
1061
1062void InputDevice::cancelVibrate(int32_t token) {
1063    size_t numMappers = mMappers.size();
1064    for (size_t i = 0; i < numMappers; i++) {
1065        InputMapper* mapper = mMappers[i];
1066        mapper->cancelVibrate(token);
1067    }
1068}
1069
1070int32_t InputDevice::getMetaState() {
1071    int32_t result = 0;
1072    size_t numMappers = mMappers.size();
1073    for (size_t i = 0; i < numMappers; i++) {
1074        InputMapper* mapper = mMappers[i];
1075        result |= mapper->getMetaState();
1076    }
1077    return result;
1078}
1079
1080void InputDevice::fadePointer() {
1081    size_t numMappers = mMappers.size();
1082    for (size_t i = 0; i < numMappers; i++) {
1083        InputMapper* mapper = mMappers[i];
1084        mapper->fadePointer();
1085    }
1086}
1087
1088void InputDevice::bumpGeneration() {
1089    mGeneration = mContext->bumpGeneration();
1090}
1091
1092void InputDevice::notifyReset(nsecs_t when) {
1093    NotifyDeviceResetArgs args(when, mId);
1094    mContext->getListener()->notifyDeviceReset(&args);
1095}
1096
1097
1098// --- CursorButtonAccumulator ---
1099
1100CursorButtonAccumulator::CursorButtonAccumulator() {
1101    clearButtons();
1102}
1103
1104void CursorButtonAccumulator::reset(InputDevice* device) {
1105    mBtnLeft = device->isKeyPressed(BTN_LEFT);
1106    mBtnRight = device->isKeyPressed(BTN_RIGHT);
1107    mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1108    mBtnBack = device->isKeyPressed(BTN_BACK);
1109    mBtnSide = device->isKeyPressed(BTN_SIDE);
1110    mBtnForward = device->isKeyPressed(BTN_FORWARD);
1111    mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1112    mBtnTask = device->isKeyPressed(BTN_TASK);
1113}
1114
1115void CursorButtonAccumulator::clearButtons() {
1116    mBtnLeft = 0;
1117    mBtnRight = 0;
1118    mBtnMiddle = 0;
1119    mBtnBack = 0;
1120    mBtnSide = 0;
1121    mBtnForward = 0;
1122    mBtnExtra = 0;
1123    mBtnTask = 0;
1124}
1125
1126void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1127    if (rawEvent->type == EV_KEY) {
1128        switch (rawEvent->code) {
1129        case BTN_LEFT:
1130            mBtnLeft = rawEvent->value;
1131            break;
1132        case BTN_RIGHT:
1133            mBtnRight = rawEvent->value;
1134            break;
1135        case BTN_MIDDLE:
1136            mBtnMiddle = rawEvent->value;
1137            break;
1138        case BTN_BACK:
1139            mBtnBack = rawEvent->value;
1140            break;
1141        case BTN_SIDE:
1142            mBtnSide = rawEvent->value;
1143            break;
1144        case BTN_FORWARD:
1145            mBtnForward = rawEvent->value;
1146            break;
1147        case BTN_EXTRA:
1148            mBtnExtra = rawEvent->value;
1149            break;
1150        case BTN_TASK:
1151            mBtnTask = rawEvent->value;
1152            break;
1153        }
1154    }
1155}
1156
1157uint32_t CursorButtonAccumulator::getButtonState() const {
1158    uint32_t result = 0;
1159    if (mBtnLeft) {
1160        result |= AMOTION_EVENT_BUTTON_PRIMARY;
1161    }
1162    if (mBtnRight) {
1163        result |= AMOTION_EVENT_BUTTON_SECONDARY;
1164    }
1165    if (mBtnMiddle) {
1166        result |= AMOTION_EVENT_BUTTON_TERTIARY;
1167    }
1168    if (mBtnBack || mBtnSide) {
1169        result |= AMOTION_EVENT_BUTTON_BACK;
1170    }
1171    if (mBtnForward || mBtnExtra) {
1172        result |= AMOTION_EVENT_BUTTON_FORWARD;
1173    }
1174    return result;
1175}
1176
1177
1178// --- CursorMotionAccumulator ---
1179
1180CursorMotionAccumulator::CursorMotionAccumulator() {
1181    clearRelativeAxes();
1182}
1183
1184void CursorMotionAccumulator::reset(InputDevice* device) {
1185    clearRelativeAxes();
1186}
1187
1188void CursorMotionAccumulator::clearRelativeAxes() {
1189    mRelX = 0;
1190    mRelY = 0;
1191}
1192
1193void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1194    if (rawEvent->type == EV_REL) {
1195        switch (rawEvent->code) {
1196        case REL_X:
1197            mRelX = rawEvent->value;
1198            break;
1199        case REL_Y:
1200            mRelY = rawEvent->value;
1201            break;
1202        }
1203    }
1204}
1205
1206void CursorMotionAccumulator::finishSync() {
1207    clearRelativeAxes();
1208}
1209
1210
1211// --- CursorScrollAccumulator ---
1212
1213CursorScrollAccumulator::CursorScrollAccumulator() :
1214        mHaveRelWheel(false), mHaveRelHWheel(false) {
1215    clearRelativeAxes();
1216}
1217
1218void CursorScrollAccumulator::configure(InputDevice* device) {
1219    mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1220    mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1221}
1222
1223void CursorScrollAccumulator::reset(InputDevice* device) {
1224    clearRelativeAxes();
1225}
1226
1227void CursorScrollAccumulator::clearRelativeAxes() {
1228    mRelWheel = 0;
1229    mRelHWheel = 0;
1230}
1231
1232void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1233    if (rawEvent->type == EV_REL) {
1234        switch (rawEvent->code) {
1235        case REL_WHEEL:
1236            mRelWheel = rawEvent->value;
1237            break;
1238        case REL_HWHEEL:
1239            mRelHWheel = rawEvent->value;
1240            break;
1241        }
1242    }
1243}
1244
1245void CursorScrollAccumulator::finishSync() {
1246    clearRelativeAxes();
1247}
1248
1249
1250// --- TouchButtonAccumulator ---
1251
1252TouchButtonAccumulator::TouchButtonAccumulator() :
1253        mHaveBtnTouch(false), mHaveStylus(false) {
1254    clearButtons();
1255}
1256
1257void TouchButtonAccumulator::configure(InputDevice* device) {
1258    mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1259    mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1260            || device->hasKey(BTN_TOOL_RUBBER)
1261            || device->hasKey(BTN_TOOL_BRUSH)
1262            || device->hasKey(BTN_TOOL_PENCIL)
1263            || device->hasKey(BTN_TOOL_AIRBRUSH);
1264}
1265
1266void TouchButtonAccumulator::reset(InputDevice* device) {
1267    mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1268    mBtnStylus = device->isKeyPressed(BTN_STYLUS);
1269    mBtnStylus2 = device->isKeyPressed(BTN_STYLUS);
1270    mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1271    mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1272    mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1273    mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1274    mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1275    mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1276    mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1277    mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1278    mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1279    mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1280    mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1281}
1282
1283void TouchButtonAccumulator::clearButtons() {
1284    mBtnTouch = 0;
1285    mBtnStylus = 0;
1286    mBtnStylus2 = 0;
1287    mBtnToolFinger = 0;
1288    mBtnToolPen = 0;
1289    mBtnToolRubber = 0;
1290    mBtnToolBrush = 0;
1291    mBtnToolPencil = 0;
1292    mBtnToolAirbrush = 0;
1293    mBtnToolMouse = 0;
1294    mBtnToolLens = 0;
1295    mBtnToolDoubleTap = 0;
1296    mBtnToolTripleTap = 0;
1297    mBtnToolQuadTap = 0;
1298}
1299
1300void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1301    if (rawEvent->type == EV_KEY) {
1302        switch (rawEvent->code) {
1303        case BTN_TOUCH:
1304            mBtnTouch = rawEvent->value;
1305            break;
1306        case BTN_STYLUS:
1307            mBtnStylus = rawEvent->value;
1308            break;
1309        case BTN_STYLUS2:
1310            mBtnStylus2 = rawEvent->value;
1311            break;
1312        case BTN_TOOL_FINGER:
1313            mBtnToolFinger = rawEvent->value;
1314            break;
1315        case BTN_TOOL_PEN:
1316            mBtnToolPen = rawEvent->value;
1317            break;
1318        case BTN_TOOL_RUBBER:
1319            mBtnToolRubber = rawEvent->value;
1320            break;
1321        case BTN_TOOL_BRUSH:
1322            mBtnToolBrush = rawEvent->value;
1323            break;
1324        case BTN_TOOL_PENCIL:
1325            mBtnToolPencil = rawEvent->value;
1326            break;
1327        case BTN_TOOL_AIRBRUSH:
1328            mBtnToolAirbrush = rawEvent->value;
1329            break;
1330        case BTN_TOOL_MOUSE:
1331            mBtnToolMouse = rawEvent->value;
1332            break;
1333        case BTN_TOOL_LENS:
1334            mBtnToolLens = rawEvent->value;
1335            break;
1336        case BTN_TOOL_DOUBLETAP:
1337            mBtnToolDoubleTap = rawEvent->value;
1338            break;
1339        case BTN_TOOL_TRIPLETAP:
1340            mBtnToolTripleTap = rawEvent->value;
1341            break;
1342        case BTN_TOOL_QUADTAP:
1343            mBtnToolQuadTap = rawEvent->value;
1344            break;
1345        }
1346    }
1347}
1348
1349uint32_t TouchButtonAccumulator::getButtonState() const {
1350    uint32_t result = 0;
1351    if (mBtnStylus) {
1352        result |= AMOTION_EVENT_BUTTON_SECONDARY;
1353    }
1354    if (mBtnStylus2) {
1355        result |= AMOTION_EVENT_BUTTON_TERTIARY;
1356    }
1357    return result;
1358}
1359
1360int32_t TouchButtonAccumulator::getToolType() const {
1361    if (mBtnToolMouse || mBtnToolLens) {
1362        return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1363    }
1364    if (mBtnToolRubber) {
1365        return AMOTION_EVENT_TOOL_TYPE_ERASER;
1366    }
1367    if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1368        return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1369    }
1370    if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1371        return AMOTION_EVENT_TOOL_TYPE_FINGER;
1372    }
1373    return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1374}
1375
1376bool TouchButtonAccumulator::isToolActive() const {
1377    return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1378            || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1379            || mBtnToolMouse || mBtnToolLens
1380            || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1381}
1382
1383bool TouchButtonAccumulator::isHovering() const {
1384    return mHaveBtnTouch && !mBtnTouch;
1385}
1386
1387bool TouchButtonAccumulator::hasStylus() const {
1388    return mHaveStylus;
1389}
1390
1391
1392// --- RawPointerAxes ---
1393
1394RawPointerAxes::RawPointerAxes() {
1395    clear();
1396}
1397
1398void RawPointerAxes::clear() {
1399    x.clear();
1400    y.clear();
1401    pressure.clear();
1402    touchMajor.clear();
1403    touchMinor.clear();
1404    toolMajor.clear();
1405    toolMinor.clear();
1406    orientation.clear();
1407    distance.clear();
1408    tiltX.clear();
1409    tiltY.clear();
1410    trackingId.clear();
1411    slot.clear();
1412}
1413
1414
1415// --- RawPointerData ---
1416
1417RawPointerData::RawPointerData() {
1418    clear();
1419}
1420
1421void RawPointerData::clear() {
1422    pointerCount = 0;
1423    clearIdBits();
1424}
1425
1426void RawPointerData::copyFrom(const RawPointerData& other) {
1427    pointerCount = other.pointerCount;
1428    hoveringIdBits = other.hoveringIdBits;
1429    touchingIdBits = other.touchingIdBits;
1430
1431    for (uint32_t i = 0; i < pointerCount; i++) {
1432        pointers[i] = other.pointers[i];
1433
1434        int id = pointers[i].id;
1435        idToIndex[id] = other.idToIndex[id];
1436    }
1437}
1438
1439void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1440    float x = 0, y = 0;
1441    uint32_t count = touchingIdBits.count();
1442    if (count) {
1443        for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1444            uint32_t id = idBits.clearFirstMarkedBit();
1445            const Pointer& pointer = pointerForId(id);
1446            x += pointer.x;
1447            y += pointer.y;
1448        }
1449        x /= count;
1450        y /= count;
1451    }
1452    *outX = x;
1453    *outY = y;
1454}
1455
1456
1457// --- CookedPointerData ---
1458
1459CookedPointerData::CookedPointerData() {
1460    clear();
1461}
1462
1463void CookedPointerData::clear() {
1464    pointerCount = 0;
1465    hoveringIdBits.clear();
1466    touchingIdBits.clear();
1467}
1468
1469void CookedPointerData::copyFrom(const CookedPointerData& other) {
1470    pointerCount = other.pointerCount;
1471    hoveringIdBits = other.hoveringIdBits;
1472    touchingIdBits = other.touchingIdBits;
1473
1474    for (uint32_t i = 0; i < pointerCount; i++) {
1475        pointerProperties[i].copyFrom(other.pointerProperties[i]);
1476        pointerCoords[i].copyFrom(other.pointerCoords[i]);
1477
1478        int id = pointerProperties[i].id;
1479        idToIndex[id] = other.idToIndex[id];
1480    }
1481}
1482
1483
1484// --- SingleTouchMotionAccumulator ---
1485
1486SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1487    clearAbsoluteAxes();
1488}
1489
1490void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1491    mAbsX = device->getAbsoluteAxisValue(ABS_X);
1492    mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1493    mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1494    mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1495    mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1496    mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1497    mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1498}
1499
1500void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1501    mAbsX = 0;
1502    mAbsY = 0;
1503    mAbsPressure = 0;
1504    mAbsToolWidth = 0;
1505    mAbsDistance = 0;
1506    mAbsTiltX = 0;
1507    mAbsTiltY = 0;
1508}
1509
1510void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1511    if (rawEvent->type == EV_ABS) {
1512        switch (rawEvent->code) {
1513        case ABS_X:
1514            mAbsX = rawEvent->value;
1515            break;
1516        case ABS_Y:
1517            mAbsY = rawEvent->value;
1518            break;
1519        case ABS_PRESSURE:
1520            mAbsPressure = rawEvent->value;
1521            break;
1522        case ABS_TOOL_WIDTH:
1523            mAbsToolWidth = rawEvent->value;
1524            break;
1525        case ABS_DISTANCE:
1526            mAbsDistance = rawEvent->value;
1527            break;
1528        case ABS_TILT_X:
1529            mAbsTiltX = rawEvent->value;
1530            break;
1531        case ABS_TILT_Y:
1532            mAbsTiltY = rawEvent->value;
1533            break;
1534        }
1535    }
1536}
1537
1538
1539// --- MultiTouchMotionAccumulator ---
1540
1541MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1542        mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1543        mHaveStylus(false) {
1544}
1545
1546MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1547    delete[] mSlots;
1548}
1549
1550void MultiTouchMotionAccumulator::configure(InputDevice* device,
1551        size_t slotCount, bool usingSlotsProtocol) {
1552    mSlotCount = slotCount;
1553    mUsingSlotsProtocol = usingSlotsProtocol;
1554    mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1555
1556    delete[] mSlots;
1557    mSlots = ne

Large files files are truncated, but you can click here to view the full file