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