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