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