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