InputReader.cpp revision 71b16e81f9cbf2e288611f32c43ea7fb4a331fcf
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::TOUCH_AFFINE_TRANSFORMATION)) {
2756        // Update location calibration to reflect current settings
2757        updateAffineTransformation();
2758    }
2759
2760    if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2761        // Update pointer speed.
2762        mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
2763        mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
2764        mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
2765    }
2766
2767    bool resetNeeded = false;
2768    if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
2769            | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
2770            | InputReaderConfiguration::CHANGE_SHOW_TOUCHES))) {
2771        // Configure device sources, surface dimensions, orientation and
2772        // scaling factors.
2773        configureSurface(when, &resetNeeded);
2774    }
2775
2776    if (changes && resetNeeded) {
2777        // Send reset, unless this is the first time the device has been configured,
2778        // in which case the reader will call reset itself after all mappers are ready.
2779        getDevice()->notifyReset(when);
2780    }
2781}
2782
2783void TouchInputMapper::configureParameters() {
2784    // Use the pointer presentation mode for devices that do not support distinct
2785    // multitouch.  The spot-based presentation relies on being able to accurately
2786    // locate two or more fingers on the touch pad.
2787    mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
2788            ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS;
2789
2790    String8 gestureModeString;
2791    if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
2792            gestureModeString)) {
2793        if (gestureModeString == "pointer") {
2794            mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
2795        } else if (gestureModeString == "spots") {
2796            mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
2797        } else if (gestureModeString != "default") {
2798            ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
2799        }
2800    }
2801
2802    if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
2803        // The device is a touch screen.
2804        mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2805    } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
2806        // The device is a pointing device like a track pad.
2807        mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2808    } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
2809            || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
2810        // The device is a cursor device with a touch pad attached.
2811        // By default don't use the touch pad to move the pointer.
2812        mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
2813    } else {
2814        // The device is a touch pad of unknown purpose.
2815        mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2816    }
2817
2818    mParameters.hasButtonUnderPad=
2819            getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
2820
2821    String8 deviceTypeString;
2822    if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
2823            deviceTypeString)) {
2824        if (deviceTypeString == "touchScreen") {
2825            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2826        } else if (deviceTypeString == "touchPad") {
2827            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
2828        } else if (deviceTypeString == "touchNavigation") {
2829            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
2830        } else if (deviceTypeString == "pointer") {
2831            mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2832        } else if (deviceTypeString != "default") {
2833            ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
2834        }
2835    }
2836
2837    mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2838    getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
2839            mParameters.orientationAware);
2840
2841    mParameters.hasAssociatedDisplay = false;
2842    mParameters.associatedDisplayIsExternal = false;
2843    if (mParameters.orientationAware
2844            || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2845            || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2846        mParameters.hasAssociatedDisplay = true;
2847        mParameters.associatedDisplayIsExternal =
2848                mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2849                        && getDevice()->isExternal();
2850    }
2851
2852    // Initial downs on external touch devices should wake the device.
2853    // Normally we don't do this for internal touch screens to prevent them from waking
2854    // up in your pocket but you can enable it using the input device configuration.
2855    mParameters.wake = getDevice()->isExternal();
2856    getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
2857            mParameters.wake);
2858}
2859
2860void TouchInputMapper::dumpParameters(String8& dump) {
2861    dump.append(INDENT3 "Parameters:\n");
2862
2863    switch (mParameters.gestureMode) {
2864    case Parameters::GESTURE_MODE_POINTER:
2865        dump.append(INDENT4 "GestureMode: pointer\n");
2866        break;
2867    case Parameters::GESTURE_MODE_SPOTS:
2868        dump.append(INDENT4 "GestureMode: spots\n");
2869        break;
2870    default:
2871        assert(false);
2872    }
2873
2874    switch (mParameters.deviceType) {
2875    case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
2876        dump.append(INDENT4 "DeviceType: touchScreen\n");
2877        break;
2878    case Parameters::DEVICE_TYPE_TOUCH_PAD:
2879        dump.append(INDENT4 "DeviceType: touchPad\n");
2880        break;
2881    case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
2882        dump.append(INDENT4 "DeviceType: touchNavigation\n");
2883        break;
2884    case Parameters::DEVICE_TYPE_POINTER:
2885        dump.append(INDENT4 "DeviceType: pointer\n");
2886        break;
2887    default:
2888        ALOG_ASSERT(false);
2889    }
2890
2891    dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
2892            toString(mParameters.hasAssociatedDisplay),
2893            toString(mParameters.associatedDisplayIsExternal));
2894    dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2895            toString(mParameters.orientationAware));
2896}
2897
2898void TouchInputMapper::configureRawPointerAxes() {
2899    mRawPointerAxes.clear();
2900}
2901
2902void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
2903    dump.append(INDENT3 "Raw Touch Axes:\n");
2904    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
2905    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
2906    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
2907    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
2908    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
2909    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
2910    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
2911    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
2912    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
2913    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
2914    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
2915    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
2916    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
2917}
2918
2919void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
2920    int32_t oldDeviceMode = mDeviceMode;
2921
2922    // Determine device mode.
2923    if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
2924            && mConfig.pointerGesturesEnabled) {
2925        mSource = AINPUT_SOURCE_MOUSE;
2926        mDeviceMode = DEVICE_MODE_POINTER;
2927        if (hasStylus()) {
2928            mSource |= AINPUT_SOURCE_STYLUS;
2929        }
2930    } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2931            && mParameters.hasAssociatedDisplay) {
2932        mSource = AINPUT_SOURCE_TOUCHSCREEN;
2933        mDeviceMode = DEVICE_MODE_DIRECT;
2934        if (hasStylus()) {
2935            mSource |= AINPUT_SOURCE_STYLUS;
2936        }
2937    } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
2938        mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
2939        mDeviceMode = DEVICE_MODE_NAVIGATION;
2940    } else {
2941        mSource = AINPUT_SOURCE_TOUCHPAD;
2942        mDeviceMode = DEVICE_MODE_UNSCALED;
2943    }
2944
2945    // Ensure we have valid X and Y axes.
2946    if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
2947        ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis!  "
2948                "The device will be inoperable.", getDeviceName().string());
2949        mDeviceMode = DEVICE_MODE_DISABLED;
2950        return;
2951    }
2952
2953    // Raw width and height in the natural orientation.
2954    int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
2955    int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
2956
2957    // Get associated display dimensions.
2958    DisplayViewport newViewport;
2959    if (mParameters.hasAssociatedDisplay) {
2960        if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
2961            ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
2962                    "display.  The device will be inoperable until the display size "
2963                    "becomes available.",
2964                    getDeviceName().string());
2965            mDeviceMode = DEVICE_MODE_DISABLED;
2966            return;
2967        }
2968    } else {
2969        newViewport.setNonDisplayViewport(rawWidth, rawHeight);
2970    }
2971    bool viewportChanged = mViewport != newViewport;
2972    if (viewportChanged) {
2973        mViewport = newViewport;
2974
2975        if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
2976            // Convert rotated viewport to natural surface coordinates.
2977            int32_t naturalLogicalWidth, naturalLogicalHeight;
2978            int32_t naturalPhysicalWidth, naturalPhysicalHeight;
2979            int32_t naturalPhysicalLeft, naturalPhysicalTop;
2980            int32_t naturalDeviceWidth, naturalDeviceHeight;
2981            switch (mViewport.orientation) {
2982            case DISPLAY_ORIENTATION_90:
2983                naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
2984                naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
2985                naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
2986                naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
2987                naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
2988                naturalPhysicalTop = mViewport.physicalLeft;
2989                naturalDeviceWidth = mViewport.deviceHeight;
2990                naturalDeviceHeight = mViewport.deviceWidth;
2991                break;
2992            case DISPLAY_ORIENTATION_180:
2993                naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
2994                naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
2995                naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
2996                naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
2997                naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
2998                naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
2999                naturalDeviceWidth = mViewport.deviceWidth;
3000                naturalDeviceHeight = mViewport.deviceHeight;
3001                break;
3002            case DISPLAY_ORIENTATION_270:
3003                naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3004                naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3005                naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3006                naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3007                naturalPhysicalLeft = mViewport.physicalTop;
3008                naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3009                naturalDeviceWidth = mViewport.deviceHeight;
3010                naturalDeviceHeight = mViewport.deviceWidth;
3011                break;
3012            case DISPLAY_ORIENTATION_0:
3013            default:
3014                naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3015                naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3016                naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3017                naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3018                naturalPhysicalLeft = mViewport.physicalLeft;
3019                naturalPhysicalTop = mViewport.physicalTop;
3020                naturalDeviceWidth = mViewport.deviceWidth;
3021                naturalDeviceHeight = mViewport.deviceHeight;
3022                break;
3023            }
3024
3025            mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3026            mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3027            mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3028            mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3029
3030            mSurfaceOrientation = mParameters.orientationAware ?
3031                    mViewport.orientation : DISPLAY_ORIENTATION_0;
3032        } else {
3033            mSurfaceWidth = rawWidth;
3034            mSurfaceHeight = rawHeight;
3035            mSurfaceLeft = 0;
3036            mSurfaceTop = 0;
3037            mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3038        }
3039    }
3040
3041    // If moving between pointer modes, need to reset some state.
3042    bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3043    if (deviceModeChanged) {
3044        mOrientedRanges.clear();
3045    }
3046
3047    // Create pointer controller if needed.
3048    if (mDeviceMode == DEVICE_MODE_POINTER ||
3049            (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3050        if (mPointerController == NULL) {
3051            mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3052        }
3053    } else {
3054        mPointerController.clear();
3055    }
3056
3057    if (viewportChanged || deviceModeChanged) {
3058        ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3059                "display id %d",
3060                getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3061                mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3062
3063        // Configure X and Y factors.
3064        mXScale = float(mSurfaceWidth) / rawWidth;
3065        mYScale = float(mSurfaceHeight) / rawHeight;
3066        mXTranslate = -mSurfaceLeft;
3067        mYTranslate = -mSurfaceTop;
3068        mXPrecision = 1.0f / mXScale;
3069        mYPrecision = 1.0f / mYScale;
3070
3071        mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3072        mOrientedRanges.x.source = mSource;
3073        mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3074        mOrientedRanges.y.source = mSource;
3075
3076        configureVirtualKeys();
3077
3078        // Scale factor for terms that are not oriented in a particular axis.
3079        // If the pixels are square then xScale == yScale otherwise we fake it
3080        // by choosing an average.
3081        mGeometricScale = avg(mXScale, mYScale);
3082
3083        // Size of diagonal axis.
3084        float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3085
3086        // Size factors.
3087        if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3088            if (mRawPointerAxes.touchMajor.valid
3089                    && mRawPointerAxes.touchMajor.maxValue != 0) {
3090                mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3091            } else if (mRawPointerAxes.toolMajor.valid
3092                    && mRawPointerAxes.toolMajor.maxValue != 0) {
3093                mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3094            } else {
3095                mSizeScale = 0.0f;
3096            }
3097
3098            mOrientedRanges.haveTouchSize = true;
3099            mOrientedRanges.haveToolSize = true;
3100            mOrientedRanges.haveSize = true;
3101
3102            mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3103            mOrientedRanges.touchMajor.source = mSource;
3104            mOrientedRanges.touchMajor.min = 0;
3105            mOrientedRanges.touchMajor.max = diagonalSize;
3106            mOrientedRanges.touchMajor.flat = 0;
3107            mOrientedRanges.touchMajor.fuzz = 0;
3108            mOrientedRanges.touchMajor.resolution = 0;
3109
3110            mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3111            mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3112
3113            mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3114            mOrientedRanges.toolMajor.source = mSource;
3115            mOrientedRanges.toolMajor.min = 0;
3116            mOrientedRanges.toolMajor.max = diagonalSize;
3117            mOrientedRanges.toolMajor.flat = 0;
3118            mOrientedRanges.toolMajor.fuzz = 0;
3119            mOrientedRanges.toolMajor.resolution = 0;
3120
3121            mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3122            mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3123
3124            mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3125            mOrientedRanges.size.source = mSource;
3126            mOrientedRanges.size.min = 0;
3127            mOrientedRanges.size.max = 1.0;
3128            mOrientedRanges.size.flat = 0;
3129            mOrientedRanges.size.fuzz = 0;
3130            mOrientedRanges.size.resolution = 0;
3131        } else {
3132            mSizeScale = 0.0f;
3133        }
3134
3135        // Pressure factors.
3136        mPressureScale = 0;
3137        if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3138                || mCalibration.pressureCalibration
3139                        == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3140            if (mCalibration.havePressureScale) {
3141                mPressureScale = mCalibration.pressureScale;
3142            } else if (mRawPointerAxes.pressure.valid
3143                    && mRawPointerAxes.pressure.maxValue != 0) {
3144                mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3145            }
3146        }
3147
3148        mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3149        mOrientedRanges.pressure.source = mSource;
3150        mOrientedRanges.pressure.min = 0;
3151        mOrientedRanges.pressure.max = 1.0;
3152        mOrientedRanges.pressure.flat = 0;
3153        mOrientedRanges.pressure.fuzz = 0;
3154        mOrientedRanges.pressure.resolution = 0;
3155
3156        // Tilt
3157        mTiltXCenter = 0;
3158        mTiltXScale = 0;
3159        mTiltYCenter = 0;
3160        mTiltYScale = 0;
3161        mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3162        if (mHaveTilt) {
3163            mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3164                    mRawPointerAxes.tiltX.maxValue);
3165            mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3166                    mRawPointerAxes.tiltY.maxValue);
3167            mTiltXScale = M_PI / 180;
3168            mTiltYScale = M_PI / 180;
3169
3170            mOrientedRanges.haveTilt = true;
3171
3172            mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3173            mOrientedRanges.tilt.source = mSource;
3174            mOrientedRanges.tilt.min = 0;
3175            mOrientedRanges.tilt.max = M_PI_2;
3176            mOrientedRanges.tilt.flat = 0;
3177            mOrientedRanges.tilt.fuzz = 0;
3178            mOrientedRanges.tilt.resolution = 0;
3179        }
3180
3181        // Orientation
3182        mOrientationScale = 0;
3183        if (mHaveTilt) {
3184            mOrientedRanges.haveOrientation = true;
3185
3186            mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3187            mOrientedRanges.orientation.source = mSource;
3188            mOrientedRanges.orientation.min = -M_PI;
3189            mOrientedRanges.orientation.max = M_PI;
3190            mOrientedRanges.orientation.flat = 0;
3191            mOrientedRanges.orientation.fuzz = 0;
3192            mOrientedRanges.orientation.resolution = 0;
3193        } else if (mCalibration.orientationCalibration !=
3194                Calibration::ORIENTATION_CALIBRATION_NONE) {
3195            if (mCalibration.orientationCalibration
3196                    == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3197                if (mRawPointerAxes.orientation.valid) {
3198                    if (mRawPointerAxes.orientation.maxValue > 0) {
3199                        mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3200                    } else if (mRawPointerAxes.orientation.minValue < 0) {
3201                        mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3202                    } else {
3203                        mOrientationScale = 0;
3204                    }
3205                }
3206            }
3207
3208            mOrientedRanges.haveOrientation = true;
3209
3210            mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3211            mOrientedRanges.orientation.source = mSource;
3212            mOrientedRanges.orientation.min = -M_PI_2;
3213            mOrientedRanges.orientation.max = M_PI_2;
3214            mOrientedRanges.orientation.flat = 0;
3215            mOrientedRanges.orientation.fuzz = 0;
3216            mOrientedRanges.orientation.resolution = 0;
3217        }
3218
3219        // Distance
3220        mDistanceScale = 0;
3221        if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3222            if (mCalibration.distanceCalibration
3223                    == Calibration::DISTANCE_CALIBRATION_SCALED) {
3224                if (mCalibration.haveDistanceScale) {
3225                    mDistanceScale = mCalibration.distanceScale;
3226                } else {
3227                    mDistanceScale = 1.0f;
3228                }
3229            }
3230
3231            mOrientedRanges.haveDistance = true;
3232
3233            mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3234            mOrientedRanges.distance.source = mSource;
3235            mOrientedRanges.distance.min =
3236                    mRawPointerAxes.distance.minValue * mDistanceScale;
3237            mOrientedRanges.distance.max =
3238                    mRawPointerAxes.distance.maxValue * mDistanceScale;
3239            mOrientedRanges.distance.flat = 0;
3240            mOrientedRanges.distance.fuzz =
3241                    mRawPointerAxes.distance.fuzz * mDistanceScale;
3242            mOrientedRanges.distance.resolution = 0;
3243        }
3244
3245        // Compute oriented precision, scales and ranges.
3246        // Note that the maximum value reported is an inclusive maximum value so it is one
3247        // unit less than the total width or height of surface.
3248        switch (mSurfaceOrientation) {
3249        case DISPLAY_ORIENTATION_90:
3250        case DISPLAY_ORIENTATION_270:
3251            mOrientedXPrecision = mYPrecision;
3252            mOrientedYPrecision = mXPrecision;
3253
3254            mOrientedRanges.x.min = mYTranslate;
3255            mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3256            mOrientedRanges.x.flat = 0;
3257            mOrientedRanges.x.fuzz = 0;
3258            mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3259
3260            mOrientedRanges.y.min = mXTranslate;
3261            mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3262            mOrientedRanges.y.flat = 0;
3263            mOrientedRanges.y.fuzz = 0;
3264            mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3265            break;
3266
3267        default:
3268            mOrientedXPrecision = mXPrecision;
3269            mOrientedYPrecision = mYPrecision;
3270
3271            mOrientedRanges.x.min = mXTranslate;
3272            mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3273            mOrientedRanges.x.flat = 0;
3274            mOrientedRanges.x.fuzz = 0;
3275            mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3276
3277            mOrientedRanges.y.min = mYTranslate;
3278            mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3279            mOrientedRanges.y.flat = 0;
3280            mOrientedRanges.y.fuzz = 0;
3281            mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3282            break;
3283        }
3284
3285        // Location
3286        updateAffineTransformation();
3287
3288        if (mDeviceMode == DEVICE_MODE_POINTER) {
3289            // Compute pointer gesture detection parameters.
3290            float rawDiagonal = hypotf(rawWidth, rawHeight);
3291            float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3292
3293            // Scale movements such that one whole swipe of the touch pad covers a
3294            // given area relative to the diagonal size of the display when no acceleration
3295            // is applied.
3296            // Assume that the touch pad has a square aspect ratio such that movements in
3297            // X and Y of the same number of raw units cover the same physical distance.
3298            mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3299                    * displayDiagonal / rawDiagonal;
3300            mPointerYMovementScale = mPointerXMovementScale;
3301
3302            // Scale zooms to cover a smaller range of the display than movements do.
3303            // This value determines the area around the pointer that is affected by freeform
3304            // pointer gestures.
3305            mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3306                    * displayDiagonal / rawDiagonal;
3307            mPointerYZoomScale = mPointerXZoomScale;
3308
3309            // Max width between pointers to detect a swipe gesture is more than some fraction
3310            // of the diagonal axis of the touch pad.  Touches that are wider than this are
3311            // translated into freeform gestures.
3312            mPointerGestureMaxSwipeWidth =
3313                    mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3314
3315            // Abort current pointer usages because the state has changed.
3316            abortPointerUsage(when, 0 /*policyFlags*/);
3317        }
3318
3319        // Inform the dispatcher about the changes.
3320        *outResetNeeded = true;
3321        bumpGeneration();
3322    }
3323}
3324
3325void TouchInputMapper::dumpSurface(String8& dump) {
3326    dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3327            "logicalFrame=[%d, %d, %d, %d], "
3328            "physicalFrame=[%d, %d, %d, %d], "
3329            "deviceSize=[%d, %d]\n",
3330            mViewport.displayId, mViewport.orientation,
3331            mViewport.logicalLeft, mViewport.logicalTop,
3332            mViewport.logicalRight, mViewport.logicalBottom,
3333            mViewport.physicalLeft, mViewport.physicalTop,
3334            mViewport.physicalRight, mViewport.physicalBottom,
3335            mViewport.deviceWidth, mViewport.deviceHeight);
3336
3337    dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3338    dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3339    dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3340    dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3341    dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3342}
3343
3344void TouchInputMapper::configureVirtualKeys() {
3345    Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3346    getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3347
3348    mVirtualKeys.clear();
3349
3350    if (virtualKeyDefinitions.size() == 0) {
3351        return;
3352    }
3353
3354    mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3355
3356    int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3357    int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3358    int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3359    int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3360
3361    for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3362        const VirtualKeyDefinition& virtualKeyDefinition =
3363                virtualKeyDefinitions[i];
3364
3365        mVirtualKeys.add();
3366        VirtualKey& virtualKey = mVirtualKeys.editTop();
3367
3368        virtualKey.scanCode = virtualKeyDefinition.scanCode;
3369        int32_t keyCode;
3370        uint32_t flags;
3371        if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, &keyCode, &flags)) {
3372            ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3373                    virtualKey.scanCode);
3374            mVirtualKeys.pop(); // drop the key
3375            continue;
3376        }
3377
3378        virtualKey.keyCode = keyCode;
3379        virtualKey.flags = flags;
3380
3381        // convert the key definition's display coordinates into touch coordinates for a hit box
3382        int32_t halfWidth = virtualKeyDefinition.width / 2;
3383        int32_t halfHeight = virtualKeyDefinition.height / 2;
3384
3385        virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3386                * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3387        virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3388                * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3389        virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3390                * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3391        virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3392                * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3393    }
3394}
3395
3396void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3397    if (!mVirtualKeys.isEmpty()) {
3398        dump.append(INDENT3 "Virtual Keys:\n");
3399
3400        for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3401            const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
3402            dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
3403                    "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3404                    i, virtualKey.scanCode, virtualKey.keyCode,
3405                    virtualKey.hitLeft, virtualKey.hitRight,
3406                    virtualKey.hitTop, virtualKey.hitBottom);
3407        }
3408    }
3409}
3410
3411void TouchInputMapper::parseCalibration() {
3412    const PropertyMap& in = getDevice()->getConfiguration();
3413    Calibration& out = mCalibration;
3414
3415    // Size
3416    out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3417    String8 sizeCalibrationString;
3418    if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3419        if (sizeCalibrationString == "none") {
3420            out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3421        } else if (sizeCalibrationString == "geometric") {
3422            out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3423        } else if (sizeCalibrationString == "diameter") {
3424            out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3425        } else if (sizeCalibrationString == "box") {
3426            out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3427        } else if (sizeCalibrationString == "area") {
3428            out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3429        } else if (sizeCalibrationString != "default") {
3430            ALOGW("Invalid value for touch.size.calibration: '%s'",
3431                    sizeCalibrationString.string());
3432        }
3433    }
3434
3435    out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3436            out.sizeScale);
3437    out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3438            out.sizeBias);
3439    out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3440            out.sizeIsSummed);
3441
3442    // Pressure
3443    out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3444    String8 pressureCalibrationString;
3445    if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3446        if (pressureCalibrationString == "none") {
3447            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3448        } else if (pressureCalibrationString == "physical") {
3449            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3450        } else if (pressureCalibrationString == "amplitude") {
3451            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3452        } else if (pressureCalibrationString != "default") {
3453            ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3454                    pressureCalibrationString.string());
3455        }
3456    }
3457
3458    out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3459            out.pressureScale);
3460
3461    // Orientation
3462    out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3463    String8 orientationCalibrationString;
3464    if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3465        if (orientationCalibrationString == "none") {
3466            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3467        } else if (orientationCalibrationString == "interpolated") {
3468            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3469        } else if (orientationCalibrationString == "vector") {
3470            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3471        } else if (orientationCalibrationString != "default") {
3472            ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3473                    orientationCalibrationString.string());
3474        }
3475    }
3476
3477    // Distance
3478    out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3479    String8 distanceCalibrationString;
3480    if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3481        if (distanceCalibrationString == "none") {
3482            out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3483        } else if (distanceCalibrationString == "scaled") {
3484            out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3485        } else if (distanceCalibrationString != "default") {
3486            ALOGW("Invalid value for touch.distance.calibration: '%s'",
3487                    distanceCalibrationString.string());
3488        }
3489    }
3490
3491    out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3492            out.distanceScale);
3493
3494    out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3495    String8 coverageCalibrationString;
3496    if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3497        if (coverageCalibrationString == "none") {
3498            out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3499        } else if (coverageCalibrationString == "box") {
3500            out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3501        } else if (coverageCalibrationString != "default") {
3502            ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3503                    coverageCalibrationString.string());
3504        }
3505    }
3506}
3507
3508void TouchInputMapper::resolveCalibration() {
3509    // Size
3510    if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3511        if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3512            mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3513        }
3514    } else {
3515        mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3516    }
3517
3518    // Pressure
3519    if (mRawPointerAxes.pressure.valid) {
3520        if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3521            mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3522        }
3523    } else {
3524        mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3525    }
3526
3527    // Orientation
3528    if (mRawPointerAxes.orientation.valid) {
3529        if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3530            mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3531        }
3532    } else {
3533        mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3534    }
3535
3536    // Distance
3537    if (mRawPointerAxes.distance.valid) {
3538        if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3539            mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3540        }
3541    } else {
3542        mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3543    }
3544
3545    // Coverage
3546    if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3547        mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3548    }
3549}
3550
3551void TouchInputMapper::dumpCalibration(String8& dump) {
3552    dump.append(INDENT3 "Calibration:\n");
3553
3554    // Size
3555    switch (mCalibration.sizeCalibration) {
3556    case Calibration::SIZE_CALIBRATION_NONE:
3557        dump.append(INDENT4 "touch.size.calibration: none\n");
3558        break;
3559    case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3560        dump.append(INDENT4 "touch.size.calibration: geometric\n");
3561        break;
3562    case Calibration::SIZE_CALIBRATION_DIAMETER:
3563        dump.append(INDENT4 "touch.size.calibration: diameter\n");
3564        break;
3565    case Calibration::SIZE_CALIBRATION_BOX:
3566        dump.append(INDENT4 "touch.size.calibration: box\n");
3567        break;
3568    case Calibration::SIZE_CALIBRATION_AREA:
3569        dump.append(INDENT4 "touch.size.calibration: area\n");
3570        break;
3571    default:
3572        ALOG_ASSERT(false);
3573    }
3574
3575    if (mCalibration.haveSizeScale) {
3576        dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3577                mCalibration.sizeScale);
3578    }
3579
3580    if (mCalibration.haveSizeBias) {
3581        dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3582                mCalibration.sizeBias);
3583    }
3584
3585    if (mCalibration.haveSizeIsSummed) {
3586        dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3587                toString(mCalibration.sizeIsSummed));
3588    }
3589
3590    // Pressure
3591    switch (mCalibration.pressureCalibration) {
3592    case Calibration::PRESSURE_CALIBRATION_NONE:
3593        dump.append(INDENT4 "touch.pressure.calibration: none\n");
3594        break;
3595    case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3596        dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3597        break;
3598    case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3599        dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
3600        break;
3601    default:
3602        ALOG_ASSERT(false);
3603    }
3604
3605    if (mCalibration.havePressureScale) {
3606        dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
3607                mCalibration.pressureScale);
3608    }
3609
3610    // Orientation
3611    switch (mCalibration.orientationCalibration) {
3612    case Calibration::ORIENTATION_CALIBRATION_NONE:
3613        dump.append(INDENT4 "touch.orientation.calibration: none\n");
3614        break;
3615    case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3616        dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
3617        break;
3618    case Calibration::ORIENTATION_CALIBRATION_VECTOR:
3619        dump.append(INDENT4 "touch.orientation.calibration: vector\n");
3620        break;
3621    default:
3622        ALOG_ASSERT(false);
3623    }
3624
3625    // Distance
3626    switch (mCalibration.distanceCalibration) {
3627    case Calibration::DISTANCE_CALIBRATION_NONE:
3628        dump.append(INDENT4 "touch.distance.calibration: none\n");
3629        break;
3630    case Calibration::DISTANCE_CALIBRATION_SCALED:
3631        dump.append(INDENT4 "touch.distance.calibration: scaled\n");
3632        break;
3633    default:
3634        ALOG_ASSERT(false);
3635    }
3636
3637    if (mCalibration.haveDistanceScale) {
3638        dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
3639                mCalibration.distanceScale);
3640    }
3641
3642    switch (mCalibration.coverageCalibration) {
3643    case Calibration::COVERAGE_CALIBRATION_NONE:
3644        dump.append(INDENT4 "touch.coverage.calibration: none\n");
3645        break;
3646    case Calibration::COVERAGE_CALIBRATION_BOX:
3647        dump.append(INDENT4 "touch.coverage.calibration: box\n");
3648        break;
3649    default:
3650        ALOG_ASSERT(false);
3651    }
3652}
3653
3654void TouchInputMapper::dumpAffineTransformation(String8& dump) {
3655    dump.append(INDENT3 "Affine Transformation:\n");
3656
3657    dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
3658    dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
3659    dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
3660    dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
3661    dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
3662    dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
3663}
3664
3665void TouchInputMapper::updateAffineTransformation() {
3666    mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
3667            mSurfaceOrientation);
3668}
3669
3670void TouchInputMapper::reset(nsecs_t when) {
3671    mCursorButtonAccumulator.reset(getDevice());
3672    mCursorScrollAccumulator.reset(getDevice());
3673    mTouchButtonAccumulator.reset(getDevice());
3674
3675    mPointerVelocityControl.reset();
3676    mWheelXVelocityControl.reset();
3677    mWheelYVelocityControl.reset();
3678
3679    mCurrentRawPointerData.clear();
3680    mLastRawPointerData.clear();
3681    mCurrentCookedPointerData.clear();
3682    mLastCookedPointerData.clear();
3683    mCurrentButtonState = 0;
3684    mLastButtonState = 0;
3685    mCurrentRawVScroll = 0;
3686    mCurrentRawHScroll = 0;
3687    mCurrentFingerIdBits.clear();
3688    mLastFingerIdBits.clear();
3689    mCurrentStylusIdBits.clear();
3690    mLastStylusIdBits.clear();
3691    mCurrentMouseIdBits.clear();
3692    mLastMouseIdBits.clear();
3693    mPointerUsage = POINTER_USAGE_NONE;
3694    mSentHoverEnter = false;
3695    mDownTime = 0;
3696
3697    mCurrentVirtualKey.down = false;
3698
3699    mPointerGesture.reset();
3700    mPointerSimple.reset();
3701
3702    if (mPointerController != NULL) {
3703        mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3704        mPointerController->clearSpots();
3705    }
3706
3707    InputMapper::reset(when);
3708}
3709
3710void TouchInputMapper::process(const RawEvent* rawEvent) {
3711    mCursorButtonAccumulator.process(rawEvent);
3712    mCursorScrollAccumulator.process(rawEvent);
3713    mTouchButtonAccumulator.process(rawEvent);
3714
3715    if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3716        sync(rawEvent->when);
3717    }
3718}
3719
3720void TouchInputMapper::sync(nsecs_t when) {
3721    // Sync button state.
3722    mCurrentButtonState = mTouchButtonAccumulator.getButtonState()
3723            | mCursorButtonAccumulator.getButtonState();
3724
3725    // Sync scroll state.
3726    mCurrentRawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
3727    mCurrentRawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
3728    mCursorScrollAccumulator.finishSync();
3729
3730    // Sync touch state.
3731    bool havePointerIds = true;
3732    mCurrentRawPointerData.clear();
3733    syncTouch(when, &havePointerIds);
3734
3735#if DEBUG_RAW_EVENTS
3736    if (!havePointerIds) {
3737        ALOGD("syncTouch: pointerCount %d -> %d, no pointer ids",
3738                mLastRawPointerData.pointerCount,
3739                mCurrentRawPointerData.pointerCount);
3740    } else {
3741        ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
3742                "hovering ids 0x%08x -> 0x%08x",
3743                mLastRawPointerData.pointerCount,
3744                mCurrentRawPointerData.pointerCount,
3745                mLastRawPointerData.touchingIdBits.value,
3746                mCurrentRawPointerData.touchingIdBits.value,
3747                mLastRawPointerData.hoveringIdBits.value,
3748                mCurrentRawPointerData.hoveringIdBits.value);
3749    }
3750#endif
3751
3752    // Reset state that we will compute below.
3753    mCurrentFingerIdBits.clear();
3754    mCurrentStylusIdBits.clear();
3755    mCurrentMouseIdBits.clear();
3756    mCurrentCookedPointerData.clear();
3757
3758    if (mDeviceMode == DEVICE_MODE_DISABLED) {
3759        // Drop all input if the device is disabled.
3760        mCurrentRawPointerData.clear();
3761        mCurrentButtonState = 0;
3762    } else {
3763        // Preprocess pointer data.
3764        if (!havePointerIds) {
3765            assignPointerIds();
3766        }
3767
3768        // Handle policy on initial down or hover events.
3769        uint32_t policyFlags = 0;
3770        bool initialDown = mLastRawPointerData.pointerCount == 0
3771                && mCurrentRawPointerData.pointerCount != 0;
3772        bool buttonsPressed = mCurrentButtonState & ~mLastButtonState;
3773        if (initialDown || buttonsPressed) {
3774            // If this is a touch screen, hide the pointer on an initial down.
3775            if (mDeviceMode == DEVICE_MODE_DIRECT) {
3776                getContext()->fadePointer();
3777            }
3778
3779            if (mParameters.wake) {
3780                policyFlags |= POLICY_FLAG_WAKE_DROPPED;
3781            }
3782        }
3783
3784        // Synthesize key down from raw buttons if needed.
3785        synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
3786                policyFlags, mLastButtonState, mCurrentButtonState);
3787
3788        // Consume raw off-screen touches before cooking pointer data.
3789        // If touches are consumed, subsequent code will not receive any pointer data.
3790        if (consumeRawTouches(when, policyFlags)) {
3791            mCurrentRawPointerData.clear();
3792        }
3793
3794        // Cook pointer data.  This call populates the mCurrentCookedPointerData structure
3795        // with cooked pointer data that has the same ids and indices as the raw data.
3796        // The following code can use either the raw or cooked data, as needed.
3797        cookPointerData();
3798
3799        // Dispatch the touches either directly or by translation through a pointer on screen.
3800        if (mDeviceMode == DEVICE_MODE_POINTER) {
3801            for (BitSet32 idBits(mCurrentRawPointerData.touchingIdBits); !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                } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
3808                        || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
3809                    mCurrentFingerIdBits.markBit(id);
3810                } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
3811                    mCurrentMouseIdBits.markBit(id);
3812                }
3813            }
3814            for (BitSet32 idBits(mCurrentRawPointerData.hoveringIdBits); !idBits.isEmpty(); ) {
3815                uint32_t id = idBits.clearFirstMarkedBit();
3816                const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3817                if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
3818                        || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
3819                    mCurrentStylusIdBits.markBit(id);
3820                }
3821            }
3822
3823            // Stylus takes precedence over all tools, then mouse, then finger.
3824            PointerUsage pointerUsage = mPointerUsage;
3825            if (!mCurrentStylusIdBits.isEmpty()) {
3826                mCurrentMouseIdBits.clear();
3827                mCurrentFingerIdBits.clear();
3828                pointerUsage = POINTER_USAGE_STYLUS;
3829            } else if (!mCurrentMouseIdBits.isEmpty()) {
3830                mCurrentFingerIdBits.clear();
3831                pointerUsage = POINTER_USAGE_MOUSE;
3832            } else if (!mCurrentFingerIdBits.isEmpty() || isPointerDown(mCurrentButtonState)) {
3833                pointerUsage = POINTER_USAGE_GESTURES;
3834            }
3835
3836            dispatchPointerUsage(when, policyFlags, pointerUsage);
3837        } else {
3838            if (mDeviceMode == DEVICE_MODE_DIRECT
3839                    && mConfig.showTouches && mPointerController != NULL) {
3840                mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
3841                mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3842
3843                mPointerController->setButtonState(mCurrentButtonState);
3844                mPointerController->setSpots(mCurrentCookedPointerData.pointerCoords,
3845                        mCurrentCookedPointerData.idToIndex,
3846                        mCurrentCookedPointerData.touchingIdBits);
3847            }
3848
3849            dispatchHoverExit(when, policyFlags);
3850            dispatchTouches(when, policyFlags);
3851            dispatchHoverEnterAndMove(when, policyFlags);
3852        }
3853
3854        // Synthesize key up from raw buttons if needed.
3855        synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
3856                policyFlags, mLastButtonState, mCurrentButtonState);
3857    }
3858
3859    // Copy current touch to last touch in preparation for the next cycle.
3860    mLastRawPointerData.copyFrom(mCurrentRawPointerData);
3861    mLastCookedPointerData.copyFrom(mCurrentCookedPointerData);
3862    mLastButtonState = mCurrentButtonState;
3863    mLastFingerIdBits = mCurrentFingerIdBits;
3864    mLastStylusIdBits = mCurrentStylusIdBits;
3865    mLastMouseIdBits = mCurrentMouseIdBits;
3866
3867    // Clear some transient state.
3868    mCurrentRawVScroll = 0;
3869    mCurrentRawHScroll = 0;
3870}
3871
3872void TouchInputMapper::timeoutExpired(nsecs_t when) {
3873    if (mDeviceMode == DEVICE_MODE_POINTER) {
3874        if (mPointerUsage == POINTER_USAGE_GESTURES) {
3875            dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
3876        }
3877    }
3878}
3879
3880bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
3881    // Check for release of a virtual key.
3882    if (mCurrentVirtualKey.down) {
3883        if (mCurrentRawPointerData.touchingIdBits.isEmpty()) {
3884            // Pointer went up while virtual key was down.
3885            mCurrentVirtualKey.down = false;
3886            if (!mCurrentVirtualKey.ignored) {
3887#if DEBUG_VIRTUAL_KEYS
3888                ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
3889                        mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
3890#endif
3891                dispatchVirtualKey(when, policyFlags,
3892                        AKEY_EVENT_ACTION_UP,
3893                        AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
3894            }
3895            return true;
3896        }
3897
3898        if (mCurrentRawPointerData.touchingIdBits.count() == 1) {
3899            uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit();
3900            const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3901            const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
3902            if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
3903                // Pointer is still within the space of the virtual key.
3904                return true;
3905            }
3906        }
3907
3908        // Pointer left virtual key area or another pointer also went down.
3909        // Send key cancellation but do not consume the touch yet.
3910        // This is useful when the user swipes through from the virtual key area
3911        // into the main display surface.
3912        mCurrentVirtualKey.down = false;
3913        if (!mCurrentVirtualKey.ignored) {
3914#if DEBUG_VIRTUAL_KEYS
3915            ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
3916                    mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
3917#endif
3918            dispatchVirtualKey(when, policyFlags,
3919                    AKEY_EVENT_ACTION_UP,
3920                    AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
3921                            | AKEY_EVENT_FLAG_CANCELED);
3922        }
3923    }
3924
3925    if (mLastRawPointerData.touchingIdBits.isEmpty()
3926            && !mCurrentRawPointerData.touchingIdBits.isEmpty()) {
3927        // Pointer just went down.  Check for virtual key press or off-screen touches.
3928        uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit();
3929        const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
3930        if (!isPointInsideSurface(pointer.x, pointer.y)) {
3931            // If exactly one pointer went down, check for virtual key hit.
3932            // Otherwise we will drop the entire stroke.
3933            if (mCurrentRawPointerData.touchingIdBits.count() == 1) {
3934                const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
3935                if (virtualKey) {
3936                    mCurrentVirtualKey.down = true;
3937                    mCurrentVirtualKey.downTime = when;
3938                    mCurrentVirtualKey.keyCode = virtualKey->keyCode;
3939                    mCurrentVirtualKey.scanCode = virtualKey->scanCode;
3940                    mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
3941                            when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
3942
3943                    if (!mCurrentVirtualKey.ignored) {
3944#if DEBUG_VIRTUAL_KEYS
3945                        ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
3946                                mCurrentVirtualKey.keyCode,
3947                                mCurrentVirtualKey.scanCode);
3948#endif
3949                        dispatchVirtualKey(when, policyFlags,
3950                                AKEY_EVENT_ACTION_DOWN,
3951                                AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
3952                    }
3953                }
3954            }
3955            return true;
3956        }
3957    }
3958
3959    // Disable all virtual key touches that happen within a short time interval of the
3960    // most recent touch within the screen area.  The idea is to filter out stray
3961    // virtual key presses when interacting with the touch screen.
3962    //
3963    // Problems we're trying to solve:
3964    //
3965    // 1. While scrolling a list or dragging the window shade, the user swipes down into a
3966    //    virtual key area that is implemented by a separate touch panel and accidentally
3967    //    triggers a virtual key.
3968    //
3969    // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
3970    //    area and accidentally triggers a virtual key.  This often happens when virtual keys
3971    //    are layed out below the screen near to where the on screen keyboard's space bar
3972    //    is displayed.
3973    if (mConfig.virtualKeyQuietTime > 0 && !mCurrentRawPointerData.touchingIdBits.isEmpty()) {
3974        mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
3975    }
3976    return false;
3977}
3978
3979void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
3980        int32_t keyEventAction, int32_t keyEventFlags) {
3981    int32_t keyCode = mCurrentVirtualKey.keyCode;
3982    int32_t scanCode = mCurrentVirtualKey.scanCode;
3983    nsecs_t downTime = mCurrentVirtualKey.downTime;
3984    int32_t metaState = mContext->getGlobalMetaState();
3985    policyFlags |= POLICY_FLAG_VIRTUAL;
3986
3987    NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
3988            keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
3989    getListener()->notifyKey(&args);
3990}
3991
3992void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
3993    BitSet32 currentIdBits = mCurrentCookedPointerData.touchingIdBits;
3994    BitSet32 lastIdBits = mLastCookedPointerData.touchingIdBits;
3995    int32_t metaState = getContext()->getGlobalMetaState();
3996    int32_t buttonState = mCurrentButtonState;
3997
3998    if (currentIdBits == lastIdBits) {
3999        if (!currentIdBits.isEmpty()) {
4000            // No pointer id changes so this is a move event.
4001            // The listener takes care of batching moves so we don't have to deal with that here.
4002            dispatchMotion(when, policyFlags, mSource,
4003                    AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState,
4004                    AMOTION_EVENT_EDGE_FLAG_NONE,
4005                    mCurrentCookedPointerData.pointerProperties,
4006                    mCurrentCookedPointerData.pointerCoords,
4007                    mCurrentCookedPointerData.idToIndex,
4008                    currentIdBits, -1,
4009                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4010        }
4011    } else {
4012        // There may be pointers going up and pointers going down and pointers moving
4013        // all at the same time.
4014        BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4015        BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4016        BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4017        BitSet32 dispatchedIdBits(lastIdBits.value);
4018
4019        // Update last coordinates of pointers that have moved so that we observe the new
4020        // pointer positions at the same time as other pointers that have just gone up.
4021        bool moveNeeded = updateMovedPointers(
4022                mCurrentCookedPointerData.pointerProperties,
4023                mCurrentCookedPointerData.pointerCoords,
4024                mCurrentCookedPointerData.idToIndex,
4025                mLastCookedPointerData.pointerProperties,
4026                mLastCookedPointerData.pointerCoords,
4027                mLastCookedPointerData.idToIndex,
4028                moveIdBits);
4029        if (buttonState != mLastButtonState) {
4030            moveNeeded = true;
4031        }
4032
4033        // Dispatch pointer up events.
4034        while (!upIdBits.isEmpty()) {
4035            uint32_t upId = upIdBits.clearFirstMarkedBit();
4036
4037            dispatchMotion(when, policyFlags, mSource,
4038                    AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, buttonState, 0,
4039                    mLastCookedPointerData.pointerProperties,
4040                    mLastCookedPointerData.pointerCoords,
4041                    mLastCookedPointerData.idToIndex,
4042                    dispatchedIdBits, upId,
4043                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4044            dispatchedIdBits.clearBit(upId);
4045        }
4046
4047        // Dispatch move events if any of the remaining pointers moved from their old locations.
4048        // Although applications receive new locations as part of individual pointer up
4049        // events, they do not generally handle them except when presented in a move event.
4050        if (moveNeeded) {
4051            ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4052            dispatchMotion(when, policyFlags, mSource,
4053                    AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, 0,
4054                    mCurrentCookedPointerData.pointerProperties,
4055                    mCurrentCookedPointerData.pointerCoords,
4056                    mCurrentCookedPointerData.idToIndex,
4057                    dispatchedIdBits, -1,
4058                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4059        }
4060
4061        // Dispatch pointer down events using the new pointer locations.
4062        while (!downIdBits.isEmpty()) {
4063            uint32_t downId = downIdBits.clearFirstMarkedBit();
4064            dispatchedIdBits.markBit(downId);
4065
4066            if (dispatchedIdBits.count() == 1) {
4067                // First pointer is going down.  Set down time.
4068                mDownTime = when;
4069            }
4070
4071            dispatchMotion(when, policyFlags, mSource,
4072                    AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0,
4073                    mCurrentCookedPointerData.pointerProperties,
4074                    mCurrentCookedPointerData.pointerCoords,
4075                    mCurrentCookedPointerData.idToIndex,
4076                    dispatchedIdBits, downId,
4077                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4078        }
4079    }
4080}
4081
4082void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4083    if (mSentHoverEnter &&
4084            (mCurrentCookedPointerData.hoveringIdBits.isEmpty()
4085                    || !mCurrentCookedPointerData.touchingIdBits.isEmpty())) {
4086        int32_t metaState = getContext()->getGlobalMetaState();
4087        dispatchMotion(when, policyFlags, mSource,
4088                AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0,
4089                mLastCookedPointerData.pointerProperties,
4090                mLastCookedPointerData.pointerCoords,
4091                mLastCookedPointerData.idToIndex,
4092                mLastCookedPointerData.hoveringIdBits, -1,
4093                mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4094        mSentHoverEnter = false;
4095    }
4096}
4097
4098void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
4099    if (mCurrentCookedPointerData.touchingIdBits.isEmpty()
4100            && !mCurrentCookedPointerData.hoveringIdBits.isEmpty()) {
4101        int32_t metaState = getContext()->getGlobalMetaState();
4102        if (!mSentHoverEnter) {
4103            dispatchMotion(when, policyFlags, mSource,
4104                    AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0,
4105                    mCurrentCookedPointerData.pointerProperties,
4106                    mCurrentCookedPointerData.pointerCoords,
4107                    mCurrentCookedPointerData.idToIndex,
4108                    mCurrentCookedPointerData.hoveringIdBits, -1,
4109                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4110            mSentHoverEnter = true;
4111        }
4112
4113        dispatchMotion(when, policyFlags, mSource,
4114                AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0,
4115                mCurrentCookedPointerData.pointerProperties,
4116                mCurrentCookedPointerData.pointerCoords,
4117                mCurrentCookedPointerData.idToIndex,
4118                mCurrentCookedPointerData.hoveringIdBits, -1,
4119                mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4120    }
4121}
4122
4123void TouchInputMapper::cookPointerData() {
4124    uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount;
4125
4126    mCurrentCookedPointerData.clear();
4127    mCurrentCookedPointerData.pointerCount = currentPointerCount;
4128    mCurrentCookedPointerData.hoveringIdBits = mCurrentRawPointerData.hoveringIdBits;
4129    mCurrentCookedPointerData.touchingIdBits = mCurrentRawPointerData.touchingIdBits;
4130
4131    // Walk through the the active pointers and map device coordinates onto
4132    // surface coordinates and adjust for display orientation.
4133    for (uint32_t i = 0; i < currentPointerCount; i++) {
4134        const RawPointerData::Pointer& in = mCurrentRawPointerData.pointers[i];
4135
4136        // Size
4137        float touchMajor, touchMinor, toolMajor, toolMinor, size;
4138        switch (mCalibration.sizeCalibration) {
4139        case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4140        case Calibration::SIZE_CALIBRATION_DIAMETER:
4141        case Calibration::SIZE_CALIBRATION_BOX:
4142        case Calibration::SIZE_CALIBRATION_AREA:
4143            if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4144                touchMajor = in.touchMajor;
4145                touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4146                toolMajor = in.toolMajor;
4147                toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4148                size = mRawPointerAxes.touchMinor.valid
4149                        ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4150            } else if (mRawPointerAxes.touchMajor.valid) {
4151                toolMajor = touchMajor = in.touchMajor;
4152                toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4153                        ? in.touchMinor : in.touchMajor;
4154                size = mRawPointerAxes.touchMinor.valid
4155                        ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4156            } else if (mRawPointerAxes.toolMajor.valid) {
4157                touchMajor = toolMajor = in.toolMajor;
4158                touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4159                        ? in.toolMinor : in.toolMajor;
4160                size = mRawPointerAxes.toolMinor.valid
4161                        ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4162            } else {
4163                ALOG_ASSERT(false, "No touch or tool axes.  "
4164                        "Size calibration should have been resolved to NONE.");
4165                touchMajor = 0;
4166                touchMinor = 0;
4167                toolMajor = 0;
4168                toolMinor = 0;
4169                size = 0;
4170            }
4171
4172            if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
4173                uint32_t touchingCount = mCurrentRawPointerData.touchingIdBits.count();
4174                if (touchingCount > 1) {
4175                    touchMajor /= touchingCount;
4176                    touchMinor /= touchingCount;
4177                    toolMajor /= touchingCount;
4178                    toolMinor /= touchingCount;
4179                    size /= touchingCount;
4180                }
4181            }
4182
4183            if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4184                touchMajor *= mGeometricScale;
4185                touchMinor *= mGeometricScale;
4186                toolMajor *= mGeometricScale;
4187                toolMinor *= mGeometricScale;
4188            } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4189                touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4190                touchMinor = touchMajor;
4191                toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4192                toolMinor = toolMajor;
4193            } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4194                touchMinor = touchMajor;
4195                toolMinor = toolMajor;
4196            }
4197
4198            mCalibration.applySizeScaleAndBias(&touchMajor);
4199            mCalibration.applySizeScaleAndBias(&touchMinor);
4200            mCalibration.applySizeScaleAndBias(&toolMajor);
4201            mCalibration.applySizeScaleAndBias(&toolMinor);
4202            size *= mSizeScale;
4203            break;
4204        default:
4205            touchMajor = 0;
4206            touchMinor = 0;
4207            toolMajor = 0;
4208            toolMinor = 0;
4209            size = 0;
4210            break;
4211        }
4212
4213        // Pressure
4214        float pressure;
4215        switch (mCalibration.pressureCalibration) {
4216        case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4217        case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4218            pressure = in.pressure * mPressureScale;
4219            break;
4220        default:
4221            pressure = in.isHovering ? 0 : 1;
4222            break;
4223        }
4224
4225        // Tilt and Orientation
4226        float tilt;
4227        float orientation;
4228        if (mHaveTilt) {
4229            float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4230            float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4231            orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4232            tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4233        } else {
4234            tilt = 0;
4235
4236            switch (mCalibration.orientationCalibration) {
4237            case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4238                orientation = in.orientation * mOrientationScale;
4239                break;
4240            case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4241                int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4242                int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4243                if (c1 != 0 || c2 != 0) {
4244                    orientation = atan2f(c1, c2) * 0.5f;
4245                    float confidence = hypotf(c1, c2);
4246                    float scale = 1.0f + confidence / 16.0f;
4247                    touchMajor *= scale;
4248                    touchMinor /= scale;
4249                    toolMajor *= scale;
4250                    toolMinor /= scale;
4251                } else {
4252                    orientation = 0;
4253                }
4254                break;
4255            }
4256            default:
4257                orientation = 0;
4258            }
4259        }
4260
4261        // Distance
4262        float distance;
4263        switch (mCalibration.distanceCalibration) {
4264        case Calibration::DISTANCE_CALIBRATION_SCALED:
4265            distance = in.distance * mDistanceScale;
4266            break;
4267        default:
4268            distance = 0;
4269        }
4270
4271        // Coverage
4272        int32_t rawLeft, rawTop, rawRight, rawBottom;
4273        switch (mCalibration.coverageCalibration) {
4274        case Calibration::COVERAGE_CALIBRATION_BOX:
4275            rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4276            rawRight = in.toolMinor & 0x0000ffff;
4277            rawBottom = in.toolMajor & 0x0000ffff;
4278            rawTop = (in.toolMajor & 0xffff0000) >> 16;
4279            break;
4280        default:
4281            rawLeft = rawTop = rawRight = rawBottom = 0;
4282            break;
4283        }
4284
4285        // Adjust X,Y coords for device calibration
4286        // TODO: Adjust coverage coords?
4287        float xTransformed = in.x, yTransformed = in.y;
4288        mAffineTransform.applyTo(xTransformed, yTransformed);
4289
4290        // Adjust X, Y, and coverage coords for surface orientation.
4291        float x, y;
4292        float left, top, right, bottom;
4293
4294        switch (mSurfaceOrientation) {
4295        case DISPLAY_ORIENTATION_90:
4296            x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4297            y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4298            left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4299            right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4300            bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4301            top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4302            orientation -= M_PI_2;
4303            if (orientation < mOrientedRanges.orientation.min) {
4304                orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4305            }
4306            break;
4307        case DISPLAY_ORIENTATION_180:
4308            x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4309            y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4310            left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4311            right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4312            bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4313            top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4314            orientation -= M_PI;
4315            if (orientation < mOrientedRanges.orientation.min) {
4316                orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4317            }
4318            break;
4319        case DISPLAY_ORIENTATION_270:
4320            x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4321            y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4322            left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4323            right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4324            bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4325            top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4326            orientation += M_PI_2;
4327            if (orientation > mOrientedRanges.orientation.max) {
4328                orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4329            }
4330            break;
4331        default:
4332            x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4333            y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4334            left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4335            right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4336            bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4337            top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4338            break;
4339        }
4340
4341        // Write output coords.
4342        PointerCoords& out = mCurrentCookedPointerData.pointerCoords[i];
4343        out.clear();
4344        out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4345        out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4346        out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4347        out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4348        out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4349        out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4350        out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4351        out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4352        out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4353        if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4354            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4355            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4356            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4357            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4358        } else {
4359            out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4360            out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4361        }
4362
4363        // Write output properties.
4364        PointerProperties& properties = mCurrentCookedPointerData.pointerProperties[i];
4365        uint32_t id = in.id;
4366        properties.clear();
4367        properties.id = id;
4368        properties.toolType = in.toolType;
4369
4370        // Write id index.
4371        mCurrentCookedPointerData.idToIndex[id] = i;
4372    }
4373}
4374
4375void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
4376        PointerUsage pointerUsage) {
4377    if (pointerUsage != mPointerUsage) {
4378        abortPointerUsage(when, policyFlags);
4379        mPointerUsage = pointerUsage;
4380    }
4381
4382    switch (mPointerUsage) {
4383    case POINTER_USAGE_GESTURES:
4384        dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
4385        break;
4386    case POINTER_USAGE_STYLUS:
4387        dispatchPointerStylus(when, policyFlags);
4388        break;
4389    case POINTER_USAGE_MOUSE:
4390        dispatchPointerMouse(when, policyFlags);
4391        break;
4392    default:
4393        break;
4394    }
4395}
4396
4397void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
4398    switch (mPointerUsage) {
4399    case POINTER_USAGE_GESTURES:
4400        abortPointerGestures(when, policyFlags);
4401        break;
4402    case POINTER_USAGE_STYLUS:
4403        abortPointerStylus(when, policyFlags);
4404        break;
4405    case POINTER_USAGE_MOUSE:
4406        abortPointerMouse(when, policyFlags);
4407        break;
4408    default:
4409        break;
4410    }
4411
4412    mPointerUsage = POINTER_USAGE_NONE;
4413}
4414
4415void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
4416        bool isTimeout) {
4417    // Update current gesture coordinates.
4418    bool cancelPreviousGesture, finishPreviousGesture;
4419    bool sendEvents = preparePointerGestures(when,
4420            &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
4421    if (!sendEvents) {
4422        return;
4423    }
4424    if (finishPreviousGesture) {
4425        cancelPreviousGesture = false;
4426    }
4427
4428    // Update the pointer presentation and spots.
4429    if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4430        mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4431        if (finishPreviousGesture || cancelPreviousGesture) {
4432            mPointerController->clearSpots();
4433        }
4434        mPointerController->setSpots(mPointerGesture.currentGestureCoords,
4435                mPointerGesture.currentGestureIdToIndex,
4436                mPointerGesture.currentGestureIdBits);
4437    } else {
4438        mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
4439    }
4440
4441    // Show or hide the pointer if needed.
4442    switch (mPointerGesture.currentGestureMode) {
4443    case PointerGesture::NEUTRAL:
4444    case PointerGesture::QUIET:
4445        if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
4446                && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE
4447                        || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) {
4448            // Remind the user of where the pointer is after finishing a gesture with spots.
4449            mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
4450        }
4451        break;
4452    case PointerGesture::TAP:
4453    case PointerGesture::TAP_DRAG:
4454    case PointerGesture::BUTTON_CLICK_OR_DRAG:
4455    case PointerGesture::HOVER:
4456    case PointerGesture::PRESS:
4457        // Unfade the pointer when the current gesture manipulates the
4458        // area directly under the pointer.
4459        mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4460        break;
4461    case PointerGesture::SWIPE:
4462    case PointerGesture::FREEFORM:
4463        // Fade the pointer when the current gesture manipulates a different
4464        // area and there are spots to guide the user experience.
4465        if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4466            mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4467        } else {
4468            mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4469        }
4470        break;
4471    }
4472
4473    // Send events!
4474    int32_t metaState = getContext()->getGlobalMetaState();
4475    int32_t buttonState = mCurrentButtonState;
4476
4477    // Update last coordinates of pointers that have moved so that we observe the new
4478    // pointer positions at the same time as other pointers that have just gone up.
4479    bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
4480            || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
4481            || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
4482            || mPointerGesture.currentGestureMode == PointerGesture::PRESS
4483            || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
4484            || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
4485    bool moveNeeded = false;
4486    if (down && !cancelPreviousGesture && !finishPreviousGesture
4487            && !mPointerGesture.lastGestureIdBits.isEmpty()
4488            && !mPointerGesture.currentGestureIdBits.isEmpty()) {
4489        BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
4490                & mPointerGesture.lastGestureIdBits.value);
4491        moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
4492                mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4493                mPointerGesture.lastGestureProperties,
4494                mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4495                movedGestureIdBits);
4496        if (buttonState != mLastButtonState) {
4497            moveNeeded = true;
4498        }
4499    }
4500
4501    // Send motion events for all pointers that went up or were canceled.
4502    BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
4503    if (!dispatchedGestureIdBits.isEmpty()) {
4504        if (cancelPreviousGesture) {
4505            dispatchMotion(when, policyFlags, mSource,
4506                    AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
4507                    AMOTION_EVENT_EDGE_FLAG_NONE,
4508                    mPointerGesture.lastGestureProperties,
4509                    mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4510                    dispatchedGestureIdBits, -1,
4511                    0, 0, mPointerGesture.downTime);
4512
4513            dispatchedGestureIdBits.clear();
4514        } else {
4515            BitSet32 upGestureIdBits;
4516            if (finishPreviousGesture) {
4517                upGestureIdBits = dispatchedGestureIdBits;
4518            } else {
4519                upGestureIdBits.value = dispatchedGestureIdBits.value
4520                        & ~mPointerGesture.currentGestureIdBits.value;
4521            }
4522            while (!upGestureIdBits.isEmpty()) {
4523                uint32_t id = upGestureIdBits.clearFirstMarkedBit();
4524
4525                dispatchMotion(when, policyFlags, mSource,
4526                        AMOTION_EVENT_ACTION_POINTER_UP, 0,
4527                        metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4528                        mPointerGesture.lastGestureProperties,
4529                        mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4530                        dispatchedGestureIdBits, id,
4531                        0, 0, mPointerGesture.downTime);
4532
4533                dispatchedGestureIdBits.clearBit(id);
4534            }
4535        }
4536    }
4537
4538    // Send motion events for all pointers that moved.
4539    if (moveNeeded) {
4540        dispatchMotion(when, policyFlags, mSource,
4541                AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4542                mPointerGesture.currentGestureProperties,
4543                mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4544                dispatchedGestureIdBits, -1,
4545                0, 0, mPointerGesture.downTime);
4546    }
4547
4548    // Send motion events for all pointers that went down.
4549    if (down) {
4550        BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
4551                & ~dispatchedGestureIdBits.value);
4552        while (!downGestureIdBits.isEmpty()) {
4553            uint32_t id = downGestureIdBits.clearFirstMarkedBit();
4554            dispatchedGestureIdBits.markBit(id);
4555
4556            if (dispatchedGestureIdBits.count() == 1) {
4557                mPointerGesture.downTime = when;
4558            }
4559
4560            dispatchMotion(when, policyFlags, mSource,
4561                    AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0,
4562                    mPointerGesture.currentGestureProperties,
4563                    mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4564                    dispatchedGestureIdBits, id,
4565                    0, 0, mPointerGesture.downTime);
4566        }
4567    }
4568
4569    // Send motion events for hover.
4570    if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
4571        dispatchMotion(when, policyFlags, mSource,
4572                AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
4573                metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4574                mPointerGesture.currentGestureProperties,
4575                mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
4576                mPointerGesture.currentGestureIdBits, -1,
4577                0, 0, mPointerGesture.downTime);
4578    } else if (dispatchedGestureIdBits.isEmpty()
4579            && !mPointerGesture.lastGestureIdBits.isEmpty()) {
4580        // Synthesize a hover move event after all pointers go up to indicate that
4581        // the pointer is hovering again even if the user is not currently touching
4582        // the touch pad.  This ensures that a view will receive a fresh hover enter
4583        // event after a tap.
4584        float x, y;
4585        mPointerController->getPosition(&x, &y);
4586
4587        PointerProperties pointerProperties;
4588        pointerProperties.clear();
4589        pointerProperties.id = 0;
4590        pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
4591
4592        PointerCoords pointerCoords;
4593        pointerCoords.clear();
4594        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4595        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4596
4597        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
4598                AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
4599                metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4600                mViewport.displayId, 1, &pointerProperties, &pointerCoords,
4601                0, 0, mPointerGesture.downTime);
4602        getListener()->notifyMotion(&args);
4603    }
4604
4605    // Update state.
4606    mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
4607    if (!down) {
4608        mPointerGesture.lastGestureIdBits.clear();
4609    } else {
4610        mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
4611        for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
4612            uint32_t id = idBits.clearFirstMarkedBit();
4613            uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
4614            mPointerGesture.lastGestureProperties[index].copyFrom(
4615                    mPointerGesture.currentGestureProperties[index]);
4616            mPointerGesture.lastGestureCoords[index].copyFrom(
4617                    mPointerGesture.currentGestureCoords[index]);
4618            mPointerGesture.lastGestureIdToIndex[id] = index;
4619        }
4620    }
4621}
4622
4623void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
4624    // Cancel previously dispatches pointers.
4625    if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
4626        int32_t metaState = getContext()->getGlobalMetaState();
4627        int32_t buttonState = mCurrentButtonState;
4628        dispatchMotion(when, policyFlags, mSource,
4629                AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
4630                AMOTION_EVENT_EDGE_FLAG_NONE,
4631                mPointerGesture.lastGestureProperties,
4632                mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
4633                mPointerGesture.lastGestureIdBits, -1,
4634                0, 0, mPointerGesture.downTime);
4635    }
4636
4637    // Reset the current pointer gesture.
4638    mPointerGesture.reset();
4639    mPointerVelocityControl.reset();
4640
4641    // Remove any current spots.
4642    if (mPointerController != NULL) {
4643        mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4644        mPointerController->clearSpots();
4645    }
4646}
4647
4648bool TouchInputMapper::preparePointerGestures(nsecs_t when,
4649        bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
4650    *outCancelPreviousGesture = false;
4651    *outFinishPreviousGesture = false;
4652
4653    // Handle TAP timeout.
4654    if (isTimeout) {
4655#if DEBUG_GESTURES
4656        ALOGD("Gestures: Processing timeout");
4657#endif
4658
4659        if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
4660            if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
4661                // The tap/drag timeout has not yet expired.
4662                getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
4663                        + mConfig.pointerGestureTapDragInterval);
4664            } else {
4665                // The tap is finished.
4666#if DEBUG_GESTURES
4667                ALOGD("Gestures: TAP finished");
4668#endif
4669                *outFinishPreviousGesture = true;
4670
4671                mPointerGesture.activeGestureId = -1;
4672                mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
4673                mPointerGesture.currentGestureIdBits.clear();
4674
4675                mPointerVelocityControl.reset();
4676                return true;
4677            }
4678        }
4679
4680        // We did not handle this timeout.
4681        return false;
4682    }
4683
4684    const uint32_t currentFingerCount = mCurrentFingerIdBits.count();
4685    const uint32_t lastFingerCount = mLastFingerIdBits.count();
4686
4687    // Update the velocity tracker.
4688    {
4689        VelocityTracker::Position positions[MAX_POINTERS];
4690        uint32_t count = 0;
4691        for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); count++) {
4692            uint32_t id = idBits.clearFirstMarkedBit();
4693            const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
4694            positions[count].x = pointer.x * mPointerXMovementScale;
4695            positions[count].y = pointer.y * mPointerYMovementScale;
4696        }
4697        mPointerGesture.velocityTracker.addMovement(when,
4698                mCurrentFingerIdBits, positions);
4699    }
4700
4701    // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
4702    // to NEUTRAL, then we should not generate tap event.
4703    if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
4704            && mPointerGesture.lastGestureMode != PointerGesture::TAP
4705            && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
4706        mPointerGesture.resetTap();
4707    }
4708
4709    // Pick a new active touch id if needed.
4710    // Choose an arbitrary pointer that just went down, if there is one.
4711    // Otherwise choose an arbitrary remaining pointer.
4712    // This guarantees we always have an active touch id when there is at least one pointer.
4713    // We keep the same active touch id for as long as possible.
4714    bool activeTouchChanged = false;
4715    int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
4716    int32_t activeTouchId = lastActiveTouchId;
4717    if (activeTouchId < 0) {
4718        if (!mCurrentFingerIdBits.isEmpty()) {
4719            activeTouchChanged = true;
4720            activeTouchId = mPointerGesture.activeTouchId =
4721                    mCurrentFingerIdBits.firstMarkedBit();
4722            mPointerGesture.firstTouchTime = when;
4723        }
4724    } else if (!mCurrentFingerIdBits.hasBit(activeTouchId)) {
4725        activeTouchChanged = true;
4726        if (!mCurrentFingerIdBits.isEmpty()) {
4727            activeTouchId = mPointerGesture.activeTouchId =
4728                    mCurrentFingerIdBits.firstMarkedBit();
4729        } else {
4730            activeTouchId = mPointerGesture.activeTouchId = -1;
4731        }
4732    }
4733
4734    // Determine whether we are in quiet time.
4735    bool isQuietTime = false;
4736    if (activeTouchId < 0) {
4737        mPointerGesture.resetQuietTime();
4738    } else {
4739        isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
4740        if (!isQuietTime) {
4741            if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
4742                    || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
4743                    || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
4744                    && currentFingerCount < 2) {
4745                // Enter quiet time when exiting swipe or freeform state.
4746                // This is to prevent accidentally entering the hover state and flinging the
4747                // pointer when finishing a swipe and there is still one pointer left onscreen.
4748                isQuietTime = true;
4749            } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
4750                    && currentFingerCount >= 2
4751                    && !isPointerDown(mCurrentButtonState)) {
4752                // Enter quiet time when releasing the button and there are still two or more
4753                // fingers down.  This may indicate that one finger was used to press the button
4754                // but it has not gone up yet.
4755                isQuietTime = true;
4756            }
4757            if (isQuietTime) {
4758                mPointerGesture.quietTime = when;
4759            }
4760        }
4761    }
4762
4763    // Switch states based on button and pointer state.
4764    if (isQuietTime) {
4765        // Case 1: Quiet time. (QUIET)
4766#if DEBUG_GESTURES
4767        ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
4768                + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
4769#endif
4770        if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
4771            *outFinishPreviousGesture = true;
4772        }
4773
4774        mPointerGesture.activeGestureId = -1;
4775        mPointerGesture.currentGestureMode = PointerGesture::QUIET;
4776        mPointerGesture.currentGestureIdBits.clear();
4777
4778        mPointerVelocityControl.reset();
4779    } else if (isPointerDown(mCurrentButtonState)) {
4780        // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
4781        // The pointer follows the active touch point.
4782        // Emit DOWN, MOVE, UP events at the pointer location.
4783        //
4784        // Only the active touch matters; other fingers are ignored.  This policy helps
4785        // to handle the case where the user places a second finger on the touch pad
4786        // to apply the necessary force to depress an integrated button below the surface.
4787        // We don't want the second finger to be delivered to applications.
4788        //
4789        // For this to work well, we need to make sure to track the pointer that is really
4790        // active.  If the user first puts one finger down to click then adds another
4791        // finger to drag then the active pointer should switch to the finger that is
4792        // being dragged.
4793#if DEBUG_GESTURES
4794        ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
4795                "currentFingerCount=%d", activeTouchId, currentFingerCount);
4796#endif
4797        // Reset state when just starting.
4798        if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
4799            *outFinishPreviousGesture = true;
4800            mPointerGesture.activeGestureId = 0;
4801        }
4802
4803        // Switch pointers if needed.
4804        // Find the fastest pointer and follow it.
4805        if (activeTouchId >= 0 && currentFingerCount > 1) {
4806            int32_t bestId = -1;
4807            float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
4808            for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); ) {
4809                uint32_t id = idBits.clearFirstMarkedBit();
4810                float vx, vy;
4811                if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
4812                    float speed = hypotf(vx, vy);
4813                    if (speed > bestSpeed) {
4814                        bestId = id;
4815                        bestSpeed = speed;
4816                    }
4817                }
4818            }
4819            if (bestId >= 0 && bestId != activeTouchId) {
4820                mPointerGesture.activeTouchId = activeTouchId = bestId;
4821                activeTouchChanged = true;
4822#if DEBUG_GESTURES
4823                ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
4824                        "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
4825#endif
4826            }
4827        }
4828
4829        if (activeTouchId >= 0 && mLastFingerIdBits.hasBit(activeTouchId)) {
4830            const RawPointerData::Pointer& currentPointer =
4831                    mCurrentRawPointerData.pointerForId(activeTouchId);
4832            const RawPointerData::Pointer& lastPointer =
4833                    mLastRawPointerData.pointerForId(activeTouchId);
4834            float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
4835            float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
4836
4837            rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
4838            mPointerVelocityControl.move(when, &deltaX, &deltaY);
4839
4840            // Move the pointer using a relative motion.
4841            // When using spots, the click will occur at the position of the anchor
4842            // spot and all other spots will move there.
4843            mPointerController->move(deltaX, deltaY);
4844        } else {
4845            mPointerVelocityControl.reset();
4846        }
4847
4848        float x, y;
4849        mPointerController->getPosition(&x, &y);
4850
4851        mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
4852        mPointerGesture.currentGestureIdBits.clear();
4853        mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4854        mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
4855        mPointerGesture.currentGestureProperties[0].clear();
4856        mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
4857        mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
4858        mPointerGesture.currentGestureCoords[0].clear();
4859        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4860        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4861        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4862    } else if (currentFingerCount == 0) {
4863        // Case 3. No fingers down and button is not pressed. (NEUTRAL)
4864        if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
4865            *outFinishPreviousGesture = true;
4866        }
4867
4868        // Watch for taps coming out of HOVER or TAP_DRAG mode.
4869        // Checking for taps after TAP_DRAG allows us to detect double-taps.
4870        bool tapped = false;
4871        if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
4872                || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
4873                && lastFingerCount == 1) {
4874            if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
4875                float x, y;
4876                mPointerController->getPosition(&x, &y);
4877                if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
4878                        && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
4879#if DEBUG_GESTURES
4880                    ALOGD("Gestures: TAP");
4881#endif
4882
4883                    mPointerGesture.tapUpTime = when;
4884                    getContext()->requestTimeoutAtTime(when
4885                            + mConfig.pointerGestureTapDragInterval);
4886
4887                    mPointerGesture.activeGestureId = 0;
4888                    mPointerGesture.currentGestureMode = PointerGesture::TAP;
4889                    mPointerGesture.currentGestureIdBits.clear();
4890                    mPointerGesture.currentGestureIdBits.markBit(
4891                            mPointerGesture.activeGestureId);
4892                    mPointerGesture.currentGestureIdToIndex[
4893                            mPointerGesture.activeGestureId] = 0;
4894                    mPointerGesture.currentGestureProperties[0].clear();
4895                    mPointerGesture.currentGestureProperties[0].id =
4896                            mPointerGesture.activeGestureId;
4897                    mPointerGesture.currentGestureProperties[0].toolType =
4898                            AMOTION_EVENT_TOOL_TYPE_FINGER;
4899                    mPointerGesture.currentGestureCoords[0].clear();
4900                    mPointerGesture.currentGestureCoords[0].setAxisValue(
4901                            AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
4902                    mPointerGesture.currentGestureCoords[0].setAxisValue(
4903                            AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
4904                    mPointerGesture.currentGestureCoords[0].setAxisValue(
4905                            AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4906
4907                    tapped = true;
4908                } else {
4909#if DEBUG_GESTURES
4910                    ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
4911                            x - mPointerGesture.tapX,
4912                            y - mPointerGesture.tapY);
4913#endif
4914                }
4915            } else {
4916#if DEBUG_GESTURES
4917                if (mPointerGesture.tapDownTime != LLONG_MIN) {
4918                    ALOGD("Gestures: Not a TAP, %0.3fms since down",
4919                            (when - mPointerGesture.tapDownTime) * 0.000001f);
4920                } else {
4921                    ALOGD("Gestures: Not a TAP, incompatible mode transitions");
4922                }
4923#endif
4924            }
4925        }
4926
4927        mPointerVelocityControl.reset();
4928
4929        if (!tapped) {
4930#if DEBUG_GESTURES
4931            ALOGD("Gestures: NEUTRAL");
4932#endif
4933            mPointerGesture.activeGestureId = -1;
4934            mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
4935            mPointerGesture.currentGestureIdBits.clear();
4936        }
4937    } else if (currentFingerCount == 1) {
4938        // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
4939        // The pointer follows the active touch point.
4940        // When in HOVER, emit HOVER_MOVE events at the pointer location.
4941        // When in TAP_DRAG, emit MOVE events at the pointer location.
4942        ALOG_ASSERT(activeTouchId >= 0);
4943
4944        mPointerGesture.currentGestureMode = PointerGesture::HOVER;
4945        if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
4946            if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
4947                float x, y;
4948                mPointerController->getPosition(&x, &y);
4949                if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
4950                        && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
4951                    mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
4952                } else {
4953#if DEBUG_GESTURES
4954                    ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
4955                            x - mPointerGesture.tapX,
4956                            y - mPointerGesture.tapY);
4957#endif
4958                }
4959            } else {
4960#if DEBUG_GESTURES
4961                ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
4962                        (when - mPointerGesture.tapUpTime) * 0.000001f);
4963#endif
4964            }
4965        } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
4966            mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
4967        }
4968
4969        if (mLastFingerIdBits.hasBit(activeTouchId)) {
4970            const RawPointerData::Pointer& currentPointer =
4971                    mCurrentRawPointerData.pointerForId(activeTouchId);
4972            const RawPointerData::Pointer& lastPointer =
4973                    mLastRawPointerData.pointerForId(activeTouchId);
4974            float deltaX = (currentPointer.x - lastPointer.x)
4975                    * mPointerXMovementScale;
4976            float deltaY = (currentPointer.y - lastPointer.y)
4977                    * mPointerYMovementScale;
4978
4979            rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
4980            mPointerVelocityControl.move(when, &deltaX, &deltaY);
4981
4982            // Move the pointer using a relative motion.
4983            // When using spots, the hover or drag will occur at the position of the anchor spot.
4984            mPointerController->move(deltaX, deltaY);
4985        } else {
4986            mPointerVelocityControl.reset();
4987        }
4988
4989        bool down;
4990        if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
4991#if DEBUG_GESTURES
4992            ALOGD("Gestures: TAP_DRAG");
4993#endif
4994            down = true;
4995        } else {
4996#if DEBUG_GESTURES
4997            ALOGD("Gestures: HOVER");
4998#endif
4999            if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5000                *outFinishPreviousGesture = true;
5001            }
5002            mPointerGesture.activeGestureId = 0;
5003            down = false;
5004        }
5005
5006        float x, y;
5007        mPointerController->getPosition(&x, &y);
5008
5009        mPointerGesture.currentGestureIdBits.clear();
5010        mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5011        mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5012        mPointerGesture.currentGestureProperties[0].clear();
5013        mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5014        mPointerGesture.currentGestureProperties[0].toolType =
5015                AMOTION_EVENT_TOOL_TYPE_FINGER;
5016        mPointerGesture.currentGestureCoords[0].clear();
5017        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5018        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5019        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5020                down ? 1.0f : 0.0f);
5021
5022        if (lastFingerCount == 0 && currentFingerCount != 0) {
5023            mPointerGesture.resetTap();
5024            mPointerGesture.tapDownTime = when;
5025            mPointerGesture.tapX = x;
5026            mPointerGesture.tapY = y;
5027        }
5028    } else {
5029        // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5030        // We need to provide feedback for each finger that goes down so we cannot wait
5031        // for the fingers to move before deciding what to do.
5032        //
5033        // The ambiguous case is deciding what to do when there are two fingers down but they
5034        // have not moved enough to determine whether they are part of a drag or part of a
5035        // freeform gesture, or just a press or long-press at the pointer location.
5036        //
5037        // When there are two fingers we start with the PRESS hypothesis and we generate a
5038        // down at the pointer location.
5039        //
5040        // When the two fingers move enough or when additional fingers are added, we make
5041        // a decision to transition into SWIPE or FREEFORM mode accordingly.
5042        ALOG_ASSERT(activeTouchId >= 0);
5043
5044        bool settled = when >= mPointerGesture.firstTouchTime
5045                + mConfig.pointerGestureMultitouchSettleInterval;
5046        if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5047                && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5048                && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5049            *outFinishPreviousGesture = true;
5050        } else if (!settled && currentFingerCount > lastFingerCount) {
5051            // Additional pointers have gone down but not yet settled.
5052            // Reset the gesture.
5053#if DEBUG_GESTURES
5054            ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5055                    "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5056                            + mConfig.pointerGestureMultitouchSettleInterval - when)
5057                            * 0.000001f);
5058#endif
5059            *outCancelPreviousGesture = true;
5060        } else {
5061            // Continue previous gesture.
5062            mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5063        }
5064
5065        if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5066            mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5067            mPointerGesture.activeGestureId = 0;
5068            mPointerGesture.referenceIdBits.clear();
5069            mPointerVelocityControl.reset();
5070
5071            // Use the centroid and pointer location as the reference points for the gesture.
5072#if DEBUG_GESTURES
5073            ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5074                    "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5075                            + mConfig.pointerGestureMultitouchSettleInterval - when)
5076                            * 0.000001f);
5077#endif
5078            mCurrentRawPointerData.getCentroidOfTouchingPointers(
5079                    &mPointerGesture.referenceTouchX,
5080                    &mPointerGesture.referenceTouchY);
5081            mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5082                    &mPointerGesture.referenceGestureY);
5083        }
5084
5085        // Clear the reference deltas for fingers not yet included in the reference calculation.
5086        for (BitSet32 idBits(mCurrentFingerIdBits.value
5087                & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5088            uint32_t id = idBits.clearFirstMarkedBit();
5089            mPointerGesture.referenceDeltas[id].dx = 0;
5090            mPointerGesture.referenceDeltas[id].dy = 0;
5091        }
5092        mPointerGesture.referenceIdBits = mCurrentFingerIdBits;
5093
5094        // Add delta for all fingers and calculate a common movement delta.
5095        float commonDeltaX = 0, commonDeltaY = 0;
5096        BitSet32 commonIdBits(mLastFingerIdBits.value
5097                & mCurrentFingerIdBits.value);
5098        for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5099            bool first = (idBits == commonIdBits);
5100            uint32_t id = idBits.clearFirstMarkedBit();
5101            const RawPointerData::Pointer& cpd = mCurrentRawPointerData.pointerForId(id);
5102            const RawPointerData::Pointer& lpd = mLastRawPointerData.pointerForId(id);
5103            PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5104            delta.dx += cpd.x - lpd.x;
5105            delta.dy += cpd.y - lpd.y;
5106
5107            if (first) {
5108                commonDeltaX = delta.dx;
5109                commonDeltaY = delta.dy;
5110            } else {
5111                commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5112                commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5113            }
5114        }
5115
5116        // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5117        if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5118            float dist[MAX_POINTER_ID + 1];
5119            int32_t distOverThreshold = 0;
5120            for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5121                uint32_t id = idBits.clearFirstMarkedBit();
5122                PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5123                dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5124                        delta.dy * mPointerYZoomScale);
5125                if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5126                    distOverThreshold += 1;
5127                }
5128            }
5129
5130            // Only transition when at least two pointers have moved further than
5131            // the minimum distance threshold.
5132            if (distOverThreshold >= 2) {
5133                if (currentFingerCount > 2) {
5134                    // There are more than two pointers, switch to FREEFORM.
5135#if DEBUG_GESTURES
5136                    ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5137                            currentFingerCount);
5138#endif
5139                    *outCancelPreviousGesture = true;
5140                    mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5141                } else {
5142                    // There are exactly two pointers.
5143                    BitSet32 idBits(mCurrentFingerIdBits);
5144                    uint32_t id1 = idBits.clearFirstMarkedBit();
5145                    uint32_t id2 = idBits.firstMarkedBit();
5146                    const RawPointerData::Pointer& p1 = mCurrentRawPointerData.pointerForId(id1);
5147                    const RawPointerData::Pointer& p2 = mCurrentRawPointerData.pointerForId(id2);
5148                    float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5149                    if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5150                        // There are two pointers but they are too far apart for a SWIPE,
5151                        // switch to FREEFORM.
5152#if DEBUG_GESTURES
5153                        ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5154                                mutualDistance, mPointerGestureMaxSwipeWidth);
5155#endif
5156                        *outCancelPreviousGesture = true;
5157                        mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5158                    } else {
5159                        // There are two pointers.  Wait for both pointers to start moving
5160                        // before deciding whether this is a SWIPE or FREEFORM gesture.
5161                        float dist1 = dist[id1];
5162                        float dist2 = dist[id2];
5163                        if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5164                                && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5165                            // Calculate the dot product of the displacement vectors.
5166                            // When the vectors are oriented in approximately the same direction,
5167                            // the angle betweeen them is near zero and the cosine of the angle
5168                            // approches 1.0.  Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5169                            PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5170                            PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5171                            float dx1 = delta1.dx * mPointerXZoomScale;
5172                            float dy1 = delta1.dy * mPointerYZoomScale;
5173                            float dx2 = delta2.dx * mPointerXZoomScale;
5174                            float dy2 = delta2.dy * mPointerYZoomScale;
5175                            float dot = dx1 * dx2 + dy1 * dy2;
5176                            float cosine = dot / (dist1 * dist2); // denominator always > 0
5177                            if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5178                                // Pointers are moving in the same direction.  Switch to SWIPE.
5179#if DEBUG_GESTURES
5180                                ALOGD("Gestures: PRESS transitioned to SWIPE, "
5181                                        "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5182                                        "cosine %0.3f >= %0.3f",
5183                                        dist1, mConfig.pointerGestureMultitouchMinDistance,
5184                                        dist2, mConfig.pointerGestureMultitouchMinDistance,
5185                                        cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5186#endif
5187                                mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5188                            } else {
5189                                // Pointers are moving in different directions.  Switch to FREEFORM.
5190#if DEBUG_GESTURES
5191                                ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5192                                        "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5193                                        "cosine %0.3f < %0.3f",
5194                                        dist1, mConfig.pointerGestureMultitouchMinDistance,
5195                                        dist2, mConfig.pointerGestureMultitouchMinDistance,
5196                                        cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5197#endif
5198                                *outCancelPreviousGesture = true;
5199                                mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5200                            }
5201                        }
5202                    }
5203                }
5204            }
5205        } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5206            // Switch from SWIPE to FREEFORM if additional pointers go down.
5207            // Cancel previous gesture.
5208            if (currentFingerCount > 2) {
5209#if DEBUG_GESTURES
5210                ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5211                        currentFingerCount);
5212#endif
5213                *outCancelPreviousGesture = true;
5214                mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5215            }
5216        }
5217
5218        // Move the reference points based on the overall group motion of the fingers
5219        // except in PRESS mode while waiting for a transition to occur.
5220        if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5221                && (commonDeltaX || commonDeltaY)) {
5222            for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5223                uint32_t id = idBits.clearFirstMarkedBit();
5224                PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5225                delta.dx = 0;
5226                delta.dy = 0;
5227            }
5228
5229            mPointerGesture.referenceTouchX += commonDeltaX;
5230            mPointerGesture.referenceTouchY += commonDeltaY;
5231
5232            commonDeltaX *= mPointerXMovementScale;
5233            commonDeltaY *= mPointerYMovementScale;
5234
5235            rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5236            mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5237
5238            mPointerGesture.referenceGestureX += commonDeltaX;
5239            mPointerGesture.referenceGestureY += commonDeltaY;
5240        }
5241
5242        // Report gestures.
5243        if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5244                || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5245            // PRESS or SWIPE mode.
5246#if DEBUG_GESTURES
5247            ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5248                    "activeGestureId=%d, currentTouchPointerCount=%d",
5249                    activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5250#endif
5251            ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5252
5253            mPointerGesture.currentGestureIdBits.clear();
5254            mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5255            mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5256            mPointerGesture.currentGestureProperties[0].clear();
5257            mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5258            mPointerGesture.currentGestureProperties[0].toolType =
5259                    AMOTION_EVENT_TOOL_TYPE_FINGER;
5260            mPointerGesture.currentGestureCoords[0].clear();
5261            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5262                    mPointerGesture.referenceGestureX);
5263            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5264                    mPointerGesture.referenceGestureY);
5265            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5266        } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5267            // FREEFORM mode.
5268#if DEBUG_GESTURES
5269            ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5270                    "activeGestureId=%d, currentTouchPointerCount=%d",
5271                    activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5272#endif
5273            ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5274
5275            mPointerGesture.currentGestureIdBits.clear();
5276
5277            BitSet32 mappedTouchIdBits;
5278            BitSet32 usedGestureIdBits;
5279            if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5280                // Initially, assign the active gesture id to the active touch point
5281                // if there is one.  No other touch id bits are mapped yet.
5282                if (!*outCancelPreviousGesture) {
5283                    mappedTouchIdBits.markBit(activeTouchId);
5284                    usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
5285                    mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
5286                            mPointerGesture.activeGestureId;
5287                } else {
5288                    mPointerGesture.activeGestureId = -1;
5289                }
5290            } else {
5291                // Otherwise, assume we mapped all touches from the previous frame.
5292                // Reuse all mappings that are still applicable.
5293                mappedTouchIdBits.value = mLastFingerIdBits.value
5294                        & mCurrentFingerIdBits.value;
5295                usedGestureIdBits = mPointerGesture.lastGestureIdBits;
5296
5297                // Check whether we need to choose a new active gesture id because the
5298                // current went went up.
5299                for (BitSet32 upTouchIdBits(mLastFingerIdBits.value
5300                        & ~mCurrentFingerIdBits.value);
5301                        !upTouchIdBits.isEmpty(); ) {
5302                    uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
5303                    uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
5304                    if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
5305                        mPointerGesture.activeGestureId = -1;
5306                        break;
5307                    }
5308                }
5309            }
5310
5311#if DEBUG_GESTURES
5312            ALOGD("Gestures: FREEFORM follow up "
5313                    "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
5314                    "activeGestureId=%d",
5315                    mappedTouchIdBits.value, usedGestureIdBits.value,
5316                    mPointerGesture.activeGestureId);
5317#endif
5318
5319            BitSet32 idBits(mCurrentFingerIdBits);
5320            for (uint32_t i = 0; i < currentFingerCount; i++) {
5321                uint32_t touchId = idBits.clearFirstMarkedBit();
5322                uint32_t gestureId;
5323                if (!mappedTouchIdBits.hasBit(touchId)) {
5324                    gestureId = usedGestureIdBits.markFirstUnmarkedBit();
5325                    mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
5326#if DEBUG_GESTURES
5327                    ALOGD("Gestures: FREEFORM "
5328                            "new mapping for touch id %d -> gesture id %d",
5329                            touchId, gestureId);
5330#endif
5331                } else {
5332                    gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
5333#if DEBUG_GESTURES
5334                    ALOGD("Gestures: FREEFORM "
5335                            "existing mapping for touch id %d -> gesture id %d",
5336                            touchId, gestureId);
5337#endif
5338                }
5339                mPointerGesture.currentGestureIdBits.markBit(gestureId);
5340                mPointerGesture.currentGestureIdToIndex[gestureId] = i;
5341
5342                const RawPointerData::Pointer& pointer =
5343                        mCurrentRawPointerData.pointerForId(touchId);
5344                float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
5345                        * mPointerXZoomScale;
5346                float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
5347                        * mPointerYZoomScale;
5348                rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5349
5350                mPointerGesture.currentGestureProperties[i].clear();
5351                mPointerGesture.currentGestureProperties[i].id = gestureId;
5352                mPointerGesture.currentGestureProperties[i].toolType =
5353                        AMOTION_EVENT_TOOL_TYPE_FINGER;
5354                mPointerGesture.currentGestureCoords[i].clear();
5355                mPointerGesture.currentGestureCoords[i].setAxisValue(
5356                        AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
5357                mPointerGesture.currentGestureCoords[i].setAxisValue(
5358                        AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
5359                mPointerGesture.currentGestureCoords[i].setAxisValue(
5360                        AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5361            }
5362
5363            if (mPointerGesture.activeGestureId < 0) {
5364                mPointerGesture.activeGestureId =
5365                        mPointerGesture.currentGestureIdBits.firstMarkedBit();
5366#if DEBUG_GESTURES
5367                ALOGD("Gestures: FREEFORM new "
5368                        "activeGestureId=%d", mPointerGesture.activeGestureId);
5369#endif
5370            }
5371        }
5372    }
5373
5374    mPointerController->setButtonState(mCurrentButtonState);
5375
5376#if DEBUG_GESTURES
5377    ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
5378            "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
5379            "lastGestureMode=%d, lastGestureIdBits=0x%08x",
5380            toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
5381            mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
5382            mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
5383    for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
5384        uint32_t id = idBits.clearFirstMarkedBit();
5385        uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5386        const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
5387        const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
5388        ALOGD("  currentGesture[%d]: index=%d, toolType=%d, "
5389                "x=%0.3f, y=%0.3f, pressure=%0.3f",
5390                id, index, properties.toolType,
5391                coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5392                coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5393                coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5394    }
5395    for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
5396        uint32_t id = idBits.clearFirstMarkedBit();
5397        uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
5398        const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
5399        const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
5400        ALOGD("  lastGesture[%d]: index=%d, toolType=%d, "
5401                "x=%0.3f, y=%0.3f, pressure=%0.3f",
5402                id, index, properties.toolType,
5403                coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5404                coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5405                coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5406    }
5407#endif
5408    return true;
5409}
5410
5411void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
5412    mPointerSimple.currentCoords.clear();
5413    mPointerSimple.currentProperties.clear();
5414
5415    bool down, hovering;
5416    if (!mCurrentStylusIdBits.isEmpty()) {
5417        uint32_t id = mCurrentStylusIdBits.firstMarkedBit();
5418        uint32_t index = mCurrentCookedPointerData.idToIndex[id];
5419        float x = mCurrentCookedPointerData.pointerCoords[index].getX();
5420        float y = mCurrentCookedPointerData.pointerCoords[index].getY();
5421        mPointerController->setPosition(x, y);
5422
5423        hovering = mCurrentCookedPointerData.hoveringIdBits.hasBit(id);
5424        down = !hovering;
5425
5426        mPointerController->getPosition(&x, &y);
5427        mPointerSimple.currentCoords.copyFrom(mCurrentCookedPointerData.pointerCoords[index]);
5428        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5429        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5430        mPointerSimple.currentProperties.id = 0;
5431        mPointerSimple.currentProperties.toolType =
5432                mCurrentCookedPointerData.pointerProperties[index].toolType;
5433    } else {
5434        down = false;
5435        hovering = false;
5436    }
5437
5438    dispatchPointerSimple(when, policyFlags, down, hovering);
5439}
5440
5441void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
5442    abortPointerSimple(when, policyFlags);
5443}
5444
5445void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
5446    mPointerSimple.currentCoords.clear();
5447    mPointerSimple.currentProperties.clear();
5448
5449    bool down, hovering;
5450    if (!mCurrentMouseIdBits.isEmpty()) {
5451        uint32_t id = mCurrentMouseIdBits.firstMarkedBit();
5452        uint32_t currentIndex = mCurrentRawPointerData.idToIndex[id];
5453        if (mLastMouseIdBits.hasBit(id)) {
5454            uint32_t lastIndex = mCurrentRawPointerData.idToIndex[id];
5455            float deltaX = (mCurrentRawPointerData.pointers[currentIndex].x
5456                    - mLastRawPointerData.pointers[lastIndex].x)
5457                    * mPointerXMovementScale;
5458            float deltaY = (mCurrentRawPointerData.pointers[currentIndex].y
5459                    - mLastRawPointerData.pointers[lastIndex].y)
5460                    * mPointerYMovementScale;
5461
5462            rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5463            mPointerVelocityControl.move(when, &deltaX, &deltaY);
5464
5465            mPointerController->move(deltaX, deltaY);
5466        } else {
5467            mPointerVelocityControl.reset();
5468        }
5469
5470        down = isPointerDown(mCurrentButtonState);
5471        hovering = !down;
5472
5473        float x, y;
5474        mPointerController->getPosition(&x, &y);
5475        mPointerSimple.currentCoords.copyFrom(
5476                mCurrentCookedPointerData.pointerCoords[currentIndex]);
5477        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5478        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5479        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5480                hovering ? 0.0f : 1.0f);
5481        mPointerSimple.currentProperties.id = 0;
5482        mPointerSimple.currentProperties.toolType =
5483                mCurrentCookedPointerData.pointerProperties[currentIndex].toolType;
5484    } else {
5485        mPointerVelocityControl.reset();
5486
5487        down = false;
5488        hovering = false;
5489    }
5490
5491    dispatchPointerSimple(when, policyFlags, down, hovering);
5492}
5493
5494void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
5495    abortPointerSimple(when, policyFlags);
5496
5497    mPointerVelocityControl.reset();
5498}
5499
5500void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
5501        bool down, bool hovering) {
5502    int32_t metaState = getContext()->getGlobalMetaState();
5503
5504    if (mPointerController != NULL) {
5505        if (down || hovering) {
5506            mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5507            mPointerController->clearSpots();
5508            mPointerController->setButtonState(mCurrentButtonState);
5509            mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5510        } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
5511            mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5512        }
5513    }
5514
5515    if (mPointerSimple.down && !down) {
5516        mPointerSimple.down = false;
5517
5518        // Send up.
5519        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5520                 AMOTION_EVENT_ACTION_UP, 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 (mPointerSimple.hovering && !hovering) {
5529        mPointerSimple.hovering = false;
5530
5531        // Send hover exit.
5532        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5533                AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0,
5534                mViewport.displayId,
5535                1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
5536                mOrientedXPrecision, mOrientedYPrecision,
5537                mPointerSimple.downTime);
5538        getListener()->notifyMotion(&args);
5539    }
5540
5541    if (down) {
5542        if (!mPointerSimple.down) {
5543            mPointerSimple.down = true;
5544            mPointerSimple.downTime = when;
5545
5546            // Send down.
5547            NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5548                    AMOTION_EVENT_ACTION_DOWN, 0, metaState, mCurrentButtonState, 0,
5549                    mViewport.displayId,
5550                    1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5551                    mOrientedXPrecision, mOrientedYPrecision,
5552                    mPointerSimple.downTime);
5553            getListener()->notifyMotion(&args);
5554        }
5555
5556        // Send move.
5557        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5558                AMOTION_EVENT_ACTION_MOVE, 0, metaState, mCurrentButtonState, 0,
5559                mViewport.displayId,
5560                1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5561                mOrientedXPrecision, mOrientedYPrecision,
5562                mPointerSimple.downTime);
5563        getListener()->notifyMotion(&args);
5564    }
5565
5566    if (hovering) {
5567        if (!mPointerSimple.hovering) {
5568            mPointerSimple.hovering = true;
5569
5570            // Send hover enter.
5571            NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5572                    AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0,
5573                    mViewport.displayId,
5574                    1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5575                    mOrientedXPrecision, mOrientedYPrecision,
5576                    mPointerSimple.downTime);
5577            getListener()->notifyMotion(&args);
5578        }
5579
5580        // Send hover move.
5581        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5582                AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0,
5583                mViewport.displayId,
5584                1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
5585                mOrientedXPrecision, mOrientedYPrecision,
5586                mPointerSimple.downTime);
5587        getListener()->notifyMotion(&args);
5588    }
5589
5590    if (mCurrentRawVScroll || mCurrentRawHScroll) {
5591        float vscroll = mCurrentRawVScroll;
5592        float hscroll = mCurrentRawHScroll;
5593        mWheelYVelocityControl.move(when, NULL, &vscroll);
5594        mWheelXVelocityControl.move(when, &hscroll, NULL);
5595
5596        // Send scroll.
5597        PointerCoords pointerCoords;
5598        pointerCoords.copyFrom(mPointerSimple.currentCoords);
5599        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
5600        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
5601
5602        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5603                AMOTION_EVENT_ACTION_SCROLL, 0, metaState, mCurrentButtonState, 0,
5604                mViewport.displayId,
5605                1, &mPointerSimple.currentProperties, &pointerCoords,
5606                mOrientedXPrecision, mOrientedYPrecision,
5607                mPointerSimple.downTime);
5608        getListener()->notifyMotion(&args);
5609    }
5610
5611    // Save state.
5612    if (down || hovering) {
5613        mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
5614        mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
5615    } else {
5616        mPointerSimple.reset();
5617    }
5618}
5619
5620void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
5621    mPointerSimple.currentCoords.clear();
5622    mPointerSimple.currentProperties.clear();
5623
5624    dispatchPointerSimple(when, policyFlags, false, false);
5625}
5626
5627void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
5628        int32_t action, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
5629        const PointerProperties* properties, const PointerCoords* coords,
5630        const uint32_t* idToIndex, BitSet32 idBits,
5631        int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
5632    PointerCoords pointerCoords[MAX_POINTERS];
5633    PointerProperties pointerProperties[MAX_POINTERS];
5634    uint32_t pointerCount = 0;
5635    while (!idBits.isEmpty()) {
5636        uint32_t id = idBits.clearFirstMarkedBit();
5637        uint32_t index = idToIndex[id];
5638        pointerProperties[pointerCount].copyFrom(properties[index]);
5639        pointerCoords[pointerCount].copyFrom(coords[index]);
5640
5641        if (changedId >= 0 && id == uint32_t(changedId)) {
5642            action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
5643        }
5644
5645        pointerCount += 1;
5646    }
5647
5648    ALOG_ASSERT(pointerCount != 0);
5649
5650    if (changedId >= 0 && pointerCount == 1) {
5651        // Replace initial down and final up action.
5652        // We can compare the action without masking off the changed pointer index
5653        // because we know the index is 0.
5654        if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
5655            action = AMOTION_EVENT_ACTION_DOWN;
5656        } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
5657            action = AMOTION_EVENT_ACTION_UP;
5658        } else {
5659            // Can't happen.
5660            ALOG_ASSERT(false);
5661        }
5662    }
5663
5664    NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
5665            action, flags, metaState, buttonState, edgeFlags,
5666            mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
5667            xPrecision, yPrecision, downTime);
5668    getListener()->notifyMotion(&args);
5669}
5670
5671bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
5672        const PointerCoords* inCoords, const uint32_t* inIdToIndex,
5673        PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
5674        BitSet32 idBits) const {
5675    bool changed = false;
5676    while (!idBits.isEmpty()) {
5677        uint32_t id = idBits.clearFirstMarkedBit();
5678        uint32_t inIndex = inIdToIndex[id];
5679        uint32_t outIndex = outIdToIndex[id];
5680
5681        const PointerProperties& curInProperties = inProperties[inIndex];
5682        const PointerCoords& curInCoords = inCoords[inIndex];
5683        PointerProperties& curOutProperties = outProperties[outIndex];
5684        PointerCoords& curOutCoords = outCoords[outIndex];
5685
5686        if (curInProperties != curOutProperties) {
5687            curOutProperties.copyFrom(curInProperties);
5688            changed = true;
5689        }
5690
5691        if (curInCoords != curOutCoords) {
5692            curOutCoords.copyFrom(curInCoords);
5693            changed = true;
5694        }
5695    }
5696    return changed;
5697}
5698
5699void TouchInputMapper::fadePointer() {
5700    if (mPointerController != NULL) {
5701        mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5702    }
5703}
5704
5705bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
5706    return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
5707            && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
5708}
5709
5710const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
5711        int32_t x, int32_t y) {
5712    size_t numVirtualKeys = mVirtualKeys.size();
5713    for (size_t i = 0; i < numVirtualKeys; i++) {
5714        const VirtualKey& virtualKey = mVirtualKeys[i];
5715
5716#if DEBUG_VIRTUAL_KEYS
5717        ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
5718                "left=%d, top=%d, right=%d, bottom=%d",
5719                x, y,
5720                virtualKey.keyCode, virtualKey.scanCode,
5721                virtualKey.hitLeft, virtualKey.hitTop,
5722                virtualKey.hitRight, virtualKey.hitBottom);
5723#endif
5724
5725        if (virtualKey.isHit(x, y)) {
5726            return & virtualKey;
5727        }
5728    }
5729
5730    return NULL;
5731}
5732
5733void TouchInputMapper::assignPointerIds() {
5734    uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount;
5735    uint32_t lastPointerCount = mLastRawPointerData.pointerCount;
5736
5737    mCurrentRawPointerData.clearIdBits();
5738
5739    if (currentPointerCount == 0) {
5740        // No pointers to assign.
5741        return;
5742    }
5743
5744    if (lastPointerCount == 0) {
5745        // All pointers are new.
5746        for (uint32_t i = 0; i < currentPointerCount; i++) {
5747            uint32_t id = i;
5748            mCurrentRawPointerData.pointers[i].id = id;
5749            mCurrentRawPointerData.idToIndex[id] = i;
5750            mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(i));
5751        }
5752        return;
5753    }
5754
5755    if (currentPointerCount == 1 && lastPointerCount == 1
5756            && mCurrentRawPointerData.pointers[0].toolType
5757                    == mLastRawPointerData.pointers[0].toolType) {
5758        // Only one pointer and no change in count so it must have the same id as before.
5759        uint32_t id = mLastRawPointerData.pointers[0].id;
5760        mCurrentRawPointerData.pointers[0].id = id;
5761        mCurrentRawPointerData.idToIndex[id] = 0;
5762        mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(0));
5763        return;
5764    }
5765
5766    // General case.
5767    // We build a heap of squared euclidean distances between current and last pointers
5768    // associated with the current and last pointer indices.  Then, we find the best
5769    // match (by distance) for each current pointer.
5770    // The pointers must have the same tool type but it is possible for them to
5771    // transition from hovering to touching or vice-versa while retaining the same id.
5772    PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
5773
5774    uint32_t heapSize = 0;
5775    for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
5776            currentPointerIndex++) {
5777        for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
5778                lastPointerIndex++) {
5779            const RawPointerData::Pointer& currentPointer =
5780                    mCurrentRawPointerData.pointers[currentPointerIndex];
5781            const RawPointerData::Pointer& lastPointer =
5782                    mLastRawPointerData.pointers[lastPointerIndex];
5783            if (currentPointer.toolType == lastPointer.toolType) {
5784                int64_t deltaX = currentPointer.x - lastPointer.x;
5785                int64_t deltaY = currentPointer.y - lastPointer.y;
5786
5787                uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
5788
5789                // Insert new element into the heap (sift up).
5790                heap[heapSize].currentPointerIndex = currentPointerIndex;
5791                heap[heapSize].lastPointerIndex = lastPointerIndex;
5792                heap[heapSize].distance = distance;
5793                heapSize += 1;
5794            }
5795        }
5796    }
5797
5798    // Heapify
5799    for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
5800        startIndex -= 1;
5801        for (uint32_t parentIndex = startIndex; ;) {
5802            uint32_t childIndex = parentIndex * 2 + 1;
5803            if (childIndex >= heapSize) {
5804                break;
5805            }
5806
5807            if (childIndex + 1 < heapSize
5808                    && heap[childIndex + 1].distance < heap[childIndex].distance) {
5809                childIndex += 1;
5810            }
5811
5812            if (heap[parentIndex].distance <= heap[childIndex].distance) {
5813                break;
5814            }
5815
5816            swap(heap[parentIndex], heap[childIndex]);
5817            parentIndex = childIndex;
5818        }
5819    }
5820
5821#if DEBUG_POINTER_ASSIGNMENT
5822    ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
5823    for (size_t i = 0; i < heapSize; i++) {
5824        ALOGD("  heap[%d]: cur=%d, last=%d, distance=%lld",
5825                i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
5826                heap[i].distance);
5827    }
5828#endif
5829
5830    // Pull matches out by increasing order of distance.
5831    // To avoid reassigning pointers that have already been matched, the loop keeps track
5832    // of which last and current pointers have been matched using the matchedXXXBits variables.
5833    // It also tracks the used pointer id bits.
5834    BitSet32 matchedLastBits(0);
5835    BitSet32 matchedCurrentBits(0);
5836    BitSet32 usedIdBits(0);
5837    bool first = true;
5838    for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
5839        while (heapSize > 0) {
5840            if (first) {
5841                // The first time through the loop, we just consume the root element of
5842                // the heap (the one with smallest distance).
5843                first = false;
5844            } else {
5845                // Previous iterations consumed the root element of the heap.
5846                // Pop root element off of the heap (sift down).
5847                heap[0] = heap[heapSize];
5848                for (uint32_t parentIndex = 0; ;) {
5849                    uint32_t childIndex = parentIndex * 2 + 1;
5850                    if (childIndex >= heapSize) {
5851                        break;
5852                    }
5853
5854                    if (childIndex + 1 < heapSize
5855                            && heap[childIndex + 1].distance < heap[childIndex].distance) {
5856                        childIndex += 1;
5857                    }
5858
5859                    if (heap[parentIndex].distance <= heap[childIndex].distance) {
5860                        break;
5861                    }
5862
5863                    swap(heap[parentIndex], heap[childIndex]);
5864                    parentIndex = childIndex;
5865                }
5866
5867#if DEBUG_POINTER_ASSIGNMENT
5868                ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
5869                for (size_t i = 0; i < heapSize; i++) {
5870                    ALOGD("  heap[%d]: cur=%d, last=%d, distance=%lld",
5871                            i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
5872                            heap[i].distance);
5873                }
5874#endif
5875            }
5876
5877            heapSize -= 1;
5878
5879            uint32_t currentPointerIndex = heap[0].currentPointerIndex;
5880            if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
5881
5882            uint32_t lastPointerIndex = heap[0].lastPointerIndex;
5883            if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
5884
5885            matchedCurrentBits.markBit(currentPointerIndex);
5886            matchedLastBits.markBit(lastPointerIndex);
5887
5888            uint32_t id = mLastRawPointerData.pointers[lastPointerIndex].id;
5889            mCurrentRawPointerData.pointers[currentPointerIndex].id = id;
5890            mCurrentRawPointerData.idToIndex[id] = currentPointerIndex;
5891            mCurrentRawPointerData.markIdBit(id,
5892                    mCurrentRawPointerData.isHovering(currentPointerIndex));
5893            usedIdBits.markBit(id);
5894
5895#if DEBUG_POINTER_ASSIGNMENT
5896            ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
5897                    lastPointerIndex, currentPointerIndex, id, heap[0].distance);
5898#endif
5899            break;
5900        }
5901    }
5902
5903    // Assign fresh ids to pointers that were not matched in the process.
5904    for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
5905        uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
5906        uint32_t id = usedIdBits.markFirstUnmarkedBit();
5907
5908        mCurrentRawPointerData.pointers[currentPointerIndex].id = id;
5909        mCurrentRawPointerData.idToIndex[id] = currentPointerIndex;
5910        mCurrentRawPointerData.markIdBit(id,
5911                mCurrentRawPointerData.isHovering(currentPointerIndex));
5912
5913#if DEBUG_POINTER_ASSIGNMENT
5914        ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
5915                currentPointerIndex, id);
5916#endif
5917    }
5918}
5919
5920int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
5921    if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
5922        return AKEY_STATE_VIRTUAL;
5923    }
5924
5925    size_t numVirtualKeys = mVirtualKeys.size();
5926    for (size_t i = 0; i < numVirtualKeys; i++) {
5927        const VirtualKey& virtualKey = mVirtualKeys[i];
5928        if (virtualKey.keyCode == keyCode) {
5929            return AKEY_STATE_UP;
5930        }
5931    }
5932
5933    return AKEY_STATE_UNKNOWN;
5934}
5935
5936int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
5937    if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
5938        return AKEY_STATE_VIRTUAL;
5939    }
5940
5941    size_t numVirtualKeys = mVirtualKeys.size();
5942    for (size_t i = 0; i < numVirtualKeys; i++) {
5943        const VirtualKey& virtualKey = mVirtualKeys[i];
5944        if (virtualKey.scanCode == scanCode) {
5945            return AKEY_STATE_UP;
5946        }
5947    }
5948
5949    return AKEY_STATE_UNKNOWN;
5950}
5951
5952bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
5953        const int32_t* keyCodes, uint8_t* outFlags) {
5954    size_t numVirtualKeys = mVirtualKeys.size();
5955    for (size_t i = 0; i < numVirtualKeys; i++) {
5956        const VirtualKey& virtualKey = mVirtualKeys[i];
5957
5958        for (size_t i = 0; i < numCodes; i++) {
5959            if (virtualKey.keyCode == keyCodes[i]) {
5960                outFlags[i] = 1;
5961            }
5962        }
5963    }
5964
5965    return true;
5966}
5967
5968
5969// --- SingleTouchInputMapper ---
5970
5971SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
5972        TouchInputMapper(device) {
5973}
5974
5975SingleTouchInputMapper::~SingleTouchInputMapper() {
5976}
5977
5978void SingleTouchInputMapper::reset(nsecs_t when) {
5979    mSingleTouchMotionAccumulator.reset(getDevice());
5980
5981    TouchInputMapper::reset(when);
5982}
5983
5984void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
5985    TouchInputMapper::process(rawEvent);
5986
5987    mSingleTouchMotionAccumulator.process(rawEvent);
5988}
5989
5990void SingleTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) {
5991    if (mTouchButtonAccumulator.isToolActive()) {
5992        mCurrentRawPointerData.pointerCount = 1;
5993        mCurrentRawPointerData.idToIndex[0] = 0;
5994
5995        bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
5996                && (mTouchButtonAccumulator.isHovering()
5997                        || (mRawPointerAxes.pressure.valid
5998                                && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
5999        mCurrentRawPointerData.markIdBit(0, isHovering);
6000
6001        RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[0];
6002        outPointer.id = 0;
6003        outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6004        outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6005        outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6006        outPointer.touchMajor = 0;
6007        outPointer.touchMinor = 0;
6008        outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6009        outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6010        outPointer.orientation = 0;
6011        outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6012        outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6013        outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6014        outPointer.toolType = mTouchButtonAccumulator.getToolType();
6015        if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6016            outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6017        }
6018        outPointer.isHovering = isHovering;
6019    }
6020}
6021
6022void SingleTouchInputMapper::configureRawPointerAxes() {
6023    TouchInputMapper::configureRawPointerAxes();
6024
6025    getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6026    getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6027    getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6028    getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6029    getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6030    getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6031    getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6032}
6033
6034bool SingleTouchInputMapper::hasStylus() const {
6035    return mTouchButtonAccumulator.hasStylus();
6036}
6037
6038
6039// --- MultiTouchInputMapper ---
6040
6041MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6042        TouchInputMapper(device) {
6043}
6044
6045MultiTouchInputMapper::~MultiTouchInputMapper() {
6046}
6047
6048void MultiTouchInputMapper::reset(nsecs_t when) {
6049    mMultiTouchMotionAccumulator.reset(getDevice());
6050
6051    mPointerIdBits.clear();
6052
6053    TouchInputMapper::reset(when);
6054}
6055
6056void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6057    TouchInputMapper::process(rawEvent);
6058
6059    mMultiTouchMotionAccumulator.process(rawEvent);
6060}
6061
6062void MultiTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) {
6063    size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6064    size_t outCount = 0;
6065    BitSet32 newPointerIdBits;
6066
6067    for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6068        const MultiTouchMotionAccumulator::Slot* inSlot =
6069                mMultiTouchMotionAccumulator.getSlot(inIndex);
6070        if (!inSlot->isInUse()) {
6071            continue;
6072        }
6073
6074        if (outCount >= MAX_POINTERS) {
6075#if DEBUG_POINTERS
6076            ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6077                    "ignoring the rest.",
6078                    getDeviceName().string(), MAX_POINTERS);
6079#endif
6080            break; // too many fingers!
6081        }
6082
6083        RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[outCount];
6084        outPointer.x = inSlot->getX();
6085        outPointer.y = inSlot->getY();
6086        outPointer.pressure = inSlot->getPressure();
6087        outPointer.touchMajor = inSlot->getTouchMajor();
6088        outPointer.touchMinor = inSlot->getTouchMinor();
6089        outPointer.toolMajor = inSlot->getToolMajor();
6090        outPointer.toolMinor = inSlot->getToolMinor();
6091        outPointer.orientation = inSlot->getOrientation();
6092        outPointer.distance = inSlot->getDistance();
6093        outPointer.tiltX = 0;
6094        outPointer.tiltY = 0;
6095
6096        outPointer.toolType = inSlot->getToolType();
6097        if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6098            outPointer.toolType = mTouchButtonAccumulator.getToolType();
6099            if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6100                outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6101            }
6102        }
6103
6104        bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6105                && (mTouchButtonAccumulator.isHovering()
6106                        || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6107        outPointer.isHovering = isHovering;
6108
6109        // Assign pointer id using tracking id if available.
6110        if (*outHavePointerIds) {
6111            int32_t trackingId = inSlot->getTrackingId();
6112            int32_t id = -1;
6113            if (trackingId >= 0) {
6114                for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6115                    uint32_t n = idBits.clearFirstMarkedBit();
6116                    if (mPointerTrackingIdMap[n] == trackingId) {
6117                        id = n;
6118                    }
6119                }
6120
6121                if (id < 0 && !mPointerIdBits.isFull()) {
6122                    id = mPointerIdBits.markFirstUnmarkedBit();
6123                    mPointerTrackingIdMap[id] = trackingId;
6124                }
6125            }
6126            if (id < 0) {
6127                *outHavePointerIds = false;
6128                mCurrentRawPointerData.clearIdBits();
6129                newPointerIdBits.clear();
6130            } else {
6131                outPointer.id = id;
6132                mCurrentRawPointerData.idToIndex[id] = outCount;
6133                mCurrentRawPointerData.markIdBit(id, isHovering);
6134                newPointerIdBits.markBit(id);
6135            }
6136        }
6137
6138        outCount += 1;
6139    }
6140
6141    mCurrentRawPointerData.pointerCount = outCount;
6142    mPointerIdBits = newPointerIdBits;
6143
6144    mMultiTouchMotionAccumulator.finishSync();
6145}
6146
6147void MultiTouchInputMapper::configureRawPointerAxes() {
6148    TouchInputMapper::configureRawPointerAxes();
6149
6150    getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6151    getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6152    getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6153    getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6154    getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6155    getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6156    getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6157    getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6158    getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6159    getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6160    getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6161
6162    if (mRawPointerAxes.trackingId.valid
6163            && mRawPointerAxes.slot.valid
6164            && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6165        size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6166        if (slotCount > MAX_SLOTS) {
6167            ALOGW("MultiTouch Device %s reported %d slots but the framework "
6168                    "only supports a maximum of %d slots at this time.",
6169                    getDeviceName().string(), slotCount, MAX_SLOTS);
6170            slotCount = MAX_SLOTS;
6171        }
6172        mMultiTouchMotionAccumulator.configure(getDevice(),
6173                slotCount, true /*usingSlotsProtocol*/);
6174    } else {
6175        mMultiTouchMotionAccumulator.configure(getDevice(),
6176                MAX_POINTERS, false /*usingSlotsProtocol*/);
6177    }
6178}
6179
6180bool MultiTouchInputMapper::hasStylus() const {
6181    return mMultiTouchMotionAccumulator.hasStylus()
6182            || mTouchButtonAccumulator.hasStylus();
6183}
6184
6185
6186// --- JoystickInputMapper ---
6187
6188JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6189        InputMapper(device) {
6190}
6191
6192JoystickInputMapper::~JoystickInputMapper() {
6193}
6194
6195uint32_t JoystickInputMapper::getSources() {
6196    return AINPUT_SOURCE_JOYSTICK;
6197}
6198
6199void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6200    InputMapper::populateDeviceInfo(info);
6201
6202    for (size_t i = 0; i < mAxes.size(); i++) {
6203        const Axis& axis = mAxes.valueAt(i);
6204        addMotionRange(axis.axisInfo.axis, axis, info);
6205
6206        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6207            addMotionRange(axis.axisInfo.highAxis, axis, info);
6208
6209        }
6210    }
6211}
6212
6213void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
6214        InputDeviceInfo* info) {
6215    info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
6216            axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6217    /* In order to ease the transition for developers from using the old axes
6218     * to the newer, more semantically correct axes, we'll continue to register
6219     * the old axes as duplicates of their corresponding new ones.  */
6220    int32_t compatAxis = getCompatAxis(axisId);
6221    if (compatAxis >= 0) {
6222        info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
6223                axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6224    }
6225}
6226
6227/* A mapping from axes the joystick actually has to the axes that should be
6228 * artificially created for compatibility purposes.
6229 * Returns -1 if no compatibility axis is needed. */
6230int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
6231    switch(axis) {
6232    case AMOTION_EVENT_AXIS_LTRIGGER:
6233        return AMOTION_EVENT_AXIS_BRAKE;
6234    case AMOTION_EVENT_AXIS_RTRIGGER:
6235        return AMOTION_EVENT_AXIS_GAS;
6236    }
6237    return -1;
6238}
6239
6240void JoystickInputMapper::dump(String8& dump) {
6241    dump.append(INDENT2 "Joystick Input Mapper:\n");
6242
6243    dump.append(INDENT3 "Axes:\n");
6244    size_t numAxes = mAxes.size();
6245    for (size_t i = 0; i < numAxes; i++) {
6246        const Axis& axis = mAxes.valueAt(i);
6247        const char* label = getAxisLabel(axis.axisInfo.axis);
6248        if (label) {
6249            dump.appendFormat(INDENT4 "%s", label);
6250        } else {
6251            dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
6252        }
6253        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6254            label = getAxisLabel(axis.axisInfo.highAxis);
6255            if (label) {
6256                dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
6257            } else {
6258                dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
6259                        axis.axisInfo.splitValue);
6260            }
6261        } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
6262            dump.append(" (invert)");
6263        }
6264
6265        dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
6266                axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6267        dump.appendFormat(INDENT4 "  scale=%0.5f, offset=%0.5f, "
6268                "highScale=%0.5f, highOffset=%0.5f\n",
6269                axis.scale, axis.offset, axis.highScale, axis.highOffset);
6270        dump.appendFormat(INDENT4 "  rawAxis=%d, rawMin=%d, rawMax=%d, "
6271                "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
6272                mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
6273                axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
6274    }
6275}
6276
6277void JoystickInputMapper::configure(nsecs_t when,
6278        const InputReaderConfiguration* config, uint32_t changes) {
6279    InputMapper::configure(when, config, changes);
6280
6281    if (!changes) { // first time only
6282        // Collect all axes.
6283        for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
6284            if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
6285                    & INPUT_DEVICE_CLASS_JOYSTICK)) {
6286                continue; // axis must be claimed by a different device
6287            }
6288
6289            RawAbsoluteAxisInfo rawAxisInfo;
6290            getAbsoluteAxisInfo(abs, &rawAxisInfo);
6291            if (rawAxisInfo.valid) {
6292                // Map axis.
6293                AxisInfo axisInfo;
6294                bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
6295                if (!explicitlyMapped) {
6296                    // Axis is not explicitly mapped, will choose a generic axis later.
6297                    axisInfo.mode = AxisInfo::MODE_NORMAL;
6298                    axisInfo.axis = -1;
6299                }
6300
6301                // Apply flat override.
6302                int32_t rawFlat = axisInfo.flatOverride < 0
6303                        ? rawAxisInfo.flat : axisInfo.flatOverride;
6304
6305                // Calculate scaling factors and limits.
6306                Axis axis;
6307                if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
6308                    float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
6309                    float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
6310                    axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6311                            scale, 0.0f, highScale, 0.0f,
6312                            0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6313                            rawAxisInfo.resolution * scale);
6314                } else if (isCenteredAxis(axisInfo.axis)) {
6315                    float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6316                    float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
6317                    axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6318                            scale, offset, scale, offset,
6319                            -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6320                            rawAxisInfo.resolution * scale);
6321                } else {
6322                    float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6323                    axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6324                            scale, 0.0f, scale, 0.0f,
6325                            0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6326                            rawAxisInfo.resolution * scale);
6327                }
6328
6329                // To eliminate noise while the joystick is at rest, filter out small variations
6330                // in axis values up front.
6331                axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
6332
6333                mAxes.add(abs, axis);
6334            }
6335        }
6336
6337        // If there are too many axes, start dropping them.
6338        // Prefer to keep explicitly mapped axes.
6339        if (mAxes.size() > PointerCoords::MAX_AXES) {
6340            ALOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
6341                    getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
6342            pruneAxes(true);
6343            pruneAxes(false);
6344        }
6345
6346        // Assign generic axis ids to remaining axes.
6347        int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
6348        size_t numAxes = mAxes.size();
6349        for (size_t i = 0; i < numAxes; i++) {
6350            Axis& axis = mAxes.editValueAt(i);
6351            if (axis.axisInfo.axis < 0) {
6352                while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
6353                        && haveAxis(nextGenericAxisId)) {
6354                    nextGenericAxisId += 1;
6355                }
6356
6357                if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
6358                    axis.axisInfo.axis = nextGenericAxisId;
6359                    nextGenericAxisId += 1;
6360                } else {
6361                    ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
6362                            "have already been assigned to other axes.",
6363                            getDeviceName().string(), mAxes.keyAt(i));
6364                    mAxes.removeItemsAt(i--);
6365                    numAxes -= 1;
6366                }
6367            }
6368        }
6369    }
6370}
6371
6372bool JoystickInputMapper::haveAxis(int32_t axisId) {
6373    size_t numAxes = mAxes.size();
6374    for (size_t i = 0; i < numAxes; i++) {
6375        const Axis& axis = mAxes.valueAt(i);
6376        if (axis.axisInfo.axis == axisId
6377                || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
6378                        && axis.axisInfo.highAxis == axisId)) {
6379            return true;
6380        }
6381    }
6382    return false;
6383}
6384
6385void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
6386    size_t i = mAxes.size();
6387    while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
6388        if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
6389            continue;
6390        }
6391        ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
6392                getDeviceName().string(), mAxes.keyAt(i));
6393        mAxes.removeItemsAt(i);
6394    }
6395}
6396
6397bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
6398    switch (axis) {
6399    case AMOTION_EVENT_AXIS_X:
6400    case AMOTION_EVENT_AXIS_Y:
6401    case AMOTION_EVENT_AXIS_Z:
6402    case AMOTION_EVENT_AXIS_RX:
6403    case AMOTION_EVENT_AXIS_RY:
6404    case AMOTION_EVENT_AXIS_RZ:
6405    case AMOTION_EVENT_AXIS_HAT_X:
6406    case AMOTION_EVENT_AXIS_HAT_Y:
6407    case AMOTION_EVENT_AXIS_ORIENTATION:
6408    case AMOTION_EVENT_AXIS_RUDDER:
6409    case AMOTION_EVENT_AXIS_WHEEL:
6410        return true;
6411    default:
6412        return false;
6413    }
6414}
6415
6416void JoystickInputMapper::reset(nsecs_t when) {
6417    // Recenter all axes.
6418    size_t numAxes = mAxes.size();
6419    for (size_t i = 0; i < numAxes; i++) {
6420        Axis& axis = mAxes.editValueAt(i);
6421        axis.resetValue();
6422    }
6423
6424    InputMapper::reset(when);
6425}
6426
6427void JoystickInputMapper::process(const RawEvent* rawEvent) {
6428    switch (rawEvent->type) {
6429    case EV_ABS: {
6430        ssize_t index = mAxes.indexOfKey(rawEvent->code);
6431        if (index >= 0) {
6432            Axis& axis = mAxes.editValueAt(index);
6433            float newValue, highNewValue;
6434            switch (axis.axisInfo.mode) {
6435            case AxisInfo::MODE_INVERT:
6436                newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
6437                        * axis.scale + axis.offset;
6438                highNewValue = 0.0f;
6439                break;
6440            case AxisInfo::MODE_SPLIT:
6441                if (rawEvent->value < axis.axisInfo.splitValue) {
6442                    newValue = (axis.axisInfo.splitValue - rawEvent->value)
6443                            * axis.scale + axis.offset;
6444                    highNewValue = 0.0f;
6445                } else if (rawEvent->value > axis.axisInfo.splitValue) {
6446                    newValue = 0.0f;
6447                    highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
6448                            * axis.highScale + axis.highOffset;
6449                } else {
6450                    newValue = 0.0f;
6451                    highNewValue = 0.0f;
6452                }
6453                break;
6454            default:
6455                newValue = rawEvent->value * axis.scale + axis.offset;
6456                highNewValue = 0.0f;
6457                break;
6458            }
6459            axis.newValue = newValue;
6460            axis.highNewValue = highNewValue;
6461        }
6462        break;
6463    }
6464
6465    case EV_SYN:
6466        switch (rawEvent->code) {
6467        case SYN_REPORT:
6468            sync(rawEvent->when, false /*force*/);
6469            break;
6470        }
6471        break;
6472    }
6473}
6474
6475void JoystickInputMapper::sync(nsecs_t when, bool force) {
6476    if (!filterAxes(force)) {
6477        return;
6478    }
6479
6480    int32_t metaState = mContext->getGlobalMetaState();
6481    int32_t buttonState = 0;
6482
6483    PointerProperties pointerProperties;
6484    pointerProperties.clear();
6485    pointerProperties.id = 0;
6486    pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
6487
6488    PointerCoords pointerCoords;
6489    pointerCoords.clear();
6490
6491    size_t numAxes = mAxes.size();
6492    for (size_t i = 0; i < numAxes; i++) {
6493        const Axis& axis = mAxes.valueAt(i);
6494        setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
6495        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6496            setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
6497                    axis.highCurrentValue);
6498        }
6499    }
6500
6501    // Moving a joystick axis should not wake the device because joysticks can
6502    // be fairly noisy even when not in use.  On the other hand, pushing a gamepad
6503    // button will likely wake the device.
6504    // TODO: Use the input device configuration to control this behavior more finely.
6505    uint32_t policyFlags = 0;
6506
6507    NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
6508            AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
6509            ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
6510    getListener()->notifyMotion(&args);
6511}
6512
6513void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
6514        int32_t axis, float value) {
6515    pointerCoords->setAxisValue(axis, value);
6516    /* In order to ease the transition for developers from using the old axes
6517     * to the newer, more semantically correct axes, we'll continue to produce
6518     * values for the old axes as mirrors of the value of their corresponding
6519     * new axes. */
6520    int32_t compatAxis = getCompatAxis(axis);
6521    if (compatAxis >= 0) {
6522        pointerCoords->setAxisValue(compatAxis, value);
6523    }
6524}
6525
6526bool JoystickInputMapper::filterAxes(bool force) {
6527    bool atLeastOneSignificantChange = force;
6528    size_t numAxes = mAxes.size();
6529    for (size_t i = 0; i < numAxes; i++) {
6530        Axis& axis = mAxes.editValueAt(i);
6531        if (force || hasValueChangedSignificantly(axis.filter,
6532                axis.newValue, axis.currentValue, axis.min, axis.max)) {
6533            axis.currentValue = axis.newValue;
6534            atLeastOneSignificantChange = true;
6535        }
6536        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6537            if (force || hasValueChangedSignificantly(axis.filter,
6538                    axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
6539                axis.highCurrentValue = axis.highNewValue;
6540                atLeastOneSignificantChange = true;
6541            }
6542        }
6543    }
6544    return atLeastOneSignificantChange;
6545}
6546
6547bool JoystickInputMapper::hasValueChangedSignificantly(
6548        float filter, float newValue, float currentValue, float min, float max) {
6549    if (newValue != currentValue) {
6550        // Filter out small changes in value unless the value is converging on the axis
6551        // bounds or center point.  This is intended to reduce the amount of information
6552        // sent to applications by particularly noisy joysticks (such as PS3).
6553        if (fabs(newValue - currentValue) > filter
6554                || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
6555                || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
6556                || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
6557            return true;
6558        }
6559    }
6560    return false;
6561}
6562
6563bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
6564        float filter, float newValue, float currentValue, float thresholdValue) {
6565    float newDistance = fabs(newValue - thresholdValue);
6566    if (newDistance < filter) {
6567        float oldDistance = fabs(currentValue - thresholdValue);
6568        if (newDistance < oldDistance) {
6569            return true;
6570        }
6571    }
6572    return false;
6573}
6574
6575} // namespace android
6576