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