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