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