InputReader.cpp revision ee03865fe5fc6ffe9deda0e0870a18206027cfaf
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        float res = 0.0f;
2755        if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2756            ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2757        }
2758        if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2759            mScalingFactor)) {
2760            ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2761              "default to 1.0!\n");
2762            mScalingFactor = 1.0f;
2763        }
2764        info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2765            res * mScalingFactor);
2766    }
2767}
2768
2769void RotaryEncoderInputMapper::dump(String8& dump) {
2770    dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2771    dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2772            toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2773}
2774
2775void RotaryEncoderInputMapper::configure(nsecs_t when,
2776        const InputReaderConfiguration* config, uint32_t changes) {
2777    InputMapper::configure(when, config, changes);
2778    if (!changes) {
2779        mRotaryEncoderScrollAccumulator.configure(getDevice());
2780    }
2781}
2782
2783void RotaryEncoderInputMapper::reset(nsecs_t when) {
2784    mRotaryEncoderScrollAccumulator.reset(getDevice());
2785
2786    InputMapper::reset(when);
2787}
2788
2789void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2790    mRotaryEncoderScrollAccumulator.process(rawEvent);
2791
2792    if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2793        sync(rawEvent->when);
2794    }
2795}
2796
2797void RotaryEncoderInputMapper::sync(nsecs_t when) {
2798    PointerCoords pointerCoords;
2799    pointerCoords.clear();
2800
2801    PointerProperties pointerProperties;
2802    pointerProperties.clear();
2803    pointerProperties.id = 0;
2804    pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2805
2806    float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2807    bool scrolled = scroll != 0;
2808
2809    // This is not a pointer, so it's not associated with a display.
2810    int32_t displayId = ADISPLAY_ID_NONE;
2811
2812    // Moving the rotary encoder should wake the device (if specified).
2813    uint32_t policyFlags = 0;
2814    if (scrolled && getDevice()->isExternal()) {
2815        policyFlags |= POLICY_FLAG_WAKE;
2816    }
2817
2818    // Send motion event.
2819    if (scrolled) {
2820        int32_t metaState = mContext->getGlobalMetaState();
2821        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
2822
2823        NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2824                AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2825                AMOTION_EVENT_EDGE_FLAG_NONE,
2826                displayId, 1, &pointerProperties, &pointerCoords,
2827                0, 0, 0);
2828        getListener()->notifyMotion(&scrollArgs);
2829    }
2830
2831    mRotaryEncoderScrollAccumulator.finishSync();
2832}
2833
2834// --- TouchInputMapper ---
2835
2836TouchInputMapper::TouchInputMapper(InputDevice* device) :
2837        InputMapper(device),
2838        mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
2839        mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
2840        mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
2841}
2842
2843TouchInputMapper::~TouchInputMapper() {
2844}
2845
2846uint32_t TouchInputMapper::getSources() {
2847    return mSource;
2848}
2849
2850void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2851    InputMapper::populateDeviceInfo(info);
2852
2853    if (mDeviceMode != DEVICE_MODE_DISABLED) {
2854        info->addMotionRange(mOrientedRanges.x);
2855        info->addMotionRange(mOrientedRanges.y);
2856        info->addMotionRange(mOrientedRanges.pressure);
2857
2858        if (mOrientedRanges.haveSize) {
2859            info->addMotionRange(mOrientedRanges.size);
2860        }
2861
2862        if (mOrientedRanges.haveTouchSize) {
2863            info->addMotionRange(mOrientedRanges.touchMajor);
2864            info->addMotionRange(mOrientedRanges.touchMinor);
2865        }
2866
2867        if (mOrientedRanges.haveToolSize) {
2868            info->addMotionRange(mOrientedRanges.toolMajor);
2869            info->addMotionRange(mOrientedRanges.toolMinor);
2870        }
2871
2872        if (mOrientedRanges.haveOrientation) {
2873            info->addMotionRange(mOrientedRanges.orientation);
2874        }
2875
2876        if (mOrientedRanges.haveDistance) {
2877            info->addMotionRange(mOrientedRanges.distance);
2878        }
2879
2880        if (mOrientedRanges.haveTilt) {
2881            info->addMotionRange(mOrientedRanges.tilt);
2882        }
2883
2884        if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2885            info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2886                    0.0f);
2887        }
2888        if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2889            info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2890                    0.0f);
2891        }
2892        if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
2893            const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
2894            const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
2895            info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
2896                    x.fuzz, x.resolution);
2897            info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
2898                    y.fuzz, y.resolution);
2899            info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
2900                    x.fuzz, x.resolution);
2901            info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
2902                    y.fuzz, y.resolution);
2903        }
2904        info->setButtonUnderPad(mParameters.hasButtonUnderPad);
2905    }
2906}
2907
2908void TouchInputMapper::dump(String8& dump) {
2909    dump.append(INDENT2 "Touch Input Mapper:\n");
2910    dumpParameters(dump);
2911    dumpVirtualKeys(dump);
2912    dumpRawPointerAxes(dump);
2913    dumpCalibration(dump);
2914    dumpAffineTransformation(dump);
2915    dumpSurface(dump);
2916
2917    dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
2918    dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
2919    dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
2920    dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
2921    dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
2922    dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
2923    dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
2924    dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
2925    dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
2926    dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
2927    dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
2928    dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
2929    dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
2930    dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
2931    dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
2932    dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
2933    dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
2934
2935    dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
2936    dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
2937            mLastRawState.rawPointerData.pointerCount);
2938    for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
2939        const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
2940        dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
2941                "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
2942                "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
2943                "toolType=%d, isHovering=%s\n", i,
2944                pointer.id, pointer.x, pointer.y, pointer.pressure,
2945                pointer.touchMajor, pointer.touchMinor,
2946                pointer.toolMajor, pointer.toolMinor,
2947                pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
2948                pointer.toolType, toString(pointer.isHovering));
2949    }
2950
2951    dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
2952    dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
2953            mLastCookedState.cookedPointerData.pointerCount);
2954    for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
2955        const PointerProperties& pointerProperties =
2956                mLastCookedState.cookedPointerData.pointerProperties[i];
2957        const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
2958        dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
2959                "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
2960                "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
2961                "toolType=%d, isHovering=%s\n", i,
2962                pointerProperties.id,
2963                pointerCoords.getX(),
2964                pointerCoords.getY(),
2965                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2966                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2967                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2968                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2969                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2970                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
2971                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
2972                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
2973                pointerProperties.toolType,
2974                toString(mLastCookedState.cookedPointerData.isHovering(i)));
2975    }
2976
2977    dump.append(INDENT3 "Stylus Fusion:\n");
2978    dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
2979            toString(mExternalStylusConnected));
2980    dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
2981    dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
2982            mExternalStylusFusionTimeout);
2983    dump.append(INDENT3 "External Stylus State:\n");
2984    dumpStylusState(dump, mExternalStylusState);
2985
2986    if (mDeviceMode == DEVICE_MODE_POINTER) {
2987        dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
2988        dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
2989                mPointerXMovementScale);
2990        dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
2991                mPointerYMovementScale);
2992        dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
2993                mPointerXZoomScale);
2994        dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
2995                mPointerYZoomScale);
2996        dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
2997                mPointerGestureMaxSwipeWidth);
2998    }
2999}
3000
3001void TouchInputMapper::configure(nsecs_t when,
3002        const InputReaderConfiguration* config, uint32_t changes) {
3003    InputMapper::configure(when, config, changes);
3004
3005    mConfig = *config;
3006
3007    if (!changes) { // first time only
3008        // Configure basic parameters.
3009        configureParameters();
3010
3011        // Configure common accumulators.
3012        mCursorScrollAccumulator.configure(getDevice());
3013        mTouchButtonAccumulator.configure(getDevice());
3014
3015        // Configure absolute axis information.
3016        configureRawPointerAxes();
3017
3018        // Prepare input device calibration.
3019        parseCalibration();
3020        resolveCalibration();
3021    }
3022
3023    if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
3024        // Update location calibration to reflect current settings
3025        updateAffineTransformation();
3026    }
3027
3028    if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3029        // Update pointer speed.
3030        mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3031        mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3032        mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3033    }
3034
3035    bool resetNeeded = false;
3036    if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3037            | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
3038            | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3039            | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
3040        // Configure device sources, surface dimensions, orientation and
3041        // scaling factors.
3042        configureSurface(when, &resetNeeded);
3043    }
3044
3045    if (changes && resetNeeded) {
3046        // Send reset, unless this is the first time the device has been configured,
3047        // in which case the reader will call reset itself after all mappers are ready.
3048        getDevice()->notifyReset(when);
3049    }
3050}
3051
3052void TouchInputMapper::resolveExternalStylusPresence() {
3053    Vector<InputDeviceInfo> devices;
3054    mContext->getExternalStylusDevices(devices);
3055    mExternalStylusConnected = !devices.isEmpty();
3056
3057    if (!mExternalStylusConnected) {
3058        resetExternalStylus();
3059    }
3060}
3061
3062void TouchInputMapper::configureParameters() {
3063    // Use the pointer presentation mode for devices that do not support distinct
3064    // multitouch.  The spot-based presentation relies on being able to accurately
3065    // locate two or more fingers on the touch pad.
3066    mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
3067            ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS;
3068
3069    String8 gestureModeString;
3070    if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3071            gestureModeString)) {
3072        if (gestureModeString == "pointer") {
3073            mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
3074        } else if (gestureModeString == "spots") {
3075            mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
3076        } else if (gestureModeString != "default") {
3077            ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3078        }
3079    }
3080
3081    if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3082        // The device is a touch screen.
3083        mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3084    } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3085        // The device is a pointing device like a track pad.
3086        mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3087    } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3088            || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3089        // The device is a cursor device with a touch pad attached.
3090        // By default don't use the touch pad to move the pointer.
3091        mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3092    } else {
3093        // The device is a touch pad of unknown purpose.
3094        mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3095    }
3096
3097    mParameters.hasButtonUnderPad=
3098            getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3099
3100    String8 deviceTypeString;
3101    if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3102            deviceTypeString)) {
3103        if (deviceTypeString == "touchScreen") {
3104            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3105        } else if (deviceTypeString == "touchPad") {
3106            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3107        } else if (deviceTypeString == "touchNavigation") {
3108            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3109        } else if (deviceTypeString == "pointer") {
3110            mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3111        } else if (deviceTypeString != "default") {
3112            ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3113        }
3114    }
3115
3116    mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3117    getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3118            mParameters.orientationAware);
3119
3120    mParameters.hasAssociatedDisplay = false;
3121    mParameters.associatedDisplayIsExternal = false;
3122    if (mParameters.orientationAware
3123            || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3124            || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3125        mParameters.hasAssociatedDisplay = true;
3126        mParameters.associatedDisplayIsExternal =
3127                mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3128                        && getDevice()->isExternal();
3129    }
3130
3131    // Initial downs on external touch devices should wake the device.
3132    // Normally we don't do this for internal touch screens to prevent them from waking
3133    // up in your pocket but you can enable it using the input device configuration.
3134    mParameters.wake = getDevice()->isExternal();
3135    getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3136            mParameters.wake);
3137}
3138
3139void TouchInputMapper::dumpParameters(String8& dump) {
3140    dump.append(INDENT3 "Parameters:\n");
3141
3142    switch (mParameters.gestureMode) {
3143    case Parameters::GESTURE_MODE_POINTER:
3144        dump.append(INDENT4 "GestureMode: pointer\n");
3145        break;
3146    case Parameters::GESTURE_MODE_SPOTS:
3147        dump.append(INDENT4 "GestureMode: spots\n");
3148        break;
3149    default:
3150        assert(false);
3151    }
3152
3153    switch (mParameters.deviceType) {
3154    case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3155        dump.append(INDENT4 "DeviceType: touchScreen\n");
3156        break;
3157    case Parameters::DEVICE_TYPE_TOUCH_PAD:
3158        dump.append(INDENT4 "DeviceType: touchPad\n");
3159        break;
3160    case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3161        dump.append(INDENT4 "DeviceType: touchNavigation\n");
3162        break;
3163    case Parameters::DEVICE_TYPE_POINTER:
3164        dump.append(INDENT4 "DeviceType: pointer\n");
3165        break;
3166    default:
3167        ALOG_ASSERT(false);
3168    }
3169
3170    dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
3171            toString(mParameters.hasAssociatedDisplay),
3172            toString(mParameters.associatedDisplayIsExternal));
3173    dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3174            toString(mParameters.orientationAware));
3175}
3176
3177void TouchInputMapper::configureRawPointerAxes() {
3178    mRawPointerAxes.clear();
3179}
3180
3181void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3182    dump.append(INDENT3 "Raw Touch Axes:\n");
3183    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3184    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3185    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3186    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3187    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3188    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3189    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3190    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3191    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3192    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3193    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3194    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3195    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3196}
3197
3198bool TouchInputMapper::hasExternalStylus() const {
3199    return mExternalStylusConnected;
3200}
3201
3202void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3203    int32_t oldDeviceMode = mDeviceMode;
3204
3205    resolveExternalStylusPresence();
3206
3207    // Determine device mode.
3208    if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3209            && mConfig.pointerGesturesEnabled) {
3210        mSource = AINPUT_SOURCE_MOUSE;
3211        mDeviceMode = DEVICE_MODE_POINTER;
3212        if (hasStylus()) {
3213            mSource |= AINPUT_SOURCE_STYLUS;
3214        }
3215    } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3216            && mParameters.hasAssociatedDisplay) {
3217        mSource = AINPUT_SOURCE_TOUCHSCREEN;
3218        mDeviceMode = DEVICE_MODE_DIRECT;
3219        if (hasStylus()) {
3220            mSource |= AINPUT_SOURCE_STYLUS;
3221        }
3222        if (hasExternalStylus()) {
3223            mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3224        }
3225    } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3226        mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3227        mDeviceMode = DEVICE_MODE_NAVIGATION;
3228    } else {
3229        mSource = AINPUT_SOURCE_TOUCHPAD;
3230        mDeviceMode = DEVICE_MODE_UNSCALED;
3231    }
3232
3233    // Ensure we have valid X and Y axes.
3234    if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3235        ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis!  "
3236                "The device will be inoperable.", getDeviceName().string());
3237        mDeviceMode = DEVICE_MODE_DISABLED;
3238        return;
3239    }
3240
3241    // Raw width and height in the natural orientation.
3242    int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3243    int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3244
3245    // Get associated display dimensions.
3246    DisplayViewport newViewport;
3247    if (mParameters.hasAssociatedDisplay) {
3248        if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
3249            ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3250                    "display.  The device will be inoperable until the display size "
3251                    "becomes available.",
3252                    getDeviceName().string());
3253            mDeviceMode = DEVICE_MODE_DISABLED;
3254            return;
3255        }
3256    } else {
3257        newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3258    }
3259    bool viewportChanged = mViewport != newViewport;
3260    if (viewportChanged) {
3261        mViewport = newViewport;
3262
3263        if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3264            // Convert rotated viewport to natural surface coordinates.
3265            int32_t naturalLogicalWidth, naturalLogicalHeight;
3266            int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3267            int32_t naturalPhysicalLeft, naturalPhysicalTop;
3268            int32_t naturalDeviceWidth, naturalDeviceHeight;
3269            switch (mViewport.orientation) {
3270            case DISPLAY_ORIENTATION_90:
3271                naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3272                naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3273                naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3274                naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3275                naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3276                naturalPhysicalTop = mViewport.physicalLeft;
3277                naturalDeviceWidth = mViewport.deviceHeight;
3278                naturalDeviceHeight = mViewport.deviceWidth;
3279                break;
3280            case DISPLAY_ORIENTATION_180:
3281                naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3282                naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3283                naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3284                naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3285                naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3286                naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3287                naturalDeviceWidth = mViewport.deviceWidth;
3288                naturalDeviceHeight = mViewport.deviceHeight;
3289                break;
3290            case DISPLAY_ORIENTATION_270:
3291                naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3292                naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3293                naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3294                naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3295                naturalPhysicalLeft = mViewport.physicalTop;
3296                naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3297                naturalDeviceWidth = mViewport.deviceHeight;
3298                naturalDeviceHeight = mViewport.deviceWidth;
3299                break;
3300            case DISPLAY_ORIENTATION_0:
3301            default:
3302                naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3303                naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3304                naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3305                naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3306                naturalPhysicalLeft = mViewport.physicalLeft;
3307                naturalPhysicalTop = mViewport.physicalTop;
3308                naturalDeviceWidth = mViewport.deviceWidth;
3309                naturalDeviceHeight = mViewport.deviceHeight;
3310                break;
3311            }
3312
3313            mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3314            mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3315            mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3316            mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3317
3318            mSurfaceOrientation = mParameters.orientationAware ?
3319                    mViewport.orientation : DISPLAY_ORIENTATION_0;
3320        } else {
3321            mSurfaceWidth = rawWidth;
3322            mSurfaceHeight = rawHeight;
3323            mSurfaceLeft = 0;
3324            mSurfaceTop = 0;
3325            mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3326        }
3327    }
3328
3329    // If moving between pointer modes, need to reset some state.
3330    bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3331    if (deviceModeChanged) {
3332        mOrientedRanges.clear();
3333    }
3334
3335    // Create pointer controller if needed.
3336    if (mDeviceMode == DEVICE_MODE_POINTER ||
3337            (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3338        if (mPointerController == NULL) {
3339            mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3340        }
3341    } else {
3342        mPointerController.clear();
3343    }
3344
3345    if (viewportChanged || deviceModeChanged) {
3346        ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3347                "display id %d",
3348                getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3349                mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3350
3351        // Configure X and Y factors.
3352        mXScale = float(mSurfaceWidth) / rawWidth;
3353        mYScale = float(mSurfaceHeight) / rawHeight;
3354        mXTranslate = -mSurfaceLeft;
3355        mYTranslate = -mSurfaceTop;
3356        mXPrecision = 1.0f / mXScale;
3357        mYPrecision = 1.0f / mYScale;
3358
3359        mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3360        mOrientedRanges.x.source = mSource;
3361        mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3362        mOrientedRanges.y.source = mSource;
3363
3364        configureVirtualKeys();
3365
3366        // Scale factor for terms that are not oriented in a particular axis.
3367        // If the pixels are square then xScale == yScale otherwise we fake it
3368        // by choosing an average.
3369        mGeometricScale = avg(mXScale, mYScale);
3370
3371        // Size of diagonal axis.
3372        float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3373
3374        // Size factors.
3375        if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3376            if (mRawPointerAxes.touchMajor.valid
3377                    && mRawPointerAxes.touchMajor.maxValue != 0) {
3378                mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3379            } else if (mRawPointerAxes.toolMajor.valid
3380                    && mRawPointerAxes.toolMajor.maxValue != 0) {
3381                mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3382            } else {
3383                mSizeScale = 0.0f;
3384            }
3385
3386            mOrientedRanges.haveTouchSize = true;
3387            mOrientedRanges.haveToolSize = true;
3388            mOrientedRanges.haveSize = true;
3389
3390            mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3391            mOrientedRanges.touchMajor.source = mSource;
3392            mOrientedRanges.touchMajor.min = 0;
3393            mOrientedRanges.touchMajor.max = diagonalSize;
3394            mOrientedRanges.touchMajor.flat = 0;
3395            mOrientedRanges.touchMajor.fuzz = 0;
3396            mOrientedRanges.touchMajor.resolution = 0;
3397
3398            mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3399            mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3400
3401            mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3402            mOrientedRanges.toolMajor.source = mSource;
3403            mOrientedRanges.toolMajor.min = 0;
3404            mOrientedRanges.toolMajor.max = diagonalSize;
3405            mOrientedRanges.toolMajor.flat = 0;
3406            mOrientedRanges.toolMajor.fuzz = 0;
3407            mOrientedRanges.toolMajor.resolution = 0;
3408
3409            mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3410            mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3411
3412            mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3413            mOrientedRanges.size.source = mSource;
3414            mOrientedRanges.size.min = 0;
3415            mOrientedRanges.size.max = 1.0;
3416            mOrientedRanges.size.flat = 0;
3417            mOrientedRanges.size.fuzz = 0;
3418            mOrientedRanges.size.resolution = 0;
3419        } else {
3420            mSizeScale = 0.0f;
3421        }
3422
3423        // Pressure factors.
3424        mPressureScale = 0;
3425        if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3426                || mCalibration.pressureCalibration
3427                        == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3428            if (mCalibration.havePressureScale) {
3429                mPressureScale = mCalibration.pressureScale;
3430            } else if (mRawPointerAxes.pressure.valid
3431                    && mRawPointerAxes.pressure.maxValue != 0) {
3432                mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3433            }
3434        }
3435
3436        mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3437        mOrientedRanges.pressure.source = mSource;
3438        mOrientedRanges.pressure.min = 0;
3439        mOrientedRanges.pressure.max = 1.0;
3440        mOrientedRanges.pressure.flat = 0;
3441        mOrientedRanges.pressure.fuzz = 0;
3442        mOrientedRanges.pressure.resolution = 0;
3443
3444        // Tilt
3445        mTiltXCenter = 0;
3446        mTiltXScale = 0;
3447        mTiltYCenter = 0;
3448        mTiltYScale = 0;
3449        mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3450        if (mHaveTilt) {
3451            mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3452                    mRawPointerAxes.tiltX.maxValue);
3453            mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3454                    mRawPointerAxes.tiltY.maxValue);
3455            mTiltXScale = M_PI / 180;
3456            mTiltYScale = M_PI / 180;
3457
3458            mOrientedRanges.haveTilt = true;
3459
3460            mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3461            mOrientedRanges.tilt.source = mSource;
3462            mOrientedRanges.tilt.min = 0;
3463            mOrientedRanges.tilt.max = M_PI_2;
3464            mOrientedRanges.tilt.flat = 0;
3465            mOrientedRanges.tilt.fuzz = 0;
3466            mOrientedRanges.tilt.resolution = 0;
3467        }
3468
3469        // Orientation
3470        mOrientationScale = 0;
3471        if (mHaveTilt) {
3472            mOrientedRanges.haveOrientation = true;
3473
3474            mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3475            mOrientedRanges.orientation.source = mSource;
3476            mOrientedRanges.orientation.min = -M_PI;
3477            mOrientedRanges.orientation.max = M_PI;
3478            mOrientedRanges.orientation.flat = 0;
3479            mOrientedRanges.orientation.fuzz = 0;
3480            mOrientedRanges.orientation.resolution = 0;
3481        } else if (mCalibration.orientationCalibration !=
3482                Calibration::ORIENTATION_CALIBRATION_NONE) {
3483            if (mCalibration.orientationCalibration
3484                    == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3485                if (mRawPointerAxes.orientation.valid) {
3486                    if (mRawPointerAxes.orientation.maxValue > 0) {
3487                        mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3488                    } else if (mRawPointerAxes.orientation.minValue < 0) {
3489                        mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3490                    } else {
3491                        mOrientationScale = 0;
3492                    }
3493                }
3494            }
3495
3496            mOrientedRanges.haveOrientation = true;
3497
3498            mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3499            mOrientedRanges.orientation.source = mSource;
3500            mOrientedRanges.orientation.min = -M_PI_2;
3501            mOrientedRanges.orientation.max = M_PI_2;
3502            mOrientedRanges.orientation.flat = 0;
3503            mOrientedRanges.orientation.fuzz = 0;
3504            mOrientedRanges.orientation.resolution = 0;
3505        }
3506
3507        // Distance
3508        mDistanceScale = 0;
3509        if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3510            if (mCalibration.distanceCalibration
3511                    == Calibration::DISTANCE_CALIBRATION_SCALED) {
3512                if (mCalibration.haveDistanceScale) {
3513                    mDistanceScale = mCalibration.distanceScale;
3514                } else {
3515                    mDistanceScale = 1.0f;
3516                }
3517            }
3518
3519            mOrientedRanges.haveDistance = true;
3520
3521            mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3522            mOrientedRanges.distance.source = mSource;
3523            mOrientedRanges.distance.min =
3524                    mRawPointerAxes.distance.minValue * mDistanceScale;
3525            mOrientedRanges.distance.max =
3526                    mRawPointerAxes.distance.maxValue * mDistanceScale;
3527            mOrientedRanges.distance.flat = 0;
3528            mOrientedRanges.distance.fuzz =
3529                    mRawPointerAxes.distance.fuzz * mDistanceScale;
3530            mOrientedRanges.distance.resolution = 0;
3531        }
3532
3533        // Compute oriented precision, scales and ranges.
3534        // Note that the maximum value reported is an inclusive maximum value so it is one
3535        // unit less than the total width or height of surface.
3536        switch (mSurfaceOrientation) {
3537        case DISPLAY_ORIENTATION_90:
3538        case DISPLAY_ORIENTATION_270:
3539            mOrientedXPrecision = mYPrecision;
3540            mOrientedYPrecision = mXPrecision;
3541
3542            mOrientedRanges.x.min = mYTranslate;
3543            mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3544            mOrientedRanges.x.flat = 0;
3545            mOrientedRanges.x.fuzz = 0;
3546            mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3547
3548            mOrientedRanges.y.min = mXTranslate;
3549            mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3550            mOrientedRanges.y.flat = 0;
3551            mOrientedRanges.y.fuzz = 0;
3552            mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3553            break;
3554
3555        default:
3556            mOrientedXPrecision = mXPrecision;
3557            mOrientedYPrecision = mYPrecision;
3558
3559            mOrientedRanges.x.min = mXTranslate;
3560            mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3561            mOrientedRanges.x.flat = 0;
3562            mOrientedRanges.x.fuzz = 0;
3563            mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3564
3565            mOrientedRanges.y.min = mYTranslate;
3566            mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3567            mOrientedRanges.y.flat = 0;
3568            mOrientedRanges.y.fuzz = 0;
3569            mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3570            break;
3571        }
3572
3573        // Location
3574        updateAffineTransformation();
3575
3576        if (mDeviceMode == DEVICE_MODE_POINTER) {
3577            // Compute pointer gesture detection parameters.
3578            float rawDiagonal = hypotf(rawWidth, rawHeight);
3579            float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3580
3581            // Scale movements such that one whole swipe of the touch pad covers a
3582            // given area relative to the diagonal size of the display when no acceleration
3583            // is applied.
3584            // Assume that the touch pad has a square aspect ratio such that movements in
3585            // X and Y of the same number of raw units cover the same physical distance.
3586            mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3587                    * displayDiagonal / rawDiagonal;
3588            mPointerYMovementScale = mPointerXMovementScale;
3589
3590            // Scale zooms to cover a smaller range of the display than movements do.
3591            // This value determines the area around the pointer that is affected by freeform
3592            // pointer gestures.
3593            mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3594                    * displayDiagonal / rawDiagonal;
3595            mPointerYZoomScale = mPointerXZoomScale;
3596
3597            // Max width between pointers to detect a swipe gesture is more than some fraction
3598            // of the diagonal axis of the touch pad.  Touches that are wider than this are
3599            // translated into freeform gestures.
3600            mPointerGestureMaxSwipeWidth =
3601                    mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3602
3603            // Abort current pointer usages because the state has changed.
3604            abortPointerUsage(when, 0 /*policyFlags*/);
3605        }
3606
3607        // Inform the dispatcher about the changes.
3608        *outResetNeeded = true;
3609        bumpGeneration();
3610    }
3611}
3612
3613void TouchInputMapper::dumpSurface(String8& dump) {
3614    dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3615            "logicalFrame=[%d, %d, %d, %d], "
3616            "physicalFrame=[%d, %d, %d, %d], "
3617            "deviceSize=[%d, %d]\n",
3618            mViewport.displayId, mViewport.orientation,
3619            mViewport.logicalLeft, mViewport.logicalTop,
3620            mViewport.logicalRight, mViewport.logicalBottom,
3621            mViewport.physicalLeft, mViewport.physicalTop,
3622            mViewport.physicalRight, mViewport.physicalBottom,
3623            mViewport.deviceWidth, mViewport.deviceHeight);
3624
3625    dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3626    dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3627    dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3628    dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3629    dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3630}
3631
3632void TouchInputMapper::configureVirtualKeys() {
3633    Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3634    getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3635
3636    mVirtualKeys.clear();
3637
3638    if (virtualKeyDefinitions.size() == 0) {
3639        return;
3640    }
3641
3642    mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3643
3644    int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3645    int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3646    int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3647    int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3648
3649    for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3650        const VirtualKeyDefinition& virtualKeyDefinition =
3651                virtualKeyDefinitions[i];
3652
3653        mVirtualKeys.add();
3654        VirtualKey& virtualKey = mVirtualKeys.editTop();
3655
3656        virtualKey.scanCode = virtualKeyDefinition.scanCode;
3657        int32_t keyCode;
3658        int32_t dummyKeyMetaState;
3659        uint32_t flags;
3660        if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3661                                  &keyCode, &dummyKeyMetaState, &flags)) {
3662            ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3663                    virtualKey.scanCode);
3664            mVirtualKeys.pop(); // drop the key
3665            continue;
3666        }
3667
3668        virtualKey.keyCode = keyCode;
3669        virtualKey.flags = flags;
3670
3671        // convert the key definition's display coordinates into touch coordinates for a hit box
3672        int32_t halfWidth = virtualKeyDefinition.width / 2;
3673        int32_t halfHeight = virtualKeyDefinition.height / 2;
3674
3675        virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3676                * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3677        virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3678                * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3679        virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3680                * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3681        virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3682                * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3683    }
3684}
3685
3686void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3687    if (!mVirtualKeys.isEmpty()) {
3688        dump.append(INDENT3 "Virtual Keys:\n");
3689
3690        for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3691            const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
3692            dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
3693                    "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3694                    i, virtualKey.scanCode, virtualKey.keyCode,
3695                    virtualKey.hitLeft, virtualKey.hitRight,
3696                    virtualKey.hitTop, virtualKey.hitBottom);
3697        }
3698    }
3699}
3700
3701void TouchInputMapper::parseCalibration() {
3702    const PropertyMap& in = getDevice()->getConfiguration();
3703    Calibration& out = mCalibration;
3704
3705    // Size
3706    out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3707    String8 sizeCalibrationString;
3708    if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3709        if (sizeCalibrationString == "none") {
3710            out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3711        } else if (sizeCalibrationString == "geometric") {
3712            out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3713        } else if (sizeCalibrationString == "diameter") {
3714            out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3715        } else if (sizeCalibrationString == "box") {
3716            out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3717        } else if (sizeCalibrationString == "area") {
3718            out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3719        } else if (sizeCalibrationString != "default") {
3720            ALOGW("Invalid value for touch.size.calibration: '%s'",
3721                    sizeCalibrationString.string());
3722        }
3723    }
3724
3725    out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3726            out.sizeScale);
3727    out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3728            out.sizeBias);
3729    out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3730            out.sizeIsSummed);
3731
3732    // Pressure
3733    out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3734    String8 pressureCalibrationString;
3735    if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3736        if (pressureCalibrationString == "none") {
3737            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3738        } else if (pressureCalibrationString == "physical") {
3739            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3740        } else if (pressureCalibrationString == "amplitude") {
3741            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3742        } else if (pressureCalibrationString != "default") {
3743            ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3744                    pressureCalibrationString.string());
3745        }
3746    }
3747
3748    out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3749            out.pressureScale);
3750
3751    // Orientation
3752    out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3753    String8 orientationCalibrationString;
3754    if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3755        if (orientationCalibrationString == "none") {
3756            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3757        } else if (orientationCalibrationString == "interpolated") {
3758            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3759        } else if (orientationCalibrationString == "vector") {
3760            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3761        } else if (orientationCalibrationString != "default") {
3762            ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3763                    orientationCalibrationString.string());
3764        }
3765    }
3766
3767    // Distance
3768    out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3769    String8 distanceCalibrationString;
3770    if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3771        if (distanceCalibrationString == "none") {
3772            out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3773        } else if (distanceCalibrationString == "scaled") {
3774            out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3775        } else if (distanceCalibrationString != "default") {
3776            ALOGW("Invalid value for touch.distance.calibration: '%s'",
3777                    distanceCalibrationString.string());
3778        }
3779    }
3780
3781    out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3782            out.distanceScale);
3783
3784    out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3785    String8 coverageCalibrationString;
3786    if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3787        if (coverageCalibrationString == "none") {
3788            out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3789        } else if (coverageCalibrationString == "box") {
3790            out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3791        } else if (coverageCalibrationString != "default") {
3792            ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3793                    coverageCalibrationString.string());
3794        }
3795    }
3796}
3797
3798void TouchInputMapper::resolveCalibration() {
3799    // Size
3800    if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3801        if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3802            mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3803        }
3804    } else {
3805        mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3806    }
3807
3808    // Pressure
3809    if (mRawPointerAxes.pressure.valid) {
3810        if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3811            mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3812        }
3813    } else {
3814        mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3815    }
3816
3817    // Orientation
3818    if (mRawPointerAxes.orientation.valid) {
3819        if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3820            mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3821        }
3822    } else {
3823        mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3824    }
3825
3826    // Distance
3827    if (mRawPointerAxes.distance.valid) {
3828        if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3829            mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3830        }
3831    } else {
3832        mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3833    }
3834
3835    // Coverage
3836    if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3837        mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3838    }
3839}
3840
3841void TouchInputMapper::dumpCalibration(String8& dump) {
3842    dump.append(INDENT3 "Calibration:\n");
3843
3844    // Size
3845    switch (mCalibration.sizeCalibration) {
3846    case Calibration::SIZE_CALIBRATION_NONE:
3847        dump.append(INDENT4 "touch.size.calibration: none\n");
3848        break;
3849    case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3850        dump.append(INDENT4 "touch.size.calibration: geometric\n");
3851        break;
3852    case Calibration::SIZE_CALIBRATION_DIAMETER:
3853        dump.append(INDENT4 "touch.size.calibration: diameter\n");
3854        break;
3855    case Calibration::SIZE_CALIBRATION_BOX:
3856        dump.append(INDENT4 "touch.size.calibration: box\n");
3857        break;
3858    case Calibration::SIZE_CALIBRATION_AREA:
3859        dump.append(INDENT4 "touch.size.calibration: area\n");
3860        break;
3861    default:
3862        ALOG_ASSERT(false);
3863    }
3864
3865    if (mCalibration.haveSizeScale) {
3866        dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3867                mCalibration.sizeScale);
3868    }
3869
3870    if (mCalibration.haveSizeBias) {
3871        dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3872                mCalibration.sizeBias);
3873    }
3874
3875    if (mCalibration.haveSizeIsSummed) {
3876        dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3877                toString(mCalibration.sizeIsSummed));
3878    }
3879
3880    // Pressure
3881    switch (mCalibration.pressureCalibration) {
3882    case Calibration::PRESSURE_CALIBRATION_NONE:
3883        dump.append(INDENT4 "touch.pressure.calibration: none\n");
3884        break;
3885    case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3886        dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3887        break;
3888    case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3889        dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
3890        break;
3891    default:
3892        ALOG_ASSERT(false);
3893    }
3894
3895    if (mCalibration.havePressureScale) {
3896        dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
3897                mCalibration.pressureScale);
3898    }
3899
3900    // Orientation
3901    switch (mCalibration.orientationCalibration) {
3902    case Calibration::ORIENTATION_CALIBRATION_NONE:
3903        dump.append(INDENT4 "touch.orientation.calibration: none\n");
3904        break;
3905    case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3906        dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
3907        break;
3908    case Calibration::ORIENTATION_CALIBRATION_VECTOR:
3909        dump.append(INDENT4 "touch.orientation.calibration: vector\n");
3910        break;
3911    default:
3912        ALOG_ASSERT(false);
3913    }
3914
3915    // Distance
3916    switch (mCalibration.distanceCalibration) {
3917    case Calibration::DISTANCE_CALIBRATION_NONE:
3918        dump.append(INDENT4 "touch.distance.calibration: none\n");
3919        break;
3920    case Calibration::DISTANCE_CALIBRATION_SCALED:
3921        dump.append(INDENT4 "touch.distance.calibration: scaled\n");
3922        break;
3923    default:
3924        ALOG_ASSERT(false);
3925    }
3926
3927    if (mCalibration.haveDistanceScale) {
3928        dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
3929                mCalibration.distanceScale);
3930    }
3931
3932    switch (mCalibration.coverageCalibration) {
3933    case Calibration::COVERAGE_CALIBRATION_NONE:
3934        dump.append(INDENT4 "touch.coverage.calibration: none\n");
3935        break;
3936    case Calibration::COVERAGE_CALIBRATION_BOX:
3937        dump.append(INDENT4 "touch.coverage.calibration: box\n");
3938        break;
3939    default:
3940        ALOG_ASSERT(false);
3941    }
3942}
3943
3944void TouchInputMapper::dumpAffineTransformation(String8& dump) {
3945    dump.append(INDENT3 "Affine Transformation:\n");
3946
3947    dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
3948    dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
3949    dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
3950    dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
3951    dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
3952    dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
3953}
3954
3955void TouchInputMapper::updateAffineTransformation() {
3956    mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
3957            mSurfaceOrientation);
3958}
3959
3960void TouchInputMapper::reset(nsecs_t when) {
3961    mCursorButtonAccumulator.reset(getDevice());
3962    mCursorScrollAccumulator.reset(getDevice());
3963    mTouchButtonAccumulator.reset(getDevice());
3964
3965    mPointerVelocityControl.reset();
3966    mWheelXVelocityControl.reset();
3967    mWheelYVelocityControl.reset();
3968
3969    mRawStatesPending.clear();
3970    mCurrentRawState.clear();
3971    mCurrentCookedState.clear();
3972    mLastRawState.clear();
3973    mLastCookedState.clear();
3974    mPointerUsage = POINTER_USAGE_NONE;
3975    mSentHoverEnter = false;
3976    mHavePointerIds = false;
3977    mCurrentMotionAborted = false;
3978    mDownTime = 0;
3979
3980    mCurrentVirtualKey.down = false;
3981
3982    mPointerGesture.reset();
3983    mPointerSimple.reset();
3984    resetExternalStylus();
3985
3986    if (mPointerController != NULL) {
3987        mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3988        mPointerController->clearSpots();
3989    }
3990
3991    InputMapper::reset(when);
3992}
3993
3994void TouchInputMapper::resetExternalStylus() {
3995    mExternalStylusState.clear();
3996    mExternalStylusId = -1;
3997    mExternalStylusFusionTimeout = LLONG_MAX;
3998    mExternalStylusDataPending = false;
3999}
4000
4001void TouchInputMapper::clearStylusDataPendingFlags() {
4002    mExternalStylusDataPending = false;
4003    mExternalStylusFusionTimeout = LLONG_MAX;
4004}
4005
4006void TouchInputMapper::process(const RawEvent* rawEvent) {
4007    mCursorButtonAccumulator.process(rawEvent);
4008    mCursorScrollAccumulator.process(rawEvent);
4009    mTouchButtonAccumulator.process(rawEvent);
4010
4011    if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4012        sync(rawEvent->when);
4013    }
4014}
4015
4016void TouchInputMapper::sync(nsecs_t when) {
4017    const RawState* last = mRawStatesPending.isEmpty() ?
4018            &mCurrentRawState : &mRawStatesPending.top();
4019
4020    // Push a new state.
4021    mRawStatesPending.push();
4022    RawState* next = &mRawStatesPending.editTop();
4023    next->clear();
4024    next->when = when;
4025
4026    // Sync button state.
4027    next->buttonState = mTouchButtonAccumulator.getButtonState()
4028            | mCursorButtonAccumulator.getButtonState();
4029
4030    // Sync scroll
4031    next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4032    next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
4033    mCursorScrollAccumulator.finishSync();
4034
4035    // Sync touch
4036    syncTouch(when, next);
4037
4038    // Assign pointer ids.
4039    if (!mHavePointerIds) {
4040        assignPointerIds(last, next);
4041    }
4042
4043#if DEBUG_RAW_EVENTS
4044    ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4045            "hovering ids 0x%08x -> 0x%08x",
4046            last->rawPointerData.pointerCount,
4047            next->rawPointerData.pointerCount,
4048            last->rawPointerData.touchingIdBits.value,
4049            next->rawPointerData.touchingIdBits.value,
4050            last->rawPointerData.hoveringIdBits.value,
4051            next->rawPointerData.hoveringIdBits.value);
4052#endif
4053
4054    processRawTouches(false /*timeout*/);
4055}
4056
4057void TouchInputMapper::processRawTouches(bool timeout) {
4058    if (mDeviceMode == DEVICE_MODE_DISABLED) {
4059        // Drop all input if the device is disabled.
4060        mCurrentRawState.clear();
4061        mRawStatesPending.clear();
4062        return;
4063    }
4064
4065    // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4066    // valid and must go through the full cook and dispatch cycle. This ensures that anything
4067    // touching the current state will only observe the events that have been dispatched to the
4068    // rest of the pipeline.
4069    const size_t N = mRawStatesPending.size();
4070    size_t count;
4071    for(count = 0; count < N; count++) {
4072        const RawState& next = mRawStatesPending[count];
4073
4074        // A failure to assign the stylus id means that we're waiting on stylus data
4075        // and so should defer the rest of the pipeline.
4076        if (assignExternalStylusId(next, timeout)) {
4077            break;
4078        }
4079
4080        // All ready to go.
4081        clearStylusDataPendingFlags();
4082        mCurrentRawState.copyFrom(next);
4083        if (mCurrentRawState.when < mLastRawState.when) {
4084            mCurrentRawState.when = mLastRawState.when;
4085        }
4086        cookAndDispatch(mCurrentRawState.when);
4087    }
4088    if (count != 0) {
4089        mRawStatesPending.removeItemsAt(0, count);
4090    }
4091
4092    if (mExternalStylusDataPending) {
4093        if (timeout) {
4094            nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4095            clearStylusDataPendingFlags();
4096            mCurrentRawState.copyFrom(mLastRawState);
4097#if DEBUG_STYLUS_FUSION
4098            ALOGD("Timeout expired, synthesizing event with new stylus data");
4099#endif
4100            cookAndDispatch(when);
4101        } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4102            mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4103            getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4104        }
4105    }
4106}
4107
4108void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4109    // Always start with a clean state.
4110    mCurrentCookedState.clear();
4111
4112    // Apply stylus buttons to current raw state.
4113    applyExternalStylusButtonState(when);
4114
4115    // Handle policy on initial down or hover events.
4116    bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4117            && mCurrentRawState.rawPointerData.pointerCount != 0;
4118
4119    uint32_t policyFlags = 0;
4120    bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4121    if (initialDown || buttonsPressed) {
4122        // If this is a touch screen, hide the pointer on an initial down.
4123        if (mDeviceMode == DEVICE_MODE_DIRECT) {
4124            getContext()->fadePointer();
4125        }
4126
4127        if (mParameters.wake) {
4128            policyFlags |= POLICY_FLAG_WAKE;
4129        }
4130    }
4131
4132    // Consume raw off-screen touches before cooking pointer data.
4133    // If touches are consumed, subsequent code will not receive any pointer data.
4134    if (consumeRawTouches(when, policyFlags)) {
4135        mCurrentRawState.rawPointerData.clear();
4136    }
4137
4138    // Cook pointer data.  This call populates the mCurrentCookedState.cookedPointerData structure
4139    // with cooked pointer data that has the same ids and indices as the raw data.
4140    // The following code can use either the raw or cooked data, as needed.
4141    cookPointerData();
4142
4143    // Apply stylus pressure to current cooked state.
4144    applyExternalStylusTouchState(when);
4145
4146    // Synthesize key down from raw buttons if needed.
4147    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
4148            policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
4149
4150    // Dispatch the touches either directly or by translation through a pointer on screen.
4151    if (mDeviceMode == DEVICE_MODE_POINTER) {
4152        for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4153                !idBits.isEmpty(); ) {
4154            uint32_t id = idBits.clearFirstMarkedBit();
4155            const RawPointerData::Pointer& pointer =
4156                    mCurrentRawState.rawPointerData.pointerForId(id);
4157            if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4158                    || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4159                mCurrentCookedState.stylusIdBits.markBit(id);
4160            } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4161                    || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4162                mCurrentCookedState.fingerIdBits.markBit(id);
4163            } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4164                mCurrentCookedState.mouseIdBits.markBit(id);
4165            }
4166        }
4167        for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4168                !idBits.isEmpty(); ) {
4169            uint32_t id = idBits.clearFirstMarkedBit();
4170            const RawPointerData::Pointer& pointer =
4171                    mCurrentRawState.rawPointerData.pointerForId(id);
4172            if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4173                    || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4174                mCurrentCookedState.stylusIdBits.markBit(id);
4175            }
4176        }
4177
4178        // Stylus takes precedence over all tools, then mouse, then finger.
4179        PointerUsage pointerUsage = mPointerUsage;
4180        if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4181            mCurrentCookedState.mouseIdBits.clear();
4182            mCurrentCookedState.fingerIdBits.clear();
4183            pointerUsage = POINTER_USAGE_STYLUS;
4184        } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4185            mCurrentCookedState.fingerIdBits.clear();
4186            pointerUsage = POINTER_USAGE_MOUSE;
4187        } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4188                isPointerDown(mCurrentRawState.buttonState)) {
4189            pointerUsage = POINTER_USAGE_GESTURES;
4190        }
4191
4192        dispatchPointerUsage(when, policyFlags, pointerUsage);
4193    } else {
4194        if (mDeviceMode == DEVICE_MODE_DIRECT
4195                && mConfig.showTouches && mPointerController != NULL) {
4196            mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4197            mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4198
4199            mPointerController->setButtonState(mCurrentRawState.buttonState);
4200            mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4201                    mCurrentCookedState.cookedPointerData.idToIndex,
4202                    mCurrentCookedState.cookedPointerData.touchingIdBits);
4203        }
4204
4205        if (!mCurrentMotionAborted) {
4206            dispatchButtonRelease(when, policyFlags);
4207            dispatchHoverExit(when, policyFlags);
4208            dispatchTouches(when, policyFlags);
4209            dispatchHoverEnterAndMove(when, policyFlags);
4210            dispatchButtonPress(when, policyFlags);
4211        }
4212
4213        if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4214            mCurrentMotionAborted = false;
4215        }
4216    }
4217
4218    // Synthesize key up from raw buttons if needed.
4219    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
4220            policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
4221
4222    // Clear some transient state.
4223    mCurrentRawState.rawVScroll = 0;
4224    mCurrentRawState.rawHScroll = 0;
4225
4226    // Copy current touch to last touch in preparation for the next cycle.
4227    mLastRawState.copyFrom(mCurrentRawState);
4228    mLastCookedState.copyFrom(mCurrentCookedState);
4229}
4230
4231void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
4232    if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
4233        mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4234    }
4235}
4236
4237void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
4238    CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4239    const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
4240
4241    if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4242        float pressure = mExternalStylusState.pressure;
4243        if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4244            const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4245            pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4246        }
4247        PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4248        coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4249
4250        PointerProperties& properties =
4251                currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
4252        if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4253            properties.toolType = mExternalStylusState.toolType;
4254        }
4255    }
4256}
4257
4258bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4259    if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4260        return false;
4261    }
4262
4263    const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4264            && state.rawPointerData.pointerCount != 0;
4265    if (initialDown) {
4266        if (mExternalStylusState.pressure != 0.0f) {
4267#if DEBUG_STYLUS_FUSION
4268            ALOGD("Have both stylus and touch data, beginning fusion");
4269#endif
4270            mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4271        } else if (timeout) {
4272#if DEBUG_STYLUS_FUSION
4273            ALOGD("Timeout expired, assuming touch is not a stylus.");
4274#endif
4275            resetExternalStylus();
4276        } else {
4277            if (mExternalStylusFusionTimeout == LLONG_MAX) {
4278                mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
4279            }
4280#if DEBUG_STYLUS_FUSION
4281            ALOGD("No stylus data but stylus is connected, requesting timeout "
4282                    "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
4283#endif
4284            getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4285            return true;
4286        }
4287    }
4288
4289    // Check if the stylus pointer has gone up.
4290    if (mExternalStylusId != -1 &&
4291            !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4292#if DEBUG_STYLUS_FUSION
4293            ALOGD("Stylus pointer is going up");
4294#endif
4295        mExternalStylusId = -1;
4296    }
4297
4298    return false;
4299}
4300
4301void TouchInputMapper::timeoutExpired(nsecs_t when) {
4302    if (mDeviceMode == DEVICE_MODE_POINTER) {
4303        if (mPointerUsage == POINTER_USAGE_GESTURES) {
4304            dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4305        }
4306    } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
4307        if (mExternalStylusFusionTimeout < when) {
4308            processRawTouches(true /*timeout*/);
4309        } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4310            getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4311        }
4312    }
4313}
4314
4315void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
4316    mExternalStylusState.copyFrom(state);
4317    if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
4318        // We're either in the middle of a fused stream of data or we're waiting on data before
4319        // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4320        // data.
4321        mExternalStylusDataPending = true;
4322        processRawTouches(false /*timeout*/);
4323    }
4324}
4325
4326bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4327    // Check for release of a virtual key.
4328    if (mCurrentVirtualKey.down) {
4329        if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
4330            // Pointer went up while virtual key was down.
4331            mCurrentVirtualKey.down = false;
4332            if (!mCurrentVirtualKey.ignored) {
4333#if DEBUG_VIRTUAL_KEYS
4334                ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4335                        mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4336#endif
4337                dispatchVirtualKey(when, policyFlags,
4338                        AKEY_EVENT_ACTION_UP,
4339                        AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4340            }
4341            return true;
4342        }
4343
4344        if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4345            uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4346            const RawPointerData::Pointer& pointer =
4347                    mCurrentRawState.rawPointerData.pointerForId(id);
4348            const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4349            if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4350                // Pointer is still within the space of the virtual key.
4351                return true;
4352            }
4353        }
4354
4355        // Pointer left virtual key area or another pointer also went down.
4356        // Send key cancellation but do not consume the touch yet.
4357        // This is useful when the user swipes through from the virtual key area
4358        // into the main display surface.
4359        mCurrentVirtualKey.down = false;
4360        if (!mCurrentVirtualKey.ignored) {
4361#if DEBUG_VIRTUAL_KEYS
4362            ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4363                    mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4364#endif
4365            dispatchVirtualKey(when, policyFlags,
4366                    AKEY_EVENT_ACTION_UP,
4367                    AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4368                            | AKEY_EVENT_FLAG_CANCELED);
4369        }
4370    }
4371
4372    if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4373            && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
4374        // Pointer just went down.  Check for virtual key press or off-screen touches.
4375        uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4376        const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
4377        if (!isPointInsideSurface(pointer.x, pointer.y)) {
4378            // If exactly one pointer went down, check for virtual key hit.
4379            // Otherwise we will drop the entire stroke.
4380            if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4381                const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4382                if (virtualKey) {
4383                    mCurrentVirtualKey.down = true;
4384                    mCurrentVirtualKey.downTime = when;
4385                    mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4386                    mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4387                    mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4388                            when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4389
4390                    if (!mCurrentVirtualKey.ignored) {
4391#if DEBUG_VIRTUAL_KEYS
4392                        ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4393                                mCurrentVirtualKey.keyCode,
4394                                mCurrentVirtualKey.scanCode);
4395#endif
4396                        dispatchVirtualKey(when, policyFlags,
4397                                AKEY_EVENT_ACTION_DOWN,
4398                                AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4399                    }
4400                }
4401            }
4402            return true;
4403        }
4404    }
4405
4406    // Disable all virtual key touches that happen within a short time interval of the
4407    // most recent touch within the screen area.  The idea is to filter out stray
4408    // virtual key presses when interacting with the touch screen.
4409    //
4410    // Problems we're trying to solve:
4411    //
4412    // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4413    //    virtual key area that is implemented by a separate touch panel and accidentally
4414    //    triggers a virtual key.
4415    //
4416    // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4417    //    area and accidentally triggers a virtual key.  This often happens when virtual keys
4418    //    are layed out below the screen near to where the on screen keyboard's space bar
4419    //    is displayed.
4420    if (mConfig.virtualKeyQuietTime > 0 &&
4421            !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
4422        mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4423    }
4424    return false;
4425}
4426
4427void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4428        int32_t keyEventAction, int32_t keyEventFlags) {
4429    int32_t keyCode = mCurrentVirtualKey.keyCode;
4430    int32_t scanCode = mCurrentVirtualKey.scanCode;
4431    nsecs_t downTime = mCurrentVirtualKey.downTime;
4432    int32_t metaState = mContext->getGlobalMetaState();
4433    policyFlags |= POLICY_FLAG_VIRTUAL;
4434
4435    NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4436            keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4437    getListener()->notifyKey(&args);
4438}
4439
4440void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4441    BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4442    if (!currentIdBits.isEmpty()) {
4443        int32_t metaState = getContext()->getGlobalMetaState();
4444        int32_t buttonState = mCurrentCookedState.buttonState;
4445        dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4446                metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4447                mCurrentCookedState.cookedPointerData.pointerProperties,
4448                mCurrentCookedState.cookedPointerData.pointerCoords,
4449                mCurrentCookedState.cookedPointerData.idToIndex,
4450                currentIdBits, -1,
4451                mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4452        mCurrentMotionAborted = true;
4453    }
4454}
4455
4456void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
4457    BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4458    BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
4459    int32_t metaState = getContext()->getGlobalMetaState();
4460    int32_t buttonState = mCurrentCookedState.buttonState;
4461
4462    if (currentIdBits == lastIdBits) {
4463        if (!currentIdBits.isEmpty()) {
4464            // No pointer id changes so this is a move event.
4465            // The listener takes care of batching moves so we don't have to deal with that here.
4466            dispatchMotion(when, policyFlags, mSource,
4467                    AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
4468                    AMOTION_EVENT_EDGE_FLAG_NONE,
4469                    mCurrentCookedState.cookedPointerData.pointerProperties,
4470                    mCurrentCookedState.cookedPointerData.pointerCoords,
4471                    mCurrentCookedState.cookedPointerData.idToIndex,
4472                    currentIdBits, -1,
4473                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4474        }
4475    } else {
4476        // There may be pointers going up and pointers going down and pointers moving
4477        // all at the same time.
4478        BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4479        BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4480        BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4481        BitSet32 dispatchedIdBits(lastIdBits.value);
4482
4483        // Update last coordinates of pointers that have moved so that we observe the new
4484        // pointer positions at the same time as other pointers that have just gone up.
4485        bool moveNeeded = updateMovedPointers(
4486                mCurrentCookedState.cookedPointerData.pointerProperties,
4487                mCurrentCookedState.cookedPointerData.pointerCoords,
4488                mCurrentCookedState.cookedPointerData.idToIndex,
4489                mLastCookedState.cookedPointerData.pointerProperties,
4490                mLastCookedState.cookedPointerData.pointerCoords,
4491                mLastCookedState.cookedPointerData.idToIndex,
4492                moveIdBits);
4493        if (buttonState != mLastCookedState.buttonState) {
4494            moveNeeded = true;
4495        }
4496
4497        // Dispatch pointer up events.
4498        while (!upIdBits.isEmpty()) {
4499            uint32_t upId = upIdBits.clearFirstMarkedBit();
4500
4501            dispatchMotion(when, policyFlags, mSource,
4502                    AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
4503                    mLastCookedState.cookedPointerData.pointerProperties,
4504                    mLastCookedState.cookedPointerData.pointerCoords,
4505                    mLastCookedState.cookedPointerData.idToIndex,
4506                    dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4507            dispatchedIdBits.clearBit(upId);
4508        }
4509
4510        // Dispatch move events if any of the remaining pointers moved from their old locations.
4511        // Although applications receive new locations as part of individual pointer up
4512        // events, they do not generally handle them except when presented in a move event.
4513        if (moveNeeded && !moveIdBits.isEmpty()) {
4514            ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4515            dispatchMotion(when, policyFlags, mSource,
4516                    AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
4517                    mCurrentCookedState.cookedPointerData.pointerProperties,
4518                    mCurrentCookedState.cookedPointerData.pointerCoords,
4519                    mCurrentCookedState.cookedPointerData.idToIndex,
4520                    dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4521        }
4522
4523        // Dispatch pointer down events using the new pointer locations.
4524        while (!downIdBits.isEmpty()) {
4525            uint32_t downId = downIdBits.clearFirstMarkedBit();
4526            dispatchedIdBits.markBit(downId);
4527
4528            if (dispatchedIdBits.count() == 1) {
4529                // First pointer is going down.  Set down time.
4530                mDownTime = when;
4531            }
4532
4533            dispatchMotion(when, policyFlags, mSource,
4534                    AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
4535                    mCurrentCookedState.cookedPointerData.pointerProperties,
4536                    mCurrentCookedState.cookedPointerData.pointerCoords,
4537                    mCurrentCookedState.cookedPointerData.idToIndex,
4538                    dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4539        }
4540    }
4541}
4542
4543void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4544    if (mSentHoverEnter &&
4545            (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4546                    || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
4547        int32_t metaState = getContext()->getGlobalMetaState();
4548        dispatchMotion(when, policyFlags, mSource,
4549                AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
4550                mLastCookedState.cookedPointerData.pointerProperties,
4551                mLastCookedState.cookedPointerData.pointerCoords,
4552                mLastCookedState.cookedPointerData.idToIndex,
4553                mLastCookedState.cookedPointerData.hoveringIdBits, -1,
4554                mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4555        mSentHoverEnter = false;
4556    }
4557}
4558
4559void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
4560    if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4561            && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
4562        int32_t metaState = getContext()->getGlobalMetaState();
4563        if (!mSentHoverEnter) {
4564            dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
4565                    0, 0, metaState, 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            mSentHoverEnter = true;
4572        }
4573
4574        dispatchMotion(when, policyFlags, mSource,
4575                AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
4576                mCurrentRawState.buttonState, 0,
4577                mCurrentCookedState.cookedPointerData.pointerProperties,
4578                mCurrentCookedState.cookedPointerData.pointerCoords,
4579                mCurrentCookedState.cookedPointerData.idToIndex,
4580                mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
4581                mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4582    }
4583}
4584
4585void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4586    BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4587    const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4588    const int32_t metaState = getContext()->getGlobalMetaState();
4589    int32_t buttonState = mLastCookedState.buttonState;
4590    while (!releasedButtons.isEmpty()) {
4591        int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4592        buttonState &= ~actionButton;
4593        dispatchMotion(when, policyFlags, mSource,
4594                    AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4595                    0, metaState, buttonState, 0,
4596                    mCurrentCookedState.cookedPointerData.pointerProperties,
4597                    mCurrentCookedState.cookedPointerData.pointerCoords,
4598                    mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4599                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4600    }
4601}
4602
4603void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4604    BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4605    const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4606    const int32_t metaState = getContext()->getGlobalMetaState();
4607    int32_t buttonState = mLastCookedState.buttonState;
4608    while (!pressedButtons.isEmpty()) {
4609        int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4610        buttonState |= actionButton;
4611        dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4612                    0, metaState, buttonState, 0,
4613                    mCurrentCookedState.cookedPointerData.pointerProperties,
4614                    mCurrentCookedState.cookedPointerData.pointerCoords,
4615                    mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4616                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4617    }
4618}
4619
4620const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4621    if (!cookedPointerData.touchingIdBits.isEmpty()) {
4622        return cookedPointerData.touchingIdBits;
4623    }
4624    return cookedPointerData.hoveringIdBits;
4625}
4626
4627void TouchInputMapper::cookPointerData() {
4628    uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
4629
4630    mCurrentCookedState.cookedPointerData.clear();
4631    mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4632    mCurrentCookedState.cookedPointerData.hoveringIdBits =
4633            mCurrentRawState.rawPointerData.hoveringIdBits;
4634    mCurrentCookedState.cookedPointerData.touchingIdBits =
4635            mCurrentRawState.rawPointerData.touchingIdBits;
4636
4637    if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4638        mCurrentCookedState.buttonState = 0;
4639    } else {
4640        mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4641    }
4642
4643    // Walk through the the active pointers and map device coordinates onto
4644    // surface coordinates and adjust for display orientation.
4645    for (uint32_t i = 0; i < currentPointerCount; i++) {
4646        const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
4647
4648        // Size
4649        float touchMajor, touchMinor, toolMajor, toolMinor, size;
4650        switch (mCalibration.sizeCalibration) {
4651        case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4652        case Calibration::SIZE_CALIBRATION_DIAMETER:
4653        case Calibration::SIZE_CALIBRATION_BOX:
4654        case Calibration::SIZE_CALIBRATION_AREA:
4655            if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4656                touchMajor = in.touchMajor;
4657                touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4658                toolMajor = in.toolMajor;
4659                toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4660                size = mRawPointerAxes.touchMinor.valid
4661                        ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4662            } else if (mRawPointerAxes.touchMajor.valid) {
4663                toolMajor = touchMajor = in.touchMajor;
4664                toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4665                        ? in.touchMinor : in.touchMajor;
4666                size = mRawPointerAxes.touchMinor.valid
4667                        ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4668            } else if (mRawPointerAxes.toolMajor.valid) {
4669                touchMajor = toolMajor = in.toolMajor;
4670                touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4671                        ? in.toolMinor : in.toolMajor;
4672                size = mRawPointerAxes.toolMinor.valid
4673                        ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4674            } else {
4675                ALOG_ASSERT(false, "No touch or tool axes.  "
4676                        "Size calibration should have been resolved to NONE.");
4677                touchMajor = 0;
4678                touchMinor = 0;
4679                toolMajor = 0;
4680                toolMinor = 0;
4681                size = 0;
4682            }
4683
4684            if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
4685                uint32_t touchingCount =
4686                        mCurrentRawState.rawPointerData.touchingIdBits.count();
4687                if (touchingCount > 1) {
4688                    touchMajor /= touchingCount;
4689                    touchMinor /= touchingCount;
4690                    toolMajor /= touchingCount;
4691                    toolMinor /= touchingCount;
4692                    size /= touchingCount;
4693                }
4694            }
4695
4696            if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4697                touchMajor *= mGeometricScale;
4698                touchMinor *= mGeometricScale;
4699                toolMajor *= mGeometricScale;
4700                toolMinor *= mGeometricScale;
4701            } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4702                touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4703                touchMinor = touchMajor;
4704                toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4705                toolMinor = toolMajor;
4706            } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4707                touchMinor = touchMajor;
4708                toolMinor = toolMajor;
4709            }
4710
4711            mCalibration.applySizeScaleAndBias(&touchMajor);
4712            mCalibration.applySizeScaleAndBias(&touchMinor);
4713            mCalibration.applySizeScaleAndBias(&toolMajor);
4714            mCalibration.applySizeScaleAndBias(&toolMinor);
4715            size *= mSizeScale;
4716            break;
4717        default:
4718            touchMajor = 0;
4719            touchMinor = 0;
4720            toolMajor = 0;
4721            toolMinor = 0;
4722            size = 0;
4723            break;
4724        }
4725
4726        // Pressure
4727        float pressure;
4728        switch (mCalibration.pressureCalibration) {
4729        case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4730        case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4731            pressure = in.pressure * mPressureScale;
4732            break;
4733        default:
4734            pressure = in.isHovering ? 0 : 1;
4735            break;
4736        }
4737
4738        // Tilt and Orientation
4739        float tilt;
4740        float orientation;
4741        if (mHaveTilt) {
4742            float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4743            float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4744            orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4745            tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4746        } else {
4747            tilt = 0;
4748
4749            switch (mCalibration.orientationCalibration) {
4750            case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4751                orientation = in.orientation * mOrientationScale;
4752                break;
4753            case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4754                int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4755                int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4756                if (c1 != 0 || c2 != 0) {
4757                    orientation = atan2f(c1, c2) * 0.5f;
4758                    float confidence = hypotf(c1, c2);
4759                    float scale = 1.0f + confidence / 16.0f;
4760                    touchMajor *= scale;
4761                    touchMinor /= scale;
4762                    toolMajor *= scale;
4763                    toolMinor /= scale;
4764                } else {
4765                    orientation = 0;
4766                }
4767                break;
4768            }
4769            default:
4770                orientation = 0;
4771            }
4772        }
4773
4774        // Distance
4775        float distance;
4776        switch (mCalibration.distanceCalibration) {
4777        case Calibration::DISTANCE_CALIBRATION_SCALED:
4778            distance = in.distance * mDistanceScale;
4779            break;
4780        default:
4781            distance = 0;
4782        }
4783
4784        // Coverage
4785        int32_t rawLeft, rawTop, rawRight, rawBottom;
4786        switch (mCalibration.coverageCalibration) {
4787        case Calibration::COVERAGE_CALIBRATION_BOX:
4788            rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4789            rawRight = in.toolMinor & 0x0000ffff;
4790            rawBottom = in.toolMajor & 0x0000ffff;
4791            rawTop = (in.toolMajor & 0xffff0000) >> 16;
4792            break;
4793        default:
4794            rawLeft = rawTop = rawRight = rawBottom = 0;
4795            break;
4796        }
4797
4798        // Adjust X,Y coords for device calibration
4799        // TODO: Adjust coverage coords?
4800        float xTransformed = in.x, yTransformed = in.y;
4801        mAffineTransform.applyTo(xTransformed, yTransformed);
4802
4803        // Adjust X, Y, and coverage coords for surface orientation.
4804        float x, y;
4805        float left, top, right, bottom;
4806
4807        switch (mSurfaceOrientation) {
4808        case DISPLAY_ORIENTATION_90:
4809            x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4810            y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4811            left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4812            right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4813            bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4814            top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4815            orientation -= M_PI_2;
4816            if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
4817                orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4818            }
4819            break;
4820        case DISPLAY_ORIENTATION_180:
4821            x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4822            y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4823            left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4824            right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4825            bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4826            top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4827            orientation -= M_PI;
4828            if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
4829                orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4830            }
4831            break;
4832        case DISPLAY_ORIENTATION_270:
4833            x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4834            y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4835            left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4836            right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4837            bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4838            top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4839            orientation += M_PI_2;
4840            if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
4841                orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4842            }
4843            break;
4844        default:
4845            x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4846            y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4847            left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4848            right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4849            bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4850            top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4851            break;
4852        }
4853
4854        // Write output coords.
4855        PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
4856        out.clear();
4857        out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4858        out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4859        out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4860        out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4861        out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4862        out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4863        out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4864        out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4865        out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4866        if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4867            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4868            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4869            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4870            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4871        } else {
4872            out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4873            out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4874        }
4875
4876        // Write output properties.
4877        PointerProperties& properties =
4878                mCurrentCookedState.cookedPointerData.pointerProperties[i];
4879        uint32_t id = in.id;
4880        properties.clear();
4881        properties.id = id;
4882        properties.toolType = in.toolType;
4883
4884        // Write id index.
4885        mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
4886    }
4887}
4888
4889void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
4890        PointerUsage pointerUsage) {
4891    if (pointerUsage != mPointerUsage) {
4892        abortPointerUsage(when, policyFlags);
4893        mPointerUsage = pointerUsage;
4894    }
4895
4896    switch (mPointerUsage) {
4897    case POINTER_USAGE_GESTURES:
4898        dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
4899        break;
4900    case POINTER_USAGE_STYLUS:
4901        dispatchPointerStylus(when, policyFlags);
4902        break;
4903    case POINTER_USAGE_MOUSE:
4904        dispatchPointerMouse(when, policyFlags);
4905        break;
4906    default:
4907        break;
4908    }
4909}
4910
4911void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
4912    switch (mPointerUsage) {
4913    case POINTER_USAGE_GESTURES:
4914        abortPointerGestures(when, policyFlags);
4915        break;
4916    case POINTER_USAGE_STYLUS:
4917        abortPointerStylus(when, policyFlags);
4918        break;
4919    case POINTER_USAGE_MOUSE:
4920        abortPointerMouse(when, policyFlags);
4921        break;
4922    default:
4923        break;
4924    }
4925
4926    mPointerUsage = POINTER_USAGE_NONE;
4927}
4928
4929void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
4930        bool isTimeout) {
4931    // Update current gesture coordinates.
4932    bool cancelPreviousGesture, finishPreviousGesture;
4933    bool sendEvents = preparePointerGestures(when,
4934            &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
4935    if (!sendEvents) {
4936        return;
4937    }
4938    if (finishPreviousGesture) {
4939        cancelPreviousGesture = false;
4940    }
4941
4942    // Update the pointer presentation and spots.
4943    if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4944        mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4945        if (finishPreviousGesture || cancelPreviousGesture) {
4946            mPointerController->clearSpots();
4947        }
4948        mPointerController->setSpots(mPointerGesture.currentGestureCoords,
4949                mPointerGesture.currentGestureIdToIndex,
4950                mPointerGesture.currentGestureIdBits);
4951    } else {
4952        mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
4953    }
4954
4955    // Show or hide the pointer if needed.
4956    switch (mPointerGesture.currentGestureMode) {
4957    case PointerGesture::NEUTRAL:
4958    case PointerGesture::QUIET:
4959        if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
4960                && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE
4961                        || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) {
4962            // Remind the user of where the pointer is after finishing a gesture with spots.
4963            mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
4964        }
4965        break;
4966    case PointerGesture::TAP:
4967    case PointerGesture::TAP_DRAG:
4968    case PointerGesture::BUTTON_CLICK_OR_DRAG:
4969    case PointerGesture::HOVER:
4970    case PointerGesture::PRESS:
4971        // Unfade the pointer when the current gesture manipulates the
4972        // area directly under the pointer.
4973        mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4974        break;
4975    case PointerGesture::SWIPE:
4976    case PointerGesture::FREEFORM:
4977        // Fade the pointer when the current gesture manipulates a different
4978        // area and there are spots to guide the user experience.
4979        if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4980            mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4981        } else {
4982            mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
4983        }
4984        break;
4985    }
4986
4987    // Send events!
4988    int32_t metaState = getContext()->getGlobalMetaState();
4989    int32_t buttonState = mCurrentCookedState.buttonState;
4990
4991    // Update last coordinates of pointers that have moved so that we observe the new
4992    // pointer positions at the same time as other pointers that have just gone up.
4993    bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
4994            || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
4995            || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
4996            || mPointerGesture.currentGestureMode == PointerGesture::PRESS
4997            || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
4998            || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
4999    bool moveNeeded = false;
5000    if (down && !cancelPreviousGesture && !finishPreviousGesture
5001            && !mPointerGesture.lastGestureIdBits.isEmpty()
5002            && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5003        BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5004                & mPointerGesture.lastGestureIdBits.value);
5005        moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5006                mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5007                mPointerGesture.lastGestureProperties,
5008                mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5009                movedGestureIdBits);
5010        if (buttonState != mLastCookedState.buttonState) {
5011            moveNeeded = true;
5012        }
5013    }
5014
5015    // Send motion events for all pointers that went up or were canceled.
5016    BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5017    if (!dispatchedGestureIdBits.isEmpty()) {
5018        if (cancelPreviousGesture) {
5019            dispatchMotion(when, policyFlags, mSource,
5020                    AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
5021                    AMOTION_EVENT_EDGE_FLAG_NONE,
5022                    mPointerGesture.lastGestureProperties,
5023                    mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5024                    dispatchedGestureIdBits, -1, 0,
5025                    0, mPointerGesture.downTime);
5026
5027            dispatchedGestureIdBits.clear();
5028        } else {
5029            BitSet32 upGestureIdBits;
5030            if (finishPreviousGesture) {
5031                upGestureIdBits = dispatchedGestureIdBits;
5032            } else {
5033                upGestureIdBits.value = dispatchedGestureIdBits.value
5034                        & ~mPointerGesture.currentGestureIdBits.value;
5035            }
5036            while (!upGestureIdBits.isEmpty()) {
5037                uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5038
5039                dispatchMotion(when, policyFlags, mSource,
5040                        AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
5041                        metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5042                        mPointerGesture.lastGestureProperties,
5043                        mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5044                        dispatchedGestureIdBits, id,
5045                        0, 0, mPointerGesture.downTime);
5046
5047                dispatchedGestureIdBits.clearBit(id);
5048            }
5049        }
5050    }
5051
5052    // Send motion events for all pointers that moved.
5053    if (moveNeeded) {
5054        dispatchMotion(when, policyFlags, mSource,
5055                AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5056                AMOTION_EVENT_EDGE_FLAG_NONE,
5057                mPointerGesture.currentGestureProperties,
5058                mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5059                dispatchedGestureIdBits, -1,
5060                0, 0, mPointerGesture.downTime);
5061    }
5062
5063    // Send motion events for all pointers that went down.
5064    if (down) {
5065        BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5066                & ~dispatchedGestureIdBits.value);
5067        while (!downGestureIdBits.isEmpty()) {
5068            uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5069            dispatchedGestureIdBits.markBit(id);
5070
5071            if (dispatchedGestureIdBits.count() == 1) {
5072                mPointerGesture.downTime = when;
5073            }
5074
5075            dispatchMotion(when, policyFlags, mSource,
5076                    AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
5077                    mPointerGesture.currentGestureProperties,
5078                    mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5079                    dispatchedGestureIdBits, id,
5080                    0, 0, mPointerGesture.downTime);
5081        }
5082    }
5083
5084    // Send motion events for hover.
5085    if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5086        dispatchMotion(when, policyFlags, mSource,
5087                AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5088                metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5089                mPointerGesture.currentGestureProperties,
5090                mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5091                mPointerGesture.currentGestureIdBits, -1,
5092                0, 0, mPointerGesture.downTime);
5093    } else if (dispatchedGestureIdBits.isEmpty()
5094            && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5095        // Synthesize a hover move event after all pointers go up to indicate that
5096        // the pointer is hovering again even if the user is not currently touching
5097        // the touch pad.  This ensures that a view will receive a fresh hover enter
5098        // event after a tap.
5099        float x, y;
5100        mPointerController->getPosition(&x, &y);
5101
5102        PointerProperties pointerProperties;
5103        pointerProperties.clear();
5104        pointerProperties.id = 0;
5105        pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5106
5107        PointerCoords pointerCoords;
5108        pointerCoords.clear();
5109        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5110        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5111
5112        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
5113                AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5114                metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5115                mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5116                0, 0, mPointerGesture.downTime);
5117        getListener()->notifyMotion(&args);
5118    }
5119
5120    // Update state.
5121    mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5122    if (!down) {
5123        mPointerGesture.lastGestureIdBits.clear();
5124    } else {
5125        mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5126        for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5127            uint32_t id = idBits.clearFirstMarkedBit();
5128            uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5129            mPointerGesture.lastGestureProperties[index].copyFrom(
5130                    mPointerGesture.currentGestureProperties[index]);
5131            mPointerGesture.lastGestureCoords[index].copyFrom(
5132                    mPointerGesture.currentGestureCoords[index]);
5133            mPointerGesture.lastGestureIdToIndex[id] = index;
5134        }
5135    }
5136}
5137
5138void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5139    // Cancel previously dispatches pointers.
5140    if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5141        int32_t metaState = getContext()->getGlobalMetaState();
5142        int32_t buttonState = mCurrentRawState.buttonState;
5143        dispatchMotion(when, policyFlags, mSource,
5144                AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
5145                AMOTION_EVENT_EDGE_FLAG_NONE,
5146                mPointerGesture.lastGestureProperties,
5147                mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5148                mPointerGesture.lastGestureIdBits, -1,
5149                0, 0, mPointerGesture.downTime);
5150    }
5151
5152    // Reset the current pointer gesture.
5153    mPointerGesture.reset();
5154    mPointerVelocityControl.reset();
5155
5156    // Remove any current spots.
5157    if (mPointerController != NULL) {
5158        mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5159        mPointerController->clearSpots();
5160    }
5161}
5162
5163bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5164        bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5165    *outCancelPreviousGesture = false;
5166    *outFinishPreviousGesture = false;
5167
5168    // Handle TAP timeout.
5169    if (isTimeout) {
5170#if DEBUG_GESTURES
5171        ALOGD("Gestures: Processing timeout");
5172#endif
5173
5174        if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5175            if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5176                // The tap/drag timeout has not yet expired.
5177                getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5178                        + mConfig.pointerGestureTapDragInterval);
5179            } else {
5180                // The tap is finished.
5181#if DEBUG_GESTURES
5182                ALOGD("Gestures: TAP finished");
5183#endif
5184                *outFinishPreviousGesture = true;
5185
5186                mPointerGesture.activeGestureId = -1;
5187                mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5188                mPointerGesture.currentGestureIdBits.clear();
5189
5190                mPointerVelocityControl.reset();
5191                return true;
5192            }
5193        }
5194
5195        // We did not handle this timeout.
5196        return false;
5197    }
5198
5199    const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5200    const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
5201
5202    // Update the velocity tracker.
5203    {
5204        VelocityTracker::Position positions[MAX_POINTERS];
5205        uint32_t count = 0;
5206        for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
5207            uint32_t id = idBits.clearFirstMarkedBit();
5208            const RawPointerData::Pointer& pointer =
5209                    mCurrentRawState.rawPointerData.pointerForId(id);
5210            positions[count].x = pointer.x * mPointerXMovementScale;
5211            positions[count].y = pointer.y * mPointerYMovementScale;
5212        }
5213        mPointerGesture.velocityTracker.addMovement(when,
5214                mCurrentCookedState.fingerIdBits, positions);
5215    }
5216
5217    // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5218    // to NEUTRAL, then we should not generate tap event.
5219    if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5220            && mPointerGesture.lastGestureMode != PointerGesture::TAP
5221            && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5222        mPointerGesture.resetTap();
5223    }
5224
5225    // Pick a new active touch id if needed.
5226    // Choose an arbitrary pointer that just went down, if there is one.
5227    // Otherwise choose an arbitrary remaining pointer.
5228    // This guarantees we always have an active touch id when there is at least one pointer.
5229    // We keep the same active touch id for as long as possible.
5230    bool activeTouchChanged = false;
5231    int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5232    int32_t activeTouchId = lastActiveTouchId;
5233    if (activeTouchId < 0) {
5234        if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
5235            activeTouchChanged = true;
5236            activeTouchId = mPointerGesture.activeTouchId =
5237                    mCurrentCookedState.fingerIdBits.firstMarkedBit();
5238            mPointerGesture.firstTouchTime = when;
5239        }
5240    } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
5241        activeTouchChanged = true;
5242        if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
5243            activeTouchId = mPointerGesture.activeTouchId =
5244                    mCurrentCookedState.fingerIdBits.firstMarkedBit();
5245        } else {
5246            activeTouchId = mPointerGesture.activeTouchId = -1;
5247        }
5248    }
5249
5250    // Determine whether we are in quiet time.
5251    bool isQuietTime = false;
5252    if (activeTouchId < 0) {
5253        mPointerGesture.resetQuietTime();
5254    } else {
5255        isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5256        if (!isQuietTime) {
5257            if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5258                    || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5259                    || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5260                    && currentFingerCount < 2) {
5261                // Enter quiet time when exiting swipe or freeform state.
5262                // This is to prevent accidentally entering the hover state and flinging the
5263                // pointer when finishing a swipe and there is still one pointer left onscreen.
5264                isQuietTime = true;
5265            } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5266                    && currentFingerCount >= 2
5267                    && !isPointerDown(mCurrentRawState.buttonState)) {
5268                // Enter quiet time when releasing the button and there are still two or more
5269                // fingers down.  This may indicate that one finger was used to press the button
5270                // but it has not gone up yet.
5271                isQuietTime = true;
5272            }
5273            if (isQuietTime) {
5274                mPointerGesture.quietTime = when;
5275            }
5276        }
5277    }
5278
5279    // Switch states based on button and pointer state.
5280    if (isQuietTime) {
5281        // Case 1: Quiet time. (QUIET)
5282#if DEBUG_GESTURES
5283        ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5284                + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5285#endif
5286        if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5287            *outFinishPreviousGesture = true;
5288        }
5289
5290        mPointerGesture.activeGestureId = -1;
5291        mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5292        mPointerGesture.currentGestureIdBits.clear();
5293
5294        mPointerVelocityControl.reset();
5295    } else if (isPointerDown(mCurrentRawState.buttonState)) {
5296        // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5297        // The pointer follows the active touch point.
5298        // Emit DOWN, MOVE, UP events at the pointer location.
5299        //
5300        // Only the active touch matters; other fingers are ignored.  This policy helps
5301        // to handle the case where the user places a second finger on the touch pad
5302        // to apply the necessary force to depress an integrated button below the surface.
5303        // We don't want the second finger to be delivered to applications.
5304        //
5305        // For this to work well, we need to make sure to track the pointer that is really
5306        // active.  If the user first puts one finger down to click then adds another
5307        // finger to drag then the active pointer should switch to the finger that is
5308        // being dragged.
5309#if DEBUG_GESTURES
5310        ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5311                "currentFingerCount=%d", activeTouchId, currentFingerCount);
5312#endif
5313        // Reset state when just starting.
5314        if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5315            *outFinishPreviousGesture = true;
5316            mPointerGesture.activeGestureId = 0;
5317        }
5318
5319        // Switch pointers if needed.
5320        // Find the fastest pointer and follow it.
5321        if (activeTouchId >= 0 && currentFingerCount > 1) {
5322            int32_t bestId = -1;
5323            float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
5324            for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
5325                uint32_t id = idBits.clearFirstMarkedBit();
5326                float vx, vy;
5327                if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5328                    float speed = hypotf(vx, vy);
5329                    if (speed > bestSpeed) {
5330                        bestId = id;
5331                        bestSpeed = speed;
5332                    }
5333                }
5334            }
5335            if (bestId >= 0 && bestId != activeTouchId) {
5336                mPointerGesture.activeTouchId = activeTouchId = bestId;
5337                activeTouchChanged = true;
5338#if DEBUG_GESTURES
5339                ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5340                        "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5341#endif
5342            }
5343        }
5344
5345        if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
5346            const RawPointerData::Pointer& currentPointer =
5347                    mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
5348            const RawPointerData::Pointer& lastPointer =
5349                    mLastRawState.rawPointerData.pointerForId(activeTouchId);
5350            float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5351            float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
5352
5353            rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5354            mPointerVelocityControl.move(when, &deltaX, &deltaY);
5355
5356            // Move the pointer using a relative motion.
5357            // When using spots, the click will occur at the position of the anchor
5358            // spot and all other spots will move there.
5359            mPointerController->move(deltaX, deltaY);
5360        } else {
5361            mPointerVelocityControl.reset();
5362        }
5363
5364        float x, y;
5365        mPointerController->getPosition(&x, &y);
5366
5367        mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5368        mPointerGesture.currentGestureIdBits.clear();
5369        mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5370        mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5371        mPointerGesture.currentGestureProperties[0].clear();
5372        mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5373        mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5374        mPointerGesture.currentGestureCoords[0].clear();
5375        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5376        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5377        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5378    } else if (currentFingerCount == 0) {
5379        // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5380        if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5381            *outFinishPreviousGesture = true;
5382        }
5383
5384        // Watch for taps coming out of HOVER or TAP_DRAG mode.
5385        // Checking for taps after TAP_DRAG allows us to detect double-taps.
5386        bool tapped = false;
5387        if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5388                || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5389                && lastFingerCount == 1) {
5390            if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5391                float x, y;
5392                mPointerController->getPosition(&x, &y);
5393                if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5394                        && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5395#if DEBUG_GESTURES
5396                    ALOGD("Gestures: TAP");
5397#endif
5398
5399                    mPointerGesture.tapUpTime = when;
5400                    getContext()->requestTimeoutAtTime(when
5401                            + mConfig.pointerGestureTapDragInterval);
5402
5403                    mPointerGesture.activeGestureId = 0;
5404                    mPointerGesture.currentGestureMode = PointerGesture::TAP;
5405                    mPointerGesture.currentGestureIdBits.clear();
5406                    mPointerGesture.currentGestureIdBits.markBit(
5407                            mPointerGesture.activeGestureId);
5408                    mPointerGesture.currentGestureIdToIndex[
5409                            mPointerGesture.activeGestureId] = 0;
5410                    mPointerGesture.currentGestureProperties[0].clear();
5411                    mPointerGesture.currentGestureProperties[0].id =
5412                            mPointerGesture.activeGestureId;
5413                    mPointerGesture.currentGestureProperties[0].toolType =
5414                            AMOTION_EVENT_TOOL_TYPE_FINGER;
5415                    mPointerGesture.currentGestureCoords[0].clear();
5416                    mPointerGesture.currentGestureCoords[0].setAxisValue(
5417                            AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5418                    mPointerGesture.currentGestureCoords[0].setAxisValue(
5419                            AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5420                    mPointerGesture.currentGestureCoords[0].setAxisValue(
5421                            AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5422
5423                    tapped = true;
5424                } else {
5425#if DEBUG_GESTURES
5426                    ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5427                            x - mPointerGesture.tapX,
5428                            y - mPointerGesture.tapY);
5429#endif
5430                }
5431            } else {
5432#if DEBUG_GESTURES
5433                if (mPointerGesture.tapDownTime != LLONG_MIN) {
5434                    ALOGD("Gestures: Not a TAP, %0.3fms since down",
5435                            (when - mPointerGesture.tapDownTime) * 0.000001f);
5436                } else {
5437                    ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5438                }
5439#endif
5440            }
5441        }
5442
5443        mPointerVelocityControl.reset();
5444
5445        if (!tapped) {
5446#if DEBUG_GESTURES
5447            ALOGD("Gestures: NEUTRAL");
5448#endif
5449            mPointerGesture.activeGestureId = -1;
5450            mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5451            mPointerGesture.currentGestureIdBits.clear();
5452        }
5453    } else if (currentFingerCount == 1) {
5454        // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5455        // The pointer follows the active touch point.
5456        // When in HOVER, emit HOVER_MOVE events at the pointer location.
5457        // When in TAP_DRAG, emit MOVE events at the pointer location.
5458        ALOG_ASSERT(activeTouchId >= 0);
5459
5460        mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5461        if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5462            if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5463                float x, y;
5464                mPointerController->getPosition(&x, &y);
5465                if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5466                        && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5467                    mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5468                } else {
5469#if DEBUG_GESTURES
5470                    ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5471                            x - mPointerGesture.tapX,
5472                            y - mPointerGesture.tapY);
5473#endif
5474                }
5475            } else {
5476#if DEBUG_GESTURES
5477                ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5478                        (when - mPointerGesture.tapUpTime) * 0.000001f);
5479#endif
5480            }
5481        } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5482            mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5483        }
5484
5485        if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
5486            const RawPointerData::Pointer& currentPointer =
5487                    mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
5488            const RawPointerData::Pointer& lastPointer =
5489                    mLastRawState.rawPointerData.pointerForId(activeTouchId);
5490            float deltaX = (currentPointer.x - lastPointer.x)
5491                    * mPointerXMovementScale;
5492            float deltaY = (currentPointer.y - lastPointer.y)
5493                    * mPointerYMovementScale;
5494
5495            rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5496            mPointerVelocityControl.move(when, &deltaX, &deltaY);
5497
5498            // Move the pointer using a relative motion.
5499            // When using spots, the hover or drag will occur at the position of the anchor spot.
5500            mPointerController->move(deltaX, deltaY);
5501        } else {
5502            mPointerVelocityControl.reset();
5503        }
5504
5505        bool down;
5506        if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5507#if DEBUG_GESTURES
5508            ALOGD("Gestures: TAP_DRAG");
5509#endif
5510            down = true;
5511        } else {
5512#if DEBUG_GESTURES
5513            ALOGD("Gestures: HOVER");
5514#endif
5515            if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5516                *outFinishPreviousGesture = true;
5517            }
5518            mPointerGesture.activeGestureId = 0;
5519            down = false;
5520        }
5521
5522        float x, y;
5523        mPointerController->getPosition(&x, &y);
5524
5525        mPointerGesture.currentGestureIdBits.clear();
5526        mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5527        mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5528        mPointerGesture.currentGestureProperties[0].clear();
5529        mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5530        mPointerGesture.currentGestureProperties[0].toolType =
5531                AMOTION_EVENT_TOOL_TYPE_FINGER;
5532        mPointerGesture.currentGestureCoords[0].clear();
5533        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5534        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5535        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5536                down ? 1.0f : 0.0f);
5537
5538        if (lastFingerCount == 0 && currentFingerCount != 0) {
5539            mPointerGesture.resetTap();
5540            mPointerGesture.tapDownTime = when;
5541            mPointerGesture.tapX = x;
5542            mPointerGesture.tapY = y;
5543        }
5544    } else {
5545        // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5546        // We need to provide feedback for each finger that goes down so we cannot wait
5547        // for the fingers to move before deciding what to do.
5548        //
5549        // The ambiguous case is deciding what to do when there are two fingers down but they
5550        // have not moved enough to determine whether they are part of a drag or part of a
5551        // freeform gesture, or just a press or long-press at the pointer location.
5552        //
5553        // When there are two fingers we start with the PRESS hypothesis and we generate a
5554        // down at the pointer location.
5555        //
5556        // When the two fingers move enough or when additional fingers are added, we make
5557        // a decision to transition into SWIPE or FREEFORM mode accordingly.
5558        ALOG_ASSERT(activeTouchId >= 0);
5559
5560        bool settled = when >= mPointerGesture.firstTouchTime
5561                + mConfig.pointerGestureMultitouchSettleInterval;
5562        if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5563                && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5564                && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5565            *outFinishPreviousGesture = true;
5566        } else if (!settled && currentFingerCount > lastFingerCount) {
5567            // Additional pointers have gone down but not yet settled.
5568            // Reset the gesture.
5569#if DEBUG_GESTURES
5570            ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5571                    "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5572                            + mConfig.pointerGestureMultitouchSettleInterval - when)
5573                            * 0.000001f);
5574#endif
5575            *outCancelPreviousGesture = true;
5576        } else {
5577            // Continue previous gesture.
5578            mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5579        }
5580
5581        if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5582            mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5583            mPointerGesture.activeGestureId = 0;
5584            mPointerGesture.referenceIdBits.clear();
5585            mPointerVelocityControl.reset();
5586
5587            // Use the centroid and pointer location as the reference points for the gesture.
5588#if DEBUG_GESTURES
5589            ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5590                    "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5591                            + mConfig.pointerGestureMultitouchSettleInterval - when)
5592                            * 0.000001f);
5593#endif
5594            mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
5595                    &mPointerGesture.referenceTouchX,
5596                    &mPointerGesture.referenceTouchY);
5597            mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5598                    &mPointerGesture.referenceGestureY);
5599        }
5600
5601        // Clear the reference deltas for fingers not yet included in the reference calculation.
5602        for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
5603                & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5604            uint32_t id = idBits.clearFirstMarkedBit();
5605            mPointerGesture.referenceDeltas[id].dx = 0;
5606            mPointerGesture.referenceDeltas[id].dy = 0;
5607        }
5608        mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
5609
5610        // Add delta for all fingers and calculate a common movement delta.
5611        float commonDeltaX = 0, commonDeltaY = 0;
5612        BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5613                & mCurrentCookedState.fingerIdBits.value);
5614        for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5615            bool first = (idBits == commonIdBits);
5616            uint32_t id = idBits.clearFirstMarkedBit();
5617            const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5618            const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
5619            PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5620            delta.dx += cpd.x - lpd.x;
5621            delta.dy += cpd.y - lpd.y;
5622
5623            if (first) {
5624                commonDeltaX = delta.dx;
5625                commonDeltaY = delta.dy;
5626            } else {
5627                commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5628                commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5629            }
5630        }
5631
5632        // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5633        if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5634            float dist[MAX_POINTER_ID + 1];
5635            int32_t distOverThreshold = 0;
5636            for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5637                uint32_t id = idBits.clearFirstMarkedBit();
5638                PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5639                dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5640                        delta.dy * mPointerYZoomScale);
5641                if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5642                    distOverThreshold += 1;
5643                }
5644            }
5645
5646            // Only transition when at least two pointers have moved further than
5647            // the minimum distance threshold.
5648            if (distOverThreshold >= 2) {
5649                if (currentFingerCount > 2) {
5650                    // There are more than two pointers, switch to FREEFORM.
5651#if DEBUG_GESTURES
5652                    ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5653                            currentFingerCount);
5654#endif
5655                    *outCancelPreviousGesture = true;
5656                    mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5657                } else {
5658                    // There are exactly two pointers.
5659                    BitSet32 idBits(mCurrentCookedState.fingerIdBits);
5660                    uint32_t id1 = idBits.clearFirstMarkedBit();
5661                    uint32_t id2 = idBits.firstMarkedBit();
5662                    const RawPointerData::Pointer& p1 =
5663                            mCurrentRawState.rawPointerData.pointerForId(id1);
5664                    const RawPointerData::Pointer& p2 =
5665                            mCurrentRawState.rawPointerData.pointerForId(id2);
5666                    float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5667                    if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5668                        // There are two pointers but they are too far apart for a SWIPE,
5669                        // switch to FREEFORM.
5670#if DEBUG_GESTURES
5671                        ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5672                                mutualDistance, mPointerGestureMaxSwipeWidth);
5673#endif
5674                        *outCancelPreviousGesture = true;
5675                        mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5676                    } else {
5677                        // There are two pointers.  Wait for both pointers to start moving
5678                        // before deciding whether this is a SWIPE or FREEFORM gesture.
5679                        float dist1 = dist[id1];
5680                        float dist2 = dist[id2];
5681                        if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5682                                && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5683                            // Calculate the dot product of the displacement vectors.
5684                            // When the vectors are oriented in approximately the same direction,
5685                            // the angle betweeen them is near zero and the cosine of the angle
5686                            // approches 1.0.  Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5687                            PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5688                            PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5689                            float dx1 = delta1.dx * mPointerXZoomScale;
5690                            float dy1 = delta1.dy * mPointerYZoomScale;
5691                            float dx2 = delta2.dx * mPointerXZoomScale;
5692                            float dy2 = delta2.dy * mPointerYZoomScale;
5693                            float dot = dx1 * dx2 + dy1 * dy2;
5694                            float cosine = dot / (dist1 * dist2); // denominator always > 0
5695                            if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5696                                // Pointers are moving in the same direction.  Switch to SWIPE.
5697#if DEBUG_GESTURES
5698                                ALOGD("Gestures: PRESS transitioned to SWIPE, "
5699                                        "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5700                                        "cosine %0.3f >= %0.3f",
5701                                        dist1, mConfig.pointerGestureMultitouchMinDistance,
5702                                        dist2, mConfig.pointerGestureMultitouchMinDistance,
5703                                        cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5704#endif
5705                                mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5706                            } else {
5707                                // Pointers are moving in different directions.  Switch to FREEFORM.
5708#if DEBUG_GESTURES
5709                                ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5710                                        "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5711                                        "cosine %0.3f < %0.3f",
5712                                        dist1, mConfig.pointerGestureMultitouchMinDistance,
5713                                        dist2, mConfig.pointerGestureMultitouchMinDistance,
5714                                        cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5715#endif
5716                                *outCancelPreviousGesture = true;
5717                                mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5718                            }
5719                        }
5720                    }
5721                }
5722            }
5723        } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5724            // Switch from SWIPE to FREEFORM if additional pointers go down.
5725            // Cancel previous gesture.
5726            if (currentFingerCount > 2) {
5727#if DEBUG_GESTURES
5728                ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5729                        currentFingerCount);
5730#endif
5731                *outCancelPreviousGesture = true;
5732                mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5733            }
5734        }
5735
5736        // Move the reference points based on the overall group motion of the fingers
5737        // except in PRESS mode while waiting for a transition to occur.
5738        if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5739                && (commonDeltaX || commonDeltaY)) {
5740            for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5741                uint32_t id = idBits.clearFirstMarkedBit();
5742                PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5743                delta.dx = 0;
5744                delta.dy = 0;
5745            }
5746
5747            mPointerGesture.referenceTouchX += commonDeltaX;
5748            mPointerGesture.referenceTouchY += commonDeltaY;
5749
5750            commonDeltaX *= mPointerXMovementScale;
5751            commonDeltaY *= mPointerYMovementScale;
5752
5753            rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5754            mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5755
5756            mPointerGesture.referenceGestureX += commonDeltaX;
5757            mPointerGesture.referenceGestureY += commonDeltaY;
5758        }
5759
5760        // Report gestures.
5761        if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5762                || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5763            // PRESS or SWIPE mode.
5764#if DEBUG_GESTURES
5765            ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5766                    "activeGestureId=%d, currentTouchPointerCount=%d",
5767                    activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5768#endif
5769            ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5770
5771            mPointerGesture.currentGestureIdBits.clear();
5772            mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5773            mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5774            mPointerGesture.currentGestureProperties[0].clear();
5775            mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5776            mPointerGesture.currentGestureProperties[0].toolType =
5777                    AMOTION_EVENT_TOOL_TYPE_FINGER;
5778            mPointerGesture.currentGestureCoords[0].clear();
5779            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5780                    mPointerGesture.referenceGestureX);
5781            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5782                    mPointerGesture.referenceGestureY);
5783            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5784        } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5785            // FREEFORM mode.
5786#if DEBUG_GESTURES
5787            ALOGD("Gestures: FREEFORM activeTouchId=%d,"
5788                    "activeGestureId=%d, currentTouchPointerCount=%d",
5789                    activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5790#endif
5791            ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5792
5793            mPointerGesture.currentGestureIdBits.clear();
5794
5795            BitSet32 mappedTouchIdBits;
5796            BitSet32 usedGestureIdBits;
5797            if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5798                // Initially, assign the active gesture id to the active touch point
5799                // if there is one.  No other touch id bits are mapped yet.
5800                if (!*outCancelPreviousGesture) {
5801                    mappedTouchIdBits.markBit(activeTouchId);
5802                    usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
5803                    mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
5804                            mPointerGesture.activeGestureId;
5805                } else {
5806                    mPointerGesture.activeGestureId = -1;
5807                }
5808            } else {
5809                // Otherwise, assume we mapped all touches from the previous frame.
5810                // Reuse all mappings that are still applicable.
5811                mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
5812                        & mCurrentCookedState.fingerIdBits.value;
5813                usedGestureIdBits = mPointerGesture.lastGestureIdBits;
5814
5815                // Check whether we need to choose a new active gesture id because the
5816                // current went went up.
5817                for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
5818                        & ~mCurrentCookedState.fingerIdBits.value);
5819                        !upTouchIdBits.isEmpty(); ) {
5820                    uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
5821                    uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
5822                    if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
5823                        mPointerGesture.activeGestureId = -1;
5824                        break;
5825                    }
5826                }
5827            }
5828
5829#if DEBUG_GESTURES
5830            ALOGD("Gestures: FREEFORM follow up "
5831                    "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
5832                    "activeGestureId=%d",
5833                    mappedTouchIdBits.value, usedGestureIdBits.value,
5834                    mPointerGesture.activeGestureId);
5835#endif
5836
5837            BitSet32 idBits(mCurrentCookedState.fingerIdBits);
5838            for (uint32_t i = 0; i < currentFingerCount; i++) {
5839                uint32_t touchId = idBits.clearFirstMarkedBit();
5840                uint32_t gestureId;
5841                if (!mappedTouchIdBits.hasBit(touchId)) {
5842                    gestureId = usedGestureIdBits.markFirstUnmarkedBit();
5843                    mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
5844#if DEBUG_GESTURES
5845                    ALOGD("Gestures: FREEFORM "
5846                            "new mapping for touch id %d -> gesture id %d",
5847                            touchId, gestureId);
5848#endif
5849                } else {
5850                    gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
5851#if DEBUG_GESTURES
5852                    ALOGD("Gestures: FREEFORM "
5853                            "existing mapping for touch id %d -> gesture id %d",
5854                            touchId, gestureId);
5855#endif
5856                }
5857                mPointerGesture.currentGestureIdBits.markBit(gestureId);
5858                mPointerGesture.currentGestureIdToIndex[gestureId] = i;
5859
5860                const RawPointerData::Pointer& pointer =
5861                        mCurrentRawState.rawPointerData.pointerForId(touchId);
5862                float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
5863                        * mPointerXZoomScale;
5864                float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
5865                        * mPointerYZoomScale;
5866                rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5867
5868                mPointerGesture.currentGestureProperties[i].clear();
5869                mPointerGesture.currentGestureProperties[i].id = gestureId;
5870                mPointerGesture.currentGestureProperties[i].toolType =
5871                        AMOTION_EVENT_TOOL_TYPE_FINGER;
5872                mPointerGesture.currentGestureCoords[i].clear();
5873                mPointerGesture.currentGestureCoords[i].setAxisValue(
5874                        AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
5875                mPointerGesture.currentGestureCoords[i].setAxisValue(
5876                        AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
5877                mPointerGesture.currentGestureCoords[i].setAxisValue(
5878                        AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5879            }
5880
5881            if (mPointerGesture.activeGestureId < 0) {
5882                mPointerGesture.activeGestureId =
5883                        mPointerGesture.currentGestureIdBits.firstMarkedBit();
5884#if DEBUG_GESTURES
5885                ALOGD("Gestures: FREEFORM new "
5886                        "activeGestureId=%d", mPointerGesture.activeGestureId);
5887#endif
5888            }
5889        }
5890    }
5891
5892    mPointerController->setButtonState(mCurrentRawState.buttonState);
5893
5894#if DEBUG_GESTURES
5895    ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
5896            "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
5897            "lastGestureMode=%d, lastGestureIdBits=0x%08x",
5898            toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
5899            mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
5900            mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
5901    for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
5902        uint32_t id = idBits.clearFirstMarkedBit();
5903        uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5904        const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
5905        const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
5906        ALOGD("  currentGesture[%d]: index=%d, toolType=%d, "
5907                "x=%0.3f, y=%0.3f, pressure=%0.3f",
5908                id, index, properties.toolType,
5909                coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5910                coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5911                coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5912    }
5913    for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
5914        uint32_t id = idBits.clearFirstMarkedBit();
5915        uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
5916        const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
5917        const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
5918        ALOGD("  lastGesture[%d]: index=%d, toolType=%d, "
5919                "x=%0.3f, y=%0.3f, pressure=%0.3f",
5920                id, index, properties.toolType,
5921                coords.getAxisValue(AMOTION_EVENT_AXIS_X),
5922                coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
5923                coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
5924    }
5925#endif
5926    return true;
5927}
5928
5929void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
5930    mPointerSimple.currentCoords.clear();
5931    mPointerSimple.currentProperties.clear();
5932
5933    bool down, hovering;
5934    if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
5935        uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
5936        uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
5937        float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
5938        float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
5939        mPointerController->setPosition(x, y);
5940
5941        hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
5942        down = !hovering;
5943
5944        mPointerController->getPosition(&x, &y);
5945        mPointerSimple.currentCoords.copyFrom(
5946                mCurrentCookedState.cookedPointerData.pointerCoords[index]);
5947        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5948        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5949        mPointerSimple.currentProperties.id = 0;
5950        mPointerSimple.currentProperties.toolType =
5951                mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
5952    } else {
5953        down = false;
5954        hovering = false;
5955    }
5956
5957    dispatchPointerSimple(when, policyFlags, down, hovering);
5958}
5959
5960void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
5961    abortPointerSimple(when, policyFlags);
5962}
5963
5964void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
5965    mPointerSimple.currentCoords.clear();
5966    mPointerSimple.currentProperties.clear();
5967
5968    bool down, hovering;
5969    if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
5970        uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
5971        uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
5972        if (mLastCookedState.mouseIdBits.hasBit(id)) {
5973            uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
5974            float deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
5975                    - mLastRawState.rawPointerData.pointers[lastIndex].x)
5976                    * mPointerXMovementScale;
5977            float deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
5978                    - mLastRawState.rawPointerData.pointers[lastIndex].y)
5979                    * mPointerYMovementScale;
5980
5981            rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5982            mPointerVelocityControl.move(when, &deltaX, &deltaY);
5983
5984            mPointerController->move(deltaX, deltaY);
5985        } else {
5986            mPointerVelocityControl.reset();
5987        }
5988
5989        down = isPointerDown(mCurrentRawState.buttonState);
5990        hovering = !down;
5991
5992        float x, y;
5993        mPointerController->getPosition(&x, &y);
5994        mPointerSimple.currentCoords.copyFrom(
5995                mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
5996        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5997        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5998        mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5999                hovering ? 0.0f : 1.0f);
6000        mPointerSimple.currentProperties.id = 0;
6001        mPointerSimple.currentProperties.toolType =
6002                mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
6003    } else {
6004        mPointerVelocityControl.reset();
6005
6006        down = false;
6007        hovering = false;
6008    }
6009
6010    dispatchPointerSimple(when, policyFlags, down, hovering);
6011}
6012
6013void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6014    abortPointerSimple(when, policyFlags);
6015
6016    mPointerVelocityControl.reset();
6017}
6018
6019void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6020        bool down, bool hovering) {
6021    int32_t metaState = getContext()->getGlobalMetaState();
6022
6023    if (mPointerController != NULL) {
6024        if (down || hovering) {
6025            mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6026            mPointerController->clearSpots();
6027            mPointerController->setButtonState(mCurrentRawState.buttonState);
6028            mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6029        } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6030            mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6031        }
6032    }
6033
6034    if (mPointerSimple.down && !down) {
6035        mPointerSimple.down = false;
6036
6037        // Send up.
6038        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
6039                 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
6040                 mViewport.displayId,
6041                 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6042                 mOrientedXPrecision, mOrientedYPrecision,
6043                 mPointerSimple.downTime);
6044        getListener()->notifyMotion(&args);
6045    }
6046
6047    if (mPointerSimple.hovering && !hovering) {
6048        mPointerSimple.hovering = false;
6049
6050        // Send hover exit.
6051        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
6052                AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
6053                mViewport.displayId,
6054                1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6055                mOrientedXPrecision, mOrientedYPrecision,
6056                mPointerSimple.downTime);
6057        getListener()->notifyMotion(&args);
6058    }
6059
6060    if (down) {
6061        if (!mPointerSimple.down) {
6062            mPointerSimple.down = true;
6063            mPointerSimple.downTime = when;
6064
6065            // Send down.
6066            NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
6067                    AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
6068                    mViewport.displayId,
6069                    1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6070                    mOrientedXPrecision, mOrientedYPrecision,
6071                    mPointerSimple.downTime);
6072            getListener()->notifyMotion(&args);
6073        }
6074
6075        // Send move.
6076        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
6077                AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
6078                mViewport.displayId,
6079                1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6080                mOrientedXPrecision, mOrientedYPrecision,
6081                mPointerSimple.downTime);
6082        getListener()->notifyMotion(&args);
6083    }
6084
6085    if (hovering) {
6086        if (!mPointerSimple.hovering) {
6087            mPointerSimple.hovering = true;
6088
6089            // Send hover enter.
6090            NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
6091                    AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
6092                    mCurrentRawState.buttonState, 0,
6093                    mViewport.displayId,
6094                    1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6095                    mOrientedXPrecision, mOrientedYPrecision,
6096                    mPointerSimple.downTime);
6097            getListener()->notifyMotion(&args);
6098        }
6099
6100        // Send hover move.
6101        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
6102                AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
6103                mCurrentRawState.buttonState, 0,
6104                mViewport.displayId,
6105                1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6106                mOrientedXPrecision, mOrientedYPrecision,
6107                mPointerSimple.downTime);
6108        getListener()->notifyMotion(&args);
6109    }
6110
6111    if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6112        float vscroll = mCurrentRawState.rawVScroll;
6113        float hscroll = mCurrentRawState.rawHScroll;
6114        mWheelYVelocityControl.move(when, NULL, &vscroll);
6115        mWheelXVelocityControl.move(when, &hscroll, NULL);
6116
6117        // Send scroll.
6118        PointerCoords pointerCoords;
6119        pointerCoords.copyFrom(mPointerSimple.currentCoords);
6120        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6121        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6122
6123        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
6124                AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
6125                mViewport.displayId,
6126                1, &mPointerSimple.currentProperties, &pointerCoords,
6127                mOrientedXPrecision, mOrientedYPrecision,
6128                mPointerSimple.downTime);
6129        getListener()->notifyMotion(&args);
6130    }
6131
6132    // Save state.
6133    if (down || hovering) {
6134        mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6135        mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6136    } else {
6137        mPointerSimple.reset();
6138    }
6139}
6140
6141void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6142    mPointerSimple.currentCoords.clear();
6143    mPointerSimple.currentProperties.clear();
6144
6145    dispatchPointerSimple(when, policyFlags, false, false);
6146}
6147
6148void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
6149        int32_t action, int32_t actionButton, int32_t flags,
6150        int32_t metaState, int32_t buttonState, int32_t edgeFlags,
6151        const PointerProperties* properties, const PointerCoords* coords,
6152        const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6153        float xPrecision, float yPrecision, nsecs_t downTime) {
6154    PointerCoords pointerCoords[MAX_POINTERS];
6155    PointerProperties pointerProperties[MAX_POINTERS];
6156    uint32_t pointerCount = 0;
6157    while (!idBits.isEmpty()) {
6158        uint32_t id = idBits.clearFirstMarkedBit();
6159        uint32_t index = idToIndex[id];
6160        pointerProperties[pointerCount].copyFrom(properties[index]);
6161        pointerCoords[pointerCount].copyFrom(coords[index]);
6162
6163        if (changedId >= 0 && id == uint32_t(changedId)) {
6164            action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6165        }
6166
6167        pointerCount += 1;
6168    }
6169
6170    ALOG_ASSERT(pointerCount != 0);
6171
6172    if (changedId >= 0 && pointerCount == 1) {
6173        // Replace initial down and final up action.
6174        // We can compare the action without masking off the changed pointer index
6175        // because we know the index is 0.
6176        if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6177            action = AMOTION_EVENT_ACTION_DOWN;
6178        } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6179            action = AMOTION_EVENT_ACTION_UP;
6180        } else {
6181            // Can't happen.
6182            ALOG_ASSERT(false);
6183        }
6184    }
6185
6186    NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
6187            action, actionButton, flags, metaState, buttonState, edgeFlags,
6188            mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6189            xPrecision, yPrecision, downTime);
6190    getListener()->notifyMotion(&args);
6191}
6192
6193bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6194        const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6195        PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6196        BitSet32 idBits) const {
6197    bool changed = false;
6198    while (!idBits.isEmpty()) {
6199        uint32_t id = idBits.clearFirstMarkedBit();
6200        uint32_t inIndex = inIdToIndex[id];
6201        uint32_t outIndex = outIdToIndex[id];
6202
6203        const PointerProperties& curInProperties = inProperties[inIndex];
6204        const PointerCoords& curInCoords = inCoords[inIndex];
6205        PointerProperties& curOutProperties = outProperties[outIndex];
6206        PointerCoords& curOutCoords = outCoords[outIndex];
6207
6208        if (curInProperties != curOutProperties) {
6209            curOutProperties.copyFrom(curInProperties);
6210            changed = true;
6211        }
6212
6213        if (curInCoords != curOutCoords) {
6214            curOutCoords.copyFrom(curInCoords);
6215            changed = true;
6216        }
6217    }
6218    return changed;
6219}
6220
6221void TouchInputMapper::fadePointer() {
6222    if (mPointerController != NULL) {
6223        mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6224    }
6225}
6226
6227void TouchInputMapper::cancelTouch(nsecs_t when) {
6228    abortPointerUsage(when, 0 /*policyFlags*/);
6229    abortTouches(when, 0 /* policyFlags*/);
6230}
6231
6232bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6233    return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6234            && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6235}
6236
6237const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6238        int32_t x, int32_t y) {
6239    size_t numVirtualKeys = mVirtualKeys.size();
6240    for (size_t i = 0; i < numVirtualKeys; i++) {
6241        const VirtualKey& virtualKey = mVirtualKeys[i];
6242
6243#if DEBUG_VIRTUAL_KEYS
6244        ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6245                "left=%d, top=%d, right=%d, bottom=%d",
6246                x, y,
6247                virtualKey.keyCode, virtualKey.scanCode,
6248                virtualKey.hitLeft, virtualKey.hitTop,
6249                virtualKey.hitRight, virtualKey.hitBottom);
6250#endif
6251
6252        if (virtualKey.isHit(x, y)) {
6253            return & virtualKey;
6254        }
6255    }
6256
6257    return NULL;
6258}
6259
6260void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6261    uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6262    uint32_t lastPointerCount = last->rawPointerData.pointerCount;
6263
6264    current->rawPointerData.clearIdBits();
6265
6266    if (currentPointerCount == 0) {
6267        // No pointers to assign.
6268        return;
6269    }
6270
6271    if (lastPointerCount == 0) {
6272        // All pointers are new.
6273        for (uint32_t i = 0; i < currentPointerCount; i++) {
6274            uint32_t id = i;
6275            current->rawPointerData.pointers[i].id = id;
6276            current->rawPointerData.idToIndex[id] = i;
6277            current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
6278        }
6279        return;
6280    }
6281
6282    if (currentPointerCount == 1 && lastPointerCount == 1
6283            && current->rawPointerData.pointers[0].toolType
6284                    == last->rawPointerData.pointers[0].toolType) {
6285        // Only one pointer and no change in count so it must have the same id as before.
6286        uint32_t id = last->rawPointerData.pointers[0].id;
6287        current->rawPointerData.pointers[0].id = id;
6288        current->rawPointerData.idToIndex[id] = 0;
6289        current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
6290        return;
6291    }
6292
6293    // General case.
6294    // We build a heap of squared euclidean distances between current and last pointers
6295    // associated with the current and last pointer indices.  Then, we find the best
6296    // match (by distance) for each current pointer.
6297    // The pointers must have the same tool type but it is possible for them to
6298    // transition from hovering to touching or vice-versa while retaining the same id.
6299    PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6300
6301    uint32_t heapSize = 0;
6302    for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6303            currentPointerIndex++) {
6304        for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6305                lastPointerIndex++) {
6306            const RawPointerData::Pointer& currentPointer =
6307                    current->rawPointerData.pointers[currentPointerIndex];
6308            const RawPointerData::Pointer& lastPointer =
6309                    last->rawPointerData.pointers[lastPointerIndex];
6310            if (currentPointer.toolType == lastPointer.toolType) {
6311                int64_t deltaX = currentPointer.x - lastPointer.x;
6312                int64_t deltaY = currentPointer.y - lastPointer.y;
6313
6314                uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6315
6316                // Insert new element into the heap (sift up).
6317                heap[heapSize].currentPointerIndex = currentPointerIndex;
6318                heap[heapSize].lastPointerIndex = lastPointerIndex;
6319                heap[heapSize].distance = distance;
6320                heapSize += 1;
6321            }
6322        }
6323    }
6324
6325    // Heapify
6326    for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6327        startIndex -= 1;
6328        for (uint32_t parentIndex = startIndex; ;) {
6329            uint32_t childIndex = parentIndex * 2 + 1;
6330            if (childIndex >= heapSize) {
6331                break;
6332            }
6333
6334            if (childIndex + 1 < heapSize
6335                    && heap[childIndex + 1].distance < heap[childIndex].distance) {
6336                childIndex += 1;
6337            }
6338
6339            if (heap[parentIndex].distance <= heap[childIndex].distance) {
6340                break;
6341            }
6342
6343            swap(heap[parentIndex], heap[childIndex]);
6344            parentIndex = childIndex;
6345        }
6346    }
6347
6348#if DEBUG_POINTER_ASSIGNMENT
6349    ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6350    for (size_t i = 0; i < heapSize; i++) {
6351        ALOGD("  heap[%d]: cur=%d, last=%d, distance=%lld",
6352                i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6353                heap[i].distance);
6354    }
6355#endif
6356
6357    // Pull matches out by increasing order of distance.
6358    // To avoid reassigning pointers that have already been matched, the loop keeps track
6359    // of which last and current pointers have been matched using the matchedXXXBits variables.
6360    // It also tracks the used pointer id bits.
6361    BitSet32 matchedLastBits(0);
6362    BitSet32 matchedCurrentBits(0);
6363    BitSet32 usedIdBits(0);
6364    bool first = true;
6365    for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6366        while (heapSize > 0) {
6367            if (first) {
6368                // The first time through the loop, we just consume the root element of
6369                // the heap (the one with smallest distance).
6370                first = false;
6371            } else {
6372                // Previous iterations consumed the root element of the heap.
6373                // Pop root element off of the heap (sift down).
6374                heap[0] = heap[heapSize];
6375                for (uint32_t parentIndex = 0; ;) {
6376                    uint32_t childIndex = parentIndex * 2 + 1;
6377                    if (childIndex >= heapSize) {
6378                        break;
6379                    }
6380
6381                    if (childIndex + 1 < heapSize
6382                            && heap[childIndex + 1].distance < heap[childIndex].distance) {
6383                        childIndex += 1;
6384                    }
6385
6386                    if (heap[parentIndex].distance <= heap[childIndex].distance) {
6387                        break;
6388                    }
6389
6390                    swap(heap[parentIndex], heap[childIndex]);
6391                    parentIndex = childIndex;
6392                }
6393
6394#if DEBUG_POINTER_ASSIGNMENT
6395                ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6396                for (size_t i = 0; i < heapSize; i++) {
6397                    ALOGD("  heap[%d]: cur=%d, last=%d, distance=%lld",
6398                            i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6399                            heap[i].distance);
6400                }
6401#endif
6402            }
6403
6404            heapSize -= 1;
6405
6406            uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6407            if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6408
6409            uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6410            if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6411
6412            matchedCurrentBits.markBit(currentPointerIndex);
6413            matchedLastBits.markBit(lastPointerIndex);
6414
6415            uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6416            current->rawPointerData.pointers[currentPointerIndex].id = id;
6417            current->rawPointerData.idToIndex[id] = currentPointerIndex;
6418            current->rawPointerData.markIdBit(id,
6419                    current->rawPointerData.isHovering(currentPointerIndex));
6420            usedIdBits.markBit(id);
6421
6422#if DEBUG_POINTER_ASSIGNMENT
6423            ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6424                    lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6425#endif
6426            break;
6427        }
6428    }
6429
6430    // Assign fresh ids to pointers that were not matched in the process.
6431    for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6432        uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6433        uint32_t id = usedIdBits.markFirstUnmarkedBit();
6434
6435        current->rawPointerData.pointers[currentPointerIndex].id = id;
6436        current->rawPointerData.idToIndex[id] = currentPointerIndex;
6437        current->rawPointerData.markIdBit(id,
6438                current->rawPointerData.isHovering(currentPointerIndex));
6439
6440#if DEBUG_POINTER_ASSIGNMENT
6441        ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6442                currentPointerIndex, id);
6443#endif
6444    }
6445}
6446
6447int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6448    if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6449        return AKEY_STATE_VIRTUAL;
6450    }
6451
6452    size_t numVirtualKeys = mVirtualKeys.size();
6453    for (size_t i = 0; i < numVirtualKeys; i++) {
6454        const VirtualKey& virtualKey = mVirtualKeys[i];
6455        if (virtualKey.keyCode == keyCode) {
6456            return AKEY_STATE_UP;
6457        }
6458    }
6459
6460    return AKEY_STATE_UNKNOWN;
6461}
6462
6463int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6464    if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6465        return AKEY_STATE_VIRTUAL;
6466    }
6467
6468    size_t numVirtualKeys = mVirtualKeys.size();
6469    for (size_t i = 0; i < numVirtualKeys; i++) {
6470        const VirtualKey& virtualKey = mVirtualKeys[i];
6471        if (virtualKey.scanCode == scanCode) {
6472            return AKEY_STATE_UP;
6473        }
6474    }
6475
6476    return AKEY_STATE_UNKNOWN;
6477}
6478
6479bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6480        const int32_t* keyCodes, uint8_t* outFlags) {
6481    size_t numVirtualKeys = mVirtualKeys.size();
6482    for (size_t i = 0; i < numVirtualKeys; i++) {
6483        const VirtualKey& virtualKey = mVirtualKeys[i];
6484
6485        for (size_t i = 0; i < numCodes; i++) {
6486            if (virtualKey.keyCode == keyCodes[i]) {
6487                outFlags[i] = 1;
6488            }
6489        }
6490    }
6491
6492    return true;
6493}
6494
6495
6496// --- SingleTouchInputMapper ---
6497
6498SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6499        TouchInputMapper(device) {
6500}
6501
6502SingleTouchInputMapper::~SingleTouchInputMapper() {
6503}
6504
6505void SingleTouchInputMapper::reset(nsecs_t when) {
6506    mSingleTouchMotionAccumulator.reset(getDevice());
6507
6508    TouchInputMapper::reset(when);
6509}
6510
6511void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6512    TouchInputMapper::process(rawEvent);
6513
6514    mSingleTouchMotionAccumulator.process(rawEvent);
6515}
6516
6517void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
6518    if (mTouchButtonAccumulator.isToolActive()) {
6519        outState->rawPointerData.pointerCount = 1;
6520        outState->rawPointerData.idToIndex[0] = 0;
6521
6522        bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6523                && (mTouchButtonAccumulator.isHovering()
6524                        || (mRawPointerAxes.pressure.valid
6525                                && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
6526        outState->rawPointerData.markIdBit(0, isHovering);
6527
6528        RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
6529        outPointer.id = 0;
6530        outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6531        outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6532        outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6533        outPointer.touchMajor = 0;
6534        outPointer.touchMinor = 0;
6535        outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6536        outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6537        outPointer.orientation = 0;
6538        outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6539        outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6540        outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6541        outPointer.toolType = mTouchButtonAccumulator.getToolType();
6542        if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6543            outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6544        }
6545        outPointer.isHovering = isHovering;
6546    }
6547}
6548
6549void SingleTouchInputMapper::configureRawPointerAxes() {
6550    TouchInputMapper::configureRawPointerAxes();
6551
6552    getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6553    getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6554    getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6555    getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6556    getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6557    getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6558    getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6559}
6560
6561bool SingleTouchInputMapper::hasStylus() const {
6562    return mTouchButtonAccumulator.hasStylus();
6563}
6564
6565
6566// --- MultiTouchInputMapper ---
6567
6568MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6569        TouchInputMapper(device) {
6570}
6571
6572MultiTouchInputMapper::~MultiTouchInputMapper() {
6573}
6574
6575void MultiTouchInputMapper::reset(nsecs_t when) {
6576    mMultiTouchMotionAccumulator.reset(getDevice());
6577
6578    mPointerIdBits.clear();
6579
6580    TouchInputMapper::reset(when);
6581}
6582
6583void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6584    TouchInputMapper::process(rawEvent);
6585
6586    mMultiTouchMotionAccumulator.process(rawEvent);
6587}
6588
6589void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
6590    size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6591    size_t outCount = 0;
6592    BitSet32 newPointerIdBits;
6593
6594    for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6595        const MultiTouchMotionAccumulator::Slot* inSlot =
6596                mMultiTouchMotionAccumulator.getSlot(inIndex);
6597        if (!inSlot->isInUse()) {
6598            continue;
6599        }
6600
6601        if (outCount >= MAX_POINTERS) {
6602#if DEBUG_POINTERS
6603            ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6604                    "ignoring the rest.",
6605                    getDeviceName().string(), MAX_POINTERS);
6606#endif
6607            break; // too many fingers!
6608        }
6609
6610        RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
6611        outPointer.x = inSlot->getX();
6612        outPointer.y = inSlot->getY();
6613        outPointer.pressure = inSlot->getPressure();
6614        outPointer.touchMajor = inSlot->getTouchMajor();
6615        outPointer.touchMinor = inSlot->getTouchMinor();
6616        outPointer.toolMajor = inSlot->getToolMajor();
6617        outPointer.toolMinor = inSlot->getToolMinor();
6618        outPointer.orientation = inSlot->getOrientation();
6619        outPointer.distance = inSlot->getDistance();
6620        outPointer.tiltX = 0;
6621        outPointer.tiltY = 0;
6622
6623        outPointer.toolType = inSlot->getToolType();
6624        if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6625            outPointer.toolType = mTouchButtonAccumulator.getToolType();
6626            if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6627                outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6628            }
6629        }
6630
6631        bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6632                && (mTouchButtonAccumulator.isHovering()
6633                        || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6634        outPointer.isHovering = isHovering;
6635
6636        // Assign pointer id using tracking id if available.
6637        mHavePointerIds = true;
6638        int32_t trackingId = inSlot->getTrackingId();
6639        int32_t id = -1;
6640        if (trackingId >= 0) {
6641            for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6642                uint32_t n = idBits.clearFirstMarkedBit();
6643                if (mPointerTrackingIdMap[n] == trackingId) {
6644                    id = n;
6645                }
6646            }
6647
6648            if (id < 0 && !mPointerIdBits.isFull()) {
6649                id = mPointerIdBits.markFirstUnmarkedBit();
6650                mPointerTrackingIdMap[id] = trackingId;
6651            }
6652        }
6653        if (id < 0) {
6654            mHavePointerIds = false;
6655            outState->rawPointerData.clearIdBits();
6656            newPointerIdBits.clear();
6657        } else {
6658            outPointer.id = id;
6659            outState->rawPointerData.idToIndex[id] = outCount;
6660            outState->rawPointerData.markIdBit(id, isHovering);
6661            newPointerIdBits.markBit(id);
6662        }
6663
6664        outCount += 1;
6665    }
6666
6667    outState->rawPointerData.pointerCount = outCount;
6668    mPointerIdBits = newPointerIdBits;
6669
6670    mMultiTouchMotionAccumulator.finishSync();
6671}
6672
6673void MultiTouchInputMapper::configureRawPointerAxes() {
6674    TouchInputMapper::configureRawPointerAxes();
6675
6676    getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6677    getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6678    getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6679    getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6680    getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6681    getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6682    getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6683    getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6684    getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6685    getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6686    getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6687
6688    if (mRawPointerAxes.trackingId.valid
6689            && mRawPointerAxes.slot.valid
6690            && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6691        size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6692        if (slotCount > MAX_SLOTS) {
6693            ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6694                    "only supports a maximum of %zu slots at this time.",
6695                    getDeviceName().string(), slotCount, MAX_SLOTS);
6696            slotCount = MAX_SLOTS;
6697        }
6698        mMultiTouchMotionAccumulator.configure(getDevice(),
6699                slotCount, true /*usingSlotsProtocol*/);
6700    } else {
6701        mMultiTouchMotionAccumulator.configure(getDevice(),
6702                MAX_POINTERS, false /*usingSlotsProtocol*/);
6703    }
6704}
6705
6706bool MultiTouchInputMapper::hasStylus() const {
6707    return mMultiTouchMotionAccumulator.hasStylus()
6708            || mTouchButtonAccumulator.hasStylus();
6709}
6710
6711// --- ExternalStylusInputMapper
6712
6713ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6714    InputMapper(device) {
6715
6716}
6717
6718uint32_t ExternalStylusInputMapper::getSources() {
6719    return AINPUT_SOURCE_STYLUS;
6720}
6721
6722void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6723    InputMapper::populateDeviceInfo(info);
6724    info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6725            0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6726}
6727
6728void ExternalStylusInputMapper::dump(String8& dump) {
6729    dump.append(INDENT2 "External Stylus Input Mapper:\n");
6730    dump.append(INDENT3 "Raw Stylus Axes:\n");
6731    dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6732    dump.append(INDENT3 "Stylus State:\n");
6733    dumpStylusState(dump, mStylusState);
6734}
6735
6736void ExternalStylusInputMapper::configure(nsecs_t when,
6737        const InputReaderConfiguration* config, uint32_t changes) {
6738    getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6739    mTouchButtonAccumulator.configure(getDevice());
6740}
6741
6742void ExternalStylusInputMapper::reset(nsecs_t when) {
6743    InputDevice* device = getDevice();
6744    mSingleTouchMotionAccumulator.reset(device);
6745    mTouchButtonAccumulator.reset(device);
6746    InputMapper::reset(when);
6747}
6748
6749void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6750    mSingleTouchMotionAccumulator.process(rawEvent);
6751    mTouchButtonAccumulator.process(rawEvent);
6752
6753    if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6754        sync(rawEvent->when);
6755    }
6756}
6757
6758void ExternalStylusInputMapper::sync(nsecs_t when) {
6759    mStylusState.clear();
6760
6761    mStylusState.when = when;
6762
6763    mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6764    if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6765        mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6766    }
6767
6768    int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6769    if (mRawPressureAxis.valid) {
6770        mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
6771    } else if (mTouchButtonAccumulator.isToolActive()) {
6772        mStylusState.pressure = 1.0f;
6773    } else {
6774        mStylusState.pressure = 0.0f;
6775    }
6776
6777    mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
6778
6779    mContext->dispatchExternalStylusState(mStylusState);
6780}
6781
6782
6783// --- JoystickInputMapper ---
6784
6785JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
6786        InputMapper(device) {
6787}
6788
6789JoystickInputMapper::~JoystickInputMapper() {
6790}
6791
6792uint32_t JoystickInputMapper::getSources() {
6793    return AINPUT_SOURCE_JOYSTICK;
6794}
6795
6796void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6797    InputMapper::populateDeviceInfo(info);
6798
6799    for (size_t i = 0; i < mAxes.size(); i++) {
6800        const Axis& axis = mAxes.valueAt(i);
6801        addMotionRange(axis.axisInfo.axis, axis, info);
6802
6803        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6804            addMotionRange(axis.axisInfo.highAxis, axis, info);
6805
6806        }
6807    }
6808}
6809
6810void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
6811        InputDeviceInfo* info) {
6812    info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
6813            axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6814    /* In order to ease the transition for developers from using the old axes
6815     * to the newer, more semantically correct axes, we'll continue to register
6816     * the old axes as duplicates of their corresponding new ones.  */
6817    int32_t compatAxis = getCompatAxis(axisId);
6818    if (compatAxis >= 0) {
6819        info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
6820                axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6821    }
6822}
6823
6824/* A mapping from axes the joystick actually has to the axes that should be
6825 * artificially created for compatibility purposes.
6826 * Returns -1 if no compatibility axis is needed. */
6827int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
6828    switch(axis) {
6829    case AMOTION_EVENT_AXIS_LTRIGGER:
6830        return AMOTION_EVENT_AXIS_BRAKE;
6831    case AMOTION_EVENT_AXIS_RTRIGGER:
6832        return AMOTION_EVENT_AXIS_GAS;
6833    }
6834    return -1;
6835}
6836
6837void JoystickInputMapper::dump(String8& dump) {
6838    dump.append(INDENT2 "Joystick Input Mapper:\n");
6839
6840    dump.append(INDENT3 "Axes:\n");
6841    size_t numAxes = mAxes.size();
6842    for (size_t i = 0; i < numAxes; i++) {
6843        const Axis& axis = mAxes.valueAt(i);
6844        const char* label = getAxisLabel(axis.axisInfo.axis);
6845        if (label) {
6846            dump.appendFormat(INDENT4 "%s", label);
6847        } else {
6848            dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
6849        }
6850        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6851            label = getAxisLabel(axis.axisInfo.highAxis);
6852            if (label) {
6853                dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
6854            } else {
6855                dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
6856                        axis.axisInfo.splitValue);
6857            }
6858        } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
6859            dump.append(" (invert)");
6860        }
6861
6862        dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
6863                axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
6864        dump.appendFormat(INDENT4 "  scale=%0.5f, offset=%0.5f, "
6865                "highScale=%0.5f, highOffset=%0.5f\n",
6866                axis.scale, axis.offset, axis.highScale, axis.highOffset);
6867        dump.appendFormat(INDENT4 "  rawAxis=%d, rawMin=%d, rawMax=%d, "
6868                "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
6869                mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
6870                axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
6871    }
6872}
6873
6874void JoystickInputMapper::configure(nsecs_t when,
6875        const InputReaderConfiguration* config, uint32_t changes) {
6876    InputMapper::configure(when, config, changes);
6877
6878    if (!changes) { // first time only
6879        // Collect all axes.
6880        for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
6881            if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
6882                    & INPUT_DEVICE_CLASS_JOYSTICK)) {
6883                continue; // axis must be claimed by a different device
6884            }
6885
6886            RawAbsoluteAxisInfo rawAxisInfo;
6887            getAbsoluteAxisInfo(abs, &rawAxisInfo);
6888            if (rawAxisInfo.valid) {
6889                // Map axis.
6890                AxisInfo axisInfo;
6891                bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
6892                if (!explicitlyMapped) {
6893                    // Axis is not explicitly mapped, will choose a generic axis later.
6894                    axisInfo.mode = AxisInfo::MODE_NORMAL;
6895                    axisInfo.axis = -1;
6896                }
6897
6898                // Apply flat override.
6899                int32_t rawFlat = axisInfo.flatOverride < 0
6900                        ? rawAxisInfo.flat : axisInfo.flatOverride;
6901
6902                // Calculate scaling factors and limits.
6903                Axis axis;
6904                if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
6905                    float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
6906                    float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
6907                    axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6908                            scale, 0.0f, highScale, 0.0f,
6909                            0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6910                            rawAxisInfo.resolution * scale);
6911                } else if (isCenteredAxis(axisInfo.axis)) {
6912                    float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6913                    float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
6914                    axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6915                            scale, offset, scale, offset,
6916                            -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6917                            rawAxisInfo.resolution * scale);
6918                } else {
6919                    float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
6920                    axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
6921                            scale, 0.0f, scale, 0.0f,
6922                            0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
6923                            rawAxisInfo.resolution * scale);
6924                }
6925
6926                // To eliminate noise while the joystick is at rest, filter out small variations
6927                // in axis values up front.
6928                axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
6929
6930                mAxes.add(abs, axis);
6931            }
6932        }
6933
6934        // If there are too many axes, start dropping them.
6935        // Prefer to keep explicitly mapped axes.
6936        if (mAxes.size() > PointerCoords::MAX_AXES) {
6937            ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
6938                    getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
6939            pruneAxes(true);
6940            pruneAxes(false);
6941        }
6942
6943        // Assign generic axis ids to remaining axes.
6944        int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
6945        size_t numAxes = mAxes.size();
6946        for (size_t i = 0; i < numAxes; i++) {
6947            Axis& axis = mAxes.editValueAt(i);
6948            if (axis.axisInfo.axis < 0) {
6949                while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
6950                        && haveAxis(nextGenericAxisId)) {
6951                    nextGenericAxisId += 1;
6952                }
6953
6954                if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
6955                    axis.axisInfo.axis = nextGenericAxisId;
6956                    nextGenericAxisId += 1;
6957                } else {
6958                    ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
6959                            "have already been assigned to other axes.",
6960                            getDeviceName().string(), mAxes.keyAt(i));
6961                    mAxes.removeItemsAt(i--);
6962                    numAxes -= 1;
6963                }
6964            }
6965        }
6966    }
6967}
6968
6969bool JoystickInputMapper::haveAxis(int32_t axisId) {
6970    size_t numAxes = mAxes.size();
6971    for (size_t i = 0; i < numAxes; i++) {
6972        const Axis& axis = mAxes.valueAt(i);
6973        if (axis.axisInfo.axis == axisId
6974                || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
6975                        && axis.axisInfo.highAxis == axisId)) {
6976            return true;
6977        }
6978    }
6979    return false;
6980}
6981
6982void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
6983    size_t i = mAxes.size();
6984    while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
6985        if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
6986            continue;
6987        }
6988        ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
6989                getDeviceName().string(), mAxes.keyAt(i));
6990        mAxes.removeItemsAt(i);
6991    }
6992}
6993
6994bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
6995    switch (axis) {
6996    case AMOTION_EVENT_AXIS_X:
6997    case AMOTION_EVENT_AXIS_Y:
6998    case AMOTION_EVENT_AXIS_Z:
6999    case AMOTION_EVENT_AXIS_RX:
7000    case AMOTION_EVENT_AXIS_RY:
7001    case AMOTION_EVENT_AXIS_RZ:
7002    case AMOTION_EVENT_AXIS_HAT_X:
7003    case AMOTION_EVENT_AXIS_HAT_Y:
7004    case AMOTION_EVENT_AXIS_ORIENTATION:
7005    case AMOTION_EVENT_AXIS_RUDDER:
7006    case AMOTION_EVENT_AXIS_WHEEL:
7007        return true;
7008    default:
7009        return false;
7010    }
7011}
7012
7013void JoystickInputMapper::reset(nsecs_t when) {
7014    // Recenter all axes.
7015    size_t numAxes = mAxes.size();
7016    for (size_t i = 0; i < numAxes; i++) {
7017        Axis& axis = mAxes.editValueAt(i);
7018        axis.resetValue();
7019    }
7020
7021    InputMapper::reset(when);
7022}
7023
7024void JoystickInputMapper::process(const RawEvent* rawEvent) {
7025    switch (rawEvent->type) {
7026    case EV_ABS: {
7027        ssize_t index = mAxes.indexOfKey(rawEvent->code);
7028        if (index >= 0) {
7029            Axis& axis = mAxes.editValueAt(index);
7030            float newValue, highNewValue;
7031            switch (axis.axisInfo.mode) {
7032            case AxisInfo::MODE_INVERT:
7033                newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7034                        * axis.scale + axis.offset;
7035                highNewValue = 0.0f;
7036                break;
7037            case AxisInfo::MODE_SPLIT:
7038                if (rawEvent->value < axis.axisInfo.splitValue) {
7039                    newValue = (axis.axisInfo.splitValue - rawEvent->value)
7040                            * axis.scale + axis.offset;
7041                    highNewValue = 0.0f;
7042                } else if (rawEvent->value > axis.axisInfo.splitValue) {
7043                    newValue = 0.0f;
7044                    highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7045                            * axis.highScale + axis.highOffset;
7046                } else {
7047                    newValue = 0.0f;
7048                    highNewValue = 0.0f;
7049                }
7050                break;
7051            default:
7052                newValue = rawEvent->value * axis.scale + axis.offset;
7053                highNewValue = 0.0f;
7054                break;
7055            }
7056            axis.newValue = newValue;
7057            axis.highNewValue = highNewValue;
7058        }
7059        break;
7060    }
7061
7062    case EV_SYN:
7063        switch (rawEvent->code) {
7064        case SYN_REPORT:
7065            sync(rawEvent->when, false /*force*/);
7066            break;
7067        }
7068        break;
7069    }
7070}
7071
7072void JoystickInputMapper::sync(nsecs_t when, bool force) {
7073    if (!filterAxes(force)) {
7074        return;
7075    }
7076
7077    int32_t metaState = mContext->getGlobalMetaState();
7078    int32_t buttonState = 0;
7079
7080    PointerProperties pointerProperties;
7081    pointerProperties.clear();
7082    pointerProperties.id = 0;
7083    pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7084
7085    PointerCoords pointerCoords;
7086    pointerCoords.clear();
7087
7088    size_t numAxes = mAxes.size();
7089    for (size_t i = 0; i < numAxes; i++) {
7090        const Axis& axis = mAxes.valueAt(i);
7091        setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7092        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7093            setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7094                    axis.highCurrentValue);
7095        }
7096    }
7097
7098    // Moving a joystick axis should not wake the device because joysticks can
7099    // be fairly noisy even when not in use.  On the other hand, pushing a gamepad
7100    // button will likely wake the device.
7101    // TODO: Use the input device configuration to control this behavior more finely.
7102    uint32_t policyFlags = 0;
7103
7104    NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
7105            AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
7106            ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7107    getListener()->notifyMotion(&args);
7108}
7109
7110void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7111        int32_t axis, float value) {
7112    pointerCoords->setAxisValue(axis, value);
7113    /* In order to ease the transition for developers from using the old axes
7114     * to the newer, more semantically correct axes, we'll continue to produce
7115     * values for the old axes as mirrors of the value of their corresponding
7116     * new axes. */
7117    int32_t compatAxis = getCompatAxis(axis);
7118    if (compatAxis >= 0) {
7119        pointerCoords->setAxisValue(compatAxis, value);
7120    }
7121}
7122
7123bool JoystickInputMapper::filterAxes(bool force) {
7124    bool atLeastOneSignificantChange = force;
7125    size_t numAxes = mAxes.size();
7126    for (size_t i = 0; i < numAxes; i++) {
7127        Axis& axis = mAxes.editValueAt(i);
7128        if (force || hasValueChangedSignificantly(axis.filter,
7129                axis.newValue, axis.currentValue, axis.min, axis.max)) {
7130            axis.currentValue = axis.newValue;
7131            atLeastOneSignificantChange = true;
7132        }
7133        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7134            if (force || hasValueChangedSignificantly(axis.filter,
7135                    axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7136                axis.highCurrentValue = axis.highNewValue;
7137                atLeastOneSignificantChange = true;
7138            }
7139        }
7140    }
7141    return atLeastOneSignificantChange;
7142}
7143
7144bool JoystickInputMapper::hasValueChangedSignificantly(
7145        float filter, float newValue, float currentValue, float min, float max) {
7146    if (newValue != currentValue) {
7147        // Filter out small changes in value unless the value is converging on the axis
7148        // bounds or center point.  This is intended to reduce the amount of information
7149        // sent to applications by particularly noisy joysticks (such as PS3).
7150        if (fabs(newValue - currentValue) > filter
7151                || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7152                || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7153                || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7154            return true;
7155        }
7156    }
7157    return false;
7158}
7159
7160bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7161        float filter, float newValue, float currentValue, float thresholdValue) {
7162    float newDistance = fabs(newValue - thresholdValue);
7163    if (newDistance < filter) {
7164        float oldDistance = fabs(currentValue - thresholdValue);
7165        if (newDistance < oldDistance) {
7166            return true;
7167        }
7168    }
7169    return false;
7170}
7171
7172} // namespace android
7173