InputReader.cpp revision 93fa9b30b91f75ee161d0791ff17f98d1a603812
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#include "InputReader.h"
40
41#include <cutils/atomic.h>
42#include <cutils/log.h>
43#include <ui/Keyboard.h>
44#include <ui/VirtualKeyMap.h>
45
46#include <stddef.h>
47#include <stdlib.h>
48#include <unistd.h>
49#include <errno.h>
50#include <limits.h>
51#include <math.h>
52
53#define INDENT "  "
54#define INDENT2 "    "
55#define INDENT3 "      "
56#define INDENT4 "        "
57
58namespace android {
59
60// --- Constants ---
61
62// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
63static const size_t MAX_SLOTS = 32;
64
65// --- Static Functions ---
66
67template<typename T>
68inline static T abs(const T& value) {
69    return value < 0 ? - value : value;
70}
71
72template<typename T>
73inline static T min(const T& a, const T& b) {
74    return a < b ? a : b;
75}
76
77template<typename T>
78inline static void swap(T& a, T& b) {
79    T temp = a;
80    a = b;
81    b = temp;
82}
83
84inline static float avg(float x, float y) {
85    return (x + y) / 2;
86}
87
88inline static float distance(float x1, float y1, float x2, float y2) {
89    return hypotf(x1 - x2, y1 - y2);
90}
91
92inline static int32_t signExtendNybble(int32_t value) {
93    return value >= 8 ? value - 16 : value;
94}
95
96static inline const char* toString(bool value) {
97    return value ? "true" : "false";
98}
99
100static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
101        const int32_t map[][4], size_t mapSize) {
102    if (orientation != DISPLAY_ORIENTATION_0) {
103        for (size_t i = 0; i < mapSize; i++) {
104            if (value == map[i][0]) {
105                return map[i][orientation];
106            }
107        }
108    }
109    return value;
110}
111
112static const int32_t keyCodeRotationMap[][4] = {
113        // key codes enumerated counter-clockwise with the original (unrotated) key first
114        // no rotation,        90 degree rotation,  180 degree rotation, 270 degree rotation
115        { AKEYCODE_DPAD_DOWN,   AKEYCODE_DPAD_RIGHT,  AKEYCODE_DPAD_UP,     AKEYCODE_DPAD_LEFT },
116        { AKEYCODE_DPAD_RIGHT,  AKEYCODE_DPAD_UP,     AKEYCODE_DPAD_LEFT,   AKEYCODE_DPAD_DOWN },
117        { AKEYCODE_DPAD_UP,     AKEYCODE_DPAD_LEFT,   AKEYCODE_DPAD_DOWN,   AKEYCODE_DPAD_RIGHT },
118        { AKEYCODE_DPAD_LEFT,   AKEYCODE_DPAD_DOWN,   AKEYCODE_DPAD_RIGHT,  AKEYCODE_DPAD_UP },
119};
120static const size_t keyCodeRotationMapSize =
121        sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
122
123int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
124    return rotateValueUsingRotationMap(keyCode, orientation,
125            keyCodeRotationMap, keyCodeRotationMapSize);
126}
127
128static const int32_t edgeFlagRotationMap[][4] = {
129        // edge flags enumerated counter-clockwise with the original (unrotated) edge flag first
130        // no rotation,        90 degree rotation,  180 degree rotation, 270 degree rotation
131        { AMOTION_EVENT_EDGE_FLAG_BOTTOM,   AMOTION_EVENT_EDGE_FLAG_RIGHT,
132                AMOTION_EVENT_EDGE_FLAG_TOP,     AMOTION_EVENT_EDGE_FLAG_LEFT },
133        { AMOTION_EVENT_EDGE_FLAG_RIGHT,  AMOTION_EVENT_EDGE_FLAG_TOP,
134                AMOTION_EVENT_EDGE_FLAG_LEFT,   AMOTION_EVENT_EDGE_FLAG_BOTTOM },
135        { AMOTION_EVENT_EDGE_FLAG_TOP,     AMOTION_EVENT_EDGE_FLAG_LEFT,
136                AMOTION_EVENT_EDGE_FLAG_BOTTOM,   AMOTION_EVENT_EDGE_FLAG_RIGHT },
137        { AMOTION_EVENT_EDGE_FLAG_LEFT,   AMOTION_EVENT_EDGE_FLAG_BOTTOM,
138                AMOTION_EVENT_EDGE_FLAG_RIGHT,  AMOTION_EVENT_EDGE_FLAG_TOP },
139};
140static const size_t edgeFlagRotationMapSize =
141        sizeof(edgeFlagRotationMap) / sizeof(edgeFlagRotationMap[0]);
142
143static int32_t rotateEdgeFlag(int32_t edgeFlag, int32_t orientation) {
144    return rotateValueUsingRotationMap(edgeFlag, orientation,
145            edgeFlagRotationMap, edgeFlagRotationMapSize);
146}
147
148static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
149    return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
150}
151
152static uint32_t getButtonStateForScanCode(int32_t scanCode) {
153    // Currently all buttons are mapped to the primary button.
154    switch (scanCode) {
155    case BTN_LEFT:
156        return AMOTION_EVENT_BUTTON_PRIMARY;
157    case BTN_RIGHT:
158        return AMOTION_EVENT_BUTTON_SECONDARY;
159    case BTN_MIDDLE:
160        return AMOTION_EVENT_BUTTON_TERTIARY;
161    case BTN_SIDE:
162        return AMOTION_EVENT_BUTTON_BACK;
163    case BTN_EXTRA:
164        return AMOTION_EVENT_BUTTON_FORWARD;
165    case BTN_FORWARD:
166        return AMOTION_EVENT_BUTTON_FORWARD;
167    case BTN_BACK:
168        return AMOTION_EVENT_BUTTON_BACK;
169    case BTN_TASK:
170    default:
171        return 0;
172    }
173}
174
175// Returns true if the pointer should be reported as being down given the specified
176// button states.  This determines whether the event is reported as a touch event.
177static bool isPointerDown(int32_t buttonState) {
178    return buttonState &
179            (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
180                    | AMOTION_EVENT_BUTTON_TERTIARY
181                    | AMOTION_EVENT_BUTTON_ERASER);
182}
183
184static int32_t calculateEdgeFlagsUsingPointerBounds(
185        const sp<PointerControllerInterface>& pointerController, float x, float y) {
186    int32_t edgeFlags = 0;
187    float minX, minY, maxX, maxY;
188    if (pointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
189        if (x <= minX) {
190            edgeFlags |= AMOTION_EVENT_EDGE_FLAG_LEFT;
191        } else if (x >= maxX) {
192            edgeFlags |= AMOTION_EVENT_EDGE_FLAG_RIGHT;
193        }
194        if (y <= minY) {
195            edgeFlags |= AMOTION_EVENT_EDGE_FLAG_TOP;
196        } else if (y >= maxY) {
197            edgeFlags |= AMOTION_EVENT_EDGE_FLAG_BOTTOM;
198        }
199    }
200    return edgeFlags;
201}
202
203static float calculateCommonVector(float a, float b) {
204    if (a > 0 && b > 0) {
205        return a < b ? a : b;
206    } else if (a < 0 && b < 0) {
207        return a > b ? a : b;
208    } else {
209        return 0;
210    }
211}
212
213static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
214        nsecs_t when, int32_t deviceId, uint32_t source,
215        uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
216        int32_t buttonState, int32_t keyCode) {
217    if (
218            (action == AKEY_EVENT_ACTION_DOWN
219                    && !(lastButtonState & buttonState)
220                    && (currentButtonState & buttonState))
221            || (action == AKEY_EVENT_ACTION_UP
222                    && (lastButtonState & buttonState)
223                    && !(currentButtonState & buttonState))) {
224        context->getDispatcher()->notifyKey(when, deviceId, source, policyFlags,
225                action, 0, keyCode, 0, context->getGlobalMetaState(), when);
226    }
227}
228
229static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
230        nsecs_t when, int32_t deviceId, uint32_t source,
231        uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
232    synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
233            lastButtonState, currentButtonState,
234            AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
235    synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
236            lastButtonState, currentButtonState,
237            AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
238}
239
240
241// --- InputReader ---
242
243InputReader::InputReader(const sp<EventHubInterface>& eventHub,
244        const sp<InputReaderPolicyInterface>& policy,
245        const sp<InputDispatcherInterface>& dispatcher) :
246        mEventHub(eventHub), mPolicy(policy), mDispatcher(dispatcher),
247        mGlobalMetaState(0), mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
248        mRefreshConfiguration(0) {
249    configure(true /*firstTime*/);
250    updateGlobalMetaState();
251    updateInputConfiguration();
252}
253
254InputReader::~InputReader() {
255    for (size_t i = 0; i < mDevices.size(); i++) {
256        delete mDevices.valueAt(i);
257    }
258}
259
260void InputReader::loopOnce() {
261    if (android_atomic_acquire_load(&mRefreshConfiguration)) {
262        android_atomic_release_store(0, &mRefreshConfiguration);
263        configure(false /*firstTime*/);
264    }
265
266    int32_t timeoutMillis = -1;
267    if (mNextTimeout != LLONG_MAX) {
268        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
269        timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
270    }
271
272    size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
273    if (count) {
274        processEvents(mEventBuffer, count);
275    }
276    if (!count || timeoutMillis == 0) {
277        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
278#if DEBUG_RAW_EVENTS
279        LOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
280#endif
281        mNextTimeout = LLONG_MAX;
282        timeoutExpired(now);
283    }
284}
285
286void InputReader::processEvents(const RawEvent* rawEvents, size_t count) {
287    for (const RawEvent* rawEvent = rawEvents; count;) {
288        int32_t type = rawEvent->type;
289        size_t batchSize = 1;
290        if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
291            int32_t deviceId = rawEvent->deviceId;
292            while (batchSize < count) {
293                if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
294                        || rawEvent[batchSize].deviceId != deviceId) {
295                    break;
296                }
297                batchSize += 1;
298            }
299#if DEBUG_RAW_EVENTS
300            LOGD("BatchSize: %d Count: %d", batchSize, count);
301#endif
302            processEventsForDevice(deviceId, rawEvent, batchSize);
303        } else {
304            switch (rawEvent->type) {
305            case EventHubInterface::DEVICE_ADDED:
306                addDevice(rawEvent->deviceId);
307                break;
308            case EventHubInterface::DEVICE_REMOVED:
309                removeDevice(rawEvent->deviceId);
310                break;
311            case EventHubInterface::FINISHED_DEVICE_SCAN:
312                handleConfigurationChanged(rawEvent->when);
313                break;
314            default:
315                LOG_ASSERT(false); // can't happen
316                break;
317            }
318        }
319        count -= batchSize;
320        rawEvent += batchSize;
321    }
322}
323
324void InputReader::addDevice(int32_t deviceId) {
325    String8 name = mEventHub->getDeviceName(deviceId);
326    uint32_t classes = mEventHub->getDeviceClasses(deviceId);
327
328    InputDevice* device = createDevice(deviceId, name, classes);
329    device->configure();
330
331    if (device->isIgnored()) {
332        LOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, name.string());
333    } else {
334        LOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, name.string(),
335                device->getSources());
336    }
337
338    bool added = false;
339    { // acquire device registry writer lock
340        RWLock::AutoWLock _wl(mDeviceRegistryLock);
341
342        ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
343        if (deviceIndex < 0) {
344            mDevices.add(deviceId, device);
345            added = true;
346        }
347    } // release device registry writer lock
348
349    if (! added) {
350        LOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
351        delete device;
352        return;
353    }
354}
355
356void InputReader::removeDevice(int32_t deviceId) {
357    bool removed = false;
358    InputDevice* device = NULL;
359    { // acquire device registry writer lock
360        RWLock::AutoWLock _wl(mDeviceRegistryLock);
361
362        ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
363        if (deviceIndex >= 0) {
364            device = mDevices.valueAt(deviceIndex);
365            mDevices.removeItemsAt(deviceIndex, 1);
366            removed = true;
367        }
368    } // release device registry writer lock
369
370    if (! removed) {
371        LOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
372        return;
373    }
374
375    if (device->isIgnored()) {
376        LOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
377                device->getId(), device->getName().string());
378    } else {
379        LOGI("Device removed: id=%d, name='%s', sources=0x%08x",
380                device->getId(), device->getName().string(), device->getSources());
381    }
382
383    device->reset();
384
385    delete device;
386}
387
388InputDevice* InputReader::createDevice(int32_t deviceId, const String8& name, uint32_t classes) {
389    InputDevice* device = new InputDevice(this, deviceId, name);
390
391    // External devices.
392    if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
393        device->setExternal(true);
394    }
395
396    // Switch-like devices.
397    if (classes & INPUT_DEVICE_CLASS_SWITCH) {
398        device->addMapper(new SwitchInputMapper(device));
399    }
400
401    // Keyboard-like devices.
402    uint32_t keyboardSource = 0;
403    int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
404    if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
405        keyboardSource |= AINPUT_SOURCE_KEYBOARD;
406    }
407    if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
408        keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
409    }
410    if (classes & INPUT_DEVICE_CLASS_DPAD) {
411        keyboardSource |= AINPUT_SOURCE_DPAD;
412    }
413    if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
414        keyboardSource |= AINPUT_SOURCE_GAMEPAD;
415    }
416
417    if (keyboardSource != 0) {
418        device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
419    }
420
421    // Cursor-like devices.
422    if (classes & INPUT_DEVICE_CLASS_CURSOR) {
423        device->addMapper(new CursorInputMapper(device));
424    }
425
426    // Touchscreens and touchpad devices.
427    if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
428        device->addMapper(new MultiTouchInputMapper(device));
429    } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
430        device->addMapper(new SingleTouchInputMapper(device));
431    }
432
433    // Joystick-like devices.
434    if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
435        device->addMapper(new JoystickInputMapper(device));
436    }
437
438    return device;
439}
440
441void InputReader::processEventsForDevice(int32_t deviceId,
442        const RawEvent* rawEvents, size_t count) {
443    { // acquire device registry reader lock
444        RWLock::AutoRLock _rl(mDeviceRegistryLock);
445
446        ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
447        if (deviceIndex < 0) {
448            LOGW("Discarding event for unknown deviceId %d.", deviceId);
449            return;
450        }
451
452        InputDevice* device = mDevices.valueAt(deviceIndex);
453        if (device->isIgnored()) {
454            //LOGD("Discarding event for ignored deviceId %d.", deviceId);
455            return;
456        }
457
458        device->process(rawEvents, count);
459    } // release device registry reader lock
460}
461
462void InputReader::timeoutExpired(nsecs_t when) {
463    { // acquire device registry reader lock
464        RWLock::AutoRLock _rl(mDeviceRegistryLock);
465
466        for (size_t i = 0; i < mDevices.size(); i++) {
467            InputDevice* device = mDevices.valueAt(i);
468            if (!device->isIgnored()) {
469                device->timeoutExpired(when);
470            }
471        }
472    } // release device registry reader lock
473}
474
475void InputReader::handleConfigurationChanged(nsecs_t when) {
476    // Reset global meta state because it depends on the list of all configured devices.
477    updateGlobalMetaState();
478
479    // Update input configuration.
480    updateInputConfiguration();
481
482    // Enqueue configuration changed.
483    mDispatcher->notifyConfigurationChanged(when);
484}
485
486void InputReader::configure(bool firstTime) {
487    mPolicy->getReaderConfiguration(&mConfig);
488    mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
489
490    if (!firstTime) {
491        mEventHub->requestReopenDevices();
492    }
493}
494
495void InputReader::updateGlobalMetaState() {
496    { // acquire state lock
497        AutoMutex _l(mStateLock);
498
499        mGlobalMetaState = 0;
500
501        { // acquire device registry reader lock
502            RWLock::AutoRLock _rl(mDeviceRegistryLock);
503
504            for (size_t i = 0; i < mDevices.size(); i++) {
505                InputDevice* device = mDevices.valueAt(i);
506                mGlobalMetaState |= device->getMetaState();
507            }
508        } // release device registry reader lock
509    } // release state lock
510}
511
512int32_t InputReader::getGlobalMetaState() {
513    { // acquire state lock
514        AutoMutex _l(mStateLock);
515
516        return mGlobalMetaState;
517    } // release state lock
518}
519
520void InputReader::updateInputConfiguration() {
521    { // acquire state lock
522        AutoMutex _l(mStateLock);
523
524        int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH;
525        int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS;
526        int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV;
527        { // acquire device registry reader lock
528            RWLock::AutoRLock _rl(mDeviceRegistryLock);
529
530            InputDeviceInfo deviceInfo;
531            for (size_t i = 0; i < mDevices.size(); i++) {
532                InputDevice* device = mDevices.valueAt(i);
533                device->getDeviceInfo(& deviceInfo);
534                uint32_t sources = deviceInfo.getSources();
535
536                if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) {
537                    touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER;
538                }
539                if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) {
540                    navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL;
541                } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) {
542                    navigationConfig = InputConfiguration::NAVIGATION_DPAD;
543                }
544                if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) {
545                    keyboardConfig = InputConfiguration::KEYBOARD_QWERTY;
546                }
547            }
548        } // release device registry reader lock
549
550        mInputConfiguration.touchScreen = touchScreenConfig;
551        mInputConfiguration.keyboard = keyboardConfig;
552        mInputConfiguration.navigation = navigationConfig;
553    } // release state lock
554}
555
556void InputReader::disableVirtualKeysUntil(nsecs_t time) {
557    mDisableVirtualKeysTimeout = time;
558}
559
560bool InputReader::shouldDropVirtualKey(nsecs_t now,
561        InputDevice* device, int32_t keyCode, int32_t scanCode) {
562    if (now < mDisableVirtualKeysTimeout) {
563        LOGI("Dropping virtual key from device %s because virtual keys are "
564                "temporarily disabled for the next %0.3fms.  keyCode=%d, scanCode=%d",
565                device->getName().string(),
566                (mDisableVirtualKeysTimeout - now) * 0.000001,
567                keyCode, scanCode);
568        return true;
569    } else {
570        return false;
571    }
572}
573
574void InputReader::fadePointer() {
575    { // acquire device registry reader lock
576        RWLock::AutoRLock _rl(mDeviceRegistryLock);
577
578        for (size_t i = 0; i < mDevices.size(); i++) {
579            InputDevice* device = mDevices.valueAt(i);
580            device->fadePointer();
581        }
582    } // release device registry reader lock
583}
584
585void InputReader::requestTimeoutAtTime(nsecs_t when) {
586    if (when < mNextTimeout) {
587        mNextTimeout = when;
588    }
589}
590
591void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) {
592    { // acquire state lock
593        AutoMutex _l(mStateLock);
594
595        *outConfiguration = mInputConfiguration;
596    } // release state lock
597}
598
599status_t InputReader::getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo) {
600    { // acquire device registry reader lock
601        RWLock::AutoRLock _rl(mDeviceRegistryLock);
602
603        ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
604        if (deviceIndex < 0) {
605            return NAME_NOT_FOUND;
606        }
607
608        InputDevice* device = mDevices.valueAt(deviceIndex);
609        if (device->isIgnored()) {
610            return NAME_NOT_FOUND;
611        }
612
613        device->getDeviceInfo(outDeviceInfo);
614        return OK;
615    } // release device registy reader lock
616}
617
618void InputReader::getInputDeviceIds(Vector<int32_t>& outDeviceIds) {
619    outDeviceIds.clear();
620
621    { // acquire device registry reader lock
622        RWLock::AutoRLock _rl(mDeviceRegistryLock);
623
624        size_t numDevices = mDevices.size();
625        for (size_t i = 0; i < numDevices; i++) {
626            InputDevice* device = mDevices.valueAt(i);
627            if (! device->isIgnored()) {
628                outDeviceIds.add(device->getId());
629            }
630        }
631    } // release device registy reader lock
632}
633
634int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
635        int32_t keyCode) {
636    return getState(deviceId, sourceMask, keyCode, & InputDevice::getKeyCodeState);
637}
638
639int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
640        int32_t scanCode) {
641    return getState(deviceId, sourceMask, scanCode, & InputDevice::getScanCodeState);
642}
643
644int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
645    return getState(deviceId, sourceMask, switchCode, & InputDevice::getSwitchState);
646}
647
648int32_t InputReader::getState(int32_t deviceId, uint32_t sourceMask, int32_t code,
649        GetStateFunc getStateFunc) {
650    { // acquire device registry reader lock
651        RWLock::AutoRLock _rl(mDeviceRegistryLock);
652
653        int32_t result = AKEY_STATE_UNKNOWN;
654        if (deviceId >= 0) {
655            ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
656            if (deviceIndex >= 0) {
657                InputDevice* device = mDevices.valueAt(deviceIndex);
658                if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
659                    result = (device->*getStateFunc)(sourceMask, code);
660                }
661            }
662        } else {
663            size_t numDevices = mDevices.size();
664            for (size_t i = 0; i < numDevices; i++) {
665                InputDevice* device = mDevices.valueAt(i);
666                if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
667                    result = (device->*getStateFunc)(sourceMask, code);
668                    if (result >= AKEY_STATE_DOWN) {
669                        return result;
670                    }
671                }
672            }
673        }
674        return result;
675    } // release device registy reader lock
676}
677
678bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
679        size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
680    memset(outFlags, 0, numCodes);
681    return markSupportedKeyCodes(deviceId, sourceMask, numCodes, keyCodes, outFlags);
682}
683
684bool InputReader::markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
685        const int32_t* keyCodes, uint8_t* outFlags) {
686    { // acquire device registry reader lock
687        RWLock::AutoRLock _rl(mDeviceRegistryLock);
688        bool result = false;
689        if (deviceId >= 0) {
690            ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
691            if (deviceIndex >= 0) {
692                InputDevice* device = mDevices.valueAt(deviceIndex);
693                if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
694                    result = device->markSupportedKeyCodes(sourceMask,
695                            numCodes, keyCodes, outFlags);
696                }
697            }
698        } else {
699            size_t numDevices = mDevices.size();
700            for (size_t i = 0; i < numDevices; i++) {
701                InputDevice* device = mDevices.valueAt(i);
702                if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
703                    result |= device->markSupportedKeyCodes(sourceMask,
704                            numCodes, keyCodes, outFlags);
705                }
706            }
707        }
708        return result;
709    } // release device registy reader lock
710}
711
712void InputReader::refreshConfiguration() {
713    android_atomic_release_store(1, &mRefreshConfiguration);
714
715    mEventHub->wake();
716}
717
718void InputReader::dump(String8& dump) {
719    mEventHub->dump(dump);
720    dump.append("\n");
721
722    dump.append("Input Reader State:\n");
723
724    { // acquire device registry reader lock
725        RWLock::AutoRLock _rl(mDeviceRegistryLock);
726
727        for (size_t i = 0; i < mDevices.size(); i++) {
728            mDevices.valueAt(i)->dump(dump);
729        }
730    } // release device registy reader lock
731
732    dump.append(INDENT "Configuration:\n");
733    dump.append(INDENT2 "ExcludedDeviceNames: [");
734    for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
735        if (i != 0) {
736            dump.append(", ");
737        }
738        dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
739    }
740    dump.append("]\n");
741    dump.appendFormat(INDENT2 "FilterTouchEvents: %s\n",
742            toString(mConfig.filterTouchEvents));
743    dump.appendFormat(INDENT2 "FilterJumpyTouchEvents: %s\n",
744            toString(mConfig.filterJumpyTouchEvents));
745    dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
746            mConfig.virtualKeyQuietTime * 0.000001f);
747
748    dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
749            "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
750            mConfig.pointerVelocityControlParameters.scale,
751            mConfig.pointerVelocityControlParameters.lowThreshold,
752            mConfig.pointerVelocityControlParameters.highThreshold,
753            mConfig.pointerVelocityControlParameters.acceleration);
754
755    dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
756            "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
757            mConfig.wheelVelocityControlParameters.scale,
758            mConfig.wheelVelocityControlParameters.lowThreshold,
759            mConfig.wheelVelocityControlParameters.highThreshold,
760            mConfig.wheelVelocityControlParameters.acceleration);
761
762    dump.appendFormat(INDENT2 "PointerGesture:\n");
763    dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
764            mConfig.pointerGestureQuietInterval * 0.000001f);
765    dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
766            mConfig.pointerGestureDragMinSwitchSpeed);
767    dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
768            mConfig.pointerGestureTapInterval * 0.000001f);
769    dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
770            mConfig.pointerGestureTapDragInterval * 0.000001f);
771    dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
772            mConfig.pointerGestureTapSlop);
773    dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
774            mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
775    dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
776            mConfig.pointerGestureMultitouchMinDistance);
777    dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
778            mConfig.pointerGestureSwipeTransitionAngleCosine);
779    dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
780            mConfig.pointerGestureSwipeMaxWidthRatio);
781    dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
782            mConfig.pointerGestureMovementSpeedRatio);
783    dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
784            mConfig.pointerGestureZoomSpeedRatio);
785}
786
787
788// --- InputReaderThread ---
789
790InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
791        Thread(/*canCallJava*/ true), mReader(reader) {
792}
793
794InputReaderThread::~InputReaderThread() {
795}
796
797bool InputReaderThread::threadLoop() {
798    mReader->loopOnce();
799    return true;
800}
801
802
803// --- InputDevice ---
804
805InputDevice::InputDevice(InputReaderContext* context, int32_t id, const String8& name) :
806        mContext(context), mId(id), mName(name), mSources(0),
807        mIsExternal(false), mDropUntilNextSync(false) {
808}
809
810InputDevice::~InputDevice() {
811    size_t numMappers = mMappers.size();
812    for (size_t i = 0; i < numMappers; i++) {
813        delete mMappers[i];
814    }
815    mMappers.clear();
816}
817
818void InputDevice::dump(String8& dump) {
819    InputDeviceInfo deviceInfo;
820    getDeviceInfo(& deviceInfo);
821
822    dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
823            deviceInfo.getName().string());
824    dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
825    dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
826    dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
827
828    const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
829    if (!ranges.isEmpty()) {
830        dump.append(INDENT2 "Motion Ranges:\n");
831        for (size_t i = 0; i < ranges.size(); i++) {
832            const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
833            const char* label = getAxisLabel(range.axis);
834            char name[32];
835            if (label) {
836                strncpy(name, label, sizeof(name));
837                name[sizeof(name) - 1] = '\0';
838            } else {
839                snprintf(name, sizeof(name), "%d", range.axis);
840            }
841            dump.appendFormat(INDENT3 "%s: source=0x%08x, "
842                    "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n",
843                    name, range.source, range.min, range.max, range.flat, range.fuzz);
844        }
845    }
846
847    size_t numMappers = mMappers.size();
848    for (size_t i = 0; i < numMappers; i++) {
849        InputMapper* mapper = mMappers[i];
850        mapper->dump(dump);
851    }
852}
853
854void InputDevice::addMapper(InputMapper* mapper) {
855    mMappers.add(mapper);
856}
857
858void InputDevice::configure() {
859    if (! isIgnored()) {
860        mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
861    }
862
863    mSources = 0;
864
865    size_t numMappers = mMappers.size();
866    for (size_t i = 0; i < numMappers; i++) {
867        InputMapper* mapper = mMappers[i];
868        mapper->configure();
869        mSources |= mapper->getSources();
870    }
871}
872
873void InputDevice::reset() {
874    size_t numMappers = mMappers.size();
875    for (size_t i = 0; i < numMappers; i++) {
876        InputMapper* mapper = mMappers[i];
877        mapper->reset();
878    }
879}
880
881void InputDevice::process(const RawEvent* rawEvents, size_t count) {
882    // Process all of the events in order for each mapper.
883    // We cannot simply ask each mapper to process them in bulk because mappers may
884    // have side-effects that must be interleaved.  For example, joystick movement events and
885    // gamepad button presses are handled by different mappers but they should be dispatched
886    // in the order received.
887    size_t numMappers = mMappers.size();
888    for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
889#if DEBUG_RAW_EVENTS
890        LOGD("Input event: device=%d type=0x%04x scancode=0x%04x "
891                "keycode=0x%04x value=0x%04x flags=0x%08x",
892                rawEvent->deviceId, rawEvent->type, rawEvent->scanCode, rawEvent->keyCode,
893                rawEvent->value, rawEvent->flags);
894#endif
895
896        if (mDropUntilNextSync) {
897            if (rawEvent->type == EV_SYN && rawEvent->scanCode == SYN_REPORT) {
898                mDropUntilNextSync = false;
899#if DEBUG_RAW_EVENTS
900                LOGD("Recovered from input event buffer overrun.");
901#endif
902            } else {
903#if DEBUG_RAW_EVENTS
904                LOGD("Dropped input event while waiting for next input sync.");
905#endif
906            }
907        } else if (rawEvent->type == EV_SYN && rawEvent->scanCode == SYN_DROPPED) {
908            LOGI("Detected input event buffer overrun for device %s.", mName.string());
909            mDropUntilNextSync = true;
910            reset();
911        } else {
912            for (size_t i = 0; i < numMappers; i++) {
913                InputMapper* mapper = mMappers[i];
914                mapper->process(rawEvent);
915            }
916        }
917    }
918}
919
920void InputDevice::timeoutExpired(nsecs_t when) {
921    size_t numMappers = mMappers.size();
922    for (size_t i = 0; i < numMappers; i++) {
923        InputMapper* mapper = mMappers[i];
924        mapper->timeoutExpired(when);
925    }
926}
927
928void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
929    outDeviceInfo->initialize(mId, mName);
930
931    size_t numMappers = mMappers.size();
932    for (size_t i = 0; i < numMappers; i++) {
933        InputMapper* mapper = mMappers[i];
934        mapper->populateDeviceInfo(outDeviceInfo);
935    }
936}
937
938int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
939    return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
940}
941
942int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
943    return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
944}
945
946int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
947    return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
948}
949
950int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
951    int32_t result = AKEY_STATE_UNKNOWN;
952    size_t numMappers = mMappers.size();
953    for (size_t i = 0; i < numMappers; i++) {
954        InputMapper* mapper = mMappers[i];
955        if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
956            result = (mapper->*getStateFunc)(sourceMask, code);
957            if (result >= AKEY_STATE_DOWN) {
958                return result;
959            }
960        }
961    }
962    return result;
963}
964
965bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
966        const int32_t* keyCodes, uint8_t* outFlags) {
967    bool result = false;
968    size_t numMappers = mMappers.size();
969    for (size_t i = 0; i < numMappers; i++) {
970        InputMapper* mapper = mMappers[i];
971        if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
972            result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
973        }
974    }
975    return result;
976}
977
978int32_t InputDevice::getMetaState() {
979    int32_t result = 0;
980    size_t numMappers = mMappers.size();
981    for (size_t i = 0; i < numMappers; i++) {
982        InputMapper* mapper = mMappers[i];
983        result |= mapper->getMetaState();
984    }
985    return result;
986}
987
988void InputDevice::fadePointer() {
989    size_t numMappers = mMappers.size();
990    for (size_t i = 0; i < numMappers; i++) {
991        InputMapper* mapper = mMappers[i];
992        mapper->fadePointer();
993    }
994}
995
996
997// --- InputMapper ---
998
999InputMapper::InputMapper(InputDevice* device) :
1000        mDevice(device), mContext(device->getContext()) {
1001}
1002
1003InputMapper::~InputMapper() {
1004}
1005
1006void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1007    info->addSource(getSources());
1008}
1009
1010void InputMapper::dump(String8& dump) {
1011}
1012
1013void InputMapper::configure() {
1014}
1015
1016void InputMapper::reset() {
1017}
1018
1019void InputMapper::timeoutExpired(nsecs_t when) {
1020}
1021
1022int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1023    return AKEY_STATE_UNKNOWN;
1024}
1025
1026int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1027    return AKEY_STATE_UNKNOWN;
1028}
1029
1030int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1031    return AKEY_STATE_UNKNOWN;
1032}
1033
1034bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1035        const int32_t* keyCodes, uint8_t* outFlags) {
1036    return false;
1037}
1038
1039int32_t InputMapper::getMetaState() {
1040    return 0;
1041}
1042
1043void InputMapper::fadePointer() {
1044}
1045
1046void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
1047        const RawAbsoluteAxisInfo& axis, const char* name) {
1048    if (axis.valid) {
1049        dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
1050                name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1051    } else {
1052        dump.appendFormat(INDENT4 "%s: unknown range\n", name);
1053    }
1054}
1055
1056
1057// --- SwitchInputMapper ---
1058
1059SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
1060        InputMapper(device) {
1061}
1062
1063SwitchInputMapper::~SwitchInputMapper() {
1064}
1065
1066uint32_t SwitchInputMapper::getSources() {
1067    return AINPUT_SOURCE_SWITCH;
1068}
1069
1070void SwitchInputMapper::process(const RawEvent* rawEvent) {
1071    switch (rawEvent->type) {
1072    case EV_SW:
1073        processSwitch(rawEvent->when, rawEvent->scanCode, rawEvent->value);
1074        break;
1075    }
1076}
1077
1078void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) {
1079    getDispatcher()->notifySwitch(when, switchCode, switchValue, 0);
1080}
1081
1082int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1083    return getEventHub()->getSwitchState(getDeviceId(), switchCode);
1084}
1085
1086
1087// --- KeyboardInputMapper ---
1088
1089KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
1090        uint32_t source, int32_t keyboardType) :
1091        InputMapper(device), mSource(source),
1092        mKeyboardType(keyboardType) {
1093    initializeLocked();
1094}
1095
1096KeyboardInputMapper::~KeyboardInputMapper() {
1097}
1098
1099void KeyboardInputMapper::initializeLocked() {
1100    mLocked.metaState = AMETA_NONE;
1101    mLocked.downTime = 0;
1102}
1103
1104uint32_t KeyboardInputMapper::getSources() {
1105    return mSource;
1106}
1107
1108void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1109    InputMapper::populateDeviceInfo(info);
1110
1111    info->setKeyboardType(mKeyboardType);
1112}
1113
1114void KeyboardInputMapper::dump(String8& dump) {
1115    { // acquire lock
1116        AutoMutex _l(mLock);
1117        dump.append(INDENT2 "Keyboard Input Mapper:\n");
1118        dumpParameters(dump);
1119        dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
1120        dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mLocked.keyDowns.size());
1121        dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mLocked.metaState);
1122        dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1123    } // release lock
1124}
1125
1126
1127void KeyboardInputMapper::configure() {
1128    InputMapper::configure();
1129
1130    // Configure basic parameters.
1131    configureParameters();
1132
1133    // Reset LEDs.
1134    {
1135        AutoMutex _l(mLock);
1136        resetLedStateLocked();
1137    }
1138}
1139
1140void KeyboardInputMapper::configureParameters() {
1141    mParameters.orientationAware = false;
1142    getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
1143            mParameters.orientationAware);
1144
1145    mParameters.associatedDisplayId = mParameters.orientationAware ? 0 : -1;
1146}
1147
1148void KeyboardInputMapper::dumpParameters(String8& dump) {
1149    dump.append(INDENT3 "Parameters:\n");
1150    dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1151            mParameters.associatedDisplayId);
1152    dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1153            toString(mParameters.orientationAware));
1154}
1155
1156void KeyboardInputMapper::reset() {
1157    for (;;) {
1158        int32_t keyCode, scanCode;
1159        { // acquire lock
1160            AutoMutex _l(mLock);
1161
1162            // Synthesize key up event on reset if keys are currently down.
1163            if (mLocked.keyDowns.isEmpty()) {
1164                initializeLocked();
1165                resetLedStateLocked();
1166                break; // done
1167            }
1168
1169            const KeyDown& keyDown = mLocked.keyDowns.top();
1170            keyCode = keyDown.keyCode;
1171            scanCode = keyDown.scanCode;
1172        } // release lock
1173
1174        nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
1175        processKey(when, false, keyCode, scanCode, 0);
1176    }
1177
1178    InputMapper::reset();
1179    getContext()->updateGlobalMetaState();
1180}
1181
1182void KeyboardInputMapper::process(const RawEvent* rawEvent) {
1183    switch (rawEvent->type) {
1184    case EV_KEY: {
1185        int32_t scanCode = rawEvent->scanCode;
1186        if (isKeyboardOrGamepadKey(scanCode)) {
1187            processKey(rawEvent->when, rawEvent->value != 0, rawEvent->keyCode, scanCode,
1188                    rawEvent->flags);
1189        }
1190        break;
1191    }
1192    }
1193}
1194
1195bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
1196    return scanCode < BTN_MOUSE
1197        || scanCode >= KEY_OK
1198        || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
1199        || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
1200}
1201
1202void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
1203        int32_t scanCode, uint32_t policyFlags) {
1204    int32_t newMetaState;
1205    nsecs_t downTime;
1206    bool metaStateChanged = false;
1207
1208    { // acquire lock
1209        AutoMutex _l(mLock);
1210
1211        if (down) {
1212            // Rotate key codes according to orientation if needed.
1213            // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
1214            if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) {
1215                int32_t orientation;
1216                if (!getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1217                        NULL, NULL, & orientation)) {
1218                    orientation = DISPLAY_ORIENTATION_0;
1219                }
1220
1221                keyCode = rotateKeyCode(keyCode, orientation);
1222            }
1223
1224            // Add key down.
1225            ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1226            if (keyDownIndex >= 0) {
1227                // key repeat, be sure to use same keycode as before in case of rotation
1228                keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
1229            } else {
1230                // key down
1231                if ((policyFlags & POLICY_FLAG_VIRTUAL)
1232                        && mContext->shouldDropVirtualKey(when,
1233                                getDevice(), keyCode, scanCode)) {
1234                    return;
1235                }
1236
1237                mLocked.keyDowns.push();
1238                KeyDown& keyDown = mLocked.keyDowns.editTop();
1239                keyDown.keyCode = keyCode;
1240                keyDown.scanCode = scanCode;
1241            }
1242
1243            mLocked.downTime = when;
1244        } else {
1245            // Remove key down.
1246            ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1247            if (keyDownIndex >= 0) {
1248                // key up, be sure to use same keycode as before in case of rotation
1249                keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
1250                mLocked.keyDowns.removeAt(size_t(keyDownIndex));
1251            } else {
1252                // key was not actually down
1253                LOGI("Dropping key up from device %s because the key was not down.  "
1254                        "keyCode=%d, scanCode=%d",
1255                        getDeviceName().string(), keyCode, scanCode);
1256                return;
1257            }
1258        }
1259
1260        int32_t oldMetaState = mLocked.metaState;
1261        newMetaState = updateMetaState(keyCode, down, oldMetaState);
1262        if (oldMetaState != newMetaState) {
1263            mLocked.metaState = newMetaState;
1264            metaStateChanged = true;
1265            updateLedStateLocked(false);
1266        }
1267
1268        downTime = mLocked.downTime;
1269    } // release lock
1270
1271    // Key down on external an keyboard should wake the device.
1272    // We don't do this for internal keyboards to prevent them from waking up in your pocket.
1273    // For internal keyboards, the key layout file should specify the policy flags for
1274    // each wake key individually.
1275    // TODO: Use the input device configuration to control this behavior more finely.
1276    if (down && getDevice()->isExternal()
1277            && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {
1278        policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1279    }
1280
1281    if (metaStateChanged) {
1282        getContext()->updateGlobalMetaState();
1283    }
1284
1285    if (down && !isMetaKey(keyCode)) {
1286        getContext()->fadePointer();
1287    }
1288
1289    getDispatcher()->notifyKey(when, getDeviceId(), mSource, policyFlags,
1290            down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
1291            AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
1292}
1293
1294ssize_t KeyboardInputMapper::findKeyDownLocked(int32_t scanCode) {
1295    size_t n = mLocked.keyDowns.size();
1296    for (size_t i = 0; i < n; i++) {
1297        if (mLocked.keyDowns[i].scanCode == scanCode) {
1298            return i;
1299        }
1300    }
1301    return -1;
1302}
1303
1304int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1305    return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
1306}
1307
1308int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1309    return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1310}
1311
1312bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1313        const int32_t* keyCodes, uint8_t* outFlags) {
1314    return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
1315}
1316
1317int32_t KeyboardInputMapper::getMetaState() {
1318    { // acquire lock
1319        AutoMutex _l(mLock);
1320        return mLocked.metaState;
1321    } // release lock
1322}
1323
1324void KeyboardInputMapper::resetLedStateLocked() {
1325    initializeLedStateLocked(mLocked.capsLockLedState, LED_CAPSL);
1326    initializeLedStateLocked(mLocked.numLockLedState, LED_NUML);
1327    initializeLedStateLocked(mLocked.scrollLockLedState, LED_SCROLLL);
1328
1329    updateLedStateLocked(true);
1330}
1331
1332void KeyboardInputMapper::initializeLedStateLocked(LockedState::LedState& ledState, int32_t led) {
1333    ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
1334    ledState.on = false;
1335}
1336
1337void KeyboardInputMapper::updateLedStateLocked(bool reset) {
1338    updateLedStateForModifierLocked(mLocked.capsLockLedState, LED_CAPSL,
1339            AMETA_CAPS_LOCK_ON, reset);
1340    updateLedStateForModifierLocked(mLocked.numLockLedState, LED_NUML,
1341            AMETA_NUM_LOCK_ON, reset);
1342    updateLedStateForModifierLocked(mLocked.scrollLockLedState, LED_SCROLLL,
1343            AMETA_SCROLL_LOCK_ON, reset);
1344}
1345
1346void KeyboardInputMapper::updateLedStateForModifierLocked(LockedState::LedState& ledState,
1347        int32_t led, int32_t modifier, bool reset) {
1348    if (ledState.avail) {
1349        bool desiredState = (mLocked.metaState & modifier) != 0;
1350        if (reset || ledState.on != desiredState) {
1351            getEventHub()->setLedState(getDeviceId(), led, desiredState);
1352            ledState.on = desiredState;
1353        }
1354    }
1355}
1356
1357
1358// --- CursorInputMapper ---
1359
1360CursorInputMapper::CursorInputMapper(InputDevice* device) :
1361        InputMapper(device) {
1362    initializeLocked();
1363}
1364
1365CursorInputMapper::~CursorInputMapper() {
1366}
1367
1368uint32_t CursorInputMapper::getSources() {
1369    return mSource;
1370}
1371
1372void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1373    InputMapper::populateDeviceInfo(info);
1374
1375    if (mParameters.mode == Parameters::MODE_POINTER) {
1376        float minX, minY, maxX, maxY;
1377        if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1378            info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f);
1379            info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f);
1380        }
1381    } else {
1382        info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale);
1383        info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale);
1384    }
1385    info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f);
1386
1387    if (mHaveVWheel) {
1388        info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
1389    }
1390    if (mHaveHWheel) {
1391        info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
1392    }
1393}
1394
1395void CursorInputMapper::dump(String8& dump) {
1396    { // acquire lock
1397        AutoMutex _l(mLock);
1398        dump.append(INDENT2 "Cursor Input Mapper:\n");
1399        dumpParameters(dump);
1400        dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
1401        dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
1402        dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
1403        dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
1404        dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mHaveVWheel));
1405        dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mHaveHWheel));
1406        dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
1407        dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
1408        dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mLocked.buttonState);
1409        dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mLocked.buttonState)));
1410        dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1411    } // release lock
1412}
1413
1414void CursorInputMapper::configure() {
1415    InputMapper::configure();
1416
1417    // Configure basic parameters.
1418    configureParameters();
1419
1420    // Configure device mode.
1421    switch (mParameters.mode) {
1422    case Parameters::MODE_POINTER:
1423        mSource = AINPUT_SOURCE_MOUSE;
1424        mXPrecision = 1.0f;
1425        mYPrecision = 1.0f;
1426        mXScale = 1.0f;
1427        mYScale = 1.0f;
1428        mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1429        break;
1430    case Parameters::MODE_NAVIGATION:
1431        mSource = AINPUT_SOURCE_TRACKBALL;
1432        mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1433        mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1434        mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1435        mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1436        break;
1437    }
1438
1439    mVWheelScale = 1.0f;
1440    mHWheelScale = 1.0f;
1441
1442    mHaveVWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_WHEEL);
1443    mHaveHWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_HWHEEL);
1444
1445    mPointerVelocityControl.setParameters(getConfig()->pointerVelocityControlParameters);
1446    mWheelXVelocityControl.setParameters(getConfig()->wheelVelocityControlParameters);
1447    mWheelYVelocityControl.setParameters(getConfig()->wheelVelocityControlParameters);
1448}
1449
1450void CursorInputMapper::configureParameters() {
1451    mParameters.mode = Parameters::MODE_POINTER;
1452    String8 cursorModeString;
1453    if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
1454        if (cursorModeString == "navigation") {
1455            mParameters.mode = Parameters::MODE_NAVIGATION;
1456        } else if (cursorModeString != "pointer" && cursorModeString != "default") {
1457            LOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
1458        }
1459    }
1460
1461    mParameters.orientationAware = false;
1462    getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
1463            mParameters.orientationAware);
1464
1465    mParameters.associatedDisplayId = mParameters.mode == Parameters::MODE_POINTER
1466            || mParameters.orientationAware ? 0 : -1;
1467}
1468
1469void CursorInputMapper::dumpParameters(String8& dump) {
1470    dump.append(INDENT3 "Parameters:\n");
1471    dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1472            mParameters.associatedDisplayId);
1473
1474    switch (mParameters.mode) {
1475    case Parameters::MODE_POINTER:
1476        dump.append(INDENT4 "Mode: pointer\n");
1477        break;
1478    case Parameters::MODE_NAVIGATION:
1479        dump.append(INDENT4 "Mode: navigation\n");
1480        break;
1481    default:
1482        LOG_ASSERT(false);
1483    }
1484
1485    dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1486            toString(mParameters.orientationAware));
1487}
1488
1489void CursorInputMapper::initializeLocked() {
1490    mAccumulator.clear();
1491
1492    mLocked.buttonState = 0;
1493    mLocked.downTime = 0;
1494}
1495
1496void CursorInputMapper::reset() {
1497    for (;;) {
1498        int32_t buttonState;
1499        { // acquire lock
1500            AutoMutex _l(mLock);
1501
1502            buttonState = mLocked.buttonState;
1503            if (!buttonState) {
1504                initializeLocked();
1505                break; // done
1506            }
1507        } // release lock
1508
1509        // Reset velocity.
1510        mPointerVelocityControl.reset();
1511        mWheelXVelocityControl.reset();
1512        mWheelYVelocityControl.reset();
1513
1514        // Synthesize button up event on reset.
1515        nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
1516        mAccumulator.clear();
1517        mAccumulator.buttonDown = 0;
1518        mAccumulator.buttonUp = buttonState;
1519        mAccumulator.fields = Accumulator::FIELD_BUTTONS;
1520        sync(when);
1521    }
1522
1523    InputMapper::reset();
1524}
1525
1526void CursorInputMapper::process(const RawEvent* rawEvent) {
1527    switch (rawEvent->type) {
1528    case EV_KEY: {
1529        int32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
1530        if (buttonState) {
1531            if (rawEvent->value) {
1532                mAccumulator.buttonDown = buttonState;
1533                mAccumulator.buttonUp = 0;
1534            } else {
1535                mAccumulator.buttonDown = 0;
1536                mAccumulator.buttonUp = buttonState;
1537            }
1538            mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
1539
1540            // Sync now since BTN_MOUSE is not necessarily followed by SYN_REPORT and
1541            // we need to ensure that we report the up/down promptly.
1542            sync(rawEvent->when);
1543            break;
1544        }
1545        break;
1546    }
1547
1548    case EV_REL:
1549        switch (rawEvent->scanCode) {
1550        case REL_X:
1551            mAccumulator.fields |= Accumulator::FIELD_REL_X;
1552            mAccumulator.relX = rawEvent->value;
1553            break;
1554        case REL_Y:
1555            mAccumulator.fields |= Accumulator::FIELD_REL_Y;
1556            mAccumulator.relY = rawEvent->value;
1557            break;
1558        case REL_WHEEL:
1559            mAccumulator.fields |= Accumulator::FIELD_REL_WHEEL;
1560            mAccumulator.relWheel = rawEvent->value;
1561            break;
1562        case REL_HWHEEL:
1563            mAccumulator.fields |= Accumulator::FIELD_REL_HWHEEL;
1564            mAccumulator.relHWheel = rawEvent->value;
1565            break;
1566        }
1567        break;
1568
1569    case EV_SYN:
1570        switch (rawEvent->scanCode) {
1571        case SYN_REPORT:
1572            sync(rawEvent->when);
1573            break;
1574        }
1575        break;
1576    }
1577}
1578
1579void CursorInputMapper::sync(nsecs_t when) {
1580    uint32_t fields = mAccumulator.fields;
1581    if (fields == 0) {
1582        return; // no new state changes, so nothing to do
1583    }
1584
1585    int32_t motionEventAction;
1586    int32_t motionEventEdgeFlags;
1587    int32_t lastButtonState, currentButtonState;
1588    PointerProperties pointerProperties;
1589    PointerCoords pointerCoords;
1590    nsecs_t downTime;
1591    float vscroll, hscroll;
1592    { // acquire lock
1593        AutoMutex _l(mLock);
1594
1595        lastButtonState = mLocked.buttonState;
1596
1597        bool down, downChanged;
1598        bool wasDown = isPointerDown(mLocked.buttonState);
1599        bool buttonsChanged = fields & Accumulator::FIELD_BUTTONS;
1600        if (buttonsChanged) {
1601            mLocked.buttonState = (mLocked.buttonState | mAccumulator.buttonDown)
1602                    & ~mAccumulator.buttonUp;
1603
1604            down = isPointerDown(mLocked.buttonState);
1605
1606            if (!wasDown && down) {
1607                mLocked.downTime = when;
1608                downChanged = true;
1609            } else if (wasDown && !down) {
1610                downChanged = true;
1611            } else {
1612                downChanged = false;
1613            }
1614        } else {
1615            down = wasDown;
1616            downChanged = false;
1617        }
1618
1619        currentButtonState = mLocked.buttonState;
1620
1621        downTime = mLocked.downTime;
1622        float deltaX = fields & Accumulator::FIELD_REL_X ? mAccumulator.relX * mXScale : 0.0f;
1623        float deltaY = fields & Accumulator::FIELD_REL_Y ? mAccumulator.relY * mYScale : 0.0f;
1624
1625        if (downChanged) {
1626            motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
1627        } else if (down || mPointerController == NULL) {
1628            motionEventAction = AMOTION_EVENT_ACTION_MOVE;
1629        } else {
1630            motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
1631        }
1632
1633        if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0
1634                && (deltaX != 0.0f || deltaY != 0.0f)) {
1635            // Rotate motion based on display orientation if needed.
1636            // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
1637            int32_t orientation;
1638            if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1639                    NULL, NULL, & orientation)) {
1640                orientation = DISPLAY_ORIENTATION_0;
1641            }
1642
1643            float temp;
1644            switch (orientation) {
1645            case DISPLAY_ORIENTATION_90:
1646                temp = deltaX;
1647                deltaX = deltaY;
1648                deltaY = -temp;
1649                break;
1650
1651            case DISPLAY_ORIENTATION_180:
1652                deltaX = -deltaX;
1653                deltaY = -deltaY;
1654                break;
1655
1656            case DISPLAY_ORIENTATION_270:
1657                temp = deltaX;
1658                deltaX = -deltaY;
1659                deltaY = temp;
1660                break;
1661            }
1662        }
1663
1664        motionEventEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
1665
1666        pointerProperties.clear();
1667        pointerProperties.id = 0;
1668        pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
1669
1670        pointerCoords.clear();
1671
1672        if (mHaveVWheel && (fields & Accumulator::FIELD_REL_WHEEL)) {
1673            vscroll = mAccumulator.relWheel;
1674        } else {
1675            vscroll = 0;
1676        }
1677        mWheelYVelocityControl.move(when, NULL, &vscroll);
1678
1679        if (mHaveHWheel && (fields & Accumulator::FIELD_REL_HWHEEL)) {
1680            hscroll = mAccumulator.relHWheel;
1681        } else {
1682            hscroll = 0;
1683        }
1684        mWheelXVelocityControl.move(when, &hscroll, NULL);
1685
1686        mPointerVelocityControl.move(when, &deltaX, &deltaY);
1687
1688        if (mPointerController != NULL) {
1689            if (deltaX != 0 || deltaY != 0 || vscroll != 0 || hscroll != 0
1690                    || buttonsChanged) {
1691                mPointerController->setPresentation(
1692                        PointerControllerInterface::PRESENTATION_POINTER);
1693
1694                if (deltaX != 0 || deltaY != 0) {
1695                    mPointerController->move(deltaX, deltaY);
1696                }
1697
1698                if (buttonsChanged) {
1699                    mPointerController->setButtonState(mLocked.buttonState);
1700                }
1701
1702                mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
1703            }
1704
1705            float x, y;
1706            mPointerController->getPosition(&x, &y);
1707            pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
1708            pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
1709
1710            if (motionEventAction == AMOTION_EVENT_ACTION_DOWN) {
1711                motionEventEdgeFlags = calculateEdgeFlagsUsingPointerBounds(
1712                        mPointerController, x, y);
1713            }
1714        } else {
1715            pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
1716            pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
1717        }
1718
1719        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
1720    } // release lock
1721
1722    // Moving an external trackball or mouse should wake the device.
1723    // We don't do this for internal cursor devices to prevent them from waking up
1724    // the device in your pocket.
1725    // TODO: Use the input device configuration to control this behavior more finely.
1726    uint32_t policyFlags = 0;
1727    if (getDevice()->isExternal()) {
1728        policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1729    }
1730
1731    // Synthesize key down from buttons if needed.
1732    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1733            policyFlags, lastButtonState, currentButtonState);
1734
1735    // Send motion event.
1736    int32_t metaState = mContext->getGlobalMetaState();
1737    getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
1738            motionEventAction, 0, metaState, currentButtonState, motionEventEdgeFlags,
1739            1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime);
1740
1741    // Send hover move after UP to tell the application that the mouse is hovering now.
1742    if (motionEventAction == AMOTION_EVENT_ACTION_UP
1743            && mPointerController != NULL) {
1744        getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
1745                AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
1746                metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1747                1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime);
1748    }
1749
1750    // Send scroll events.
1751    if (vscroll != 0 || hscroll != 0) {
1752        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
1753        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
1754
1755        getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
1756                AMOTION_EVENT_ACTION_SCROLL, 0, metaState, currentButtonState,
1757                AMOTION_EVENT_EDGE_FLAG_NONE,
1758                1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime);
1759    }
1760
1761    // Synthesize key up from buttons if needed.
1762    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1763            policyFlags, lastButtonState, currentButtonState);
1764
1765    mAccumulator.clear();
1766}
1767
1768int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1769    if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
1770        return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1771    } else {
1772        return AKEY_STATE_UNKNOWN;
1773    }
1774}
1775
1776void CursorInputMapper::fadePointer() {
1777    { // acquire lock
1778        AutoMutex _l(mLock);
1779        if (mPointerController != NULL) {
1780            mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
1781        }
1782    } // release lock
1783}
1784
1785
1786// --- TouchInputMapper ---
1787
1788TouchInputMapper::TouchInputMapper(InputDevice* device) :
1789        InputMapper(device) {
1790    mConfig = getConfig();
1791
1792    mLocked.surfaceOrientation = -1;
1793    mLocked.surfaceWidth = -1;
1794    mLocked.surfaceHeight = -1;
1795
1796    initializeLocked();
1797}
1798
1799TouchInputMapper::~TouchInputMapper() {
1800}
1801
1802uint32_t TouchInputMapper::getSources() {
1803    return mTouchSource | mPointerSource;
1804}
1805
1806void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1807    InputMapper::populateDeviceInfo(info);
1808
1809    { // acquire lock
1810        AutoMutex _l(mLock);
1811
1812        // Ensure surface information is up to date so that orientation changes are
1813        // noticed immediately.
1814        if (!configureSurfaceLocked()) {
1815            return;
1816        }
1817
1818        info->addMotionRange(mLocked.orientedRanges.x);
1819        info->addMotionRange(mLocked.orientedRanges.y);
1820
1821        if (mLocked.orientedRanges.havePressure) {
1822            info->addMotionRange(mLocked.orientedRanges.pressure);
1823        }
1824
1825        if (mLocked.orientedRanges.haveSize) {
1826            info->addMotionRange(mLocked.orientedRanges.size);
1827        }
1828
1829        if (mLocked.orientedRanges.haveTouchSize) {
1830            info->addMotionRange(mLocked.orientedRanges.touchMajor);
1831            info->addMotionRange(mLocked.orientedRanges.touchMinor);
1832        }
1833
1834        if (mLocked.orientedRanges.haveToolSize) {
1835            info->addMotionRange(mLocked.orientedRanges.toolMajor);
1836            info->addMotionRange(mLocked.orientedRanges.toolMinor);
1837        }
1838
1839        if (mLocked.orientedRanges.haveOrientation) {
1840            info->addMotionRange(mLocked.orientedRanges.orientation);
1841        }
1842
1843        if (mLocked.orientedRanges.haveDistance) {
1844            info->addMotionRange(mLocked.orientedRanges.distance);
1845        }
1846
1847        if (mPointerController != NULL) {
1848            float minX, minY, maxX, maxY;
1849            if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1850                info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource,
1851                        minX, maxX, 0.0f, 0.0f);
1852                info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource,
1853                        minY, maxY, 0.0f, 0.0f);
1854            }
1855            info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource,
1856                    0.0f, 1.0f, 0.0f, 0.0f);
1857        }
1858    } // release lock
1859}
1860
1861void TouchInputMapper::dump(String8& dump) {
1862    { // acquire lock
1863        AutoMutex _l(mLock);
1864        dump.append(INDENT2 "Touch Input Mapper:\n");
1865        dumpParameters(dump);
1866        dumpVirtualKeysLocked(dump);
1867        dumpRawAxes(dump);
1868        dumpCalibration(dump);
1869        dumpSurfaceLocked(dump);
1870
1871        dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
1872        dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale);
1873        dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale);
1874        dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision);
1875        dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision);
1876        dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale);
1877        dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale);
1878        dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias);
1879        dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale);
1880        dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias);
1881        dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale);
1882        dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale);
1883        dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale);
1884        dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mLocked.distanceScale);
1885
1886        dump.appendFormat(INDENT3 "Last Touch:\n");
1887        dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount);
1888        dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState);
1889
1890        if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
1891            dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
1892            dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
1893                    mLocked.pointerGestureXMovementScale);
1894            dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
1895                    mLocked.pointerGestureYMovementScale);
1896            dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
1897                    mLocked.pointerGestureXZoomScale);
1898            dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
1899                    mLocked.pointerGestureYZoomScale);
1900            dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
1901                    mLocked.pointerGestureMaxSwipeWidth);
1902        }
1903    } // release lock
1904}
1905
1906void TouchInputMapper::initializeLocked() {
1907    mCurrentTouch.clear();
1908    mLastTouch.clear();
1909    mDownTime = 0;
1910
1911    for (uint32_t i = 0; i < MAX_POINTERS; i++) {
1912        mAveragingTouchFilter.historyStart[i] = 0;
1913        mAveragingTouchFilter.historyEnd[i] = 0;
1914    }
1915
1916    mJumpyTouchFilter.jumpyPointsDropped = 0;
1917
1918    mLocked.currentVirtualKey.down = false;
1919
1920    mLocked.orientedRanges.havePressure = false;
1921    mLocked.orientedRanges.haveSize = false;
1922    mLocked.orientedRanges.haveTouchSize = false;
1923    mLocked.orientedRanges.haveToolSize = false;
1924    mLocked.orientedRanges.haveOrientation = false;
1925    mLocked.orientedRanges.haveDistance = false;
1926
1927    mPointerGesture.reset();
1928    mPointerGesture.pointerVelocityControl.setParameters(mConfig->pointerVelocityControlParameters);
1929}
1930
1931void TouchInputMapper::configure() {
1932    InputMapper::configure();
1933
1934    // Configure basic parameters.
1935    configureParameters();
1936
1937    // Configure sources.
1938    switch (mParameters.deviceType) {
1939    case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
1940        mTouchSource = AINPUT_SOURCE_TOUCHSCREEN;
1941        mPointerSource = 0;
1942        break;
1943    case Parameters::DEVICE_TYPE_TOUCH_PAD:
1944        mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1945        mPointerSource = 0;
1946        break;
1947    case Parameters::DEVICE_TYPE_POINTER:
1948        mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1949        mPointerSource = AINPUT_SOURCE_MOUSE;
1950        break;
1951    default:
1952        LOG_ASSERT(false);
1953    }
1954
1955    // Configure absolute axis information.
1956    configureRawAxes();
1957
1958    // Prepare input device calibration.
1959    parseCalibration();
1960    resolveCalibration();
1961
1962    { // acquire lock
1963        AutoMutex _l(mLock);
1964
1965         // Configure surface dimensions and orientation.
1966        configureSurfaceLocked();
1967    } // release lock
1968}
1969
1970void TouchInputMapper::configureParameters() {
1971    mParameters.useBadTouchFilter = mConfig->filterTouchEvents;
1972    mParameters.useAveragingTouchFilter = mConfig->filterTouchEvents;
1973    mParameters.useJumpyTouchFilter = mConfig->filterJumpyTouchEvents;
1974
1975    // Use the pointer presentation mode for devices that do not support distinct
1976    // multitouch.  The spot-based presentation relies on being able to accurately
1977    // locate two or more fingers on the touch pad.
1978    mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
1979            ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS;
1980
1981    String8 gestureModeString;
1982    if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
1983            gestureModeString)) {
1984        if (gestureModeString == "pointer") {
1985            mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
1986        } else if (gestureModeString == "spots") {
1987            mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
1988        } else if (gestureModeString != "default") {
1989            LOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
1990        }
1991    }
1992
1993    if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
1994            || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
1995        // The device is a cursor device with a touch pad attached.
1996        // By default don't use the touch pad to move the pointer.
1997        mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
1998    } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
1999        // The device is a pointing device like a track pad.
2000        mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2001    } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
2002        // The device is a touch screen.
2003        mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2004    } else {
2005        // The device is a touch pad of unknown purpose.
2006        mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2007    }
2008
2009    String8 deviceTypeString;
2010    if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
2011            deviceTypeString)) {
2012        if (deviceTypeString == "touchScreen") {
2013            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2014        } else if (deviceTypeString == "touchPad") {
2015            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
2016        } else if (deviceTypeString == "pointer") {
2017            mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2018        } else if (deviceTypeString != "default") {
2019            LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
2020        }
2021    }
2022
2023    mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
2024    getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
2025            mParameters.orientationAware);
2026
2027    mParameters.associatedDisplayId = mParameters.orientationAware
2028            || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
2029            || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
2030            ? 0 : -1;
2031}
2032
2033void TouchInputMapper::dumpParameters(String8& dump) {
2034    dump.append(INDENT3 "Parameters:\n");
2035
2036    switch (mParameters.gestureMode) {
2037    case Parameters::GESTURE_MODE_POINTER:
2038        dump.append(INDENT4 "GestureMode: pointer\n");
2039        break;
2040    case Parameters::GESTURE_MODE_SPOTS:
2041        dump.append(INDENT4 "GestureMode: spots\n");
2042        break;
2043    default:
2044        assert(false);
2045    }
2046
2047    switch (mParameters.deviceType) {
2048    case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
2049        dump.append(INDENT4 "DeviceType: touchScreen\n");
2050        break;
2051    case Parameters::DEVICE_TYPE_TOUCH_PAD:
2052        dump.append(INDENT4 "DeviceType: touchPad\n");
2053        break;
2054    case Parameters::DEVICE_TYPE_POINTER:
2055        dump.append(INDENT4 "DeviceType: pointer\n");
2056        break;
2057    default:
2058        LOG_ASSERT(false);
2059    }
2060
2061    dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
2062            mParameters.associatedDisplayId);
2063    dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2064            toString(mParameters.orientationAware));
2065
2066    dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n",
2067            toString(mParameters.useBadTouchFilter));
2068    dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n",
2069            toString(mParameters.useAveragingTouchFilter));
2070    dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n",
2071            toString(mParameters.useJumpyTouchFilter));
2072}
2073
2074void TouchInputMapper::configureRawAxes() {
2075    mRawAxes.x.clear();
2076    mRawAxes.y.clear();
2077    mRawAxes.pressure.clear();
2078    mRawAxes.touchMajor.clear();
2079    mRawAxes.touchMinor.clear();
2080    mRawAxes.toolMajor.clear();
2081    mRawAxes.toolMinor.clear();
2082    mRawAxes.orientation.clear();
2083    mRawAxes.distance.clear();
2084    mRawAxes.trackingId.clear();
2085    mRawAxes.slot.clear();
2086}
2087
2088void TouchInputMapper::dumpRawAxes(String8& dump) {
2089    dump.append(INDENT3 "Raw Axes:\n");
2090    dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X");
2091    dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y");
2092    dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure");
2093    dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor");
2094    dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor");
2095    dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor");
2096    dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor");
2097    dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation");
2098    dumpRawAbsoluteAxisInfo(dump, mRawAxes.distance, "Distance");
2099    dumpRawAbsoluteAxisInfo(dump, mRawAxes.trackingId, "TrackingId");
2100    dumpRawAbsoluteAxisInfo(dump, mRawAxes.slot, "Slot");
2101}
2102
2103bool TouchInputMapper::configureSurfaceLocked() {
2104    // Ensure we have valid X and Y axes.
2105    if (!mRawAxes.x.valid || !mRawAxes.y.valid) {
2106        LOGW(INDENT "Touch device '%s' did not report support for X or Y axis!  "
2107                "The device will be inoperable.", getDeviceName().string());
2108        return false;
2109    }
2110
2111    // Update orientation and dimensions if needed.
2112    int32_t orientation = DISPLAY_ORIENTATION_0;
2113    int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2114    int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
2115
2116    if (mParameters.associatedDisplayId >= 0) {
2117        // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
2118        if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
2119                &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight,
2120                &mLocked.associatedDisplayOrientation)) {
2121            return false;
2122        }
2123
2124        // A touch screen inherits the dimensions of the display.
2125        if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2126            width = mLocked.associatedDisplayWidth;
2127            height = mLocked.associatedDisplayHeight;
2128        }
2129
2130        // The device inherits the orientation of the display if it is orientation aware.
2131        if (mParameters.orientationAware) {
2132            orientation = mLocked.associatedDisplayOrientation;
2133        }
2134    }
2135
2136    if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
2137            && mPointerController == NULL) {
2138        mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2139    }
2140
2141    bool orientationChanged = mLocked.surfaceOrientation != orientation;
2142    if (orientationChanged) {
2143        mLocked.surfaceOrientation = orientation;
2144    }
2145
2146    bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height;
2147    if (sizeChanged) {
2148        LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d",
2149                getDeviceId(), getDeviceName().string(), width, height);
2150
2151        mLocked.surfaceWidth = width;
2152        mLocked.surfaceHeight = height;
2153
2154        // Configure X and Y factors.
2155        mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1);
2156        mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1);
2157        mLocked.xPrecision = 1.0f / mLocked.xScale;
2158        mLocked.yPrecision = 1.0f / mLocked.yScale;
2159
2160        mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
2161        mLocked.orientedRanges.x.source = mTouchSource;
2162        mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
2163        mLocked.orientedRanges.y.source = mTouchSource;
2164
2165        configureVirtualKeysLocked();
2166
2167        // Scale factor for terms that are not oriented in a particular axis.
2168        // If the pixels are square then xScale == yScale otherwise we fake it
2169        // by choosing an average.
2170        mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale);
2171
2172        // Size of diagonal axis.
2173        float diagonalSize = hypotf(width, height);
2174
2175        // TouchMajor and TouchMinor factors.
2176        if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) {
2177            mLocked.orientedRanges.haveTouchSize = true;
2178
2179            mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
2180            mLocked.orientedRanges.touchMajor.source = mTouchSource;
2181            mLocked.orientedRanges.touchMajor.min = 0;
2182            mLocked.orientedRanges.touchMajor.max = diagonalSize;
2183            mLocked.orientedRanges.touchMajor.flat = 0;
2184            mLocked.orientedRanges.touchMajor.fuzz = 0;
2185
2186            mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor;
2187            mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
2188        }
2189
2190        // ToolMajor and ToolMinor factors.
2191        mLocked.toolSizeLinearScale = 0;
2192        mLocked.toolSizeLinearBias = 0;
2193        mLocked.toolSizeAreaScale = 0;
2194        mLocked.toolSizeAreaBias = 0;
2195        if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2196            if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) {
2197                if (mCalibration.haveToolSizeLinearScale) {
2198                    mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
2199                } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2200                    mLocked.toolSizeLinearScale = float(min(width, height))
2201                            / mRawAxes.toolMajor.maxValue;
2202                }
2203
2204                if (mCalibration.haveToolSizeLinearBias) {
2205                    mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2206                }
2207            } else if (mCalibration.toolSizeCalibration ==
2208                    Calibration::TOOL_SIZE_CALIBRATION_AREA) {
2209                if (mCalibration.haveToolSizeLinearScale) {
2210                    mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
2211                } else {
2212                    mLocked.toolSizeLinearScale = min(width, height);
2213                }
2214
2215                if (mCalibration.haveToolSizeLinearBias) {
2216                    mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2217                }
2218
2219                if (mCalibration.haveToolSizeAreaScale) {
2220                    mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale;
2221                } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2222                    mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue;
2223                }
2224
2225                if (mCalibration.haveToolSizeAreaBias) {
2226                    mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias;
2227                }
2228            }
2229
2230            mLocked.orientedRanges.haveToolSize = true;
2231
2232            mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
2233            mLocked.orientedRanges.toolMajor.source = mTouchSource;
2234            mLocked.orientedRanges.toolMajor.min = 0;
2235            mLocked.orientedRanges.toolMajor.max = diagonalSize;
2236            mLocked.orientedRanges.toolMajor.flat = 0;
2237            mLocked.orientedRanges.toolMajor.fuzz = 0;
2238
2239            mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor;
2240            mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
2241        }
2242
2243        // Pressure factors.
2244        mLocked.pressureScale = 0;
2245        if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) {
2246            RawAbsoluteAxisInfo rawPressureAxis;
2247            switch (mCalibration.pressureSource) {
2248            case Calibration::PRESSURE_SOURCE_PRESSURE:
2249                rawPressureAxis = mRawAxes.pressure;
2250                break;
2251            case Calibration::PRESSURE_SOURCE_TOUCH:
2252                rawPressureAxis = mRawAxes.touchMajor;
2253                break;
2254            default:
2255                rawPressureAxis.clear();
2256            }
2257
2258            if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
2259                    || mCalibration.pressureCalibration
2260                            == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
2261                if (mCalibration.havePressureScale) {
2262                    mLocked.pressureScale = mCalibration.pressureScale;
2263                } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) {
2264                    mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue;
2265                }
2266            }
2267
2268            mLocked.orientedRanges.havePressure = true;
2269
2270            mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
2271            mLocked.orientedRanges.pressure.source = mTouchSource;
2272            mLocked.orientedRanges.pressure.min = 0;
2273            mLocked.orientedRanges.pressure.max = 1.0;
2274            mLocked.orientedRanges.pressure.flat = 0;
2275            mLocked.orientedRanges.pressure.fuzz = 0;
2276        }
2277
2278        // Size factors.
2279        mLocked.sizeScale = 0;
2280        if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
2281            if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) {
2282                if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2283                    mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue;
2284                }
2285            }
2286
2287            mLocked.orientedRanges.haveSize = true;
2288
2289            mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
2290            mLocked.orientedRanges.size.source = mTouchSource;
2291            mLocked.orientedRanges.size.min = 0;
2292            mLocked.orientedRanges.size.max = 1.0;
2293            mLocked.orientedRanges.size.flat = 0;
2294            mLocked.orientedRanges.size.fuzz = 0;
2295        }
2296
2297        // Orientation
2298        mLocked.orientationScale = 0;
2299        if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) {
2300            if (mCalibration.orientationCalibration
2301                    == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
2302                if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) {
2303                    mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue;
2304                }
2305            }
2306
2307            mLocked.orientedRanges.haveOrientation = true;
2308
2309            mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
2310            mLocked.orientedRanges.orientation.source = mTouchSource;
2311            mLocked.orientedRanges.orientation.min = - M_PI_2;
2312            mLocked.orientedRanges.orientation.max = M_PI_2;
2313            mLocked.orientedRanges.orientation.flat = 0;
2314            mLocked.orientedRanges.orientation.fuzz = 0;
2315        }
2316
2317        // Distance
2318        mLocked.distanceScale = 0;
2319        if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
2320            if (mCalibration.distanceCalibration
2321                    == Calibration::DISTANCE_CALIBRATION_SCALED) {
2322                if (mCalibration.haveDistanceScale) {
2323                    mLocked.distanceScale = mCalibration.distanceScale;
2324                } else {
2325                    mLocked.distanceScale = 1.0f;
2326                }
2327            }
2328
2329            mLocked.orientedRanges.haveDistance = true;
2330
2331            mLocked.orientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
2332            mLocked.orientedRanges.distance.source = mTouchSource;
2333            mLocked.orientedRanges.distance.min =
2334                    mRawAxes.distance.minValue * mLocked.distanceScale;
2335            mLocked.orientedRanges.distance.max =
2336                    mRawAxes.distance.minValue * mLocked.distanceScale;
2337            mLocked.orientedRanges.distance.flat = 0;
2338            mLocked.orientedRanges.distance.fuzz =
2339                    mRawAxes.distance.fuzz * mLocked.distanceScale;
2340        }
2341    }
2342
2343    if (orientationChanged || sizeChanged) {
2344        // Compute oriented surface dimensions, precision, scales and ranges.
2345        // Note that the maximum value reported is an inclusive maximum value so it is one
2346        // unit less than the total width or height of surface.
2347        switch (mLocked.surfaceOrientation) {
2348        case DISPLAY_ORIENTATION_90:
2349        case DISPLAY_ORIENTATION_270:
2350            mLocked.orientedSurfaceWidth = mLocked.surfaceHeight;
2351            mLocked.orientedSurfaceHeight = mLocked.surfaceWidth;
2352
2353            mLocked.orientedXPrecision = mLocked.yPrecision;
2354            mLocked.orientedYPrecision = mLocked.xPrecision;
2355
2356            mLocked.orientedRanges.x.min = 0;
2357            mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2358                    * mLocked.yScale;
2359            mLocked.orientedRanges.x.flat = 0;
2360            mLocked.orientedRanges.x.fuzz = mLocked.yScale;
2361
2362            mLocked.orientedRanges.y.min = 0;
2363            mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2364                    * mLocked.xScale;
2365            mLocked.orientedRanges.y.flat = 0;
2366            mLocked.orientedRanges.y.fuzz = mLocked.xScale;
2367            break;
2368
2369        default:
2370            mLocked.orientedSurfaceWidth = mLocked.surfaceWidth;
2371            mLocked.orientedSurfaceHeight = mLocked.surfaceHeight;
2372
2373            mLocked.orientedXPrecision = mLocked.xPrecision;
2374            mLocked.orientedYPrecision = mLocked.yPrecision;
2375
2376            mLocked.orientedRanges.x.min = 0;
2377            mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2378                    * mLocked.xScale;
2379            mLocked.orientedRanges.x.flat = 0;
2380            mLocked.orientedRanges.x.fuzz = mLocked.xScale;
2381
2382            mLocked.orientedRanges.y.min = 0;
2383            mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2384                    * mLocked.yScale;
2385            mLocked.orientedRanges.y.flat = 0;
2386            mLocked.orientedRanges.y.fuzz = mLocked.yScale;
2387            break;
2388        }
2389
2390        // Compute pointer gesture detection parameters.
2391        // TODO: These factors should not be hardcoded.
2392        if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2393            int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2394            int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
2395            float rawDiagonal = hypotf(rawWidth, rawHeight);
2396            float displayDiagonal = hypotf(mLocked.associatedDisplayWidth,
2397                    mLocked.associatedDisplayHeight);
2398
2399            // Scale movements such that one whole swipe of the touch pad covers a
2400            // given area relative to the diagonal size of the display when no acceleration
2401            // is applied.
2402            // Assume that the touch pad has a square aspect ratio such that movements in
2403            // X and Y of the same number of raw units cover the same physical distance.
2404            mLocked.pointerGestureXMovementScale = mConfig->pointerGestureMovementSpeedRatio
2405                    * displayDiagonal / rawDiagonal;
2406            mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale;
2407
2408            // Scale zooms to cover a smaller range of the display than movements do.
2409            // This value determines the area around the pointer that is affected by freeform
2410            // pointer gestures.
2411            mLocked.pointerGestureXZoomScale = mConfig->pointerGestureZoomSpeedRatio
2412                    * displayDiagonal / rawDiagonal;
2413            mLocked.pointerGestureYZoomScale = mLocked.pointerGestureXZoomScale;
2414
2415            // Max width between pointers to detect a swipe gesture is more than some fraction
2416            // of the diagonal axis of the touch pad.  Touches that are wider than this are
2417            // translated into freeform gestures.
2418            mLocked.pointerGestureMaxSwipeWidth =
2419                    mConfig->pointerGestureSwipeMaxWidthRatio * rawDiagonal;
2420
2421            // Reset the current pointer gesture.
2422            mPointerGesture.reset();
2423
2424            // Remove any current spots.
2425            if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2426                mPointerController->clearSpots();
2427            }
2428        }
2429    }
2430
2431    return true;
2432}
2433
2434void TouchInputMapper::dumpSurfaceLocked(String8& dump) {
2435    dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth);
2436    dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight);
2437    dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation);
2438}
2439
2440void TouchInputMapper::configureVirtualKeysLocked() {
2441    Vector<VirtualKeyDefinition> virtualKeyDefinitions;
2442    getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
2443
2444    mLocked.virtualKeys.clear();
2445
2446    if (virtualKeyDefinitions.size() == 0) {
2447        return;
2448    }
2449
2450    mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size());
2451
2452    int32_t touchScreenLeft = mRawAxes.x.minValue;
2453    int32_t touchScreenTop = mRawAxes.y.minValue;
2454    int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2455    int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
2456
2457    for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
2458        const VirtualKeyDefinition& virtualKeyDefinition =
2459                virtualKeyDefinitions[i];
2460
2461        mLocked.virtualKeys.add();
2462        VirtualKey& virtualKey = mLocked.virtualKeys.editTop();
2463
2464        virtualKey.scanCode = virtualKeyDefinition.scanCode;
2465        int32_t keyCode;
2466        uint32_t flags;
2467        if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode,
2468                & keyCode, & flags)) {
2469            LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
2470                    virtualKey.scanCode);
2471            mLocked.virtualKeys.pop(); // drop the key
2472            continue;
2473        }
2474
2475        virtualKey.keyCode = keyCode;
2476        virtualKey.flags = flags;
2477
2478        // convert the key definition's display coordinates into touch coordinates for a hit box
2479        int32_t halfWidth = virtualKeyDefinition.width / 2;
2480        int32_t halfHeight = virtualKeyDefinition.height / 2;
2481
2482        virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
2483                * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2484        virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
2485                * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2486        virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
2487                * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2488        virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
2489                * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2490    }
2491}
2492
2493void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) {
2494    if (!mLocked.virtualKeys.isEmpty()) {
2495        dump.append(INDENT3 "Virtual Keys:\n");
2496
2497        for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) {
2498            const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i);
2499            dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
2500                    "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
2501                    i, virtualKey.scanCode, virtualKey.keyCode,
2502                    virtualKey.hitLeft, virtualKey.hitRight,
2503                    virtualKey.hitTop, virtualKey.hitBottom);
2504        }
2505    }
2506}
2507
2508void TouchInputMapper::parseCalibration() {
2509    const PropertyMap& in = getDevice()->getConfiguration();
2510    Calibration& out = mCalibration;
2511
2512    // Touch Size
2513    out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT;
2514    String8 touchSizeCalibrationString;
2515    if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) {
2516        if (touchSizeCalibrationString == "none") {
2517            out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2518        } else if (touchSizeCalibrationString == "geometric") {
2519            out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC;
2520        } else if (touchSizeCalibrationString == "pressure") {
2521            out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2522        } else if (touchSizeCalibrationString != "default") {
2523            LOGW("Invalid value for touch.touchSize.calibration: '%s'",
2524                    touchSizeCalibrationString.string());
2525        }
2526    }
2527
2528    // Tool Size
2529    out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT;
2530    String8 toolSizeCalibrationString;
2531    if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) {
2532        if (toolSizeCalibrationString == "none") {
2533            out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2534        } else if (toolSizeCalibrationString == "geometric") {
2535            out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC;
2536        } else if (toolSizeCalibrationString == "linear") {
2537            out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2538        } else if (toolSizeCalibrationString == "area") {
2539            out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA;
2540        } else if (toolSizeCalibrationString != "default") {
2541            LOGW("Invalid value for touch.toolSize.calibration: '%s'",
2542                    toolSizeCalibrationString.string());
2543        }
2544    }
2545
2546    out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"),
2547            out.toolSizeLinearScale);
2548    out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"),
2549            out.toolSizeLinearBias);
2550    out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"),
2551            out.toolSizeAreaScale);
2552    out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"),
2553            out.toolSizeAreaBias);
2554    out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"),
2555            out.toolSizeIsSummed);
2556
2557    // Pressure
2558    out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
2559    String8 pressureCalibrationString;
2560    if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
2561        if (pressureCalibrationString == "none") {
2562            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2563        } else if (pressureCalibrationString == "physical") {
2564            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
2565        } else if (pressureCalibrationString == "amplitude") {
2566            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2567        } else if (pressureCalibrationString != "default") {
2568            LOGW("Invalid value for touch.pressure.calibration: '%s'",
2569                    pressureCalibrationString.string());
2570        }
2571    }
2572
2573    out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT;
2574    String8 pressureSourceString;
2575    if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) {
2576        if (pressureSourceString == "pressure") {
2577            out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2578        } else if (pressureSourceString == "touch") {
2579            out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2580        } else if (pressureSourceString != "default") {
2581            LOGW("Invalid value for touch.pressure.source: '%s'",
2582                    pressureSourceString.string());
2583        }
2584    }
2585
2586    out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
2587            out.pressureScale);
2588
2589    // Size
2590    out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
2591    String8 sizeCalibrationString;
2592    if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
2593        if (sizeCalibrationString == "none") {
2594            out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2595        } else if (sizeCalibrationString == "normalized") {
2596            out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2597        } else if (sizeCalibrationString != "default") {
2598            LOGW("Invalid value for touch.size.calibration: '%s'",
2599                    sizeCalibrationString.string());
2600        }
2601    }
2602
2603    // Orientation
2604    out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
2605    String8 orientationCalibrationString;
2606    if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
2607        if (orientationCalibrationString == "none") {
2608            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2609        } else if (orientationCalibrationString == "interpolated") {
2610            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2611        } else if (orientationCalibrationString == "vector") {
2612            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
2613        } else if (orientationCalibrationString != "default") {
2614            LOGW("Invalid value for touch.orientation.calibration: '%s'",
2615                    orientationCalibrationString.string());
2616        }
2617    }
2618
2619    // Distance
2620    out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
2621    String8 distanceCalibrationString;
2622    if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
2623        if (distanceCalibrationString == "none") {
2624            out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
2625        } else if (distanceCalibrationString == "scaled") {
2626            out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
2627        } else if (distanceCalibrationString != "default") {
2628            LOGW("Invalid value for touch.distance.calibration: '%s'",
2629                    distanceCalibrationString.string());
2630        }
2631    }
2632
2633    out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
2634            out.distanceScale);
2635}
2636
2637void TouchInputMapper::resolveCalibration() {
2638    // Pressure
2639    switch (mCalibration.pressureSource) {
2640    case Calibration::PRESSURE_SOURCE_DEFAULT:
2641        if (mRawAxes.pressure.valid) {
2642            mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2643        } else if (mRawAxes.touchMajor.valid) {
2644            mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2645        }
2646        break;
2647
2648    case Calibration::PRESSURE_SOURCE_PRESSURE:
2649        if (! mRawAxes.pressure.valid) {
2650            LOGW("Calibration property touch.pressure.source is 'pressure' but "
2651                    "the pressure axis is not available.");
2652        }
2653        break;
2654
2655    case Calibration::PRESSURE_SOURCE_TOUCH:
2656        if (! mRawAxes.touchMajor.valid) {
2657            LOGW("Calibration property touch.pressure.source is 'touch' but "
2658                    "the touchMajor axis is not available.");
2659        }
2660        break;
2661
2662    default:
2663        break;
2664    }
2665
2666    switch (mCalibration.pressureCalibration) {
2667    case Calibration::PRESSURE_CALIBRATION_DEFAULT:
2668        if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) {
2669            mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2670        } else {
2671            mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2672        }
2673        break;
2674
2675    default:
2676        break;
2677    }
2678
2679    // Tool Size
2680    switch (mCalibration.toolSizeCalibration) {
2681    case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT:
2682        if (mRawAxes.toolMajor.valid) {
2683            mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2684        } else {
2685            mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2686        }
2687        break;
2688
2689    default:
2690        break;
2691    }
2692
2693    // Touch Size
2694    switch (mCalibration.touchSizeCalibration) {
2695    case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT:
2696        if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE
2697                && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2698            mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2699        } else {
2700            mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2701        }
2702        break;
2703
2704    default:
2705        break;
2706    }
2707
2708    // Size
2709    switch (mCalibration.sizeCalibration) {
2710    case Calibration::SIZE_CALIBRATION_DEFAULT:
2711        if (mRawAxes.toolMajor.valid) {
2712            mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2713        } else {
2714            mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2715        }
2716        break;
2717
2718    default:
2719        break;
2720    }
2721
2722    // Orientation
2723    switch (mCalibration.orientationCalibration) {
2724    case Calibration::ORIENTATION_CALIBRATION_DEFAULT:
2725        if (mRawAxes.orientation.valid) {
2726            mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2727        } else {
2728            mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2729        }
2730        break;
2731
2732    default:
2733        break;
2734    }
2735
2736    // Distance
2737    switch (mCalibration.distanceCalibration) {
2738    case Calibration::DISTANCE_CALIBRATION_DEFAULT:
2739        if (mRawAxes.distance.valid) {
2740            mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
2741        } else {
2742            mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
2743        }
2744        break;
2745
2746    default:
2747        break;
2748    }
2749}
2750
2751void TouchInputMapper::dumpCalibration(String8& dump) {
2752    dump.append(INDENT3 "Calibration:\n");
2753
2754    // Touch Size
2755    switch (mCalibration.touchSizeCalibration) {
2756    case Calibration::TOUCH_SIZE_CALIBRATION_NONE:
2757        dump.append(INDENT4 "touch.touchSize.calibration: none\n");
2758        break;
2759    case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2760        dump.append(INDENT4 "touch.touchSize.calibration: geometric\n");
2761        break;
2762    case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2763        dump.append(INDENT4 "touch.touchSize.calibration: pressure\n");
2764        break;
2765    default:
2766        LOG_ASSERT(false);
2767    }
2768
2769    // Tool Size
2770    switch (mCalibration.toolSizeCalibration) {
2771    case Calibration::TOOL_SIZE_CALIBRATION_NONE:
2772        dump.append(INDENT4 "touch.toolSize.calibration: none\n");
2773        break;
2774    case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2775        dump.append(INDENT4 "touch.toolSize.calibration: geometric\n");
2776        break;
2777    case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2778        dump.append(INDENT4 "touch.toolSize.calibration: linear\n");
2779        break;
2780    case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2781        dump.append(INDENT4 "touch.toolSize.calibration: area\n");
2782        break;
2783    default:
2784        LOG_ASSERT(false);
2785    }
2786
2787    if (mCalibration.haveToolSizeLinearScale) {
2788        dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n",
2789                mCalibration.toolSizeLinearScale);
2790    }
2791
2792    if (mCalibration.haveToolSizeLinearBias) {
2793        dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n",
2794                mCalibration.toolSizeLinearBias);
2795    }
2796
2797    if (mCalibration.haveToolSizeAreaScale) {
2798        dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n",
2799                mCalibration.toolSizeAreaScale);
2800    }
2801
2802    if (mCalibration.haveToolSizeAreaBias) {
2803        dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n",
2804                mCalibration.toolSizeAreaBias);
2805    }
2806
2807    if (mCalibration.haveToolSizeIsSummed) {
2808        dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n",
2809                toString(mCalibration.toolSizeIsSummed));
2810    }
2811
2812    // Pressure
2813    switch (mCalibration.pressureCalibration) {
2814    case Calibration::PRESSURE_CALIBRATION_NONE:
2815        dump.append(INDENT4 "touch.pressure.calibration: none\n");
2816        break;
2817    case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
2818        dump.append(INDENT4 "touch.pressure.calibration: physical\n");
2819        break;
2820    case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
2821        dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
2822        break;
2823    default:
2824        LOG_ASSERT(false);
2825    }
2826
2827    switch (mCalibration.pressureSource) {
2828    case Calibration::PRESSURE_SOURCE_PRESSURE:
2829        dump.append(INDENT4 "touch.pressure.source: pressure\n");
2830        break;
2831    case Calibration::PRESSURE_SOURCE_TOUCH:
2832        dump.append(INDENT4 "touch.pressure.source: touch\n");
2833        break;
2834    case Calibration::PRESSURE_SOURCE_DEFAULT:
2835        break;
2836    default:
2837        LOG_ASSERT(false);
2838    }
2839
2840    if (mCalibration.havePressureScale) {
2841        dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
2842                mCalibration.pressureScale);
2843    }
2844
2845    // Size
2846    switch (mCalibration.sizeCalibration) {
2847    case Calibration::SIZE_CALIBRATION_NONE:
2848        dump.append(INDENT4 "touch.size.calibration: none\n");
2849        break;
2850    case Calibration::SIZE_CALIBRATION_NORMALIZED:
2851        dump.append(INDENT4 "touch.size.calibration: normalized\n");
2852        break;
2853    default:
2854        LOG_ASSERT(false);
2855    }
2856
2857    // Orientation
2858    switch (mCalibration.orientationCalibration) {
2859    case Calibration::ORIENTATION_CALIBRATION_NONE:
2860        dump.append(INDENT4 "touch.orientation.calibration: none\n");
2861        break;
2862    case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
2863        dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
2864        break;
2865    case Calibration::ORIENTATION_CALIBRATION_VECTOR:
2866        dump.append(INDENT4 "touch.orientation.calibration: vector\n");
2867        break;
2868    default:
2869        LOG_ASSERT(false);
2870    }
2871
2872    // Distance
2873    switch (mCalibration.distanceCalibration) {
2874    case Calibration::DISTANCE_CALIBRATION_NONE:
2875        dump.append(INDENT4 "touch.distance.calibration: none\n");
2876        break;
2877    case Calibration::DISTANCE_CALIBRATION_SCALED:
2878        dump.append(INDENT4 "touch.distance.calibration: scaled\n");
2879        break;
2880    default:
2881        LOG_ASSERT(false);
2882    }
2883
2884    if (mCalibration.haveDistanceScale) {
2885        dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
2886                mCalibration.distanceScale);
2887    }
2888}
2889
2890void TouchInputMapper::reset() {
2891    // Synthesize touch up event if touch is currently down.
2892    // This will also take care of finishing virtual key processing if needed.
2893    if (mLastTouch.pointerCount != 0) {
2894        nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
2895        mCurrentTouch.clear();
2896        syncTouch(when, true);
2897    }
2898
2899    { // acquire lock
2900        AutoMutex _l(mLock);
2901        initializeLocked();
2902
2903        if (mPointerController != NULL
2904                && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2905            mPointerController->clearSpots();
2906        }
2907    } // release lock
2908
2909    InputMapper::reset();
2910}
2911
2912void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) {
2913#if DEBUG_RAW_EVENTS
2914    if (!havePointerIds) {
2915        LOGD("syncTouch: pointerCount=%d, no pointer ids", mCurrentTouch.pointerCount);
2916    } else {
2917        LOGD("syncTouch: pointerCount=%d, up=0x%08x, down=0x%08x, move=0x%08x, "
2918                "last=0x%08x, current=0x%08x", mCurrentTouch.pointerCount,
2919                mLastTouch.idBits.value & ~mCurrentTouch.idBits.value,
2920                mCurrentTouch.idBits.value & ~mLastTouch.idBits.value,
2921                mLastTouch.idBits.value & mCurrentTouch.idBits.value,
2922                mLastTouch.idBits.value, mCurrentTouch.idBits.value);
2923    }
2924#endif
2925
2926    // Preprocess pointer data.
2927    if (mParameters.useBadTouchFilter) {
2928        if (applyBadTouchFilter()) {
2929            havePointerIds = false;
2930        }
2931    }
2932
2933    if (mParameters.useJumpyTouchFilter) {
2934        if (applyJumpyTouchFilter()) {
2935            havePointerIds = false;
2936        }
2937    }
2938
2939    if (!havePointerIds) {
2940        calculatePointerIds();
2941    }
2942
2943    TouchData temp;
2944    TouchData* savedTouch;
2945    if (mParameters.useAveragingTouchFilter) {
2946        temp.copyFrom(mCurrentTouch);
2947        savedTouch = & temp;
2948
2949        applyAveragingTouchFilter();
2950    } else {
2951        savedTouch = & mCurrentTouch;
2952    }
2953
2954    uint32_t policyFlags = 0;
2955    if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
2956        if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2957            // If this is a touch screen, hide the pointer on an initial down.
2958            getContext()->fadePointer();
2959        }
2960
2961        // Initial downs on external touch devices should wake the device.
2962        // We don't do this for internal touch screens to prevent them from waking
2963        // up in your pocket.
2964        // TODO: Use the input device configuration to control this behavior more finely.
2965        if (getDevice()->isExternal()) {
2966            policyFlags |= POLICY_FLAG_WAKE_DROPPED;
2967        }
2968    }
2969
2970    // Synthesize key down from buttons if needed.
2971    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mTouchSource,
2972            policyFlags, mLastTouch.buttonState, mCurrentTouch.buttonState);
2973
2974    // Send motion events.
2975    TouchResult touchResult;
2976    if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount == 0
2977            && mLastTouch.buttonState == mCurrentTouch.buttonState) {
2978        // Drop spurious syncs.
2979        touchResult = DROP_STROKE;
2980    } else {
2981        // Process touches and virtual keys.
2982        touchResult = consumeOffScreenTouches(when, policyFlags);
2983        if (touchResult == DISPATCH_TOUCH) {
2984            suppressSwipeOntoVirtualKeys(when);
2985            if (mPointerController != NULL) {
2986                dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2987            }
2988            dispatchTouches(when, policyFlags);
2989        }
2990    }
2991
2992    // Synthesize key up from buttons if needed.
2993    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mTouchSource,
2994            policyFlags, mLastTouch.buttonState, mCurrentTouch.buttonState);
2995
2996    // Copy current touch to last touch in preparation for the next cycle.
2997    // Keep the button state so we can track edge-triggered button state changes.
2998    if (touchResult == DROP_STROKE) {
2999        mLastTouch.clear();
3000        mLastTouch.buttonState = savedTouch->buttonState;
3001    } else {
3002        mLastTouch.copyFrom(*savedTouch);
3003    }
3004}
3005
3006void TouchInputMapper::timeoutExpired(nsecs_t when) {
3007    if (mPointerController != NULL) {
3008        dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
3009    }
3010}
3011
3012TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches(
3013        nsecs_t when, uint32_t policyFlags) {
3014    int32_t keyEventAction, keyEventFlags;
3015    int32_t keyCode, scanCode, downTime;
3016    TouchResult touchResult;
3017
3018    { // acquire lock
3019        AutoMutex _l(mLock);
3020
3021        // Update surface size and orientation, including virtual key positions.
3022        if (! configureSurfaceLocked()) {
3023            return DROP_STROKE;
3024        }
3025
3026        // Check for virtual key press.
3027        if (mLocked.currentVirtualKey.down) {
3028            if (mCurrentTouch.pointerCount == 0) {
3029                // Pointer went up while virtual key was down.
3030                mLocked.currentVirtualKey.down = false;
3031#if DEBUG_VIRTUAL_KEYS
3032                LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
3033                        mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
3034#endif
3035                keyEventAction = AKEY_EVENT_ACTION_UP;
3036                keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3037                touchResult = SKIP_TOUCH;
3038                goto DispatchVirtualKey;
3039            }
3040
3041            if (mCurrentTouch.pointerCount == 1) {
3042                int32_t x = mCurrentTouch.pointers[0].x;
3043                int32_t y = mCurrentTouch.pointers[0].y;
3044                const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
3045                if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) {
3046                    // Pointer is still within the space of the virtual key.
3047                    return SKIP_TOUCH;
3048                }
3049            }
3050
3051            // Pointer left virtual key area or another pointer also went down.
3052            // Send key cancellation and drop the stroke so subsequent motions will be
3053            // considered fresh downs.  This is useful when the user swipes away from the
3054            // virtual key area into the main display surface.
3055            mLocked.currentVirtualKey.down = false;
3056#if DEBUG_VIRTUAL_KEYS
3057            LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
3058                    mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
3059#endif
3060            keyEventAction = AKEY_EVENT_ACTION_UP;
3061            keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
3062                    | AKEY_EVENT_FLAG_CANCELED;
3063
3064            // Check whether the pointer moved inside the display area where we should
3065            // start a new stroke.
3066            int32_t x = mCurrentTouch.pointers[0].x;
3067            int32_t y = mCurrentTouch.pointers[0].y;
3068            if (isPointInsideSurfaceLocked(x, y)) {
3069                mLastTouch.clear();
3070                touchResult = DISPATCH_TOUCH;
3071            } else {
3072                touchResult = DROP_STROKE;
3073            }
3074        } else {
3075            if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) {
3076                // Pointer just went down.  Handle off-screen touches, if needed.
3077                int32_t x = mCurrentTouch.pointers[0].x;
3078                int32_t y = mCurrentTouch.pointers[0].y;
3079                if (! isPointInsideSurfaceLocked(x, y)) {
3080                    // If exactly one pointer went down, check for virtual key hit.
3081                    // Otherwise we will drop the entire stroke.
3082                    if (mCurrentTouch.pointerCount == 1) {
3083                        const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
3084                        if (virtualKey) {
3085                            if (mContext->shouldDropVirtualKey(when, getDevice(),
3086                                    virtualKey->keyCode, virtualKey->scanCode)) {
3087                                return DROP_STROKE;
3088                            }
3089
3090                            mLocked.currentVirtualKey.down = true;
3091                            mLocked.currentVirtualKey.downTime = when;
3092                            mLocked.currentVirtualKey.keyCode = virtualKey->keyCode;
3093                            mLocked.currentVirtualKey.scanCode = virtualKey->scanCode;
3094#if DEBUG_VIRTUAL_KEYS
3095                            LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
3096                                    mLocked.currentVirtualKey.keyCode,
3097                                    mLocked.currentVirtualKey.scanCode);
3098#endif
3099                            keyEventAction = AKEY_EVENT_ACTION_DOWN;
3100                            keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM
3101                                    | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3102                            touchResult = SKIP_TOUCH;
3103                            goto DispatchVirtualKey;
3104                        }
3105                    }
3106                    return DROP_STROKE;
3107                }
3108            }
3109            return DISPATCH_TOUCH;
3110        }
3111
3112    DispatchVirtualKey:
3113        // Collect remaining state needed to dispatch virtual key.
3114        keyCode = mLocked.currentVirtualKey.keyCode;
3115        scanCode = mLocked.currentVirtualKey.scanCode;
3116        downTime = mLocked.currentVirtualKey.downTime;
3117    } // release lock
3118
3119    // Dispatch virtual key.
3120    int32_t metaState = mContext->getGlobalMetaState();
3121    policyFlags |= POLICY_FLAG_VIRTUAL;
3122    getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
3123            keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
3124    return touchResult;
3125}
3126
3127void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) {
3128    // Disable all virtual key touches that happen within a short time interval of the
3129    // most recent touch.  The idea is to filter out stray virtual key presses when
3130    // interacting with the touch screen.
3131    //
3132    // Problems we're trying to solve:
3133    //
3134    // 1. While scrolling a list or dragging the window shade, the user swipes down into a
3135    //    virtual key area that is implemented by a separate touch panel and accidentally
3136    //    triggers a virtual key.
3137    //
3138    // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
3139    //    area and accidentally triggers a virtual key.  This often happens when virtual keys
3140    //    are layed out below the screen near to where the on screen keyboard's space bar
3141    //    is displayed.
3142    if (mConfig->virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) {
3143        mContext->disableVirtualKeysUntil(when + mConfig->virtualKeyQuietTime);
3144    }
3145}
3146
3147void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
3148    uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3149    uint32_t lastPointerCount = mLastTouch.pointerCount;
3150    if (currentPointerCount == 0 && lastPointerCount == 0) {
3151        return; // nothing to do!
3152    }
3153
3154    // Update current touch coordinates.
3155    int32_t edgeFlags;
3156    float xPrecision, yPrecision;
3157    prepareTouches(&edgeFlags, &xPrecision, &yPrecision);
3158
3159    // Dispatch motions.
3160    BitSet32 currentIdBits = mCurrentTouch.idBits;
3161    BitSet32 lastIdBits = mLastTouch.idBits;
3162    int32_t metaState = getContext()->getGlobalMetaState();
3163    int32_t buttonState = mCurrentTouch.buttonState;
3164
3165    if (currentIdBits == lastIdBits) {
3166        // No pointer id changes so this is a move event.
3167        // The dispatcher takes care of batching moves so we don't have to deal with that here.
3168        dispatchMotion(when, policyFlags, mTouchSource,
3169                AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState,
3170                AMOTION_EVENT_EDGE_FLAG_NONE,
3171                mCurrentTouchProperties, mCurrentTouchCoords,
3172                mCurrentTouch.idToIndex, currentIdBits, -1,
3173                xPrecision, yPrecision, mDownTime);
3174    } else {
3175        // There may be pointers going up and pointers going down and pointers moving
3176        // all at the same time.
3177        BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
3178        BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
3179        BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
3180        BitSet32 dispatchedIdBits(lastIdBits.value);
3181
3182        // Update last coordinates of pointers that have moved so that we observe the new
3183        // pointer positions at the same time as other pointers that have just gone up.
3184        bool moveNeeded = updateMovedPointers(
3185                mCurrentTouchProperties, mCurrentTouchCoords, mCurrentTouch.idToIndex,
3186                mLastTouchProperties, mLastTouchCoords, mLastTouch.idToIndex,
3187                moveIdBits);
3188        if (buttonState != mLastTouch.buttonState) {
3189            moveNeeded = true;
3190        }
3191
3192        // Dispatch pointer up events.
3193        while (!upIdBits.isEmpty()) {
3194            uint32_t upId = upIdBits.firstMarkedBit();
3195            upIdBits.clearBit(upId);
3196
3197            dispatchMotion(when, policyFlags, mTouchSource,
3198                    AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, buttonState, 0,
3199                    mLastTouchProperties, mLastTouchCoords,
3200                    mLastTouch.idToIndex, dispatchedIdBits, upId,
3201                    xPrecision, yPrecision, mDownTime);
3202            dispatchedIdBits.clearBit(upId);
3203        }
3204
3205        // Dispatch move events if any of the remaining pointers moved from their old locations.
3206        // Although applications receive new locations as part of individual pointer up
3207        // events, they do not generally handle them except when presented in a move event.
3208        if (moveNeeded) {
3209            LOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
3210            dispatchMotion(when, policyFlags, mTouchSource,
3211                    AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, 0,
3212                    mCurrentTouchProperties, mCurrentTouchCoords,
3213                    mCurrentTouch.idToIndex, dispatchedIdBits, -1,
3214                    xPrecision, yPrecision, mDownTime);
3215        }
3216
3217        // Dispatch pointer down events using the new pointer locations.
3218        while (!downIdBits.isEmpty()) {
3219            uint32_t downId = downIdBits.firstMarkedBit();
3220            downIdBits.clearBit(downId);
3221            dispatchedIdBits.markBit(downId);
3222
3223            if (dispatchedIdBits.count() == 1) {
3224                // First pointer is going down.  Set down time.
3225                mDownTime = when;
3226            } else {
3227                // Only send edge flags with first pointer down.
3228                edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3229            }
3230
3231            dispatchMotion(when, policyFlags, mTouchSource,
3232                    AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, edgeFlags,
3233                    mCurrentTouchProperties, mCurrentTouchCoords,
3234                    mCurrentTouch.idToIndex, dispatchedIdBits, downId,
3235                    xPrecision, yPrecision, mDownTime);
3236        }
3237    }
3238
3239    // Update state for next time.
3240    for (uint32_t i = 0; i < currentPointerCount; i++) {
3241        mLastTouchProperties[i].copyFrom(mCurrentTouchProperties[i]);
3242        mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]);
3243    }
3244}
3245
3246void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags,
3247        float* outXPrecision, float* outYPrecision) {
3248    uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3249    uint32_t lastPointerCount = mLastTouch.pointerCount;
3250
3251    AutoMutex _l(mLock);
3252
3253    // Walk through the the active pointers and map touch screen coordinates (TouchData) into
3254    // display or surface coordinates (PointerCoords) and adjust for display orientation.
3255    for (uint32_t i = 0; i < currentPointerCount; i++) {
3256        const PointerData& in = mCurrentTouch.pointers[i];
3257
3258        // ToolMajor and ToolMinor
3259        float toolMajor, toolMinor;
3260        switch (mCalibration.toolSizeCalibration) {
3261        case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
3262            toolMajor = in.toolMajor * mLocked.geometricScale;
3263            if (mRawAxes.toolMinor.valid) {
3264                toolMinor = in.toolMinor * mLocked.geometricScale;
3265            } else {
3266                toolMinor = toolMajor;
3267            }
3268            break;
3269        case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
3270            toolMajor = in.toolMajor != 0
3271                    ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias
3272                    : 0;
3273            if (mRawAxes.toolMinor.valid) {
3274                toolMinor = in.toolMinor != 0
3275                        ? in.toolMinor * mLocked.toolSizeLinearScale
3276                                + mLocked.toolSizeLinearBias
3277                        : 0;
3278            } else {
3279                toolMinor = toolMajor;
3280            }
3281            break;
3282        case Calibration::TOOL_SIZE_CALIBRATION_AREA:
3283            if (in.toolMajor != 0) {
3284                float diameter = sqrtf(in.toolMajor
3285                        * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias);
3286                toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias;
3287            } else {
3288                toolMajor = 0;
3289            }
3290            toolMinor = toolMajor;
3291            break;
3292        default:
3293            toolMajor = 0;
3294            toolMinor = 0;
3295            break;
3296        }
3297
3298        if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) {
3299            toolMajor /= currentPointerCount;
3300            toolMinor /= currentPointerCount;
3301        }
3302
3303        // Pressure
3304        float rawPressure;
3305        switch (mCalibration.pressureSource) {
3306        case Calibration::PRESSURE_SOURCE_PRESSURE:
3307            rawPressure = in.pressure;
3308            break;
3309        case Calibration::PRESSURE_SOURCE_TOUCH:
3310            rawPressure = in.touchMajor;
3311            break;
3312        default:
3313            rawPressure = 0;
3314        }
3315
3316        float pressure;
3317        switch (mCalibration.pressureCalibration) {
3318        case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3319        case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3320            pressure = rawPressure * mLocked.pressureScale;
3321            break;
3322        default:
3323            pressure = 1;
3324            break;
3325        }
3326
3327        // TouchMajor and TouchMinor
3328        float touchMajor, touchMinor;
3329        switch (mCalibration.touchSizeCalibration) {
3330        case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
3331            touchMajor = in.touchMajor * mLocked.geometricScale;
3332            if (mRawAxes.touchMinor.valid) {
3333                touchMinor = in.touchMinor * mLocked.geometricScale;
3334            } else {
3335                touchMinor = touchMajor;
3336            }
3337            break;
3338        case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
3339            touchMajor = toolMajor * pressure;
3340            touchMinor = toolMinor * pressure;
3341            break;
3342        default:
3343            touchMajor = 0;
3344            touchMinor = 0;
3345            break;
3346        }
3347
3348        if (touchMajor > toolMajor) {
3349            touchMajor = toolMajor;
3350        }
3351        if (touchMinor > toolMinor) {
3352            touchMinor = toolMinor;
3353        }
3354
3355        // Size
3356        float size;
3357        switch (mCalibration.sizeCalibration) {
3358        case Calibration::SIZE_CALIBRATION_NORMALIZED: {
3359            float rawSize = mRawAxes.toolMinor.valid
3360                    ? avg(in.toolMajor, in.toolMinor)
3361                    : in.toolMajor;
3362            size = rawSize * mLocked.sizeScale;
3363            break;
3364        }
3365        default:
3366            size = 0;
3367            break;
3368        }
3369
3370        // Orientation
3371        float orientation;
3372        switch (mCalibration.orientationCalibration) {
3373        case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3374            orientation = in.orientation * mLocked.orientationScale;
3375            break;
3376        case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
3377            int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
3378            int32_t c2 = signExtendNybble(in.orientation & 0x0f);
3379            if (c1 != 0 || c2 != 0) {
3380                orientation = atan2f(c1, c2) * 0.5f;
3381                float scale = 1.0f + hypotf(c1, c2) / 16.0f;
3382                touchMajor *= scale;
3383                touchMinor /= scale;
3384                toolMajor *= scale;
3385                toolMinor /= scale;
3386            } else {
3387                orientation = 0;
3388            }
3389            break;
3390        }
3391        default:
3392            orientation = 0;
3393        }
3394
3395        // Distance
3396        float distance;
3397        switch (mCalibration.distanceCalibration) {
3398        case Calibration::DISTANCE_CALIBRATION_SCALED:
3399            distance = in.distance * mLocked.distanceScale;
3400            break;
3401        default:
3402            distance = 0;
3403        }
3404
3405        // X and Y
3406        // Adjust coords for surface orientation.
3407        float x, y;
3408        switch (mLocked.surfaceOrientation) {
3409        case DISPLAY_ORIENTATION_90:
3410            x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3411            y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3412            orientation -= M_PI_2;
3413            if (orientation < - M_PI_2) {
3414                orientation += M_PI;
3415            }
3416            break;
3417        case DISPLAY_ORIENTATION_180:
3418            x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3419            y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3420            break;
3421        case DISPLAY_ORIENTATION_270:
3422            x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3423            y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3424            orientation += M_PI_2;
3425            if (orientation > M_PI_2) {
3426                orientation -= M_PI;
3427            }
3428            break;
3429        default:
3430            x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3431            y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3432            break;
3433        }
3434
3435        // Write output coords.
3436        PointerCoords& out = mCurrentTouchCoords[i];
3437        out.clear();
3438        out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3439        out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3440        out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
3441        out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
3442        out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
3443        out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
3444        out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
3445        out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
3446        out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
3447        if (distance != 0) {
3448            out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
3449        }
3450
3451        // Write output properties.
3452        PointerProperties& properties = mCurrentTouchProperties[i];
3453        properties.clear();
3454        properties.id = mCurrentTouch.pointers[i].id;
3455        properties.toolType = getTouchToolType(mCurrentTouch.pointers[i].isStylus);
3456    }
3457
3458    // Check edge flags by looking only at the first pointer since the flags are
3459    // global to the event.
3460    *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3461    if (lastPointerCount == 0 && currentPointerCount > 0) {
3462        const PointerData& in = mCurrentTouch.pointers[0];
3463
3464        if (in.x <= mRawAxes.x.minValue) {
3465            *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT,
3466                    mLocked.surfaceOrientation);
3467        } else if (in.x >= mRawAxes.x.maxValue) {
3468            *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT,
3469                    mLocked.surfaceOrientation);
3470        }
3471        if (in.y <= mRawAxes.y.minValue) {
3472            *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP,
3473                    mLocked.surfaceOrientation);
3474        } else if (in.y >= mRawAxes.y.maxValue) {
3475            *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM,
3476                    mLocked.surfaceOrientation);
3477        }
3478    }
3479
3480    *outXPrecision = mLocked.orientedXPrecision;
3481    *outYPrecision = mLocked.orientedYPrecision;
3482}
3483
3484void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
3485        bool isTimeout) {
3486    // Update current gesture coordinates.
3487    bool cancelPreviousGesture, finishPreviousGesture;
3488    bool sendEvents = preparePointerGestures(when,
3489            &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
3490    if (!sendEvents) {
3491        return;
3492    }
3493    if (finishPreviousGesture) {
3494        cancelPreviousGesture = false;
3495    }
3496
3497    // Update the pointer presentation and spots.
3498    if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3499        mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
3500        if (finishPreviousGesture || cancelPreviousGesture) {
3501            mPointerController->clearSpots();
3502        }
3503        mPointerController->setSpots(mPointerGesture.currentGestureCoords,
3504                mPointerGesture.currentGestureIdToIndex,
3505                mPointerGesture.currentGestureIdBits);
3506    } else {
3507        mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
3508    }
3509
3510    // Show or hide the pointer if needed.
3511    switch (mPointerGesture.currentGestureMode) {
3512    case PointerGesture::NEUTRAL:
3513    case PointerGesture::QUIET:
3514        if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3515                && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3516                        || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) {
3517            // Remind the user of where the pointer is after finishing a gesture with spots.
3518            mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
3519        }
3520        break;
3521    case PointerGesture::TAP:
3522    case PointerGesture::TAP_DRAG:
3523    case PointerGesture::BUTTON_CLICK_OR_DRAG:
3524    case PointerGesture::HOVER:
3525    case PointerGesture::PRESS:
3526        // Unfade the pointer when the current gesture manipulates the
3527        // area directly under the pointer.
3528        mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
3529        break;
3530    case PointerGesture::SWIPE:
3531    case PointerGesture::FREEFORM:
3532        // Fade the pointer when the current gesture manipulates a different
3533        // area and there are spots to guide the user experience.
3534        if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3535            mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3536        } else {
3537            mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
3538        }
3539        break;
3540    }
3541
3542    // Send events!
3543    int32_t metaState = getContext()->getGlobalMetaState();
3544    int32_t buttonState = mCurrentTouch.buttonState;
3545
3546    // Update last coordinates of pointers that have moved so that we observe the new
3547    // pointer positions at the same time as other pointers that have just gone up.
3548    bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
3549            || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
3550            || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
3551            || mPointerGesture.currentGestureMode == PointerGesture::PRESS
3552            || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
3553            || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
3554    bool moveNeeded = false;
3555    if (down && !cancelPreviousGesture && !finishPreviousGesture
3556            && !mPointerGesture.lastGestureIdBits.isEmpty()
3557            && !mPointerGesture.currentGestureIdBits.isEmpty()) {
3558        BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
3559                & mPointerGesture.lastGestureIdBits.value);
3560        moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
3561                mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3562                mPointerGesture.lastGestureProperties,
3563                mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3564                movedGestureIdBits);
3565        if (buttonState != mLastTouch.buttonState) {
3566            moveNeeded = true;
3567        }
3568    }
3569
3570    // Send motion events for all pointers that went up or were canceled.
3571    BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
3572    if (!dispatchedGestureIdBits.isEmpty()) {
3573        if (cancelPreviousGesture) {
3574            dispatchMotion(when, policyFlags, mPointerSource,
3575                    AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
3576                    AMOTION_EVENT_EDGE_FLAG_NONE,
3577                    mPointerGesture.lastGestureProperties,
3578                    mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3579                    dispatchedGestureIdBits, -1,
3580                    0, 0, mPointerGesture.downTime);
3581
3582            dispatchedGestureIdBits.clear();
3583        } else {
3584            BitSet32 upGestureIdBits;
3585            if (finishPreviousGesture) {
3586                upGestureIdBits = dispatchedGestureIdBits;
3587            } else {
3588                upGestureIdBits.value = dispatchedGestureIdBits.value
3589                        & ~mPointerGesture.currentGestureIdBits.value;
3590            }
3591            while (!upGestureIdBits.isEmpty()) {
3592                uint32_t id = upGestureIdBits.firstMarkedBit();
3593                upGestureIdBits.clearBit(id);
3594
3595                dispatchMotion(when, policyFlags, mPointerSource,
3596                        AMOTION_EVENT_ACTION_POINTER_UP, 0,
3597                        metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
3598                        mPointerGesture.lastGestureProperties,
3599                        mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3600                        dispatchedGestureIdBits, id,
3601                        0, 0, mPointerGesture.downTime);
3602
3603                dispatchedGestureIdBits.clearBit(id);
3604            }
3605        }
3606    }
3607
3608    // Send motion events for all pointers that moved.
3609    if (moveNeeded) {
3610        dispatchMotion(when, policyFlags, mPointerSource,
3611                AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
3612                mPointerGesture.currentGestureProperties,
3613                mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3614                dispatchedGestureIdBits, -1,
3615                0, 0, mPointerGesture.downTime);
3616    }
3617
3618    // Send motion events for all pointers that went down.
3619    if (down) {
3620        BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
3621                & ~dispatchedGestureIdBits.value);
3622        while (!downGestureIdBits.isEmpty()) {
3623            uint32_t id = downGestureIdBits.firstMarkedBit();
3624            downGestureIdBits.clearBit(id);
3625            dispatchedGestureIdBits.markBit(id);
3626
3627            int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3628            if (dispatchedGestureIdBits.count() == 1) {
3629                // First pointer is going down.  Calculate edge flags and set down time.
3630                uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3631                const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index];
3632                edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3633                        downCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
3634                        downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3635                mPointerGesture.downTime = when;
3636            }
3637
3638            dispatchMotion(when, policyFlags, mPointerSource,
3639                    AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, edgeFlags,
3640                    mPointerGesture.currentGestureProperties,
3641                    mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3642                    dispatchedGestureIdBits, id,
3643                    0, 0, mPointerGesture.downTime);
3644        }
3645    }
3646
3647    // Send motion events for hover.
3648    if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
3649        dispatchMotion(when, policyFlags, mPointerSource,
3650                AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
3651                metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
3652                mPointerGesture.currentGestureProperties,
3653                mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3654                mPointerGesture.currentGestureIdBits, -1,
3655                0, 0, mPointerGesture.downTime);
3656    }
3657
3658    // Update state.
3659    mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
3660    if (!down) {
3661        mPointerGesture.lastGestureIdBits.clear();
3662    } else {
3663        mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
3664        for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
3665            uint32_t id = idBits.firstMarkedBit();
3666            idBits.clearBit(id);
3667            uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3668            mPointerGesture.lastGestureProperties[index].copyFrom(
3669                    mPointerGesture.currentGestureProperties[index]);
3670            mPointerGesture.lastGestureCoords[index].copyFrom(
3671                    mPointerGesture.currentGestureCoords[index]);
3672            mPointerGesture.lastGestureIdToIndex[id] = index;
3673        }
3674    }
3675}
3676
3677bool TouchInputMapper::preparePointerGestures(nsecs_t when,
3678        bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
3679    *outCancelPreviousGesture = false;
3680    *outFinishPreviousGesture = false;
3681
3682    AutoMutex _l(mLock);
3683
3684    // Handle TAP timeout.
3685    if (isTimeout) {
3686#if DEBUG_GESTURES
3687        LOGD("Gestures: Processing timeout");
3688#endif
3689
3690        if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
3691            if (when <= mPointerGesture.tapUpTime + mConfig->pointerGestureTapDragInterval) {
3692                // The tap/drag timeout has not yet expired.
3693                getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
3694                        + mConfig->pointerGestureTapDragInterval);
3695            } else {
3696                // The tap is finished.
3697#if DEBUG_GESTURES
3698                LOGD("Gestures: TAP finished");
3699#endif
3700                *outFinishPreviousGesture = true;
3701
3702                mPointerGesture.activeGestureId = -1;
3703                mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
3704                mPointerGesture.currentGestureIdBits.clear();
3705
3706                mPointerGesture.pointerVelocityControl.reset();
3707                return true;
3708            }
3709        }
3710
3711        // We did not handle this timeout.
3712        return false;
3713    }
3714
3715    // Update the velocity tracker.
3716    {
3717        VelocityTracker::Position positions[MAX_POINTERS];
3718        uint32_t count = 0;
3719        for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) {
3720            uint32_t id = idBits.firstMarkedBit();
3721            idBits.clearBit(id);
3722            uint32_t index = mCurrentTouch.idToIndex[id];
3723            positions[count].x = mCurrentTouch.pointers[index].x
3724                    * mLocked.pointerGestureXMovementScale;
3725            positions[count].y = mCurrentTouch.pointers[index].y
3726                    * mLocked.pointerGestureYMovementScale;
3727        }
3728        mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions);
3729    }
3730
3731    // Pick a new active touch id if needed.
3732    // Choose an arbitrary pointer that just went down, if there is one.
3733    // Otherwise choose an arbitrary remaining pointer.
3734    // This guarantees we always have an active touch id when there is at least one pointer.
3735    // We keep the same active touch id for as long as possible.
3736    bool activeTouchChanged = false;
3737    int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
3738    int32_t activeTouchId = lastActiveTouchId;
3739    if (activeTouchId < 0) {
3740        if (!mCurrentTouch.idBits.isEmpty()) {
3741            activeTouchChanged = true;
3742            activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3743            mPointerGesture.firstTouchTime = when;
3744        }
3745    } else if (!mCurrentTouch.idBits.hasBit(activeTouchId)) {
3746        activeTouchChanged = true;
3747        if (!mCurrentTouch.idBits.isEmpty()) {
3748            activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3749        } else {
3750            activeTouchId = mPointerGesture.activeTouchId = -1;
3751        }
3752    }
3753
3754    // Determine whether we are in quiet time.
3755    bool isQuietTime = false;
3756    if (activeTouchId < 0) {
3757        mPointerGesture.resetQuietTime();
3758    } else {
3759        isQuietTime = when < mPointerGesture.quietTime + mConfig->pointerGestureQuietInterval;
3760        if (!isQuietTime) {
3761            if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
3762                    || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3763                    || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
3764                    && mCurrentTouch.pointerCount < 2) {
3765                // Enter quiet time when exiting swipe or freeform state.
3766                // This is to prevent accidentally entering the hover state and flinging the
3767                // pointer when finishing a swipe and there is still one pointer left onscreen.
3768                isQuietTime = true;
3769            } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
3770                    && mCurrentTouch.pointerCount >= 2
3771                    && !isPointerDown(mCurrentTouch.buttonState)) {
3772                // Enter quiet time when releasing the button and there are still two or more
3773                // fingers down.  This may indicate that one finger was used to press the button
3774                // but it has not gone up yet.
3775                isQuietTime = true;
3776            }
3777            if (isQuietTime) {
3778                mPointerGesture.quietTime = when;
3779            }
3780        }
3781    }
3782
3783    // Switch states based on button and pointer state.
3784    if (isQuietTime) {
3785        // Case 1: Quiet time. (QUIET)
3786#if DEBUG_GESTURES
3787        LOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
3788                + mConfig->pointerGestureQuietInterval - when) * 0.000001f);
3789#endif
3790        if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
3791            *outFinishPreviousGesture = true;
3792        }
3793
3794        mPointerGesture.activeGestureId = -1;
3795        mPointerGesture.currentGestureMode = PointerGesture::QUIET;
3796        mPointerGesture.currentGestureIdBits.clear();
3797
3798        mPointerGesture.pointerVelocityControl.reset();
3799    } else if (isPointerDown(mCurrentTouch.buttonState)) {
3800        // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
3801        // The pointer follows the active touch point.
3802        // Emit DOWN, MOVE, UP events at the pointer location.
3803        //
3804        // Only the active touch matters; other fingers are ignored.  This policy helps
3805        // to handle the case where the user places a second finger on the touch pad
3806        // to apply the necessary force to depress an integrated button below the surface.
3807        // We don't want the second finger to be delivered to applications.
3808        //
3809        // For this to work well, we need to make sure to track the pointer that is really
3810        // active.  If the user first puts one finger down to click then adds another
3811        // finger to drag then the active pointer should switch to the finger that is
3812        // being dragged.
3813#if DEBUG_GESTURES
3814        LOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
3815                "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount);
3816#endif
3817        // Reset state when just starting.
3818        if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
3819            *outFinishPreviousGesture = true;
3820            mPointerGesture.activeGestureId = 0;
3821        }
3822
3823        // Switch pointers if needed.
3824        // Find the fastest pointer and follow it.
3825        if (activeTouchId >= 0 && mCurrentTouch.pointerCount > 1) {
3826            int32_t bestId = -1;
3827            float bestSpeed = mConfig->pointerGestureDragMinSwitchSpeed;
3828            for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3829                uint32_t id = mCurrentTouch.pointers[i].id;
3830                float vx, vy;
3831                if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
3832                    float speed = hypotf(vx, vy);
3833                    if (speed > bestSpeed) {
3834                        bestId = id;
3835                        bestSpeed = speed;
3836                    }
3837                }
3838            }
3839            if (bestId >= 0 && bestId != activeTouchId) {
3840                mPointerGesture.activeTouchId = activeTouchId = bestId;
3841                activeTouchChanged = true;
3842#if DEBUG_GESTURES
3843                LOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
3844                        "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
3845#endif
3846            }
3847        }
3848
3849        if (activeTouchId >= 0 && mLastTouch.idBits.hasBit(activeTouchId)) {
3850            const PointerData& currentPointer =
3851                    mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3852            const PointerData& lastPointer =
3853                    mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3854            float deltaX = (currentPointer.x - lastPointer.x)
3855                    * mLocked.pointerGestureXMovementScale;
3856            float deltaY = (currentPointer.y - lastPointer.y)
3857                    * mLocked.pointerGestureYMovementScale;
3858
3859            mPointerGesture.pointerVelocityControl.move(when, &deltaX, &deltaY);
3860
3861            // Move the pointer using a relative motion.
3862            // When using spots, the click will occur at the position of the anchor
3863            // spot and all other spots will move there.
3864            mPointerController->move(deltaX, deltaY);
3865        } else {
3866            mPointerGesture.pointerVelocityControl.reset();
3867        }
3868
3869        float x, y;
3870        mPointerController->getPosition(&x, &y);
3871
3872        mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
3873        mPointerGesture.currentGestureIdBits.clear();
3874        mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3875        mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3876        mPointerGesture.currentGestureProperties[0].clear();
3877        mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3878        mPointerGesture.currentGestureProperties[0].toolType =
3879                AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
3880        mPointerGesture.currentGestureCoords[0].clear();
3881        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3882        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3883        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3884    } else if (mCurrentTouch.pointerCount == 0) {
3885        // Case 3. No fingers down and button is not pressed. (NEUTRAL)
3886        if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
3887            *outFinishPreviousGesture = true;
3888        }
3889
3890        // Watch for taps coming out of HOVER or TAP_DRAG mode.
3891        // Checking for taps after TAP_DRAG allows us to detect double-taps.
3892        bool tapped = false;
3893        if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
3894                || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
3895                && mLastTouch.pointerCount == 1) {
3896            if (when <= mPointerGesture.tapDownTime + mConfig->pointerGestureTapInterval) {
3897                float x, y;
3898                mPointerController->getPosition(&x, &y);
3899                if (fabs(x - mPointerGesture.tapX) <= mConfig->pointerGestureTapSlop
3900                        && fabs(y - mPointerGesture.tapY) <= mConfig->pointerGestureTapSlop) {
3901#if DEBUG_GESTURES
3902                    LOGD("Gestures: TAP");
3903#endif
3904
3905                    mPointerGesture.tapUpTime = when;
3906                    getContext()->requestTimeoutAtTime(when
3907                            + mConfig->pointerGestureTapDragInterval);
3908
3909                    mPointerGesture.activeGestureId = 0;
3910                    mPointerGesture.currentGestureMode = PointerGesture::TAP;
3911                    mPointerGesture.currentGestureIdBits.clear();
3912                    mPointerGesture.currentGestureIdBits.markBit(
3913                            mPointerGesture.activeGestureId);
3914                    mPointerGesture.currentGestureIdToIndex[
3915                            mPointerGesture.activeGestureId] = 0;
3916                    mPointerGesture.currentGestureProperties[0].clear();
3917                    mPointerGesture.currentGestureProperties[0].id =
3918                            mPointerGesture.activeGestureId;
3919                    mPointerGesture.currentGestureProperties[0].toolType =
3920                            AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
3921                    mPointerGesture.currentGestureCoords[0].clear();
3922                    mPointerGesture.currentGestureCoords[0].setAxisValue(
3923                            AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
3924                    mPointerGesture.currentGestureCoords[0].setAxisValue(
3925                            AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
3926                    mPointerGesture.currentGestureCoords[0].setAxisValue(
3927                            AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3928
3929                    tapped = true;
3930                } else {
3931#if DEBUG_GESTURES
3932                    LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3933                            x - mPointerGesture.tapX,
3934                            y - mPointerGesture.tapY);
3935#endif
3936                }
3937            } else {
3938#if DEBUG_GESTURES
3939                LOGD("Gestures: Not a TAP, %0.3fms since down",
3940                        (when - mPointerGesture.tapDownTime) * 0.000001f);
3941#endif
3942            }
3943        }
3944
3945        mPointerGesture.pointerVelocityControl.reset();
3946
3947        if (!tapped) {
3948#if DEBUG_GESTURES
3949            LOGD("Gestures: NEUTRAL");
3950#endif
3951            mPointerGesture.activeGestureId = -1;
3952            mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
3953            mPointerGesture.currentGestureIdBits.clear();
3954        }
3955    } else if (mCurrentTouch.pointerCount == 1) {
3956        // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3957        // The pointer follows the active touch point.
3958        // When in HOVER, emit HOVER_MOVE events at the pointer location.
3959        // When in TAP_DRAG, emit MOVE events at the pointer location.
3960        LOG_ASSERT(activeTouchId >= 0);
3961
3962        mPointerGesture.currentGestureMode = PointerGesture::HOVER;
3963        if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
3964            if (when <= mPointerGesture.tapUpTime + mConfig->pointerGestureTapDragInterval) {
3965                float x, y;
3966                mPointerController->getPosition(&x, &y);
3967                if (fabs(x - mPointerGesture.tapX) <= mConfig->pointerGestureTapSlop
3968                        && fabs(y - mPointerGesture.tapY) <= mConfig->pointerGestureTapSlop) {
3969                    mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
3970                } else {
3971#if DEBUG_GESTURES
3972                    LOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3973                            x - mPointerGesture.tapX,
3974                            y - mPointerGesture.tapY);
3975#endif
3976                }
3977            } else {
3978#if DEBUG_GESTURES
3979                LOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
3980                        (when - mPointerGesture.tapUpTime) * 0.000001f);
3981#endif
3982            }
3983        } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
3984            mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
3985        }
3986
3987        if (mLastTouch.idBits.hasBit(activeTouchId)) {
3988            const PointerData& currentPointer =
3989                    mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3990            const PointerData& lastPointer =
3991                    mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3992            float deltaX = (currentPointer.x - lastPointer.x)
3993                    * mLocked.pointerGestureXMovementScale;
3994            float deltaY = (currentPointer.y - lastPointer.y)
3995                    * mLocked.pointerGestureYMovementScale;
3996
3997            mPointerGesture.pointerVelocityControl.move(when, &deltaX, &deltaY);
3998
3999            // Move the pointer using a relative motion.
4000            // When using spots, the hover or drag will occur at the position of the anchor spot.
4001            mPointerController->move(deltaX, deltaY);
4002        } else {
4003            mPointerGesture.pointerVelocityControl.reset();
4004        }
4005
4006        bool down;
4007        if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
4008#if DEBUG_GESTURES
4009            LOGD("Gestures: TAP_DRAG");
4010#endif
4011            down = true;
4012        } else {
4013#if DEBUG_GESTURES
4014            LOGD("Gestures: HOVER");
4015#endif
4016            if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
4017                *outFinishPreviousGesture = true;
4018            }
4019            mPointerGesture.activeGestureId = 0;
4020            down = false;
4021        }
4022
4023        float x, y;
4024        mPointerController->getPosition(&x, &y);
4025
4026        mPointerGesture.currentGestureIdBits.clear();
4027        mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4028        mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
4029        mPointerGesture.currentGestureProperties[0].clear();
4030        mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
4031        mPointerGesture.currentGestureProperties[0].toolType =
4032                AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
4033        mPointerGesture.currentGestureCoords[0].clear();
4034        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4035        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4036        mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
4037                down ? 1.0f : 0.0f);
4038
4039        if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
4040            mPointerGesture.resetTap();
4041            mPointerGesture.tapDownTime = when;
4042            mPointerGesture.tapX = x;
4043            mPointerGesture.tapY = y;
4044        }
4045    } else {
4046        // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
4047        // We need to provide feedback for each finger that goes down so we cannot wait
4048        // for the fingers to move before deciding what to do.
4049        //
4050        // The ambiguous case is deciding what to do when there are two fingers down but they
4051        // have not moved enough to determine whether they are part of a drag or part of a
4052        // freeform gesture, or just a press or long-press at the pointer location.
4053        //
4054        // When there are two fingers we start with the PRESS hypothesis and we generate a
4055        // down at the pointer location.
4056        //
4057        // When the two fingers move enough or when additional fingers are added, we make
4058        // a decision to transition into SWIPE or FREEFORM mode accordingly.
4059        LOG_ASSERT(activeTouchId >= 0);
4060
4061        bool settled = when >= mPointerGesture.firstTouchTime
4062                + mConfig->pointerGestureMultitouchSettleInterval;
4063        if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
4064                && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
4065                && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
4066            *outFinishPreviousGesture = true;
4067        } else if (!settled && mCurrentTouch.pointerCount > mLastTouch.pointerCount) {
4068            // Additional pointers have gone down but not yet settled.
4069            // Reset the gesture.
4070#if DEBUG_GESTURES
4071            LOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
4072                    "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
4073                            + mConfig->pointerGestureMultitouchSettleInterval - when)
4074                            * 0.000001f);
4075#endif
4076            *outCancelPreviousGesture = true;
4077        } else {
4078            // Continue previous gesture.
4079            mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
4080        }
4081
4082        if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
4083            mPointerGesture.currentGestureMode = PointerGesture::PRESS;
4084            mPointerGesture.activeGestureId = 0;
4085            mPointerGesture.referenceIdBits.clear();
4086            mPointerGesture.pointerVelocityControl.reset();
4087
4088            // Use the centroid and pointer location as the reference points for the gesture.
4089#if DEBUG_GESTURES
4090            LOGD("Gestures: Using centroid as reference for MULTITOUCH, "
4091                    "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
4092                            + mConfig->pointerGestureMultitouchSettleInterval - when)
4093                            * 0.000001f);
4094#endif
4095            mCurrentTouch.getCentroid(&mPointerGesture.referenceTouchX,
4096                    &mPointerGesture.referenceTouchY);
4097            mPointerController->getPosition(&mPointerGesture.referenceGestureX,
4098                    &mPointerGesture.referenceGestureY);
4099        }
4100
4101        // Clear the reference deltas for fingers not yet included in the reference calculation.
4102        for (BitSet32 idBits(mCurrentTouch.idBits.value & ~mPointerGesture.referenceIdBits.value);
4103                !idBits.isEmpty(); ) {
4104            uint32_t id = idBits.firstMarkedBit();
4105            idBits.clearBit(id);
4106
4107            mPointerGesture.referenceDeltas[id].dx = 0;
4108            mPointerGesture.referenceDeltas[id].dy = 0;
4109        }
4110        mPointerGesture.referenceIdBits = mCurrentTouch.idBits;
4111
4112        // Add delta for all fingers and calculate a common movement delta.
4113        float commonDeltaX = 0, commonDeltaY = 0;
4114        BitSet32 commonIdBits(mLastTouch.idBits.value & mCurrentTouch.idBits.value);
4115        for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
4116            bool first = (idBits == commonIdBits);
4117            uint32_t id = idBits.firstMarkedBit();
4118            idBits.clearBit(id);
4119
4120            const PointerData& cpd = mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]];
4121            const PointerData& lpd = mLastTouch.pointers[mLastTouch.idToIndex[id]];
4122            PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
4123            delta.dx += cpd.x - lpd.x;
4124            delta.dy += cpd.y - lpd.y;
4125
4126            if (first) {
4127                commonDeltaX = delta.dx;
4128                commonDeltaY = delta.dy;
4129            } else {
4130                commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
4131                commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
4132            }
4133        }
4134
4135        // Consider transitions from PRESS to SWIPE or MULTITOUCH.
4136        if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
4137            float dist[MAX_POINTER_ID + 1];
4138            int32_t distOverThreshold = 0;
4139            for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
4140                uint32_t id = idBits.firstMarkedBit();
4141                idBits.clearBit(id);
4142
4143                PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
4144                dist[id] = hypotf(delta.dx * mLocked.pointerGestureXZoomScale,
4145                        delta.dy * mLocked.pointerGestureYZoomScale);
4146                if (dist[id] > mConfig->pointerGestureMultitouchMinDistance) {
4147                    distOverThreshold += 1;
4148                }
4149            }
4150
4151            // Only transition when at least two pointers have moved further than
4152            // the minimum distance threshold.
4153            if (distOverThreshold >= 2) {
4154                float d;
4155                if (mCurrentTouch.pointerCount > 2) {
4156                    // There are more than two pointers, switch to FREEFORM.
4157#if DEBUG_GESTURES
4158                    LOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
4159                            mCurrentTouch.pointerCount);
4160#endif
4161                    *outCancelPreviousGesture = true;
4162                    mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
4163                } else if (((d = distance(
4164                        mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y,
4165                        mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y))
4166                                > mLocked.pointerGestureMaxSwipeWidth)) {
4167                    // There are two pointers but they are too far apart for a SWIPE,
4168                    // switch to FREEFORM.
4169#if DEBUG_GESTURES
4170                    LOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
4171                            d, mLocked.pointerGestureMaxSwipeWidth);
4172#endif
4173                    *outCancelPreviousGesture = true;
4174                    mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
4175                } else {
4176                    // There are two pointers.  Wait for both pointers to start moving
4177                    // before deciding whether this is a SWIPE or FREEFORM gesture.
4178                    uint32_t id1 = mCurrentTouch.pointers[0].id;
4179                    uint32_t id2 = mCurrentTouch.pointers[1].id;
4180                    float dist1 = dist[id1];
4181                    float dist2 = dist[id2];
4182                    if (dist1 >= mConfig->pointerGestureMultitouchMinDistance
4183                            && dist2 >= mConfig->pointerGestureMultitouchMinDistance) {
4184                        // Calculate the dot product of the displacement vectors.
4185                        // When the vectors are oriented in approximately the same direction,
4186                        // the angle betweeen them is near zero and the cosine of the angle
4187                        // approches 1.0.  Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
4188                        PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
4189                        PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
4190                        float dx1 = delta1.dx * mLocked.pointerGestureXZoomScale;
4191                        float dy1 = delta1.dy * mLocked.pointerGestureYZoomScale;
4192                        float dx2 = delta2.dx * mLocked.pointerGestureXZoomScale;
4193                        float dy2 = delta2.dy * mLocked.pointerGestureYZoomScale;
4194                        float dot = dx1 * dx2 + dy1 * dy2;
4195                        float cosine = dot / (dist1 * dist2); // denominator always > 0
4196                        if (cosine >= mConfig->pointerGestureSwipeTransitionAngleCosine) {
4197                            // Pointers are moving in the same direction.  Switch to SWIPE.
4198#if DEBUG_GESTURES
4199                            LOGD("Gestures: PRESS transitioned to SWIPE, "
4200                                    "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
4201                                    "cosine %0.3f >= %0.3f",
4202                                    dist1, mConfig->pointerGestureMultitouchMinDistance,
4203                                    dist2, mConfig->pointerGestureMultitouchMinDistance,
4204                                    cosine, mConfig->pointerGestureSwipeTransitionAngleCosine);
4205#endif
4206                            mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
4207                        } else {
4208                            // Pointers are moving in different directions.  Switch to FREEFORM.
4209#if DEBUG_GESTURES
4210                            LOGD("Gestures: PRESS transitioned to FREEFORM, "
4211                                    "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
4212                                    "cosine %0.3f < %0.3f",
4213                                    dist1, mConfig->pointerGestureMultitouchMinDistance,
4214                                    dist2, mConfig->pointerGestureMultitouchMinDistance,
4215                                    cosine, mConfig->pointerGestureSwipeTransitionAngleCosine);
4216#endif
4217                            *outCancelPreviousGesture = true;
4218                            mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
4219                        }
4220                    }
4221                }
4222            }
4223        } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
4224            // Switch from SWIPE to FREEFORM if additional pointers go down.
4225            // Cancel previous gesture.
4226            if (mCurrentTouch.pointerCount > 2) {
4227#if DEBUG_GESTURES
4228                LOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
4229                        mCurrentTouch.pointerCount);
4230#endif
4231                *outCancelPreviousGesture = true;
4232                mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
4233            }
4234        }
4235
4236        // Move the reference points based on the overall group motion of the fingers
4237        // except in PRESS mode while waiting for a transition to occur.
4238        if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
4239                && (commonDeltaX || commonDeltaY)) {
4240            for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
4241                uint32_t id = idBits.firstMarkedBit();
4242                idBits.clearBit(id);
4243
4244                PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
4245                delta.dx = 0;
4246                delta.dy = 0;
4247            }
4248
4249            mPointerGesture.referenceTouchX += commonDeltaX;
4250            mPointerGesture.referenceTouchY += commonDeltaY;
4251
4252            commonDeltaX *= mLocked.pointerGestureXMovementScale;
4253            commonDeltaY *= mLocked.pointerGestureYMovementScale;
4254            mPointerGesture.pointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
4255
4256            mPointerGesture.referenceGestureX += commonDeltaX;
4257            mPointerGesture.referenceGestureY += commonDeltaY;
4258        }
4259
4260        // Report gestures.
4261        if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
4262            // PRESS mode.
4263#if DEBUG_GESTURES
4264            LOGD("Gestures: PRESS activeTouchId=%d,"
4265                    "activeGestureId=%d, currentTouchPointerCount=%d",
4266                    activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
4267#endif
4268            LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
4269
4270            mPointerGesture.currentGestureIdBits.clear();
4271            mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4272            mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
4273            mPointerGesture.currentGestureProperties[0].clear();
4274            mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
4275            mPointerGesture.currentGestureProperties[0].toolType =
4276                    AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
4277            mPointerGesture.currentGestureCoords[0].clear();
4278            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4279                    mPointerGesture.referenceGestureX);
4280            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
4281                    mPointerGesture.referenceGestureY);
4282            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4283        } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
4284            // SWIPE mode.
4285#if DEBUG_GESTURES
4286            LOGD("Gestures: SWIPE activeTouchId=%d,"
4287                    "activeGestureId=%d, currentTouchPointerCount=%d",
4288                    activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
4289#endif
4290            LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
4291
4292            mPointerGesture.currentGestureIdBits.clear();
4293            mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4294            mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
4295            mPointerGesture.currentGestureProperties[0].clear();
4296            mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
4297            mPointerGesture.currentGestureProperties[0].toolType =
4298                    AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
4299            mPointerGesture.currentGestureCoords[0].clear();
4300            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4301                    mPointerGesture.referenceGestureX);
4302            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
4303                    mPointerGesture.referenceGestureY);
4304            mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4305        } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
4306            // FREEFORM mode.
4307#if DEBUG_GESTURES
4308            LOGD("Gestures: FREEFORM activeTouchId=%d,"
4309                    "activeGestureId=%d, currentTouchPointerCount=%d",
4310                    activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
4311#endif
4312            LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
4313
4314            mPointerGesture.currentGestureIdBits.clear();
4315
4316            BitSet32 mappedTouchIdBits;
4317            BitSet32 usedGestureIdBits;
4318            if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
4319                // Initially, assign the active gesture id to the active touch point
4320                // if there is one.  No other touch id bits are mapped yet.
4321                if (!*outCancelPreviousGesture) {
4322                    mappedTouchIdBits.markBit(activeTouchId);
4323                    usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
4324                    mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
4325                            mPointerGesture.activeGestureId;
4326                } else {
4327                    mPointerGesture.activeGestureId = -1;
4328                }
4329            } else {
4330                // Otherwise, assume we mapped all touches from the previous frame.
4331                // Reuse all mappings that are still applicable.
4332                mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value;
4333                usedGestureIdBits = mPointerGesture.lastGestureIdBits;
4334
4335                // Check whether we need to choose a new active gesture id because the
4336                // current went went up.
4337                for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value);
4338                        !upTouchIdBits.isEmpty(); ) {
4339                    uint32_t upTouchId = upTouchIdBits.firstMarkedBit();
4340                    upTouchIdBits.clearBit(upTouchId);
4341                    uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
4342                    if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
4343                        mPointerGesture.activeGestureId = -1;
4344                        break;
4345                    }
4346                }
4347            }
4348
4349#if DEBUG_GESTURES
4350            LOGD("Gestures: FREEFORM follow up "
4351                    "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
4352                    "activeGestureId=%d",
4353                    mappedTouchIdBits.value, usedGestureIdBits.value,
4354                    mPointerGesture.activeGestureId);
4355#endif
4356
4357            for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
4358                uint32_t touchId = mCurrentTouch.pointers[i].id;
4359                uint32_t gestureId;
4360                if (!mappedTouchIdBits.hasBit(touchId)) {
4361                    gestureId = usedGestureIdBits.firstUnmarkedBit();
4362                    usedGestureIdBits.markBit(gestureId);
4363                    mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
4364#if DEBUG_GESTURES
4365                    LOGD("Gestures: FREEFORM "
4366                            "new mapping for touch id %d -> gesture id %d",
4367                            touchId, gestureId);
4368#endif
4369                } else {
4370                    gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
4371#if DEBUG_GESTURES
4372                    LOGD("Gestures: FREEFORM "
4373                            "existing mapping for touch id %d -> gesture id %d",
4374                            touchId, gestureId);
4375#endif
4376                }
4377                mPointerGesture.currentGestureIdBits.markBit(gestureId);
4378                mPointerGesture.currentGestureIdToIndex[gestureId] = i;
4379
4380                float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4381                        * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4382                float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4383                        * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
4384
4385                mPointerGesture.currentGestureProperties[i].clear();
4386                mPointerGesture.currentGestureProperties[i].id = gestureId;
4387                mPointerGesture.currentGestureProperties[i].toolType =
4388                        AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
4389                mPointerGesture.currentGestureCoords[i].clear();
4390                mPointerGesture.currentGestureCoords[i].setAxisValue(
4391                        AMOTION_EVENT_AXIS_X, x);
4392                mPointerGesture.currentGestureCoords[i].setAxisValue(
4393                        AMOTION_EVENT_AXIS_Y, y);
4394                mPointerGesture.currentGestureCoords[i].setAxisValue(
4395                        AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4396            }
4397
4398            if (mPointerGesture.activeGestureId < 0) {
4399                mPointerGesture.activeGestureId =
4400                        mPointerGesture.currentGestureIdBits.firstMarkedBit();
4401#if DEBUG_GESTURES
4402                LOGD("Gestures: FREEFORM new "
4403                        "activeGestureId=%d", mPointerGesture.activeGestureId);
4404#endif
4405            }
4406        }
4407    }
4408
4409    mPointerController->setButtonState(mCurrentTouch.buttonState);
4410
4411#if DEBUG_GESTURES
4412    LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
4413            "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
4414            "lastGestureMode=%d, lastGestureIdBits=0x%08x",
4415            toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
4416            mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
4417            mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
4418    for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
4419        uint32_t id = idBits.firstMarkedBit();
4420        idBits.clearBit(id);
4421        uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
4422        const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
4423        const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
4424        LOGD("  currentGesture[%d]: index=%d, toolType=%d, "
4425                "x=%0.3f, y=%0.3f, pressure=%0.3f",
4426                id, index, properties.toolType,
4427                coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4428                coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4429                coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4430    }
4431    for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
4432        uint32_t id = idBits.firstMarkedBit();
4433        idBits.clearBit(id);
4434        uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
4435        const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
4436        const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
4437        LOGD("  lastGesture[%d]: index=%d, toolType=%d, "
4438                "x=%0.3f, y=%0.3f, pressure=%0.3f",
4439                id, index, properties.toolType,
4440                coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4441                coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4442                coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4443    }
4444#endif
4445    return true;
4446}
4447
4448void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
4449        int32_t action, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4450        const PointerProperties* properties, const PointerCoords* coords,
4451        const uint32_t* idToIndex, BitSet32 idBits,
4452        int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
4453    PointerCoords pointerCoords[MAX_POINTERS];
4454    PointerProperties pointerProperties[MAX_POINTERS];
4455    uint32_t pointerCount = 0;
4456    while (!idBits.isEmpty()) {
4457        uint32_t id = idBits.firstMarkedBit();
4458        idBits.clearBit(id);
4459        uint32_t index = idToIndex[id];
4460        pointerProperties[pointerCount].copyFrom(properties[index]);
4461        pointerCoords[pointerCount].copyFrom(coords[index]);
4462
4463        if (changedId >= 0 && id == uint32_t(changedId)) {
4464            action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
4465        }
4466
4467        pointerCount += 1;
4468    }
4469
4470    LOG_ASSERT(pointerCount != 0);
4471
4472    if (changedId >= 0 && pointerCount == 1) {
4473        // Replace initial down and final up action.
4474        // We can compare the action without masking off the changed pointer index
4475        // because we know the index is 0.
4476        if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
4477            action = AMOTION_EVENT_ACTION_DOWN;
4478        } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
4479            action = AMOTION_EVENT_ACTION_UP;
4480        } else {
4481            // Can't happen.
4482            LOG_ASSERT(false);
4483        }
4484    }
4485
4486    getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags,
4487            action, flags, metaState, buttonState, edgeFlags,
4488            pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime);
4489}
4490
4491bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
4492        const PointerCoords* inCoords, const uint32_t* inIdToIndex,
4493        PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
4494        BitSet32 idBits) const {
4495    bool changed = false;
4496    while (!idBits.isEmpty()) {
4497        uint32_t id = idBits.firstMarkedBit();
4498        idBits.clearBit(id);
4499
4500        uint32_t inIndex = inIdToIndex[id];
4501        uint32_t outIndex = outIdToIndex[id];
4502
4503        const PointerProperties& curInProperties = inProperties[inIndex];
4504        const PointerCoords& curInCoords = inCoords[inIndex];
4505        PointerProperties& curOutProperties = outProperties[outIndex];
4506        PointerCoords& curOutCoords = outCoords[outIndex];
4507
4508        if (curInProperties != curOutProperties) {
4509            curOutProperties.copyFrom(curInProperties);
4510            changed = true;
4511        }
4512
4513        if (curInCoords != curOutCoords) {
4514            curOutCoords.copyFrom(curInCoords);
4515            changed = true;
4516        }
4517    }
4518    return changed;
4519}
4520
4521void TouchInputMapper::fadePointer() {
4522    { // acquire lock
4523        AutoMutex _l(mLock);
4524        if (mPointerController != NULL) {
4525            mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4526        }
4527    } // release lock
4528}
4529
4530int32_t TouchInputMapper::getTouchToolType(bool isStylus) const {
4531    if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
4532        return isStylus ? AMOTION_EVENT_TOOL_TYPE_STYLUS : AMOTION_EVENT_TOOL_TYPE_FINGER;
4533    } else {
4534        return isStylus ? AMOTION_EVENT_TOOL_TYPE_INDIRECT_STYLUS
4535                : AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
4536    }
4537}
4538
4539bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) {
4540    return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue
4541            && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue;
4542}
4543
4544const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked(
4545        int32_t x, int32_t y) {
4546    size_t numVirtualKeys = mLocked.virtualKeys.size();
4547    for (size_t i = 0; i < numVirtualKeys; i++) {
4548        const VirtualKey& virtualKey = mLocked.virtualKeys[i];
4549
4550#if DEBUG_VIRTUAL_KEYS
4551        LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
4552                "left=%d, top=%d, right=%d, bottom=%d",
4553                x, y,
4554                virtualKey.keyCode, virtualKey.scanCode,
4555                virtualKey.hitLeft, virtualKey.hitTop,
4556                virtualKey.hitRight, virtualKey.hitBottom);
4557#endif
4558
4559        if (virtualKey.isHit(x, y)) {
4560            return & virtualKey;
4561        }
4562    }
4563
4564    return NULL;
4565}
4566
4567void TouchInputMapper::calculatePointerIds() {
4568    uint32_t currentPointerCount = mCurrentTouch.pointerCount;
4569    uint32_t lastPointerCount = mLastTouch.pointerCount;
4570
4571    if (currentPointerCount == 0) {
4572        // No pointers to assign.
4573        mCurrentTouch.idBits.clear();
4574    } else if (lastPointerCount == 0) {
4575        // All pointers are new.
4576        mCurrentTouch.idBits.clear();
4577        for (uint32_t i = 0; i < currentPointerCount; i++) {
4578            mCurrentTouch.pointers[i].id = i;
4579            mCurrentTouch.idToIndex[i] = i;
4580            mCurrentTouch.idBits.markBit(i);
4581        }
4582    } else if (currentPointerCount == 1 && lastPointerCount == 1) {
4583        // Only one pointer and no change in count so it must have the same id as before.
4584        uint32_t id = mLastTouch.pointers[0].id;
4585        mCurrentTouch.pointers[0].id = id;
4586        mCurrentTouch.idToIndex[id] = 0;
4587        mCurrentTouch.idBits.value = BitSet32::valueForBit(id);
4588    } else {
4589        // General case.
4590        // We build a heap of squared euclidean distances between current and last pointers
4591        // associated with the current and last pointer indices.  Then, we find the best
4592        // match (by distance) for each current pointer.
4593        PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
4594
4595        uint32_t heapSize = 0;
4596        for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
4597                currentPointerIndex++) {
4598            for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
4599                    lastPointerIndex++) {
4600                int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x
4601                        - mLastTouch.pointers[lastPointerIndex].x;
4602                int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y
4603                        - mLastTouch.pointers[lastPointerIndex].y;
4604
4605                uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4606
4607                // Insert new element into the heap (sift up).
4608                heap[heapSize].currentPointerIndex = currentPointerIndex;
4609                heap[heapSize].lastPointerIndex = lastPointerIndex;
4610                heap[heapSize].distance = distance;
4611                heapSize += 1;
4612            }
4613        }
4614
4615        // Heapify
4616        for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
4617            startIndex -= 1;
4618            for (uint32_t parentIndex = startIndex; ;) {
4619                uint32_t childIndex = parentIndex * 2 + 1;
4620                if (childIndex >= heapSize) {
4621                    break;
4622                }
4623
4624                if (childIndex + 1 < heapSize
4625                        && heap[childIndex + 1].distance < heap[childIndex].distance) {
4626                    childIndex += 1;
4627                }
4628
4629                if (heap[parentIndex].distance <= heap[childIndex].distance) {
4630                    break;
4631                }
4632
4633                swap(heap[parentIndex], heap[childIndex]);
4634                parentIndex = childIndex;
4635            }
4636        }
4637
4638#if DEBUG_POINTER_ASSIGNMENT
4639        LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize);
4640        for (size_t i = 0; i < heapSize; i++) {
4641            LOGD("  heap[%d]: cur=%d, last=%d, distance=%lld",
4642                    i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4643                    heap[i].distance);
4644        }
4645#endif
4646
4647        // Pull matches out by increasing order of distance.
4648        // To avoid reassigning pointers that have already been matched, the loop keeps track
4649        // of which last and current pointers have been matched using the matchedXXXBits variables.
4650        // It also tracks the used pointer id bits.
4651        BitSet32 matchedLastBits(0);
4652        BitSet32 matchedCurrentBits(0);
4653        BitSet32 usedIdBits(0);
4654        bool first = true;
4655        for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) {
4656            for (;;) {
4657                if (first) {
4658                    // The first time through the loop, we just consume the root element of
4659                    // the heap (the one with smallest distance).
4660                    first = false;
4661                } else {
4662                    // Previous iterations consumed the root element of the heap.
4663                    // Pop root element off of the heap (sift down).
4664                    heapSize -= 1;
4665                    LOG_ASSERT(heapSize > 0);
4666
4667                    // Sift down.
4668                    heap[0] = heap[heapSize];
4669                    for (uint32_t parentIndex = 0; ;) {
4670                        uint32_t childIndex = parentIndex * 2 + 1;
4671                        if (childIndex >= heapSize) {
4672                            break;
4673                        }
4674
4675                        if (childIndex + 1 < heapSize
4676                                && heap[childIndex + 1].distance < heap[childIndex].distance) {
4677                            childIndex += 1;
4678                        }
4679
4680                        if (heap[parentIndex].distance <= heap[childIndex].distance) {
4681                            break;
4682                        }
4683
4684                        swap(heap[parentIndex], heap[childIndex]);
4685                        parentIndex = childIndex;
4686                    }
4687
4688#if DEBUG_POINTER_ASSIGNMENT
4689                    LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize);
4690                    for (size_t i = 0; i < heapSize; i++) {
4691                        LOGD("  heap[%d]: cur=%d, last=%d, distance=%lld",
4692                                i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4693                                heap[i].distance);
4694                    }
4695#endif
4696                }
4697
4698                uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4699                if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4700
4701                uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4702                if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4703
4704                matchedCurrentBits.markBit(currentPointerIndex);
4705                matchedLastBits.markBit(lastPointerIndex);
4706
4707                uint32_t id = mLastTouch.pointers[lastPointerIndex].id;
4708                mCurrentTouch.pointers[currentPointerIndex].id = id;
4709                mCurrentTouch.idToIndex[id] = currentPointerIndex;
4710                usedIdBits.markBit(id);
4711
4712#if DEBUG_POINTER_ASSIGNMENT
4713                LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
4714                        lastPointerIndex, currentPointerIndex, id, heap[0].distance);
4715#endif
4716                break;
4717            }
4718        }
4719
4720        // Assign fresh ids to new pointers.
4721        if (currentPointerCount > lastPointerCount) {
4722            for (uint32_t i = currentPointerCount - lastPointerCount; ;) {
4723                uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit();
4724                uint32_t id = usedIdBits.firstUnmarkedBit();
4725
4726                mCurrentTouch.pointers[currentPointerIndex].id = id;
4727                mCurrentTouch.idToIndex[id] = currentPointerIndex;
4728                usedIdBits.markBit(id);
4729
4730#if DEBUG_POINTER_ASSIGNMENT
4731                LOGD("calculatePointerIds - assigned: cur=%d, id=%d",
4732                        currentPointerIndex, id);
4733#endif
4734
4735                if (--i == 0) break; // done
4736                matchedCurrentBits.markBit(currentPointerIndex);
4737            }
4738        }
4739
4740        // Fix id bits.
4741        mCurrentTouch.idBits = usedIdBits;
4742    }
4743}
4744
4745/* Special hack for devices that have bad screen data: if one of the
4746 * points has moved more than a screen height from the last position,
4747 * then drop it. */
4748bool TouchInputMapper::applyBadTouchFilter() {
4749    uint32_t pointerCount = mCurrentTouch.pointerCount;
4750
4751    // Nothing to do if there are no points.
4752    if (pointerCount == 0) {
4753        return false;
4754    }
4755
4756    // Don't do anything if a finger is going down or up.  We run
4757    // here before assigning pointer IDs, so there isn't a good
4758    // way to do per-finger matching.
4759    if (pointerCount != mLastTouch.pointerCount) {
4760        return false;
4761    }
4762
4763    // We consider a single movement across more than a 7/16 of
4764    // the long size of the screen to be bad.  This was a magic value
4765    // determined by looking at the maximum distance it is feasible
4766    // to actually move in one sample.
4767    int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16;
4768
4769    // XXX The original code in InputDevice.java included commented out
4770    //     code for testing the X axis.  Note that when we drop a point
4771    //     we don't actually restore the old X either.  Strange.
4772    //     The old code also tries to track when bad points were previously
4773    //     detected but it turns out that due to the placement of a "break"
4774    //     at the end of the loop, we never set mDroppedBadPoint to true
4775    //     so it is effectively dead code.
4776    // Need to figure out if the old code is busted or just overcomplicated
4777    // but working as intended.
4778
4779    // Look through all new points and see if any are farther than
4780    // acceptable from all previous points.
4781    for (uint32_t i = pointerCount; i-- > 0; ) {
4782        int32_t y = mCurrentTouch.pointers[i].y;
4783        int32_t closestY = INT_MAX;
4784        int32_t closestDeltaY = 0;
4785
4786#if DEBUG_HACKS
4787        LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y);
4788#endif
4789
4790        for (uint32_t j = pointerCount; j-- > 0; ) {
4791            int32_t lastY = mLastTouch.pointers[j].y;
4792            int32_t deltaY = abs(y - lastY);
4793
4794#if DEBUG_HACKS
4795            LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d",
4796                    j, lastY, deltaY);
4797#endif
4798
4799            if (deltaY < maxDeltaY) {
4800                goto SkipSufficientlyClosePoint;
4801            }
4802            if (deltaY < closestDeltaY) {
4803                closestDeltaY = deltaY;
4804                closestY = lastY;
4805            }
4806        }
4807
4808        // Must not have found a close enough match.
4809#if DEBUG_HACKS
4810        LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d",
4811                i, y, closestY, closestDeltaY, maxDeltaY);
4812#endif
4813
4814        mCurrentTouch.pointers[i].y = closestY;
4815        return true; // XXX original code only corrects one point
4816
4817    SkipSufficientlyClosePoint: ;
4818    }
4819
4820    // No change.
4821    return false;
4822}
4823
4824/* Special hack for devices that have bad screen data: drop points where
4825 * the coordinate value for one axis has jumped to the other pointer's location.
4826 */
4827bool TouchInputMapper::applyJumpyTouchFilter() {
4828    uint32_t pointerCount = mCurrentTouch.pointerCount;
4829    if (mLastTouch.pointerCount != pointerCount) {
4830#if DEBUG_HACKS
4831        LOGD("JumpyTouchFilter: Different pointer count %d -> %d",
4832                mLastTouch.pointerCount, pointerCount);
4833        for (uint32_t i = 0; i < pointerCount; i++) {
4834            LOGD("  Pointer %d (%d, %d)", i,
4835                    mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4836        }
4837#endif
4838
4839        if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) {
4840            if (mLastTouch.pointerCount == 1 && pointerCount == 2) {
4841                // Just drop the first few events going from 1 to 2 pointers.
4842                // They're bad often enough that they're not worth considering.
4843                mCurrentTouch.pointerCount = 1;
4844                mJumpyTouchFilter.jumpyPointsDropped += 1;
4845
4846#if DEBUG_HACKS
4847                LOGD("JumpyTouchFilter: Pointer 2 dropped");
4848#endif
4849                return true;
4850            } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) {
4851                // The event when we go from 2 -> 1 tends to be messed up too
4852                mCurrentTouch.pointerCount = 2;
4853                mCurrentTouch.pointers[0] = mLastTouch.pointers[0];
4854                mCurrentTouch.pointers[1] = mLastTouch.pointers[1];
4855                mJumpyTouchFilter.jumpyPointsDropped += 1;
4856
4857#if DEBUG_HACKS
4858                for (int32_t i = 0; i < 2; i++) {
4859                    LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i,
4860                            mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4861                }
4862#endif
4863                return true;
4864            }
4865        }
4866        // Reset jumpy points dropped on other transitions or if limit exceeded.
4867        mJumpyTouchFilter.jumpyPointsDropped = 0;
4868
4869#if DEBUG_HACKS
4870        LOGD("JumpyTouchFilter: Transition - drop limit reset");
4871#endif
4872        return false;
4873    }
4874
4875    // We have the same number of pointers as last time.
4876    // A 'jumpy' point is one where the coordinate value for one axis
4877    // has jumped to the other pointer's location. No need to do anything
4878    // else if we only have one pointer.
4879    if (pointerCount < 2) {
4880        return false;
4881    }
4882
4883    if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) {
4884        int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR;
4885
4886        // We only replace the single worst jumpy point as characterized by pointer distance
4887        // in a single axis.
4888        int32_t badPointerIndex = -1;
4889        int32_t badPointerReplacementIndex = -1;
4890        int32_t badPointerDistance = INT_MIN; // distance to be corrected
4891
4892        for (uint32_t i = pointerCount; i-- > 0; ) {
4893            int32_t x = mCurrentTouch.pointers[i].x;
4894            int32_t y = mCurrentTouch.pointers[i].y;
4895
4896#if DEBUG_HACKS
4897            LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y);
4898#endif
4899
4900            // Check if a touch point is too close to another's coordinates
4901            bool dropX = false, dropY = false;
4902            for (uint32_t j = 0; j < pointerCount; j++) {
4903                if (i == j) {
4904                    continue;
4905                }
4906
4907                if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) {
4908                    dropX = true;
4909                    break;
4910                }
4911
4912                if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) {
4913                    dropY = true;
4914                    break;
4915                }
4916            }
4917            if (! dropX && ! dropY) {
4918                continue; // not jumpy
4919            }
4920
4921            // Find a replacement candidate by comparing with older points on the
4922            // complementary (non-jumpy) axis.
4923            int32_t distance = INT_MIN; // distance to be corrected
4924            int32_t replacementIndex = -1;
4925
4926            if (dropX) {
4927                // X looks too close.  Find an older replacement point with a close Y.
4928                int32_t smallestDeltaY = INT_MAX;
4929                for (uint32_t j = 0; j < pointerCount; j++) {
4930                    int32_t deltaY = abs(y - mLastTouch.pointers[j].y);
4931                    if (deltaY < smallestDeltaY) {
4932                        smallestDeltaY = deltaY;
4933                        replacementIndex = j;
4934                    }
4935                }
4936                distance = abs(x - mLastTouch.pointers[replacementIndex].x);
4937            } else {
4938                // Y looks too close.  Find an older replacement point with a close X.
4939                int32_t smallestDeltaX = INT_MAX;
4940                for (uint32_t j = 0; j < pointerCount; j++) {
4941                    int32_t deltaX = abs(x - mLastTouch.pointers[j].x);
4942                    if (deltaX < smallestDeltaX) {
4943                        smallestDeltaX = deltaX;
4944                        replacementIndex = j;
4945                    }
4946                }
4947                distance = abs(y - mLastTouch.pointers[replacementIndex].y);
4948            }
4949
4950            // If replacing this pointer would correct a worse error than the previous ones
4951            // considered, then use this replacement instead.
4952            if (distance > badPointerDistance) {
4953                badPointerIndex = i;
4954                badPointerReplacementIndex = replacementIndex;
4955                badPointerDistance = distance;
4956            }
4957        }
4958
4959        // Correct the jumpy pointer if one was found.
4960        if (badPointerIndex >= 0) {
4961#if DEBUG_HACKS
4962            LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)",
4963                    badPointerIndex,
4964                    mLastTouch.pointers[badPointerReplacementIndex].x,
4965                    mLastTouch.pointers[badPointerReplacementIndex].y);
4966#endif
4967
4968            mCurrentTouch.pointers[badPointerIndex].x =
4969                    mLastTouch.pointers[badPointerReplacementIndex].x;
4970            mCurrentTouch.pointers[badPointerIndex].y =
4971                    mLastTouch.pointers[badPointerReplacementIndex].y;
4972            mJumpyTouchFilter.jumpyPointsDropped += 1;
4973            return true;
4974        }
4975    }
4976
4977    mJumpyTouchFilter.jumpyPointsDropped = 0;
4978    return false;
4979}
4980
4981/* Special hack for devices that have bad screen data: aggregate and
4982 * compute averages of the coordinate data, to reduce the amount of
4983 * jitter seen by applications. */
4984void TouchInputMapper::applyAveragingTouchFilter() {
4985    for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) {
4986        uint32_t id = mCurrentTouch.pointers[currentIndex].id;
4987        int32_t x = mCurrentTouch.pointers[currentIndex].x;
4988        int32_t y = mCurrentTouch.pointers[currentIndex].y;
4989        int32_t pressure;
4990        switch (mCalibration.pressureSource) {
4991        case Calibration::PRESSURE_SOURCE_PRESSURE:
4992            pressure = mCurrentTouch.pointers[currentIndex].pressure;
4993            break;
4994        case Calibration::PRESSURE_SOURCE_TOUCH:
4995            pressure = mCurrentTouch.pointers[currentIndex].touchMajor;
4996            break;
4997        default:
4998            pressure = 1;
4999            break;
5000        }
5001
5002        if (mLastTouch.idBits.hasBit(id)) {
5003            // Pointer was down before and is still down now.
5004            // Compute average over history trace.
5005            uint32_t start = mAveragingTouchFilter.historyStart[id];
5006            uint32_t end = mAveragingTouchFilter.historyEnd[id];
5007
5008            int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x;
5009            int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y;
5010            uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
5011
5012#if DEBUG_HACKS
5013            LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld",
5014                    id, distance);
5015#endif
5016
5017            if (distance < AVERAGING_DISTANCE_LIMIT) {
5018                // Increment end index in preparation for recording new historical data.
5019                end += 1;
5020                if (end > AVERAGING_HISTORY_SIZE) {
5021                    end = 0;
5022                }
5023
5024                // If the end index has looped back to the start index then we have filled
5025                // the historical trace up to the desired size so we drop the historical
5026                // data at the start of the trace.
5027                if (end == start) {
5028                    start += 1;
5029                    if (start > AVERAGING_HISTORY_SIZE) {
5030                        start = 0;
5031                    }
5032                }
5033
5034                // Add the raw data to the historical trace.
5035                mAveragingTouchFilter.historyStart[id] = start;
5036                mAveragingTouchFilter.historyEnd[id] = end;
5037                mAveragingTouchFilter.historyData[end].pointers[id].x = x;
5038                mAveragingTouchFilter.historyData[end].pointers[id].y = y;
5039                mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure;
5040
5041                // Average over all historical positions in the trace by total pressure.
5042                int32_t averagedX = 0;
5043                int32_t averagedY = 0;
5044                int32_t totalPressure = 0;
5045                for (;;) {
5046                    int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x;
5047                    int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y;
5048                    int32_t historicalPressure = mAveragingTouchFilter.historyData[start]
5049                            .pointers[id].pressure;
5050
5051                    averagedX += historicalX * historicalPressure;
5052                    averagedY += historicalY * historicalPressure;
5053                    totalPressure += historicalPressure;
5054
5055                    if (start == end) {
5056                        break;
5057                    }
5058
5059                    start += 1;
5060                    if (start > AVERAGING_HISTORY_SIZE) {
5061                        start = 0;
5062                    }
5063                }
5064
5065                if (totalPressure != 0) {
5066                    averagedX /= totalPressure;
5067                    averagedY /= totalPressure;
5068
5069#if DEBUG_HACKS
5070                    LOGD("AveragingTouchFilter: Pointer id %d - "
5071                            "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure,
5072                            averagedX, averagedY);
5073#endif
5074
5075                    mCurrentTouch.pointers[currentIndex].x = averagedX;
5076                    mCurrentTouch.pointers[currentIndex].y = averagedY;
5077                }
5078            } else {
5079#if DEBUG_HACKS
5080                LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id);
5081#endif
5082            }
5083        } else {
5084#if DEBUG_HACKS
5085            LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id);
5086#endif
5087        }
5088
5089        // Reset pointer history.
5090        mAveragingTouchFilter.historyStart[id] = 0;
5091        mAveragingTouchFilter.historyEnd[id] = 0;
5092        mAveragingTouchFilter.historyData[0].pointers[id].x = x;
5093        mAveragingTouchFilter.historyData[0].pointers[id].y = y;
5094        mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure;
5095    }
5096}
5097
5098int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
5099    { // acquire lock
5100        AutoMutex _l(mLock);
5101
5102        if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) {
5103            return AKEY_STATE_VIRTUAL;
5104        }
5105
5106        size_t numVirtualKeys = mLocked.virtualKeys.size();
5107        for (size_t i = 0; i < numVirtualKeys; i++) {
5108            const VirtualKey& virtualKey = mLocked.virtualKeys[i];
5109            if (virtualKey.keyCode == keyCode) {
5110                return AKEY_STATE_UP;
5111            }
5112        }
5113    } // release lock
5114
5115    return AKEY_STATE_UNKNOWN;
5116}
5117
5118int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
5119    { // acquire lock
5120        AutoMutex _l(mLock);
5121
5122        if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) {
5123            return AKEY_STATE_VIRTUAL;
5124        }
5125
5126        size_t numVirtualKeys = mLocked.virtualKeys.size();
5127        for (size_t i = 0; i < numVirtualKeys; i++) {
5128            const VirtualKey& virtualKey = mLocked.virtualKeys[i];
5129            if (virtualKey.scanCode == scanCode) {
5130                return AKEY_STATE_UP;
5131            }
5132        }
5133    } // release lock
5134
5135    return AKEY_STATE_UNKNOWN;
5136}
5137
5138bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
5139        const int32_t* keyCodes, uint8_t* outFlags) {
5140    { // acquire lock
5141        AutoMutex _l(mLock);
5142
5143        size_t numVirtualKeys = mLocked.virtualKeys.size();
5144        for (size_t i = 0; i < numVirtualKeys; i++) {
5145            const VirtualKey& virtualKey = mLocked.virtualKeys[i];
5146
5147            for (size_t i = 0; i < numCodes; i++) {
5148                if (virtualKey.keyCode == keyCodes[i]) {
5149                    outFlags[i] = 1;
5150                }
5151            }
5152        }
5153    } // release lock
5154
5155    return true;
5156}
5157
5158
5159// --- SingleTouchInputMapper ---
5160
5161SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
5162        TouchInputMapper(device) {
5163    clearState();
5164}
5165
5166SingleTouchInputMapper::~SingleTouchInputMapper() {
5167}
5168
5169void SingleTouchInputMapper::clearState() {
5170    mAccumulator.clear();
5171
5172    mDown = false;
5173    mX = 0;
5174    mY = 0;
5175    mPressure = 0; // default to 0 for devices that don't report pressure
5176    mToolWidth = 0; // default to 0 for devices that don't report tool width
5177    mButtonState = 0;
5178}
5179
5180void SingleTouchInputMapper::reset() {
5181    TouchInputMapper::reset();
5182
5183    clearState();
5184 }
5185
5186void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
5187    switch (rawEvent->type) {
5188    case EV_KEY:
5189        switch (rawEvent->scanCode) {
5190        case BTN_TOUCH:
5191            mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH;
5192            mAccumulator.btnTouch = rawEvent->value != 0;
5193            // Don't sync immediately.  Wait until the next SYN_REPORT since we might
5194            // not have received valid position information yet.  This logic assumes that
5195            // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet.
5196            break;
5197        default:
5198            if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
5199                int32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
5200                if (buttonState) {
5201                    if (rawEvent->value) {
5202                        mAccumulator.buttonDown |= buttonState;
5203                    } else {
5204                        mAccumulator.buttonUp |= buttonState;
5205                    }
5206                    mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
5207                }
5208            }
5209            break;
5210        }
5211        break;
5212
5213    case EV_ABS:
5214        switch (rawEvent->scanCode) {
5215        case ABS_X:
5216            mAccumulator.fields |= Accumulator::FIELD_ABS_X;
5217            mAccumulator.absX = rawEvent->value;
5218            break;
5219        case ABS_Y:
5220            mAccumulator.fields |= Accumulator::FIELD_ABS_Y;
5221            mAccumulator.absY = rawEvent->value;
5222            break;
5223        case ABS_PRESSURE:
5224            mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE;
5225            mAccumulator.absPressure = rawEvent->value;
5226            break;
5227        case ABS_TOOL_WIDTH:
5228            mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH;
5229            mAccumulator.absToolWidth = rawEvent->value;
5230            break;
5231        }
5232        break;
5233
5234    case EV_SYN:
5235        switch (rawEvent->scanCode) {
5236        case SYN_REPORT:
5237            sync(rawEvent->when);
5238            break;
5239        }
5240        break;
5241    }
5242}
5243
5244void SingleTouchInputMapper::sync(nsecs_t when) {
5245    uint32_t fields = mAccumulator.fields;
5246    if (fields == 0) {
5247        return; // no new state changes, so nothing to do
5248    }
5249
5250    if (fields & Accumulator::FIELD_BTN_TOUCH) {
5251        mDown = mAccumulator.btnTouch;
5252    }
5253
5254    if (fields & Accumulator::FIELD_ABS_X) {
5255        mX = mAccumulator.absX;
5256    }
5257
5258    if (fields & Accumulator::FIELD_ABS_Y) {
5259        mY = mAccumulator.absY;
5260    }
5261
5262    if (fields & Accumulator::FIELD_ABS_PRESSURE) {
5263        mPressure = mAccumulator.absPressure;
5264    }
5265
5266    if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) {
5267        mToolWidth = mAccumulator.absToolWidth;
5268    }
5269
5270    if (fields & Accumulator::FIELD_BUTTONS) {
5271        mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5272    }
5273
5274    mCurrentTouch.clear();
5275
5276    if (mDown) {
5277        mCurrentTouch.pointerCount = 1;
5278        mCurrentTouch.pointers[0].id = 0;
5279        mCurrentTouch.pointers[0].x = mX;
5280        mCurrentTouch.pointers[0].y = mY;
5281        mCurrentTouch.pointers[0].pressure = mPressure;
5282        mCurrentTouch.pointers[0].touchMajor = 0;
5283        mCurrentTouch.pointers[0].touchMinor = 0;
5284        mCurrentTouch.pointers[0].toolMajor = mToolWidth;
5285        mCurrentTouch.pointers[0].toolMinor = mToolWidth;
5286        mCurrentTouch.pointers[0].orientation = 0;
5287        mCurrentTouch.pointers[0].distance = 0;
5288        mCurrentTouch.pointers[0].isStylus = false; // TODO: Set stylus
5289        mCurrentTouch.idToIndex[0] = 0;
5290        mCurrentTouch.idBits.markBit(0);
5291        mCurrentTouch.buttonState = mButtonState;
5292    }
5293
5294    syncTouch(when, true);
5295
5296    mAccumulator.clear();
5297}
5298
5299void SingleTouchInputMapper::configureRawAxes() {
5300    TouchInputMapper::configureRawAxes();
5301
5302    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x);
5303    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y);
5304    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure);
5305    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor);
5306}
5307
5308
5309// --- MultiTouchInputMapper ---
5310
5311MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
5312        TouchInputMapper(device), mSlotCount(0), mUsingSlotsProtocol(false) {
5313    clearState();
5314}
5315
5316MultiTouchInputMapper::~MultiTouchInputMapper() {
5317}
5318
5319void MultiTouchInputMapper::clearState() {
5320    mAccumulator.clearSlots(mSlotCount);
5321    mAccumulator.clearButtons();
5322    mButtonState = 0;
5323}
5324
5325void MultiTouchInputMapper::reset() {
5326    TouchInputMapper::reset();
5327
5328    clearState();
5329}
5330
5331void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
5332    switch (rawEvent->type) {
5333    case EV_KEY: {
5334        if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
5335            int32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
5336            if (buttonState) {
5337                if (rawEvent->value) {
5338                    mAccumulator.buttonDown |= buttonState;
5339                } else {
5340                    mAccumulator.buttonUp |= buttonState;
5341                }
5342            }
5343        }
5344        break;
5345    }
5346
5347    case EV_ABS: {
5348        bool newSlot = false;
5349        if (mUsingSlotsProtocol && rawEvent->scanCode == ABS_MT_SLOT) {
5350            mAccumulator.currentSlot = rawEvent->value;
5351            newSlot = true;
5352        }
5353
5354        if (mAccumulator.currentSlot < 0 || size_t(mAccumulator.currentSlot) >= mSlotCount) {
5355#if DEBUG_POINTERS
5356            if (newSlot) {
5357                LOGW("MultiTouch device %s emitted invalid slot index %d but it "
5358                        "should be between 0 and %d; ignoring this slot.",
5359                        getDeviceName().string(), mAccumulator.currentSlot, mSlotCount);
5360            }
5361#endif
5362            break;
5363        }
5364
5365        Accumulator::Slot* slot = &mAccumulator.slots[mAccumulator.currentSlot];
5366
5367        switch (rawEvent->scanCode) {
5368        case ABS_MT_POSITION_X:
5369            slot->fields |= Accumulator::FIELD_ABS_MT_POSITION_X;
5370            slot->absMTPositionX = rawEvent->value;
5371            break;
5372        case ABS_MT_POSITION_Y:
5373            slot->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y;
5374            slot->absMTPositionY = rawEvent->value;
5375            break;
5376        case ABS_MT_TOUCH_MAJOR:
5377            slot->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR;
5378            slot->absMTTouchMajor = rawEvent->value;
5379            break;
5380        case ABS_MT_TOUCH_MINOR:
5381            slot->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR;
5382            slot->absMTTouchMinor = rawEvent->value;
5383            break;
5384        case ABS_MT_WIDTH_MAJOR:
5385            slot->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR;
5386            slot->absMTWidthMajor = rawEvent->value;
5387            break;
5388        case ABS_MT_WIDTH_MINOR:
5389            slot->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR;
5390            slot->absMTWidthMinor = rawEvent->value;
5391            break;
5392        case ABS_MT_ORIENTATION:
5393            slot->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION;
5394            slot->absMTOrientation = rawEvent->value;
5395            break;
5396        case ABS_MT_TRACKING_ID:
5397            if (mUsingSlotsProtocol && rawEvent->value < 0) {
5398                slot->clear();
5399            } else {
5400                slot->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID;
5401                slot->absMTTrackingId = rawEvent->value;
5402            }
5403            break;
5404        case ABS_MT_PRESSURE:
5405            slot->fields |= Accumulator::FIELD_ABS_MT_PRESSURE;
5406            slot->absMTPressure = rawEvent->value;
5407            break;
5408        case ABS_MT_TOOL_TYPE:
5409            slot->fields |= Accumulator::FIELD_ABS_MT_TOOL_TYPE;
5410            slot->absMTToolType = rawEvent->value;
5411            break;
5412        }
5413        break;
5414    }
5415
5416    case EV_SYN:
5417        switch (rawEvent->scanCode) {
5418        case SYN_MT_REPORT: {
5419            // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
5420            mAccumulator.currentSlot += 1;
5421            break;
5422        }
5423
5424        case SYN_REPORT:
5425            sync(rawEvent->when);
5426            break;
5427        }
5428        break;
5429    }
5430}
5431
5432void MultiTouchInputMapper::sync(nsecs_t when) {
5433    static const uint32_t REQUIRED_FIELDS =
5434            Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y;
5435
5436    size_t inCount = mSlotCount;
5437    size_t outCount = 0;
5438    bool havePointerIds = true;
5439
5440    mCurrentTouch.clear();
5441
5442    for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
5443        const Accumulator::Slot& inSlot = mAccumulator.slots[inIndex];
5444        uint32_t fields = inSlot.fields;
5445
5446        if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) {
5447            // Some drivers send empty MT sync packets without X / Y to indicate a pointer up.
5448            // This may also indicate an unused slot.
5449            // Drop this finger.
5450            continue;
5451        }
5452
5453        if (outCount >= MAX_POINTERS) {
5454#if DEBUG_POINTERS
5455            LOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
5456                    "ignoring the rest.",
5457                    getDeviceName().string(), MAX_POINTERS);
5458#endif
5459            break; // too many fingers!
5460        }
5461
5462        PointerData& outPointer = mCurrentTouch.pointers[outCount];
5463        outPointer.x = inSlot.absMTPositionX;
5464        outPointer.y = inSlot.absMTPositionY;
5465
5466        if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) {
5467            outPointer.pressure = inSlot.absMTPressure;
5468        } else {
5469            // Default pressure to 0 if absent.
5470            outPointer.pressure = 0;
5471        }
5472
5473        if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) {
5474            if (inSlot.absMTTouchMajor <= 0) {
5475                // Some devices send sync packets with X / Y but with a 0 touch major to indicate
5476                // a pointer going up.  Drop this finger.
5477                continue;
5478            }
5479            outPointer.touchMajor = inSlot.absMTTouchMajor;
5480        } else {
5481            // Default touch area to 0 if absent.
5482            outPointer.touchMajor = 0;
5483        }
5484
5485        if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) {
5486            outPointer.touchMinor = inSlot.absMTTouchMinor;
5487        } else {
5488            // Assume touch area is circular.
5489            outPointer.touchMinor = outPointer.touchMajor;
5490        }
5491
5492        if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) {
5493            outPointer.toolMajor = inSlot.absMTWidthMajor;
5494        } else {
5495            // Default tool area to 0 if absent.
5496            outPointer.toolMajor = 0;
5497        }
5498
5499        if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) {
5500            outPointer.toolMinor = inSlot.absMTWidthMinor;
5501        } else {
5502            // Assume tool area is circular.
5503            outPointer.toolMinor = outPointer.toolMajor;
5504        }
5505
5506        if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) {
5507            outPointer.orientation = inSlot.absMTOrientation;
5508        } else {
5509            // Default orientation to vertical if absent.
5510            outPointer.orientation = 0;
5511        }
5512
5513        if (fields & Accumulator::FIELD_ABS_MT_DISTANCE) {
5514            outPointer.distance = inSlot.absMTDistance;
5515        } else {
5516            // Default distance is 0 (direct contact).
5517            outPointer.distance = 0;
5518        }
5519
5520        if (fields & Accumulator::FIELD_ABS_MT_TOOL_TYPE) {
5521            outPointer.isStylus = (inSlot.absMTToolType == MT_TOOL_PEN);
5522        } else {
5523            // Assume this is not a stylus.
5524            outPointer.isStylus = false;
5525        }
5526
5527        // Assign pointer id using tracking id if available.
5528        if (havePointerIds) {
5529            int32_t id;
5530            if (mUsingSlotsProtocol) {
5531                id = inIndex;
5532            } else if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
5533                id = inSlot.absMTTrackingId;
5534            } else {
5535                id = -1;
5536            }
5537
5538            if (id >= 0 && id <= MAX_POINTER_ID) {
5539                outPointer.id = id;
5540                mCurrentTouch.idToIndex[id] = outCount;
5541                mCurrentTouch.idBits.markBit(id);
5542            } else {
5543                if (id >= 0) {
5544#if DEBUG_POINTERS
5545                    LOGD("Pointers: Ignoring driver provided slot index or tracking id %d because "
5546                            "it is larger than the maximum supported pointer id %d",
5547                            id, MAX_POINTER_ID);
5548#endif
5549                }
5550                havePointerIds = false;
5551            }
5552        }
5553
5554        outCount += 1;
5555    }
5556
5557    mCurrentTouch.pointerCount = outCount;
5558
5559    mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5560    mCurrentTouch.buttonState = mButtonState;
5561
5562    syncTouch(when, havePointerIds);
5563
5564    if (!mUsingSlotsProtocol) {
5565        mAccumulator.clearSlots(mSlotCount);
5566    }
5567    mAccumulator.clearButtons();
5568}
5569
5570void MultiTouchInputMapper::configureRawAxes() {
5571    TouchInputMapper::configureRawAxes();
5572
5573    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, &mRawAxes.x);
5574    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, &mRawAxes.y);
5575    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, &mRawAxes.touchMajor);
5576    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, &mRawAxes.touchMinor);
5577    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, &mRawAxes.toolMajor);
5578    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, &mRawAxes.toolMinor);
5579    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, &mRawAxes.orientation);
5580    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, &mRawAxes.pressure);
5581    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_DISTANCE, &mRawAxes.distance);
5582    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TRACKING_ID, &mRawAxes.trackingId);
5583    getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_SLOT, &mRawAxes.slot);
5584
5585    if (mRawAxes.trackingId.valid
5586            && mRawAxes.slot.valid && mRawAxes.slot.minValue == 0 && mRawAxes.slot.maxValue > 0) {
5587        mSlotCount = mRawAxes.slot.maxValue + 1;
5588        if (mSlotCount > MAX_SLOTS) {
5589            LOGW("MultiTouch Device %s reported %d slots but the framework "
5590                    "only supports a maximum of %d slots at this time.",
5591                    getDeviceName().string(), mSlotCount, MAX_SLOTS);
5592            mSlotCount = MAX_SLOTS;
5593        }
5594        mUsingSlotsProtocol = true;
5595    } else {
5596        mSlotCount = MAX_POINTERS;
5597        mUsingSlotsProtocol = false;
5598    }
5599
5600    mAccumulator.allocateSlots(mSlotCount);
5601}
5602
5603
5604// --- JoystickInputMapper ---
5605
5606JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
5607        InputMapper(device) {
5608}
5609
5610JoystickInputMapper::~JoystickInputMapper() {
5611}
5612
5613uint32_t JoystickInputMapper::getSources() {
5614    return AINPUT_SOURCE_JOYSTICK;
5615}
5616
5617void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
5618    InputMapper::populateDeviceInfo(info);
5619
5620    for (size_t i = 0; i < mAxes.size(); i++) {
5621        const Axis& axis = mAxes.valueAt(i);
5622        info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK,
5623                axis.min, axis.max, axis.flat, axis.fuzz);
5624        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5625            info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK,
5626                    axis.min, axis.max, axis.flat, axis.fuzz);
5627        }
5628    }
5629}
5630
5631void JoystickInputMapper::dump(String8& dump) {
5632    dump.append(INDENT2 "Joystick Input Mapper:\n");
5633
5634    dump.append(INDENT3 "Axes:\n");
5635    size_t numAxes = mAxes.size();
5636    for (size_t i = 0; i < numAxes; i++) {
5637        const Axis& axis = mAxes.valueAt(i);
5638        const char* label = getAxisLabel(axis.axisInfo.axis);
5639        if (label) {
5640            dump.appendFormat(INDENT4 "%s", label);
5641        } else {
5642            dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
5643        }
5644        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5645            label = getAxisLabel(axis.axisInfo.highAxis);
5646            if (label) {
5647                dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
5648            } else {
5649                dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
5650                        axis.axisInfo.splitValue);
5651            }
5652        } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
5653            dump.append(" (invert)");
5654        }
5655
5656        dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n",
5657                axis.min, axis.max, axis.flat, axis.fuzz);
5658        dump.appendFormat(INDENT4 "  scale=%0.5f, offset=%0.5f, "
5659                "highScale=%0.5f, highOffset=%0.5f\n",
5660                axis.scale, axis.offset, axis.highScale, axis.highOffset);
5661        dump.appendFormat(INDENT4 "  rawAxis=%d, rawMin=%d, rawMax=%d, "
5662                "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
5663                mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
5664                axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
5665    }
5666}
5667
5668void JoystickInputMapper::configure() {
5669    InputMapper::configure();
5670
5671    // Collect all axes.
5672    for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
5673        RawAbsoluteAxisInfo rawAxisInfo;
5674        getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo);
5675        if (rawAxisInfo.valid) {
5676            // Map axis.
5677            AxisInfo axisInfo;
5678            bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
5679            if (!explicitlyMapped) {
5680                // Axis is not explicitly mapped, will choose a generic axis later.
5681                axisInfo.mode = AxisInfo::MODE_NORMAL;
5682                axisInfo.axis = -1;
5683            }
5684
5685            // Apply flat override.
5686            int32_t rawFlat = axisInfo.flatOverride < 0
5687                    ? rawAxisInfo.flat : axisInfo.flatOverride;
5688
5689            // Calculate scaling factors and limits.
5690            Axis axis;
5691            if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
5692                float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
5693                float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
5694                axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5695                        scale, 0.0f, highScale, 0.0f,
5696                        0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5697            } else if (isCenteredAxis(axisInfo.axis)) {
5698                float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5699                float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
5700                axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5701                        scale, offset, scale, offset,
5702                        -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5703            } else {
5704                float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5705                axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5706                        scale, 0.0f, scale, 0.0f,
5707                        0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5708            }
5709
5710            // To eliminate noise while the joystick is at rest, filter out small variations
5711            // in axis values up front.
5712            axis.filter = axis.flat * 0.25f;
5713
5714            mAxes.add(abs, axis);
5715        }
5716    }
5717
5718    // If there are too many axes, start dropping them.
5719    // Prefer to keep explicitly mapped axes.
5720    if (mAxes.size() > PointerCoords::MAX_AXES) {
5721        LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
5722                getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
5723        pruneAxes(true);
5724        pruneAxes(false);
5725    }
5726
5727    // Assign generic axis ids to remaining axes.
5728    int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
5729    size_t numAxes = mAxes.size();
5730    for (size_t i = 0; i < numAxes; i++) {
5731        Axis& axis = mAxes.editValueAt(i);
5732        if (axis.axisInfo.axis < 0) {
5733            while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
5734                    && haveAxis(nextGenericAxisId)) {
5735                nextGenericAxisId += 1;
5736            }
5737
5738            if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
5739                axis.axisInfo.axis = nextGenericAxisId;
5740                nextGenericAxisId += 1;
5741            } else {
5742                LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
5743                        "have already been assigned to other axes.",
5744                        getDeviceName().string(), mAxes.keyAt(i));
5745                mAxes.removeItemsAt(i--);
5746                numAxes -= 1;
5747            }
5748        }
5749    }
5750}
5751
5752bool JoystickInputMapper::haveAxis(int32_t axisId) {
5753    size_t numAxes = mAxes.size();
5754    for (size_t i = 0; i < numAxes; i++) {
5755        const Axis& axis = mAxes.valueAt(i);
5756        if (axis.axisInfo.axis == axisId
5757                || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
5758                        && axis.axisInfo.highAxis == axisId)) {
5759            return true;
5760        }
5761    }
5762    return false;
5763}
5764
5765void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
5766    size_t i = mAxes.size();
5767    while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
5768        if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
5769            continue;
5770        }
5771        LOGI("Discarding joystick '%s' axis %d because there are too many axes.",
5772                getDeviceName().string(), mAxes.keyAt(i));
5773        mAxes.removeItemsAt(i);
5774    }
5775}
5776
5777bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
5778    switch (axis) {
5779    case AMOTION_EVENT_AXIS_X:
5780    case AMOTION_EVENT_AXIS_Y:
5781    case AMOTION_EVENT_AXIS_Z:
5782    case AMOTION_EVENT_AXIS_RX:
5783    case AMOTION_EVENT_AXIS_RY:
5784    case AMOTION_EVENT_AXIS_RZ:
5785    case AMOTION_EVENT_AXIS_HAT_X:
5786    case AMOTION_EVENT_AXIS_HAT_Y:
5787    case AMOTION_EVENT_AXIS_ORIENTATION:
5788    case AMOTION_EVENT_AXIS_RUDDER:
5789    case AMOTION_EVENT_AXIS_WHEEL:
5790        return true;
5791    default:
5792        return false;
5793    }
5794}
5795
5796void JoystickInputMapper::reset() {
5797    // Recenter all axes.
5798    nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
5799
5800    size_t numAxes = mAxes.size();
5801    for (size_t i = 0; i < numAxes; i++) {
5802        Axis& axis = mAxes.editValueAt(i);
5803        axis.resetValue();
5804    }
5805
5806    sync(when, true /*force*/);
5807
5808    InputMapper::reset();
5809}
5810
5811void JoystickInputMapper::process(const RawEvent* rawEvent) {
5812    switch (rawEvent->type) {
5813    case EV_ABS: {
5814        ssize_t index = mAxes.indexOfKey(rawEvent->scanCode);
5815        if (index >= 0) {
5816            Axis& axis = mAxes.editValueAt(index);
5817            float newValue, highNewValue;
5818            switch (axis.axisInfo.mode) {
5819            case AxisInfo::MODE_INVERT:
5820                newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
5821                        * axis.scale + axis.offset;
5822                highNewValue = 0.0f;
5823                break;
5824            case AxisInfo::MODE_SPLIT:
5825                if (rawEvent->value < axis.axisInfo.splitValue) {
5826                    newValue = (axis.axisInfo.splitValue - rawEvent->value)
5827                            * axis.scale + axis.offset;
5828                    highNewValue = 0.0f;
5829                } else if (rawEvent->value > axis.axisInfo.splitValue) {
5830                    newValue = 0.0f;
5831                    highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
5832                            * axis.highScale + axis.highOffset;
5833                } else {
5834                    newValue = 0.0f;
5835                    highNewValue = 0.0f;
5836                }
5837                break;
5838            default:
5839                newValue = rawEvent->value * axis.scale + axis.offset;
5840                highNewValue = 0.0f;
5841                break;
5842            }
5843            axis.newValue = newValue;
5844            axis.highNewValue = highNewValue;
5845        }
5846        break;
5847    }
5848
5849    case EV_SYN:
5850        switch (rawEvent->scanCode) {
5851        case SYN_REPORT:
5852            sync(rawEvent->when, false /*force*/);
5853            break;
5854        }
5855        break;
5856    }
5857}
5858
5859void JoystickInputMapper::sync(nsecs_t when, bool force) {
5860    if (!filterAxes(force)) {
5861        return;
5862    }
5863
5864    int32_t metaState = mContext->getGlobalMetaState();
5865    int32_t buttonState = 0;
5866
5867    PointerProperties pointerProperties;
5868    pointerProperties.clear();
5869    pointerProperties.id = 0;
5870    pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
5871
5872    PointerCoords pointerCoords;
5873    pointerCoords.clear();
5874
5875    size_t numAxes = mAxes.size();
5876    for (size_t i = 0; i < numAxes; i++) {
5877        const Axis& axis = mAxes.valueAt(i);
5878        pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue);
5879        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5880            pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue);
5881        }
5882    }
5883
5884    // Moving a joystick axis should not wake the devide because joysticks can
5885    // be fairly noisy even when not in use.  On the other hand, pushing a gamepad
5886    // button will likely wake the device.
5887    // TODO: Use the input device configuration to control this behavior more finely.
5888    uint32_t policyFlags = 0;
5889
5890    getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
5891            AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5892            1, &pointerProperties, &pointerCoords, 0, 0, 0);
5893}
5894
5895bool JoystickInputMapper::filterAxes(bool force) {
5896    bool atLeastOneSignificantChange = force;
5897    size_t numAxes = mAxes.size();
5898    for (size_t i = 0; i < numAxes; i++) {
5899        Axis& axis = mAxes.editValueAt(i);
5900        if (force || hasValueChangedSignificantly(axis.filter,
5901                axis.newValue, axis.currentValue, axis.min, axis.max)) {
5902            axis.currentValue = axis.newValue;
5903            atLeastOneSignificantChange = true;
5904        }
5905        if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5906            if (force || hasValueChangedSignificantly(axis.filter,
5907                    axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
5908                axis.highCurrentValue = axis.highNewValue;
5909                atLeastOneSignificantChange = true;
5910            }
5911        }
5912    }
5913    return atLeastOneSignificantChange;
5914}
5915
5916bool JoystickInputMapper::hasValueChangedSignificantly(
5917        float filter, float newValue, float currentValue, float min, float max) {
5918    if (newValue != currentValue) {
5919        // Filter out small changes in value unless the value is converging on the axis
5920        // bounds or center point.  This is intended to reduce the amount of information
5921        // sent to applications by particularly noisy joysticks (such as PS3).
5922        if (fabs(newValue - currentValue) > filter
5923                || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
5924                || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
5925                || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
5926            return true;
5927        }
5928    }
5929    return false;
5930}
5931
5932bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
5933        float filter, float newValue, float currentValue, float thresholdValue) {
5934    float newDistance = fabs(newValue - thresholdValue);
5935    if (newDistance < filter) {
5936        float oldDistance = fabs(currentValue - thresholdValue);
5937        if (newDistance < oldDistance) {
5938            return true;
5939        }
5940    }
5941    return false;
5942}
5943
5944} // namespace android
5945