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