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