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