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