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