1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
25#define DEBUG_HACKS 0
26
27// Log debug messages about virtual key processing.
28#define DEBUG_VIRTUAL_KEYS 0
29
30// Log debug messages about pointers.
31#define DEBUG_POINTERS 0
32
33// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
36// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
39// Log debug messages about the vibrator.
40#define DEBUG_VIBRATOR 0
41
42// Log debug messages about fusing stylus data.
43#define DEBUG_STYLUS_FUSION 0
44
45#include "InputReader.h"
46
47#include <cutils/log.h>
48#include <input/Keyboard.h>
49#include <input/VirtualKeyMap.h>
50
51#include <inttypes.h>
52#include <stddef.h>
53#include <stdlib.h>
54#include <unistd.h>
55#include <errno.h>
56#include <limits.h>
57#include <math.h>
58
59#define INDENT "  "
60#define INDENT2 "    "
61#define INDENT3 "      "
62#define INDENT4 "        "
63#define INDENT5 "          "
64
65namespace android {
66
67// --- Constants ---
68
69// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
70static const size_t MAX_SLOTS = 32;
71
72// Maximum amount of latency to add to touch events while waiting for data from an
73// external stylus.
74static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
75
76// Maximum amount of time to wait on touch data before pushing out new pressure data.
77static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
78
79// Artificial latency on synthetic events created from stylus data without corresponding touch
80// data.
81static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
82
83// --- Static Functions ---
84
85template<typename T>
86inline static T abs(const T& value) {
87    return value < 0 ? - value : value;
88}
89
90template<typename T>
91inline static T min(const T& a, const T& b) {
92    return a < b ? a : b;
93}
94
95template<typename T>
96inline static void swap(T& a, T& b) {
97    T temp = a;
98    a = b;
99    b = temp;
100}
101
102inline static float avg(float x, float y) {
103    return (x + y) / 2;
104}
105
106inline static float distance(float x1, float y1, float x2, float y2) {
107    return hypotf(x1 - x2, y1 - y2);
108}
109
110inline static int32_t signExtendNybble(int32_t value) {
111    return value >= 8 ? value - 16 : value;
112}
113
114static inline const char* toString(bool value) {
115    return value ? "true" : "false";
116}
117
118static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
119        const int32_t map[][4], size_t mapSize) {
120    if (orientation != DISPLAY_ORIENTATION_0) {
121        for (size_t i = 0; i < mapSize; i++) {
122            if (value == map[i][0]) {
123                return map[i][orientation];
124            }
125        }
126    }
127    return value;
128}
129
130static const int32_t keyCodeRotationMap[][4] = {
131        // key codes enumerated counter-clockwise with the original (unrotated) key first
132        // no rotation,        90 degree rotation,  180 degree rotation, 270 degree rotation
133        { AKEYCODE_DPAD_DOWN,   AKEYCODE_DPAD_RIGHT,  AKEYCODE_DPAD_UP,     AKEYCODE_DPAD_LEFT },
134        { AKEYCODE_DPAD_RIGHT,  AKEYCODE_DPAD_UP,     AKEYCODE_DPAD_LEFT,   AKEYCODE_DPAD_DOWN },
135        { AKEYCODE_DPAD_UP,     AKEYCODE_DPAD_LEFT,   AKEYCODE_DPAD_DOWN,   AKEYCODE_DPAD_RIGHT },
136        { AKEYCODE_DPAD_LEFT,   AKEYCODE_DPAD_DOWN,   AKEYCODE_DPAD_RIGHT,  AKEYCODE_DPAD_UP },
137};
138static const size_t keyCodeRotationMapSize =
139        sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
140
141static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
142    return rotateValueUsingRotationMap(keyCode, orientation,
143            keyCodeRotationMap, keyCodeRotationMapSize);
144}
145
146static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
147    float temp;
148    switch (orientation) {
149    case DISPLAY_ORIENTATION_90:
150        temp = *deltaX;
151        *deltaX = *deltaY;
152        *deltaY = -temp;
153        break;
154
155    case DISPLAY_ORIENTATION_180:
156        *deltaX = -*deltaX;
157        *deltaY = -*deltaY;
158        break;
159
160    case DISPLAY_ORIENTATION_270:
161        temp = *deltaX;
162        *deltaX = -*deltaY;
163        *deltaY = temp;
164        break;
165    }
166}
167
168static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
169    return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
170}
171
172// Returns true if the pointer should be reported as being down given the specified
173// button states.  This determines whether the event is reported as a touch event.
174static bool isPointerDown(int32_t buttonState) {
175    return buttonState &
176            (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
177                    | AMOTION_EVENT_BUTTON_TERTIARY);
178}
179
180static float calculateCommonVector(float a, float b) {
181    if (a > 0 && b > 0) {
182        return a < b ? a : b;
183    } else if (a < 0 && b < 0) {
184        return a > b ? a : b;
185    } else {
186        return 0;
187    }
188}
189
190static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
191        nsecs_t when, int32_t deviceId, uint32_t source,
192        uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
193        int32_t buttonState, int32_t keyCode) {
194    if (
195            (action == AKEY_EVENT_ACTION_DOWN
196                    && !(lastButtonState & buttonState)
197                    && (currentButtonState & buttonState))
198            || (action == AKEY_EVENT_ACTION_UP
199                    && (lastButtonState & buttonState)
200                    && !(currentButtonState & buttonState))) {
201        NotifyKeyArgs args(when, deviceId, source, policyFlags,
202                action, 0, keyCode, 0, context->getGlobalMetaState(), when);
203        context->getListener()->notifyKey(&args);
204    }
205}
206
207static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
208        nsecs_t when, int32_t deviceId, uint32_t source,
209        uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
210    synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
211            lastButtonState, currentButtonState,
212            AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
213    synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
214            lastButtonState, currentButtonState,
215            AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
216}
217
218
219// --- InputReaderConfiguration ---
220
221bool InputReaderConfiguration::getDisplayInfo(bool external, DisplayViewport* outViewport) const {
222    const DisplayViewport& viewport = external ? mExternalDisplay : mInternalDisplay;
223    if (viewport.displayId >= 0) {
224        *outViewport = viewport;
225        return true;
226    }
227    return false;
228}
229
230void InputReaderConfiguration::setDisplayInfo(bool external, const DisplayViewport& viewport) {
231    DisplayViewport& v = external ? mExternalDisplay : mInternalDisplay;
232    v = viewport;
233}
234
235
236// -- TouchAffineTransformation --
237void TouchAffineTransformation::applyTo(float& x, float& y) const {
238    float newX, newY;
239    newX = x * x_scale + y * x_ymix + x_offset;
240    newY = x * y_xmix + y * y_scale + y_offset;
241
242    x = newX;
243    y = newY;
244}
245
246
247// --- InputReader ---
248
249InputReader::InputReader(const sp<EventHubInterface>& eventHub,
250        const sp<InputReaderPolicyInterface>& policy,
251        const sp<InputListenerInterface>& listener) :
252        mContext(this), mEventHub(eventHub), mPolicy(policy),
253        mGlobalMetaState(0), mGeneration(1),
254        mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
255        mConfigurationChangesToRefresh(0) {
256    mQueuedListener = new QueuedInputListener(listener);
257
258    { // acquire lock
259        AutoMutex _l(mLock);
260
261        refreshConfigurationLocked(0);
262        updateGlobalMetaStateLocked();
263    } // release lock
264}
265
266InputReader::~InputReader() {
267    for (size_t i = 0; i < mDevices.size(); i++) {
268        delete mDevices.valueAt(i);
269    }
270}
271
272void InputReader::loopOnce() {
273    int32_t oldGeneration;
274    int32_t timeoutMillis;
275    bool inputDevicesChanged = false;
276    Vector<InputDeviceInfo> inputDevices;
277    { // acquire lock
278        AutoMutex _l(mLock);
279
280        oldGeneration = mGeneration;
281        timeoutMillis = -1;
282
283        uint32_t changes = mConfigurationChangesToRefresh;
284        if (changes) {
285            mConfigurationChangesToRefresh = 0;
286            timeoutMillis = 0;
287            refreshConfigurationLocked(changes);
288        } else if (mNextTimeout != LLONG_MAX) {
289            nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
290            timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
291        }
292    } // release lock
293
294    size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
295
296    { // acquire lock
297        AutoMutex _l(mLock);
298        mReaderIsAliveCondition.broadcast();
299
300        if (count) {
301            processEventsLocked(mEventBuffer, count);
302        }
303
304        if (mNextTimeout != LLONG_MAX) {
305            nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
306            if (now >= mNextTimeout) {
307#if DEBUG_RAW_EVENTS
308                ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
309#endif
310                mNextTimeout = LLONG_MAX;
311                timeoutExpiredLocked(now);
312            }
313        }
314
315        if (oldGeneration != mGeneration) {
316            inputDevicesChanged = true;
317            getInputDevicesLocked(inputDevices);
318        }
319    } // release lock
320
321    // Send out a message that the describes the changed input devices.
322    if (inputDevicesChanged) {
323        mPolicy->notifyInputDevicesChanged(inputDevices);
324    }
325
326    // Flush queued events out to the listener.
327    // This must happen outside of the lock because the listener could potentially call
328    // back into the InputReader's methods, such as getScanCodeState, or become blocked
329    // on another thread similarly waiting to acquire the InputReader lock thereby
330    // resulting in a deadlock.  This situation is actually quite plausible because the
331    // listener is actually the input dispatcher, which calls into the window manager,
332    // which occasionally calls into the input reader.
333    mQueuedListener->flush();
334}
335
336void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
337    for (const RawEvent* rawEvent = rawEvents; count;) {
338        int32_t type = rawEvent->type;
339        size_t batchSize = 1;
340        if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
341            int32_t deviceId = rawEvent->deviceId;
342            while (batchSize < count) {
343                if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
344                        || rawEvent[batchSize].deviceId != deviceId) {
345                    break;
346                }
347                batchSize += 1;
348            }
349#if DEBUG_RAW_EVENTS
350            ALOGD("BatchSize: %d Count: %d", batchSize, count);
351#endif
352            processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
353        } else {
354            switch (rawEvent->type) {
355            case EventHubInterface::DEVICE_ADDED:
356                addDeviceLocked(rawEvent->when, rawEvent->deviceId);
357                break;
358            case EventHubInterface::DEVICE_REMOVED:
359                removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
360                break;
361            case EventHubInterface::FINISHED_DEVICE_SCAN:
362                handleConfigurationChangedLocked(rawEvent->when);
363                break;
364            default:
365                ALOG_ASSERT(false); // can't happen
366                break;
367            }
368        }
369        count -= batchSize;
370        rawEvent += batchSize;
371    }
372}
373
374void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
375    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
376    if (deviceIndex >= 0) {
377        ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
378        return;
379    }
380
381    InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
382    uint32_t classes = mEventHub->getDeviceClasses(deviceId);
383    int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
384
385    InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
386    device->configure(when, &mConfig, 0);
387    device->reset(when);
388
389    if (device->isIgnored()) {
390        ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
391                identifier.name.string());
392    } else {
393        ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
394                identifier.name.string(), device->getSources());
395    }
396
397    mDevices.add(deviceId, device);
398    bumpGenerationLocked();
399
400    if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
401        notifyExternalStylusPresenceChanged();
402    }
403}
404
405void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
406    InputDevice* device = NULL;
407    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
408    if (deviceIndex < 0) {
409        ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
410        return;
411    }
412
413    device = mDevices.valueAt(deviceIndex);
414    mDevices.removeItemsAt(deviceIndex, 1);
415    bumpGenerationLocked();
416
417    if (device->isIgnored()) {
418        ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
419                device->getId(), device->getName().string());
420    } else {
421        ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
422                device->getId(), device->getName().string(), device->getSources());
423    }
424
425    if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
426        notifyExternalStylusPresenceChanged();
427    }
428
429    device->reset(when);
430    delete device;
431}
432
433InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
434        const InputDeviceIdentifier& identifier, uint32_t classes) {
435    InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
436            controllerNumber, identifier, classes);
437
438    // External devices.
439    if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
440        device->setExternal(true);
441    }
442
443    // Devices with mics.
444    if (classes & INPUT_DEVICE_CLASS_MIC) {
445        device->setMic(true);
446    }
447
448    // Switch-like devices.
449    if (classes & INPUT_DEVICE_CLASS_SWITCH) {
450        device->addMapper(new SwitchInputMapper(device));
451    }
452
453    // Scroll wheel-like devices.
454    if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
455        device->addMapper(new RotaryEncoderInputMapper(device));
456    }
457
458    // Vibrator-like devices.
459    if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
460        device->addMapper(new VibratorInputMapper(device));
461    }
462
463    // Keyboard-like devices.
464    uint32_t keyboardSource = 0;
465    int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
466    if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
467        keyboardSource |= AINPUT_SOURCE_KEYBOARD;
468    }
469    if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
470        keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
471    }
472    if (classes & INPUT_DEVICE_CLASS_DPAD) {
473        keyboardSource |= AINPUT_SOURCE_DPAD;
474    }
475    if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
476        keyboardSource |= AINPUT_SOURCE_GAMEPAD;
477    }
478
479    if (keyboardSource != 0) {
480        device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
481    }
482
483    // Cursor-like devices.
484    if (classes & INPUT_DEVICE_CLASS_CURSOR) {
485        device->addMapper(new CursorInputMapper(device));
486    }
487
488    // Touchscreens and touchpad devices.
489    if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
490        device->addMapper(new MultiTouchInputMapper(device));
491    } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
492        device->addMapper(new SingleTouchInputMapper(device));
493    }
494
495    // Joystick-like devices.
496    if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
497        device->addMapper(new JoystickInputMapper(device));
498    }
499
500    // External stylus-like devices.
501    if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
502        device->addMapper(new ExternalStylusInputMapper(device));
503    }
504
505    return device;
506}
507
508void InputReader::processEventsForDeviceLocked(int32_t deviceId,
509        const RawEvent* rawEvents, size_t count) {
510    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
511    if (deviceIndex < 0) {
512        ALOGW("Discarding event for unknown deviceId %d.", deviceId);
513        return;
514    }
515
516    InputDevice* device = mDevices.valueAt(deviceIndex);
517    if (device->isIgnored()) {
518        //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
519        return;
520    }
521
522    device->process(rawEvents, count);
523}
524
525void InputReader::timeoutExpiredLocked(nsecs_t when) {
526    for (size_t i = 0; i < mDevices.size(); i++) {
527        InputDevice* device = mDevices.valueAt(i);
528        if (!device->isIgnored()) {
529            device->timeoutExpired(when);
530        }
531    }
532}
533
534void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
535    // Reset global meta state because it depends on the list of all configured devices.
536    updateGlobalMetaStateLocked();
537
538    // Enqueue configuration changed.
539    NotifyConfigurationChangedArgs args(when);
540    mQueuedListener->notifyConfigurationChanged(&args);
541}
542
543void InputReader::refreshConfigurationLocked(uint32_t changes) {
544    mPolicy->getReaderConfiguration(&mConfig);
545    mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
546
547    if (changes) {
548        ALOGI("Reconfiguring input devices.  changes=0x%08x", changes);
549        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
550
551        if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
552            mEventHub->requestReopenDevices();
553        } else {
554            for (size_t i = 0; i < mDevices.size(); i++) {
555                InputDevice* device = mDevices.valueAt(i);
556                device->configure(now, &mConfig, changes);
557            }
558        }
559    }
560}
561
562void InputReader::updateGlobalMetaStateLocked() {
563    mGlobalMetaState = 0;
564
565    for (size_t i = 0; i < mDevices.size(); i++) {
566        InputDevice* device = mDevices.valueAt(i);
567        mGlobalMetaState |= device->getMetaState();
568    }
569}
570
571int32_t InputReader::getGlobalMetaStateLocked() {
572    return mGlobalMetaState;
573}
574
575void InputReader::notifyExternalStylusPresenceChanged() {
576    refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
577}
578
579void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
580    for (size_t i = 0; i < mDevices.size(); i++) {
581        InputDevice* device = mDevices.valueAt(i);
582        if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
583            outDevices.push();
584            device->getDeviceInfo(&outDevices.editTop());
585        }
586    }
587}
588
589void InputReader::dispatchExternalStylusState(const StylusState& state) {
590    for (size_t i = 0; i < mDevices.size(); i++) {
591        InputDevice* device = mDevices.valueAt(i);
592        device->updateExternalStylusState(state);
593    }
594}
595
596void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
597    mDisableVirtualKeysTimeout = time;
598}
599
600bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
601        InputDevice* device, int32_t keyCode, int32_t scanCode) {
602    if (now < mDisableVirtualKeysTimeout) {
603        ALOGI("Dropping virtual key from device %s because virtual keys are "
604                "temporarily disabled for the next %0.3fms.  keyCode=%d, scanCode=%d",
605                device->getName().string(),
606                (mDisableVirtualKeysTimeout - now) * 0.000001,
607                keyCode, scanCode);
608        return true;
609    } else {
610        return false;
611    }
612}
613
614void InputReader::fadePointerLocked() {
615    for (size_t i = 0; i < mDevices.size(); i++) {
616        InputDevice* device = mDevices.valueAt(i);
617        device->fadePointer();
618    }
619}
620
621void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
622    if (when < mNextTimeout) {
623        mNextTimeout = when;
624        mEventHub->wake();
625    }
626}
627
628int32_t InputReader::bumpGenerationLocked() {
629    return ++mGeneration;
630}
631
632void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
633    AutoMutex _l(mLock);
634    getInputDevicesLocked(outInputDevices);
635}
636
637void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
638    outInputDevices.clear();
639
640    size_t numDevices = mDevices.size();
641    for (size_t i = 0; i < numDevices; i++) {
642        InputDevice* device = mDevices.valueAt(i);
643        if (!device->isIgnored()) {
644            outInputDevices.push();
645            device->getDeviceInfo(&outInputDevices.editTop());
646        }
647    }
648}
649
650int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
651        int32_t keyCode) {
652    AutoMutex _l(mLock);
653
654    return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
655}
656
657int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
658        int32_t scanCode) {
659    AutoMutex _l(mLock);
660
661    return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
662}
663
664int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
665    AutoMutex _l(mLock);
666
667    return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
668}
669
670int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
671        GetStateFunc getStateFunc) {
672    int32_t result = AKEY_STATE_UNKNOWN;
673    if (deviceId >= 0) {
674        ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
675        if (deviceIndex >= 0) {
676            InputDevice* device = mDevices.valueAt(deviceIndex);
677            if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
678                result = (device->*getStateFunc)(sourceMask, code);
679            }
680        }
681    } else {
682        size_t numDevices = mDevices.size();
683        for (size_t i = 0; i < numDevices; i++) {
684            InputDevice* device = mDevices.valueAt(i);
685            if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
686                // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
687                // value.  Otherwise, return AKEY_STATE_UP as long as one device reports it.
688                int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
689                if (currentResult >= AKEY_STATE_DOWN) {
690                    return currentResult;
691                } else if (currentResult == AKEY_STATE_UP) {
692                    result = currentResult;
693                }
694            }
695        }
696    }
697    return result;
698}
699
700void InputReader::toggleCapsLockState(int32_t deviceId) {
701    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
702    if (deviceIndex < 0) {
703        ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
704        return;
705    }
706
707    InputDevice* device = mDevices.valueAt(deviceIndex);
708    if (device->isIgnored()) {
709        return;
710    }
711
712    device->updateMetaState(AKEYCODE_CAPS_LOCK);
713}
714
715bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
716        size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
717    AutoMutex _l(mLock);
718
719    memset(outFlags, 0, numCodes);
720    return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
721}
722
723bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
724        size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
725    bool result = false;
726    if (deviceId >= 0) {
727        ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
728        if (deviceIndex >= 0) {
729            InputDevice* device = mDevices.valueAt(deviceIndex);
730            if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
731                result = device->markSupportedKeyCodes(sourceMask,
732                        numCodes, keyCodes, outFlags);
733            }
734        }
735    } else {
736        size_t numDevices = mDevices.size();
737        for (size_t i = 0; i < numDevices; i++) {
738            InputDevice* device = mDevices.valueAt(i);
739            if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
740                result |= device->markSupportedKeyCodes(sourceMask,
741                        numCodes, keyCodes, outFlags);
742            }
743        }
744    }
745    return result;
746}
747
748void InputReader::requestRefreshConfiguration(uint32_t changes) {
749    AutoMutex _l(mLock);
750
751    if (changes) {
752        bool needWake = !mConfigurationChangesToRefresh;
753        mConfigurationChangesToRefresh |= changes;
754
755        if (needWake) {
756            mEventHub->wake();
757        }
758    }
759}
760
761void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
762        ssize_t repeat, int32_t token) {
763    AutoMutex _l(mLock);
764
765    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
766    if (deviceIndex >= 0) {
767        InputDevice* device = mDevices.valueAt(deviceIndex);
768        device->vibrate(pattern, patternSize, repeat, token);
769    }
770}
771
772void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
773    AutoMutex _l(mLock);
774
775    ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
776    if (deviceIndex >= 0) {
777        InputDevice* device = mDevices.valueAt(deviceIndex);
778        device->cancelVibrate(token);
779    }
780}
781
782void InputReader::dump(String8& dump) {
783    AutoMutex _l(mLock);
784
785    mEventHub->dump(dump);
786    dump.append("\n");
787
788    dump.append("Input Reader State:\n");
789
790    for (size_t i = 0; i < mDevices.size(); i++) {
791        mDevices.valueAt(i)->dump(dump);
792    }
793
794    dump.append(INDENT "Configuration:\n");
795    dump.append(INDENT2 "ExcludedDeviceNames: [");
796    for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
797        if (i != 0) {
798            dump.append(", ");
799        }
800        dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
801    }
802    dump.append("]\n");
803    dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
804            mConfig.virtualKeyQuietTime * 0.000001f);
805
806    dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
807            "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
808            mConfig.pointerVelocityControlParameters.scale,
809            mConfig.pointerVelocityControlParameters.lowThreshold,
810            mConfig.pointerVelocityControlParameters.highThreshold,
811            mConfig.pointerVelocityControlParameters.acceleration);
812
813    dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
814            "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
815            mConfig.wheelVelocityControlParameters.scale,
816            mConfig.wheelVelocityControlParameters.lowThreshold,
817            mConfig.wheelVelocityControlParameters.highThreshold,
818            mConfig.wheelVelocityControlParameters.acceleration);
819
820    dump.appendFormat(INDENT2 "PointerGesture:\n");
821    dump.appendFormat(INDENT3 "Enabled: %s\n",
822            toString(mConfig.pointerGesturesEnabled));
823    dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
824            mConfig.pointerGestureQuietInterval * 0.000001f);
825    dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
826            mConfig.pointerGestureDragMinSwitchSpeed);
827    dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
828            mConfig.pointerGestureTapInterval * 0.000001f);
829    dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
830            mConfig.pointerGestureTapDragInterval * 0.000001f);
831    dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
832            mConfig.pointerGestureTapSlop);
833    dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
834            mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
835    dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
836            mConfig.pointerGestureMultitouchMinDistance);
837    dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
838            mConfig.pointerGestureSwipeTransitionAngleCosine);
839    dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
840            mConfig.pointerGestureSwipeMaxWidthRatio);
841    dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
842            mConfig.pointerGestureMovementSpeedRatio);
843    dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
844            mConfig.pointerGestureZoomSpeedRatio);
845}
846
847void InputReader::monitor() {
848    // Acquire and release the lock to ensure that the reader has not deadlocked.
849    mLock.lock();
850    mEventHub->wake();
851    mReaderIsAliveCondition.wait(mLock);
852    mLock.unlock();
853
854    // Check the EventHub
855    mEventHub->monitor();
856}
857
858
859// --- InputReader::ContextImpl ---
860
861InputReader::ContextImpl::ContextImpl(InputReader* reader) :
862        mReader(reader) {
863}
864
865void InputReader::ContextImpl::updateGlobalMetaState() {
866    // lock is already held by the input loop
867    mReader->updateGlobalMetaStateLocked();
868}
869
870int32_t InputReader::ContextImpl::getGlobalMetaState() {
871    // lock is already held by the input loop
872    return mReader->getGlobalMetaStateLocked();
873}
874
875void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
876    // lock is already held by the input loop
877    mReader->disableVirtualKeysUntilLocked(time);
878}
879
880bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
881        InputDevice* device, int32_t keyCode, int32_t scanCode) {
882    // lock is already held by the input loop
883    return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
884}
885
886void InputReader::ContextImpl::fadePointer() {
887    // lock is already held by the input loop
888    mReader->fadePointerLocked();
889}
890
891void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
892    // lock is already held by the input loop
893    mReader->requestTimeoutAtTimeLocked(when);
894}
895
896int32_t InputReader::ContextImpl::bumpGeneration() {
897    // lock is already held by the input loop
898    return mReader->bumpGenerationLocked();
899}
900
901void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
902    // lock is already held by whatever called refreshConfigurationLocked
903    mReader->getExternalStylusDevicesLocked(outDevices);
904}
905
906void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
907    mReader->dispatchExternalStylusState(state);
908}
909
910InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
911    return mReader->mPolicy.get();
912}
913
914InputListenerInterface* InputReader::ContextImpl::getListener() {
915    return mReader->mQueuedListener.get();
916}
917
918EventHubInterface* InputReader::ContextImpl::getEventHub() {
919    return mReader->mEventHub.get();
920}
921
922
923// --- InputReaderThread ---
924
925InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
926        Thread(/*canCallJava*/ true), mReader(reader) {
927}
928
929InputReaderThread::~InputReaderThread() {
930}
931
932bool InputReaderThread::threadLoop() {
933    mReader->loopOnce();
934    return true;
935}
936
937
938// --- InputDevice ---
939
940InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
941        int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
942        mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
943        mIdentifier(identifier), mClasses(classes),
944        mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
945}
946
947InputDevice::~InputDevice() {
948    size_t numMappers = mMappers.size();
949    for (size_t i = 0; i < numMappers; i++) {
950        delete mMappers[i];
951    }
952    mMappers.clear();
953}
954
955void InputDevice::dump(String8& dump) {
956    InputDeviceInfo deviceInfo;
957    getDeviceInfo(& deviceInfo);
958
959    dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
960            deviceInfo.getDisplayName().string());
961    dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
962    dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
963    dump.appendFormat(INDENT2 "HasMic:     %s\n", toString(mHasMic));
964    dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
965    dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
966
967    const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
968    if (!ranges.isEmpty()) {
969        dump.append(INDENT2 "Motion Ranges:\n");
970        for (size_t i = 0; i < ranges.size(); i++) {
971            const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
972            const char* label = getAxisLabel(range.axis);
973            char name[32];
974            if (label) {
975                strncpy(name, label, sizeof(name));
976                name[sizeof(name) - 1] = '\0';
977            } else {
978                snprintf(name, sizeof(name), "%d", range.axis);
979            }
980            dump.appendFormat(INDENT3 "%s: source=0x%08x, "
981                    "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
982                    name, range.source, range.min, range.max, range.flat, range.fuzz,
983                    range.resolution);
984        }
985    }
986
987    size_t numMappers = mMappers.size();
988    for (size_t i = 0; i < numMappers; i++) {
989        InputMapper* mapper = mMappers[i];
990        mapper->dump(dump);
991    }
992}
993
994void InputDevice::addMapper(InputMapper* mapper) {
995    mMappers.add(mapper);
996}
997
998void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
999    mSources = 0;
1000
1001    if (!isIgnored()) {
1002        if (!changes) { // first time only
1003            mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1004        }
1005
1006        if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1007            if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1008                sp<KeyCharacterMap> keyboardLayout =
1009                        mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1010                if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1011                    bumpGeneration();
1012                }
1013            }
1014        }
1015
1016        if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1017            if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1018                String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
1019                if (mAlias != alias) {
1020                    mAlias = alias;
1021                    bumpGeneration();
1022                }
1023            }
1024        }
1025
1026        size_t numMappers = mMappers.size();
1027        for (size_t i = 0; i < numMappers; i++) {
1028            InputMapper* mapper = mMappers[i];
1029            mapper->configure(when, config, changes);
1030            mSources |= mapper->getSources();
1031        }
1032    }
1033}
1034
1035void InputDevice::reset(nsecs_t when) {
1036    size_t numMappers = mMappers.size();
1037    for (size_t i = 0; i < numMappers; i++) {
1038        InputMapper* mapper = mMappers[i];
1039        mapper->reset(when);
1040    }
1041
1042    mContext->updateGlobalMetaState();
1043
1044    notifyReset(when);
1045}
1046
1047void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1048    // Process all of the events in order for each mapper.
1049    // We cannot simply ask each mapper to process them in bulk because mappers may
1050    // have side-effects that must be interleaved.  For example, joystick movement events and
1051    // gamepad button presses are handled by different mappers but they should be dispatched
1052    // in the order received.
1053    size_t numMappers = mMappers.size();
1054    for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
1055#if DEBUG_RAW_EVENTS
1056        ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
1057                rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1058                rawEvent->when);
1059#endif
1060
1061        if (mDropUntilNextSync) {
1062            if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1063                mDropUntilNextSync = false;
1064#if DEBUG_RAW_EVENTS
1065                ALOGD("Recovered from input event buffer overrun.");
1066#endif
1067            } else {
1068#if DEBUG_RAW_EVENTS
1069                ALOGD("Dropped input event while waiting for next input sync.");
1070#endif
1071            }
1072        } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
1073            ALOGI("Detected input event buffer overrun for device %s.", getName().string());
1074            mDropUntilNextSync = true;
1075            reset(rawEvent->when);
1076        } else {
1077            for (size_t i = 0; i < numMappers; i++) {
1078                InputMapper* mapper = mMappers[i];
1079                mapper->process(rawEvent);
1080            }
1081        }
1082    }
1083}
1084
1085void InputDevice::timeoutExpired(nsecs_t when) {
1086    size_t numMappers = mMappers.size();
1087    for (size_t i = 0; i < numMappers; i++) {
1088        InputMapper* mapper = mMappers[i];
1089        mapper->timeoutExpired(when);
1090    }
1091}
1092
1093void InputDevice::updateExternalStylusState(const StylusState& state) {
1094    size_t numMappers = mMappers.size();
1095    for (size_t i = 0; i < numMappers; i++) {
1096        InputMapper* mapper = mMappers[i];
1097        mapper->updateExternalStylusState(state);
1098    }
1099}
1100
1101void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1102    outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
1103            mIsExternal, mHasMic);
1104    size_t numMappers = mMappers.size();
1105    for (size_t i = 0; i < numMappers; i++) {
1106        InputMapper* mapper = mMappers[i];
1107        mapper->populateDeviceInfo(outDeviceInfo);
1108    }
1109}
1110
1111int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1112    return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1113}
1114
1115int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1116    return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1117}
1118
1119int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1120    return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1121}
1122
1123int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1124    int32_t result = AKEY_STATE_UNKNOWN;
1125    size_t numMappers = mMappers.size();
1126    for (size_t i = 0; i < numMappers; i++) {
1127        InputMapper* mapper = mMappers[i];
1128        if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1129            // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1130            // value.  Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1131            int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1132            if (currentResult >= AKEY_STATE_DOWN) {
1133                return currentResult;
1134            } else if (currentResult == AKEY_STATE_UP) {
1135                result = currentResult;
1136            }
1137        }
1138    }
1139    return result;
1140}
1141
1142bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1143        const int32_t* keyCodes, uint8_t* outFlags) {
1144    bool result = false;
1145    size_t numMappers = mMappers.size();
1146    for (size_t i = 0; i < numMappers; i++) {
1147        InputMapper* mapper = mMappers[i];
1148        if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1149            result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1150        }
1151    }
1152    return result;
1153}
1154
1155void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1156        int32_t token) {
1157    size_t numMappers = mMappers.size();
1158    for (size_t i = 0; i < numMappers; i++) {
1159        InputMapper* mapper = mMappers[i];
1160        mapper->vibrate(pattern, patternSize, repeat, token);
1161    }
1162}
1163
1164void InputDevice::cancelVibrate(int32_t token) {
1165    size_t numMappers = mMappers.size();
1166    for (size_t i = 0; i < numMappers; i++) {
1167        InputMapper* mapper = mMappers[i];
1168        mapper->cancelVibrate(token);
1169    }
1170}
1171
1172void InputDevice::cancelTouch(nsecs_t when) {
1173    size_t numMappers = mMappers.size();
1174    for (size_t i = 0; i < numMappers; i++) {
1175        InputMapper* mapper = mMappers[i];
1176        mapper->cancelTouch(when);
1177    }
1178}
1179
1180int32_t InputDevice::getMetaState() {
1181    int32_t result = 0;
1182    size_t numMappers = mMappers.size();
1183    for (size_t i = 0; i < numMappers; i++) {
1184        InputMapper* mapper = mMappers[i];
1185        result |= mapper->getMetaState();
1186    }
1187    return result;
1188}
1189
1190void InputDevice::updateMetaState(int32_t keyCode) {
1191    size_t numMappers = mMappers.size();
1192    for (size_t i = 0; i < numMappers; i++) {
1193        mMappers[i]->updateMetaState(keyCode);
1194    }
1195}
1196
1197void InputDevice::fadePointer() {
1198    size_t numMappers = mMappers.size();
1199    for (size_t i = 0; i < numMappers; i++) {
1200        InputMapper* mapper = mMappers[i];
1201        mapper->fadePointer();
1202    }
1203}
1204
1205void InputDevice::bumpGeneration() {
1206    mGeneration = mContext->bumpGeneration();
1207}
1208
1209void InputDevice::notifyReset(nsecs_t when) {
1210    NotifyDeviceResetArgs args(when, mId);
1211    mContext->getListener()->notifyDeviceReset(&args);
1212}
1213
1214
1215// --- CursorButtonAccumulator ---
1216
1217CursorButtonAccumulator::CursorButtonAccumulator() {
1218    clearButtons();
1219}
1220
1221void CursorButtonAccumulator::reset(InputDevice* device) {
1222    mBtnLeft = device->isKeyPressed(BTN_LEFT);
1223    mBtnRight = device->isKeyPressed(BTN_RIGHT);
1224    mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1225    mBtnBack = device->isKeyPressed(BTN_BACK);
1226    mBtnSide = device->isKeyPressed(BTN_SIDE);
1227    mBtnForward = device->isKeyPressed(BTN_FORWARD);
1228    mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1229    mBtnTask = device->isKeyPressed(BTN_TASK);
1230}
1231
1232void CursorButtonAccumulator::clearButtons() {
1233    mBtnLeft = 0;
1234    mBtnRight = 0;
1235    mBtnMiddle = 0;
1236    mBtnBack = 0;
1237    mBtnSide = 0;
1238    mBtnForward = 0;
1239    mBtnExtra = 0;
1240    mBtnTask = 0;
1241}
1242
1243void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1244    if (rawEvent->type == EV_KEY) {
1245        switch (rawEvent->code) {
1246        case BTN_LEFT:
1247            mBtnLeft = rawEvent->value;
1248            break;
1249        case BTN_RIGHT:
1250            mBtnRight = rawEvent->value;
1251            break;
1252        case BTN_MIDDLE:
1253            mBtnMiddle = rawEvent->value;
1254            break;
1255        case BTN_BACK:
1256            mBtnBack = rawEvent->value;
1257            break;
1258        case BTN_SIDE:
1259            mBtnSide = rawEvent->value;
1260            break;
1261        case BTN_FORWARD:
1262            mBtnForward = rawEvent->value;
1263            break;
1264        case BTN_EXTRA:
1265            mBtnExtra = rawEvent->value;
1266            break;
1267        case BTN_TASK:
1268            mBtnTask = rawEvent->value;
1269            break;
1270        }
1271    }
1272}
1273
1274uint32_t CursorButtonAccumulator::getButtonState() const {
1275    uint32_t result = 0;
1276    if (mBtnLeft) {
1277        result |= AMOTION_EVENT_BUTTON_PRIMARY;
1278    }
1279    if (mBtnRight) {
1280        result |= AMOTION_EVENT_BUTTON_SECONDARY;
1281    }
1282    if (mBtnMiddle) {
1283        result |= AMOTION_EVENT_BUTTON_TERTIARY;
1284    }
1285    if (mBtnBack || mBtnSide) {
1286        result |= AMOTION_EVENT_BUTTON_BACK;
1287    }
1288    if (mBtnForward || mBtnExtra) {
1289        result |= AMOTION_EVENT_BUTTON_FORWARD;
1290    }
1291    return result;
1292}
1293
1294
1295// --- CursorMotionAccumulator ---
1296
1297CursorMotionAccumulator::CursorMotionAccumulator() {
1298    clearRelativeAxes();
1299}
1300
1301void CursorMotionAccumulator::reset(InputDevice* device) {
1302    clearRelativeAxes();
1303}
1304
1305void CursorMotionAccumulator::clearRelativeAxes() {
1306    mRelX = 0;
1307    mRelY = 0;
1308}
1309
1310void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1311    if (rawEvent->type == EV_REL) {
1312        switch (rawEvent->code) {
1313        case REL_X:
1314            mRelX = rawEvent->value;
1315            break;
1316        case REL_Y:
1317            mRelY = rawEvent->value;
1318            break;
1319        }
1320    }
1321}
1322
1323void CursorMotionAccumulator::finishSync() {
1324    clearRelativeAxes();
1325}
1326
1327
1328// --- CursorScrollAccumulator ---
1329
1330CursorScrollAccumulator::CursorScrollAccumulator() :
1331        mHaveRelWheel(false), mHaveRelHWheel(false) {
1332    clearRelativeAxes();
1333}
1334
1335void CursorScrollAccumulator::configure(InputDevice* device) {
1336    mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1337    mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1338}
1339
1340void CursorScrollAccumulator::reset(InputDevice* device) {
1341    clearRelativeAxes();
1342}
1343
1344void CursorScrollAccumulator::clearRelativeAxes() {
1345    mRelWheel = 0;
1346    mRelHWheel = 0;
1347}
1348
1349void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1350    if (rawEvent->type == EV_REL) {
1351        switch (rawEvent->code) {
1352        case REL_WHEEL:
1353            mRelWheel = rawEvent->value;
1354            break;
1355        case REL_HWHEEL:
1356            mRelHWheel = rawEvent->value;
1357            break;
1358        }
1359    }
1360}
1361
1362void CursorScrollAccumulator::finishSync() {
1363    clearRelativeAxes();
1364}
1365
1366
1367// --- TouchButtonAccumulator ---
1368
1369TouchButtonAccumulator::TouchButtonAccumulator() :
1370        mHaveBtnTouch(false), mHaveStylus(false) {
1371    clearButtons();
1372}
1373
1374void TouchButtonAccumulator::configure(InputDevice* device) {
1375    mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1376    mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1377            || device->hasKey(BTN_TOOL_RUBBER)
1378            || device->hasKey(BTN_TOOL_BRUSH)
1379            || device->hasKey(BTN_TOOL_PENCIL)
1380            || device->hasKey(BTN_TOOL_AIRBRUSH);
1381}
1382
1383void TouchButtonAccumulator::reset(InputDevice* device) {
1384    mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1385    mBtnStylus = device->isKeyPressed(BTN_STYLUS);
1386    // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1387    mBtnStylus2 =
1388            device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
1389    mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1390    mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1391    mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1392    mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1393    mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1394    mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1395    mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1396    mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1397    mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1398    mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1399    mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1400}
1401
1402void TouchButtonAccumulator::clearButtons() {
1403    mBtnTouch = 0;
1404    mBtnStylus = 0;
1405    mBtnStylus2 = 0;
1406    mBtnToolFinger = 0;
1407    mBtnToolPen = 0;
1408    mBtnToolRubber = 0;
1409    mBtnToolBrush = 0;
1410    mBtnToolPencil = 0;
1411    mBtnToolAirbrush = 0;
1412    mBtnToolMouse = 0;
1413    mBtnToolLens = 0;
1414    mBtnToolDoubleTap = 0;
1415    mBtnToolTripleTap = 0;
1416    mBtnToolQuadTap = 0;
1417}
1418
1419void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1420    if (rawEvent->type == EV_KEY) {
1421        switch (rawEvent->code) {
1422        case BTN_TOUCH:
1423            mBtnTouch = rawEvent->value;
1424            break;
1425        case BTN_STYLUS:
1426            mBtnStylus = rawEvent->value;
1427            break;
1428        case BTN_STYLUS2:
1429        case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1430            mBtnStylus2 = rawEvent->value;
1431            break;
1432        case BTN_TOOL_FINGER:
1433            mBtnToolFinger = rawEvent->value;
1434            break;
1435        case BTN_TOOL_PEN:
1436            mBtnToolPen = rawEvent->value;
1437            break;
1438        case BTN_TOOL_RUBBER:
1439            mBtnToolRubber = rawEvent->value;
1440            break;
1441        case BTN_TOOL_BRUSH:
1442            mBtnToolBrush = rawEvent->value;
1443            break;
1444        case BTN_TOOL_PENCIL:
1445            mBtnToolPencil = rawEvent->value;
1446            break;
1447        case BTN_TOOL_AIRBRUSH:
1448            mBtnToolAirbrush = rawEvent->value;
1449            break;
1450        case BTN_TOOL_MOUSE:
1451            mBtnToolMouse = rawEvent->value;
1452            break;
1453        case BTN_TOOL_LENS:
1454            mBtnToolLens = rawEvent->value;
1455            break;
1456        case BTN_TOOL_DOUBLETAP:
1457            mBtnToolDoubleTap = rawEvent->value;
1458            break;
1459        case BTN_TOOL_TRIPLETAP:
1460            mBtnToolTripleTap = rawEvent->value;
1461            break;
1462        case BTN_TOOL_QUADTAP:
1463            mBtnToolQuadTap = rawEvent->value;
1464            break;
1465        }
1466    }
1467}
1468
1469uint32_t TouchButtonAccumulator::getButtonState() const {
1470    uint32_t result = 0;
1471    if (mBtnStylus) {
1472        result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
1473    }
1474    if (mBtnStylus2) {
1475        result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
1476    }
1477    return result;
1478}
1479
1480int32_t TouchButtonAccumulator::getToolType() const {
1481    if (mBtnToolMouse || mBtnToolLens) {
1482        return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1483    }
1484    if (mBtnToolRubber) {
1485        return AMOTION_EVENT_TOOL_TYPE_ERASER;
1486    }
1487    if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1488        return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1489    }
1490    if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1491        return AMOTION_EVENT_TOOL_TYPE_FINGER;
1492    }
1493    return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1494}
1495
1496bool TouchButtonAccumulator::isToolActive() const {
1497    return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1498            || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1499            || mBtnToolMouse || mBtnToolLens
1500            || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1501}
1502
1503bool TouchButtonAccumulator::isHovering() const {
1504    return mHaveBtnTouch && !mBtnTouch;
1505}
1506
1507bool TouchButtonAccumulator::hasStylus() const {
1508    return mHaveStylus;
1509}
1510
1511
1512// --- RawPointerAxes ---
1513
1514RawPointerAxes::RawPointerAxes() {
1515    clear();
1516}
1517
1518void RawPointerAxes::clear() {
1519    x.clear();
1520    y.clear();
1521    pressure.clear();
1522    touchMajor.clear();
1523    touchMinor.clear();
1524    toolMajor.clear();
1525    toolMinor.clear();
1526    orientation.clear();
1527    distance.clear();
1528    tiltX.clear();
1529    tiltY.clear();
1530    trackingId.clear();
1531    slot.clear();
1532}
1533
1534
1535// --- RawPointerData ---
1536
1537RawPointerData::RawPointerData() {
1538    clear();
1539}
1540
1541void RawPointerData::clear() {
1542    pointerCount = 0;
1543    clearIdBits();
1544}
1545
1546void RawPointerData::copyFrom(const RawPointerData& other) {
1547    pointerCount = other.pointerCount;
1548    hoveringIdBits = other.hoveringIdBits;
1549    touchingIdBits = other.touchingIdBits;
1550
1551    for (uint32_t i = 0; i < pointerCount; i++) {
1552        pointers[i] = other.pointers[i];
1553
1554        int id = pointers[i].id;
1555        idToIndex[id] = other.idToIndex[id];
1556    }
1557}
1558
1559void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1560    float x = 0, y = 0;
1561    uint32_t count = touchingIdBits.count();
1562    if (count) {
1563        for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1564            uint32_t id = idBits.clearFirstMarkedBit();
1565            const Pointer& pointer = pointerForId(id);
1566            x += pointer.x;
1567            y += pointer.y;
1568        }
1569        x /= count;
1570        y /= count;
1571    }
1572    *outX = x;
1573    *outY = y;
1574}
1575
1576
1577// --- CookedPointerData ---
1578
1579CookedPointerData::CookedPointerData() {
1580    clear();
1581}
1582
1583void CookedPointerData::clear() {
1584    pointerCount = 0;
1585    hoveringIdBits.clear();
1586    touchingIdBits.clear();
1587}
1588
1589void CookedPointerData::copyFrom(const CookedPointerData& other) {
1590    pointerCount = other.pointerCount;
1591    hoveringIdBits = other.hoveringIdBits;
1592    touchingIdBits = other.touchingIdBits;
1593
1594    for (uint32_t i = 0; i < pointerCount; i++) {
1595        pointerProperties[i].copyFrom(other.pointerProperties[i]);
1596        pointerCoords[i].copyFrom(other.pointerCoords[i]);
1597
1598        int id = pointerProperties[i].id;
1599        idToIndex[id] = other.idToIndex[id];
1600    }
1601}
1602
1603
1604// --- SingleTouchMotionAccumulator ---
1605
1606SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1607    clearAbsoluteAxes();
1608}
1609
1610void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1611    mAbsX = device->getAbsoluteAxisValue(ABS_X);
1612    mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1613    mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1614    mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1615    mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1616    mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1617    mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1618}
1619
1620void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1621    mAbsX = 0;
1622    mAbsY = 0;
1623    mAbsPressure = 0;
1624    mAbsToolWidth = 0;
1625    mAbsDistance = 0;
1626    mAbsTiltX = 0;
1627    mAbsTiltY = 0;
1628}
1629
1630void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1631    if (rawEvent->type == EV_ABS) {
1632        switch (rawEvent->code) {
1633        case ABS_X:
1634            mAbsX = rawEvent->value;
1635            break;
1636        case ABS_Y:
1637            mAbsY = rawEvent->value;
1638            break;
1639        case ABS_PRESSURE:
1640            mAbsPressure = rawEvent->value;
1641            break;
1642        case ABS_TOOL_WIDTH:
1643            mAbsToolWidth = rawEvent->value;
1644            break;
1645        case ABS_DISTANCE:
1646            mAbsDistance = rawEvent->value;
1647            break;
1648        case ABS_TILT_X:
1649            mAbsTiltX = rawEvent->value;
1650            break;
1651        case ABS_TILT_Y:
1652            mAbsTiltY = rawEvent->value;
1653            break;
1654        }
1655    }
1656}
1657
1658
1659// --- MultiTouchMotionAccumulator ---
1660
1661MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1662        mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1663        mHaveStylus(false) {
1664}
1665
1666MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1667    delete[] mSlots;
1668}
1669
1670void MultiTouchMotionAccumulator::configure(InputDevice* device,
1671        size_t slotCount, bool usingSlotsProtocol) {
1672    mSlotCount = slotCount;
1673    mUsingSlotsProtocol = usingSlotsProtocol;
1674    mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1675
1676    delete[] mSlots;
1677    mSlots = new Slot[slotCount];
1678}
1679
1680void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1681    // Unfortunately there is no way to read the initial contents of the slots.
1682    // So when we reset the accumulator, we must assume they are all zeroes.
1683    if (mUsingSlotsProtocol) {
1684        // Query the driver for the current slot index and use it as the initial slot
1685        // before we start reading events from the device.  It is possible that the
1686        // current slot index will not be the same as it was when the first event was
1687        // written into the evdev buffer, which means the input mapper could start
1688        // out of sync with the initial state of the events in the evdev buffer.
1689        // In the extremely unlikely case that this happens, the data from
1690        // two slots will be confused until the next ABS_MT_SLOT event is received.
1691        // This can cause the touch point to "jump", but at least there will be
1692        // no stuck touches.
1693        int32_t initialSlot;
1694        status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1695                ABS_MT_SLOT, &initialSlot);
1696        if (status) {
1697            ALOGD("Could not retrieve current multitouch slot index.  status=%d", status);
1698            initialSlot = -1;
1699        }
1700        clearSlots(initialSlot);
1701    } else {
1702        clearSlots(-1);
1703    }
1704}
1705
1706void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1707    if (mSlots) {
1708        for (size_t i = 0; i < mSlotCount; i++) {
1709            mSlots[i].clear();
1710        }
1711    }
1712    mCurrentSlot = initialSlot;
1713}
1714
1715void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1716    if (rawEvent->type == EV_ABS) {
1717        bool newSlot = false;
1718        if (mUsingSlotsProtocol) {
1719            if (rawEvent->code == ABS_MT_SLOT) {
1720                mCurrentSlot = rawEvent->value;
1721                newSlot = true;
1722            }
1723        } else if (mCurrentSlot < 0) {
1724            mCurrentSlot = 0;
1725        }
1726
1727        if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1728#if DEBUG_POINTERS
1729            if (newSlot) {
1730                ALOGW("MultiTouch device emitted invalid slot index %d but it "
1731                        "should be between 0 and %d; ignoring this slot.",
1732                        mCurrentSlot, mSlotCount - 1);
1733            }
1734#endif
1735        } else {
1736            Slot* slot = &mSlots[mCurrentSlot];
1737
1738            switch (rawEvent->code) {
1739            case ABS_MT_POSITION_X:
1740                slot->mInUse = true;
1741                slot->mAbsMTPositionX = rawEvent->value;
1742                break;
1743            case ABS_MT_POSITION_Y:
1744                slot->mInUse = true;
1745                slot->mAbsMTPositionY = rawEvent->value;
1746                break;
1747            case ABS_MT_TOUCH_MAJOR:
1748                slot->mInUse = true;
1749                slot->mAbsMTTouchMajor = rawEvent->value;
1750                break;
1751            case ABS_MT_TOUCH_MINOR:
1752                slot->mInUse = true;
1753                slot->mAbsMTTouchMinor = rawEvent->value;
1754                slot->mHaveAbsMTTouchMinor = true;
1755                break;
1756            case ABS_MT_WIDTH_MAJOR:
1757                slot->mInUse = true;
1758                slot->mAbsMTWidthMajor = rawEvent->value;
1759                break;
1760            case ABS_MT_WIDTH_MINOR:
1761                slot->mInUse = true;
1762                slot->mAbsMTWidthMinor = rawEvent->value;
1763                slot->mHaveAbsMTWidthMinor = true;
1764                break;
1765            case ABS_MT_ORIENTATION:
1766                slot->mInUse = true;
1767                slot->mAbsMTOrientation = rawEvent->value;
1768                break;
1769            case ABS_MT_TRACKING_ID:
1770                if (mUsingSlotsProtocol && rawEvent->value < 0) {
1771                    // The slot is no longer in use but it retains its previous contents,
1772                    // which may be reused for subsequent touches.
1773                    slot->mInUse = false;
1774                } else {
1775                    slot->mInUse = true;
1776                    slot->mAbsMTTrackingId = rawEvent->value;
1777                }
1778                break;
1779            case ABS_MT_PRESSURE:
1780                slot->mInUse = true;
1781                slot->mAbsMTPressure = rawEvent->value;
1782                break;
1783            case ABS_MT_DISTANCE:
1784                slot->mInUse = true;
1785                slot->mAbsMTDistance = rawEvent->value;
1786                break;
1787            case ABS_MT_TOOL_TYPE:
1788                slot->mInUse = true;
1789                slot->mAbsMTToolType = rawEvent->value;
1790                slot->mHaveAbsMTToolType = true;
1791                break;
1792            }
1793        }
1794    } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1795        // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1796        mCurrentSlot += 1;
1797    }
1798}
1799
1800void MultiTouchMotionAccumulator::finishSync() {
1801    if (!mUsingSlotsProtocol) {
1802        clearSlots(-1);
1803    }
1804}
1805
1806bool MultiTouchMotionAccumulator::hasStylus() const {
1807    return mHaveStylus;
1808}
1809
1810
1811// --- MultiTouchMotionAccumulator::Slot ---
1812
1813MultiTouchMotionAccumulator::Slot::Slot() {
1814    clear();
1815}
1816
1817void MultiTouchMotionAccumulator::Slot::clear() {
1818    mInUse = false;
1819    mHaveAbsMTTouchMinor = false;
1820    mHaveAbsMTWidthMinor = false;
1821    mHaveAbsMTToolType = false;
1822    mAbsMTPositionX = 0;
1823    mAbsMTPositionY = 0;
1824    mAbsMTTouchMajor = 0;
1825    mAbsMTTouchMinor = 0;
1826    mAbsMTWidthMajor = 0;
1827    mAbsMTWidthMinor = 0;
1828    mAbsMTOrientation = 0;
1829    mAbsMTTrackingId = -1;
1830    mAbsMTPressure = 0;
1831    mAbsMTDistance = 0;
1832    mAbsMTToolType = 0;
1833}
1834
1835int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1836    if (mHaveAbsMTToolType) {
1837        switch (mAbsMTToolType) {
1838        case MT_TOOL_FINGER:
1839            return AMOTION_EVENT_TOOL_TYPE_FINGER;
1840        case MT_TOOL_PEN:
1841            return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1842        }
1843    }
1844    return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1845}
1846
1847
1848// --- InputMapper ---
1849
1850InputMapper::InputMapper(InputDevice* device) :
1851        mDevice(device), mContext(device->getContext()) {
1852}
1853
1854InputMapper::~InputMapper() {
1855}
1856
1857void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1858    info->addSource(getSources());
1859}
1860
1861void InputMapper::dump(String8& dump) {
1862}
1863
1864void InputMapper::configure(nsecs_t when,
1865        const InputReaderConfiguration* config, uint32_t changes) {
1866}
1867
1868void InputMapper::reset(nsecs_t when) {
1869}
1870
1871void InputMapper::timeoutExpired(nsecs_t when) {
1872}
1873
1874int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1875    return AKEY_STATE_UNKNOWN;
1876}
1877
1878int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1879    return AKEY_STATE_UNKNOWN;
1880}
1881
1882int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1883    return AKEY_STATE_UNKNOWN;
1884}
1885
1886bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1887        const int32_t* keyCodes, uint8_t* outFlags) {
1888    return false;
1889}
1890
1891void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1892        int32_t token) {
1893}
1894
1895void InputMapper::cancelVibrate(int32_t token) {
1896}
1897
1898void InputMapper::cancelTouch(nsecs_t when) {
1899}
1900
1901int32_t InputMapper::getMetaState() {
1902    return 0;
1903}
1904
1905void InputMapper::updateMetaState(int32_t keyCode) {
1906}
1907
1908void InputMapper::updateExternalStylusState(const StylusState& state) {
1909
1910}
1911
1912void InputMapper::fadePointer() {
1913}
1914
1915status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1916    return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1917}
1918
1919void InputMapper::bumpGeneration() {
1920    mDevice->bumpGeneration();
1921}
1922
1923void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
1924        const RawAbsoluteAxisInfo& axis, const char* name) {
1925    if (axis.valid) {
1926        dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
1927                name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1928    } else {
1929        dump.appendFormat(INDENT4 "%s: unknown range\n", name);
1930    }
1931}
1932
1933void InputMapper::dumpStylusState(String8& dump, const StylusState& state) {
1934    dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when);
1935    dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure);
1936    dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons);
1937    dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
1938}
1939
1940// --- SwitchInputMapper ---
1941
1942SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
1943        InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
1944}
1945
1946SwitchInputMapper::~SwitchInputMapper() {
1947}
1948
1949uint32_t SwitchInputMapper::getSources() {
1950    return AINPUT_SOURCE_SWITCH;
1951}
1952
1953void SwitchInputMapper::process(const RawEvent* rawEvent) {
1954    switch (rawEvent->type) {
1955    case EV_SW:
1956        processSwitch(rawEvent->code, rawEvent->value);
1957        break;
1958
1959    case EV_SYN:
1960        if (rawEvent->code == SYN_REPORT) {
1961            sync(rawEvent->when);
1962        }
1963    }
1964}
1965
1966void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
1967    if (switchCode >= 0 && switchCode < 32) {
1968        if (switchValue) {
1969            mSwitchValues |= 1 << switchCode;
1970        } else {
1971            mSwitchValues &= ~(1 << switchCode);
1972        }
1973        mUpdatedSwitchMask |= 1 << switchCode;
1974    }
1975}
1976
1977void SwitchInputMapper::sync(nsecs_t when) {
1978    if (mUpdatedSwitchMask) {
1979        uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
1980        NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
1981        getListener()->notifySwitch(&args);
1982
1983        mUpdatedSwitchMask = 0;
1984    }
1985}
1986
1987int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1988    return getEventHub()->getSwitchState(getDeviceId(), switchCode);
1989}
1990
1991void SwitchInputMapper::dump(String8& dump) {
1992    dump.append(INDENT2 "Switch Input Mapper:\n");
1993    dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
1994}
1995
1996// --- VibratorInputMapper ---
1997
1998VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
1999        InputMapper(device), mVibrating(false) {
2000}
2001
2002VibratorInputMapper::~VibratorInputMapper() {
2003}
2004
2005uint32_t VibratorInputMapper::getSources() {
2006    return 0;
2007}
2008
2009void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2010    InputMapper::populateDeviceInfo(info);
2011
2012    info->setVibrator(true);
2013}
2014
2015void VibratorInputMapper::process(const RawEvent* rawEvent) {
2016    // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2017}
2018
2019void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2020        int32_t token) {
2021#if DEBUG_VIBRATOR
2022    String8 patternStr;
2023    for (size_t i = 0; i < patternSize; i++) {
2024        if (i != 0) {
2025            patternStr.append(", ");
2026        }
2027        patternStr.appendFormat("%lld", pattern[i]);
2028    }
2029    ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
2030            getDeviceId(), patternStr.string(), repeat, token);
2031#endif
2032
2033    mVibrating = true;
2034    memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2035    mPatternSize = patternSize;
2036    mRepeat = repeat;
2037    mToken = token;
2038    mIndex = -1;
2039
2040    nextStep();
2041}
2042
2043void VibratorInputMapper::cancelVibrate(int32_t token) {
2044#if DEBUG_VIBRATOR
2045    ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2046#endif
2047
2048    if (mVibrating && mToken == token) {
2049        stopVibrating();
2050    }
2051}
2052
2053void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2054    if (mVibrating) {
2055        if (when >= mNextStepTime) {
2056            nextStep();
2057        } else {
2058            getContext()->requestTimeoutAtTime(mNextStepTime);
2059        }
2060    }
2061}
2062
2063void VibratorInputMapper::nextStep() {
2064    mIndex += 1;
2065    if (size_t(mIndex) >= mPatternSize) {
2066        if (mRepeat < 0) {
2067            // We are done.
2068            stopVibrating();
2069            return;
2070        }
2071        mIndex = mRepeat;
2072    }
2073
2074    bool vibratorOn = mIndex & 1;
2075    nsecs_t duration = mPattern[mIndex];
2076    if (vibratorOn) {
2077#if DEBUG_VIBRATOR
2078        ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
2079                getDeviceId(), duration);
2080#endif
2081        getEventHub()->vibrate(getDeviceId(), duration);
2082    } else {
2083#if DEBUG_VIBRATOR
2084        ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2085#endif
2086        getEventHub()->cancelVibrate(getDeviceId());
2087    }
2088    nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2089    mNextStepTime = now + duration;
2090    getContext()->requestTimeoutAtTime(mNextStepTime);
2091#if DEBUG_VIBRATOR
2092    ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2093#endif
2094}
2095
2096void VibratorInputMapper::stopVibrating() {
2097    mVibrating = false;
2098#if DEBUG_VIBRATOR
2099    ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2100#endif
2101    getEventHub()->cancelVibrate(getDeviceId());
2102}
2103
2104void VibratorInputMapper::dump(String8& dump) {
2105    dump.append(INDENT2 "Vibrator Input Mapper:\n");
2106    dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2107}
2108
2109
2110// --- KeyboardInputMapper ---
2111
2112KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2113        uint32_t source, int32_t keyboardType) :
2114        InputMapper(device), mSource(source),
2115        mKeyboardType(keyboardType) {
2116}
2117
2118KeyboardInputMapper::~KeyboardInputMapper() {
2119}
2120
2121uint32_t KeyboardInputMapper::getSources() {
2122    return mSource;
2123}
2124
2125void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2126    InputMapper::populateDeviceInfo(info);
2127
2128    info->setKeyboardType(mKeyboardType);
2129    info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2130}
2131
2132void KeyboardInputMapper::dump(String8& dump) {
2133    dump.append(INDENT2 "Keyboard Input Mapper:\n");
2134    dumpParameters(dump);
2135    dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2136    dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2137    dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2138    dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2139    dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
2140}
2141
2142
2143void KeyboardInputMapper::configure(nsecs_t when,
2144        const InputReaderConfiguration* config, uint32_t changes) {
2145    InputMapper::configure(when, config, changes);
2146
2147    if (!changes) { // first time only
2148        // Configure basic parameters.
2149        configureParameters();
2150    }
2151
2152    if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2153        if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2154            DisplayViewport v;
2155            if (config->getDisplayInfo(false /*external*/, &v)) {
2156                mOrientation = v.orientation;
2157            } else {
2158                mOrientation = DISPLAY_ORIENTATION_0;
2159            }
2160        } else {
2161            mOrientation = DISPLAY_ORIENTATION_0;
2162        }
2163    }
2164}
2165
2166void KeyboardInputMapper::configureParameters() {
2167    mParameters.orientationAware = false;
2168    getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
2169            mParameters.orientationAware);
2170
2171    mParameters.hasAssociatedDisplay = false;
2172    if (mParameters.orientationAware) {
2173        mParameters.hasAssociatedDisplay = true;
2174    }
2175
2176    mParameters.handlesKeyRepeat = false;
2177    getDevice()->getConfiguration().tryGetProperty(String8("keyboard.handlesKeyRepeat"),
2178            mParameters.handlesKeyRepeat);
2179}
2180
2181void KeyboardInputMapper::dumpParameters(String8& dump) {
2182    dump.append(INDENT3 "Parameters:\n");
2183    dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2184            toString(mParameters.hasAssociatedDisplay));
2185    dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2186            toString(mParameters.orientationAware));
2187    dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2188            toString(mParameters.handlesKeyRepeat));
2189}
2190
2191void KeyboardInputMapper::reset(nsecs_t when) {
2192    mMetaState = AMETA_NONE;
2193    mDownTime = 0;
2194    mKeyDowns.clear();
2195    mCurrentHidUsage = 0;
2196
2197    resetLedState();
2198
2199    InputMapper::reset(when);
2200}
2201
2202void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2203    switch (rawEvent->type) {
2204    case EV_KEY: {
2205        int32_t scanCode = rawEvent->code;
2206        int32_t usageCode = mCurrentHidUsage;
2207        mCurrentHidUsage = 0;
2208
2209        if (isKeyboardOrGamepadKey(scanCode)) {
2210            processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
2211        }
2212        break;
2213    }
2214    case EV_MSC: {
2215        if (rawEvent->code == MSC_SCAN) {
2216            mCurrentHidUsage = rawEvent->value;
2217        }
2218        break;
2219    }
2220    case EV_SYN: {
2221        if (rawEvent->code == SYN_REPORT) {
2222            mCurrentHidUsage = 0;
2223        }
2224    }
2225    }
2226}
2227
2228bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2229    return scanCode < BTN_MOUSE
2230        || scanCode >= KEY_OK
2231        || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2232        || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2233}
2234
2235void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2236        int32_t usageCode) {
2237    int32_t keyCode;
2238    int32_t keyMetaState;
2239    uint32_t policyFlags;
2240
2241    if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2242                              &keyCode, &keyMetaState, &policyFlags)) {
2243        keyCode = AKEYCODE_UNKNOWN;
2244        keyMetaState = mMetaState;
2245        policyFlags = 0;
2246    }
2247
2248    if (down) {
2249        // Rotate key codes according to orientation if needed.
2250        if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2251            keyCode = rotateKeyCode(keyCode, mOrientation);
2252        }
2253
2254        // Add key down.
2255        ssize_t keyDownIndex = findKeyDown(scanCode);
2256        if (keyDownIndex >= 0) {
2257            // key repeat, be sure to use same keycode as before in case of rotation
2258            keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2259        } else {
2260            // key down
2261            if ((policyFlags & POLICY_FLAG_VIRTUAL)
2262                    && mContext->shouldDropVirtualKey(when,
2263                            getDevice(), keyCode, scanCode)) {
2264                return;
2265            }
2266            if (policyFlags & POLICY_FLAG_GESTURE) {
2267                mDevice->cancelTouch(when);
2268            }
2269
2270            mKeyDowns.push();
2271            KeyDown& keyDown = mKeyDowns.editTop();
2272            keyDown.keyCode = keyCode;
2273            keyDown.scanCode = scanCode;
2274        }
2275
2276        mDownTime = when;
2277    } else {
2278        // Remove key down.
2279        ssize_t keyDownIndex = findKeyDown(scanCode);
2280        if (keyDownIndex >= 0) {
2281            // key up, be sure to use same keycode as before in case of rotation
2282            keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2283            mKeyDowns.removeAt(size_t(keyDownIndex));
2284        } else {
2285            // key was not actually down
2286            ALOGI("Dropping key up from device %s because the key was not down.  "
2287                    "keyCode=%d, scanCode=%d",
2288                    getDeviceName().string(), keyCode, scanCode);
2289            return;
2290        }
2291    }
2292
2293    if (updateMetaStateIfNeeded(keyCode, down)) {
2294        // If global meta state changed send it along with the key.
2295        // If it has not changed then we'll use what keymap gave us,
2296        // since key replacement logic might temporarily reset a few
2297        // meta bits for given key.
2298        keyMetaState = mMetaState;
2299    }
2300
2301    nsecs_t downTime = mDownTime;
2302
2303    // Key down on external an keyboard should wake the device.
2304    // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2305    // For internal keyboards, the key layout file should specify the policy flags for
2306    // each wake key individually.
2307    // TODO: Use the input device configuration to control this behavior more finely.
2308    if (down && getDevice()->isExternal()) {
2309        policyFlags |= POLICY_FLAG_WAKE;
2310    }
2311
2312    if (mParameters.handlesKeyRepeat) {
2313        policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2314    }
2315
2316    if (down && !isMetaKey(keyCode)) {
2317        getContext()->fadePointer();
2318    }
2319
2320    NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2321            down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
2322            AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
2323    getListener()->notifyKey(&args);
2324}
2325
2326ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2327    size_t n = mKeyDowns.size();
2328    for (size_t i = 0; i < n; i++) {
2329        if (mKeyDowns[i].scanCode == scanCode) {
2330            return i;
2331        }
2332    }
2333    return -1;
2334}
2335
2336int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2337    return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2338}
2339
2340int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2341    return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2342}
2343
2344bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2345        const int32_t* keyCodes, uint8_t* outFlags) {
2346    return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2347}
2348
2349int32_t KeyboardInputMapper::getMetaState() {
2350    return mMetaState;
2351}
2352
2353void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2354    updateMetaStateIfNeeded(keyCode, false);
2355}
2356
2357bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2358    int32_t oldMetaState = mMetaState;
2359    int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2360    bool metaStateChanged = oldMetaState != newMetaState;
2361    if (metaStateChanged) {
2362        mMetaState = newMetaState;
2363        updateLedState(false);
2364
2365        getContext()->updateGlobalMetaState();
2366    }
2367
2368    return metaStateChanged;
2369}
2370
2371void KeyboardInputMapper::resetLedState() {
2372    initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2373    initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2374    initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2375
2376    updateLedState(true);
2377}
2378
2379void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2380    ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2381    ledState.on = false;
2382}
2383
2384void KeyboardInputMapper::updateLedState(bool reset) {
2385    updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2386            AMETA_CAPS_LOCK_ON, reset);
2387    updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2388            AMETA_NUM_LOCK_ON, reset);
2389    updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2390            AMETA_SCROLL_LOCK_ON, reset);
2391}
2392
2393void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2394        int32_t led, int32_t modifier, bool reset) {
2395    if (ledState.avail) {
2396        bool desiredState = (mMetaState & modifier) != 0;
2397        if (reset || ledState.on != desiredState) {
2398            getEventHub()->setLedState(getDeviceId(), led, desiredState);
2399            ledState.on = desiredState;
2400        }
2401    }
2402}
2403
2404
2405// --- CursorInputMapper ---
2406
2407CursorInputMapper::CursorInputMapper(InputDevice* device) :
2408        InputMapper(device) {
2409}
2410
2411CursorInputMapper::~CursorInputMapper() {
2412}
2413
2414uint32_t CursorInputMapper::getSources() {
2415    return mSource;
2416}
2417
2418void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2419    InputMapper::populateDeviceInfo(info);
2420
2421    if (mParameters.mode == Parameters::MODE_POINTER) {
2422        float minX, minY, maxX, maxY;
2423        if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2424            info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2425            info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2426        }
2427    } else {
2428        info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2429        info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2430    }
2431    info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2432
2433    if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2434        info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2435    }
2436    if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2437        info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2438    }
2439}
2440
2441void CursorInputMapper::dump(String8& dump) {
2442    dump.append(INDENT2 "Cursor Input Mapper:\n");
2443    dumpParameters(dump);
2444    dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2445    dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2446    dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2447    dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2448    dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2449            toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2450    dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2451            toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2452    dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2453    dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2454    dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2455    dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2456    dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2457    dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
2458}
2459
2460void CursorInputMapper::configure(nsecs_t when,
2461        const InputReaderConfiguration* config, uint32_t changes) {
2462    InputMapper::configure(when, config, changes);
2463
2464    if (!changes) { // first time only
2465        mCursorScrollAccumulator.configure(getDevice());
2466
2467        // Configure basic parameters.
2468        configureParameters();
2469
2470        // Configure device mode.
2471        switch (mParameters.mode) {
2472        case Parameters::MODE_POINTER:
2473            mSource = AINPUT_SOURCE_MOUSE;
2474            mXPrecision = 1.0f;
2475            mYPrecision = 1.0f;
2476            mXScale = 1.0f;
2477            mYScale = 1.0f;
2478            mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2479            break;
2480        case Parameters::MODE_NAVIGATION:
2481            mSource = AINPUT_SOURCE_TRACKBALL;
2482            mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2483            mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2484            mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2485            mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2486            break;
2487        }
2488
2489        mVWheelScale = 1.0f;
2490        mHWheelScale = 1.0f;
2491    }
2492
2493    if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2494        mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2495        mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2496        mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2497    }
2498
2499    if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2500        if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2501            DisplayViewport v;
2502            if (config->getDisplayInfo(false /*external*/, &v)) {
2503                mOrientation = v.orientation;
2504            } else {
2505                mOrientation = DISPLAY_ORIENTATION_0;
2506            }
2507        } else {
2508            mOrientation = DISPLAY_ORIENTATION_0;
2509        }
2510        bumpGeneration();
2511    }
2512}
2513
2514void CursorInputMapper::configureParameters() {
2515    mParameters.mode = Parameters::MODE_POINTER;
2516    String8 cursorModeString;
2517    if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2518        if (cursorModeString == "navigation") {
2519            mParameters.mode = Parameters::MODE_NAVIGATION;
2520        } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2521            ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2522        }
2523    }
2524
2525    mParameters.orientationAware = false;
2526    getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2527            mParameters.orientationAware);
2528
2529    mParameters.hasAssociatedDisplay = false;
2530    if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2531        mParameters.hasAssociatedDisplay = true;
2532    }
2533}
2534
2535void CursorInputMapper::dumpParameters(String8& dump) {
2536    dump.append(INDENT3 "Parameters:\n");
2537    dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2538            toString(mParameters.hasAssociatedDisplay));
2539
2540    switch (mParameters.mode) {
2541    case Parameters::MODE_POINTER:
2542        dump.append(INDENT4 "Mode: pointer\n");
2543        break;
2544    case Parameters::MODE_NAVIGATION:
2545        dump.append(INDENT4 "Mode: navigation\n");
2546        break;
2547    default:
2548        ALOG_ASSERT(false);
2549    }
2550
2551    dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2552            toString(mParameters.orientationAware));
2553}
2554
2555void CursorInputMapper::reset(nsecs_t when) {
2556    mButtonState = 0;
2557    mDownTime = 0;
2558
2559    mPointerVelocityControl.reset();
2560    mWheelXVelocityControl.reset();
2561    mWheelYVelocityControl.reset();
2562
2563    mCursorButtonAccumulator.reset(getDevice());
2564    mCursorMotionAccumulator.reset(getDevice());
2565    mCursorScrollAccumulator.reset(getDevice());
2566
2567    InputMapper::reset(when);
2568}
2569
2570void CursorInputMapper::process(const RawEvent* rawEvent) {
2571    mCursorButtonAccumulator.process(rawEvent);
2572    mCursorMotionAccumulator.process(rawEvent);
2573    mCursorScrollAccumulator.process(rawEvent);
2574
2575    if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2576        sync(rawEvent->when);
2577    }
2578}
2579
2580void CursorInputMapper::sync(nsecs_t when) {
2581    int32_t lastButtonState = mButtonState;
2582    int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2583    mButtonState = currentButtonState;
2584
2585    bool wasDown = isPointerDown(lastButtonState);
2586    bool down = isPointerDown(currentButtonState);
2587    bool downChanged;
2588    if (!wasDown && down) {
2589        mDownTime = when;
2590        downChanged = true;
2591    } else if (wasDown && !down) {
2592        downChanged = true;
2593    } else {
2594        downChanged = false;
2595    }
2596    nsecs_t downTime = mDownTime;
2597    bool buttonsChanged = currentButtonState != lastButtonState;
2598    int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2599    int32_t buttonsReleased = lastButtonState & ~currentButtonState;
2600
2601    float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2602    float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2603    bool moved = deltaX != 0 || deltaY != 0;
2604
2605    // Rotate delta according to orientation if needed.
2606    if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2607            && (deltaX != 0.0f || deltaY != 0.0f)) {
2608        rotateDelta(mOrientation, &deltaX, &deltaY);
2609    }
2610
2611    // Move the pointer.
2612    PointerProperties pointerProperties;
2613    pointerProperties.clear();
2614    pointerProperties.id = 0;
2615    pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2616
2617    PointerCoords pointerCoords;
2618    pointerCoords.clear();
2619
2620    float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2621    float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2622    bool scrolled = vscroll != 0 || hscroll != 0;
2623
2624    mWheelYVelocityControl.move(when, NULL, &vscroll);
2625    mWheelXVelocityControl.move(when, &hscroll, NULL);
2626
2627    mPointerVelocityControl.move(when, &deltaX, &deltaY);
2628
2629    int32_t displayId;
2630    if (mPointerController != NULL) {
2631        if (moved || scrolled || buttonsChanged) {
2632            mPointerController->setPresentation(
2633                    PointerControllerInterface::PRESENTATION_POINTER);
2634
2635            if (moved) {
2636                mPointerController->move(deltaX, deltaY);
2637            }
2638
2639            if (buttonsChanged) {
2640                mPointerController->setButtonState(currentButtonState);
2641            }
2642
2643            mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2644        }
2645
2646        float x, y;
2647        mPointerController->getPosition(&x, &y);
2648        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2649        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2650        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2651        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
2652        displayId = ADISPLAY_ID_DEFAULT;
2653    } else {
2654        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2655        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2656        displayId = ADISPLAY_ID_NONE;
2657    }
2658
2659    pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2660
2661    // Moving an external trackball or mouse should wake the device.
2662    // We don't do this for internal cursor devices to prevent them from waking up
2663    // the device in your pocket.
2664    // TODO: Use the input device configuration to control this behavior more finely.
2665    uint32_t policyFlags = 0;
2666    if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
2667        policyFlags |= POLICY_FLAG_WAKE;
2668    }
2669
2670    // Synthesize key down from buttons if needed.
2671    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2672            policyFlags, lastButtonState, currentButtonState);
2673
2674    // Send motion event.
2675    if (downChanged || moved || scrolled || buttonsChanged) {
2676        int32_t metaState = mContext->getGlobalMetaState();
2677        int32_t buttonState = lastButtonState;
2678        int32_t motionEventAction;
2679        if (downChanged) {
2680            motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2681        } else if (down || mPointerController == NULL) {
2682            motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2683        } else {
2684            motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2685        }
2686
2687        if (buttonsReleased) {
2688            BitSet32 released(buttonsReleased);
2689            while (!released.isEmpty()) {
2690                int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2691                buttonState &= ~actionButton;
2692                NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2693                        AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2694                        metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2695                        displayId, 1, &pointerProperties, &pointerCoords,
2696                        mXPrecision, mYPrecision, downTime);
2697                getListener()->notifyMotion(&releaseArgs);
2698            }
2699        }
2700
2701        NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
2702                motionEventAction, 0, 0, metaState, currentButtonState,
2703                AMOTION_EVENT_EDGE_FLAG_NONE,
2704                displayId, 1, &pointerProperties, &pointerCoords,
2705                mXPrecision, mYPrecision, downTime);
2706        getListener()->notifyMotion(&args);
2707
2708        if (buttonsPressed) {
2709            BitSet32 pressed(buttonsPressed);
2710            while (!pressed.isEmpty()) {
2711                int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2712                buttonState |= actionButton;
2713                NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2714                        AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2715                        metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2716                        displayId, 1, &pointerProperties, &pointerCoords,
2717                        mXPrecision, mYPrecision, downTime);
2718                getListener()->notifyMotion(&pressArgs);
2719            }
2720        }
2721
2722        ALOG_ASSERT(buttonState == currentButtonState);
2723
2724        // Send hover move after UP to tell the application that the mouse is hovering now.
2725        if (motionEventAction == AMOTION_EVENT_ACTION_UP
2726                && mPointerController != NULL) {
2727            NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
2728                    AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2729                    metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2730                    displayId, 1, &pointerProperties, &pointerCoords,
2731                    mXPrecision, mYPrecision, downTime);
2732            getListener()->notifyMotion(&hoverArgs);
2733        }
2734
2735        // Send scroll events.
2736        if (scrolled) {
2737            pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2738            pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2739
2740            NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2741                    AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
2742                    AMOTION_EVENT_EDGE_FLAG_NONE,
2743                    displayId, 1, &pointerProperties, &pointerCoords,
2744                    mXPrecision, mYPrecision, downTime);
2745            getListener()->notifyMotion(&scrollArgs);
2746        }
2747    }
2748
2749    // Synthesize key up from buttons if needed.
2750    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2751            policyFlags, lastButtonState, currentButtonState);
2752
2753    mCursorMotionAccumulator.finishSync();
2754    mCursorScrollAccumulator.finishSync();
2755}
2756
2757int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2758    if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2759        return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2760    } else {
2761        return AKEY_STATE_UNKNOWN;
2762    }
2763}
2764
2765void CursorInputMapper::fadePointer() {
2766    if (mPointerController != NULL) {
2767        mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2768    }
2769}
2770
2771// --- RotaryEncoderInputMapper ---
2772
2773RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
2774        InputMapper(device) {
2775    mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2776}
2777
2778RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2779}
2780
2781uint32_t RotaryEncoderInputMapper::getSources() {
2782    return mSource;
2783}
2784
2785void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2786    InputMapper::populateDeviceInfo(info);
2787
2788    if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
2789        float res = 0.0f;
2790        if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2791            ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2792        }
2793        if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2794            mScalingFactor)) {
2795            ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2796              "default to 1.0!\n");
2797            mScalingFactor = 1.0f;
2798        }
2799        info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2800            res * mScalingFactor);
2801    }
2802}
2803
2804void RotaryEncoderInputMapper::dump(String8& dump) {
2805    dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2806    dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2807            toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2808}
2809
2810void RotaryEncoderInputMapper::configure(nsecs_t when,
2811        const InputReaderConfiguration* config, uint32_t changes) {
2812    InputMapper::configure(when, config, changes);
2813    if (!changes) {
2814        mRotaryEncoderScrollAccumulator.configure(getDevice());
2815    }
2816}
2817
2818void RotaryEncoderInputMapper::reset(nsecs_t when) {
2819    mRotaryEncoderScrollAccumulator.reset(getDevice());
2820
2821    InputMapper::reset(when);
2822}
2823
2824void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2825    mRotaryEncoderScrollAccumulator.process(rawEvent);
2826
2827    if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2828        sync(rawEvent->when);
2829    }
2830}
2831
2832void RotaryEncoderInputMapper::sync(nsecs_t when) {
2833    PointerCoords pointerCoords;
2834    pointerCoords.clear();
2835
2836    PointerProperties pointerProperties;
2837    pointerProperties.clear();
2838    pointerProperties.id = 0;
2839    pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2840
2841    float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2842    bool scrolled = scroll != 0;
2843
2844    // This is not a pointer, so it's not associated with a display.
2845    int32_t displayId = ADISPLAY_ID_NONE;
2846
2847    // Moving the rotary encoder should wake the device (if specified).
2848    uint32_t policyFlags = 0;
2849    if (scrolled && getDevice()->isExternal()) {
2850        policyFlags |= POLICY_FLAG_WAKE;
2851    }
2852
2853    // Send motion event.
2854    if (scrolled) {
2855        int32_t metaState = mContext->getGlobalMetaState();
2856        pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
2857
2858        NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
2859                AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2860                AMOTION_EVENT_EDGE_FLAG_NONE,
2861                displayId, 1, &pointerProperties, &pointerCoords,
2862                0, 0, 0);
2863        getListener()->notifyMotion(&scrollArgs);
2864    }
2865
2866    mRotaryEncoderScrollAccumulator.finishSync();
2867}
2868
2869// --- TouchInputMapper ---
2870
2871TouchInputMapper::TouchInputMapper(InputDevice* device) :
2872        InputMapper(device),
2873        mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
2874        mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
2875        mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
2876}
2877
2878TouchInputMapper::~TouchInputMapper() {
2879}
2880
2881uint32_t TouchInputMapper::getSources() {
2882    return mSource;
2883}
2884
2885void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2886    InputMapper::populateDeviceInfo(info);
2887
2888    if (mDeviceMode != DEVICE_MODE_DISABLED) {
2889        info->addMotionRange(mOrientedRanges.x);
2890        info->addMotionRange(mOrientedRanges.y);
2891        info->addMotionRange(mOrientedRanges.pressure);
2892
2893        if (mOrientedRanges.haveSize) {
2894            info->addMotionRange(mOrientedRanges.size);
2895        }
2896
2897        if (mOrientedRanges.haveTouchSize) {
2898            info->addMotionRange(mOrientedRanges.touchMajor);
2899            info->addMotionRange(mOrientedRanges.touchMinor);
2900        }
2901
2902        if (mOrientedRanges.haveToolSize) {
2903            info->addMotionRange(mOrientedRanges.toolMajor);
2904            info->addMotionRange(mOrientedRanges.toolMinor);
2905        }
2906
2907        if (mOrientedRanges.haveOrientation) {
2908            info->addMotionRange(mOrientedRanges.orientation);
2909        }
2910
2911        if (mOrientedRanges.haveDistance) {
2912            info->addMotionRange(mOrientedRanges.distance);
2913        }
2914
2915        if (mOrientedRanges.haveTilt) {
2916            info->addMotionRange(mOrientedRanges.tilt);
2917        }
2918
2919        if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2920            info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2921                    0.0f);
2922        }
2923        if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2924            info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2925                    0.0f);
2926        }
2927        if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
2928            const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
2929            const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
2930            info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
2931                    x.fuzz, x.resolution);
2932            info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
2933                    y.fuzz, y.resolution);
2934            info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
2935                    x.fuzz, x.resolution);
2936            info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
2937                    y.fuzz, y.resolution);
2938        }
2939        info->setButtonUnderPad(mParameters.hasButtonUnderPad);
2940    }
2941}
2942
2943void TouchInputMapper::dump(String8& dump) {
2944    dump.append(INDENT2 "Touch Input Mapper:\n");
2945    dumpParameters(dump);
2946    dumpVirtualKeys(dump);
2947    dumpRawPointerAxes(dump);
2948    dumpCalibration(dump);
2949    dumpAffineTransformation(dump);
2950    dumpSurface(dump);
2951
2952    dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
2953    dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
2954    dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
2955    dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
2956    dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
2957    dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
2958    dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
2959    dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
2960    dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
2961    dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
2962    dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
2963    dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
2964    dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
2965    dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
2966    dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
2967    dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
2968    dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
2969
2970    dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
2971    dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
2972            mLastRawState.rawPointerData.pointerCount);
2973    for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
2974        const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
2975        dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
2976                "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
2977                "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
2978                "toolType=%d, isHovering=%s\n", i,
2979                pointer.id, pointer.x, pointer.y, pointer.pressure,
2980                pointer.touchMajor, pointer.touchMinor,
2981                pointer.toolMajor, pointer.toolMinor,
2982                pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
2983                pointer.toolType, toString(pointer.isHovering));
2984    }
2985
2986    dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
2987    dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
2988            mLastCookedState.cookedPointerData.pointerCount);
2989    for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
2990        const PointerProperties& pointerProperties =
2991                mLastCookedState.cookedPointerData.pointerProperties[i];
2992        const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
2993        dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
2994                "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
2995                "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
2996                "toolType=%d, isHovering=%s\n", i,
2997                pointerProperties.id,
2998                pointerCoords.getX(),
2999                pointerCoords.getY(),
3000                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3001                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3002                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3003                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3004                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3005                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3006                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3007                pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3008                pointerProperties.toolType,
3009                toString(mLastCookedState.cookedPointerData.isHovering(i)));
3010    }
3011
3012    dump.append(INDENT3 "Stylus Fusion:\n");
3013    dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3014            toString(mExternalStylusConnected));
3015    dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3016    dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
3017            mExternalStylusFusionTimeout);
3018    dump.append(INDENT3 "External Stylus State:\n");
3019    dumpStylusState(dump, mExternalStylusState);
3020
3021    if (mDeviceMode == DEVICE_MODE_POINTER) {
3022        dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3023        dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3024                mPointerXMovementScale);
3025        dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3026                mPointerYMovementScale);
3027        dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3028                mPointerXZoomScale);
3029        dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3030                mPointerYZoomScale);
3031        dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3032                mPointerGestureMaxSwipeWidth);
3033    }
3034}
3035
3036void TouchInputMapper::configure(nsecs_t when,
3037        const InputReaderConfiguration* config, uint32_t changes) {
3038    InputMapper::configure(when, config, changes);
3039
3040    mConfig = *config;
3041
3042    if (!changes) { // first time only
3043        // Configure basic parameters.
3044        configureParameters();
3045
3046        // Configure common accumulators.
3047        mCursorScrollAccumulator.configure(getDevice());
3048        mTouchButtonAccumulator.configure(getDevice());
3049
3050        // Configure absolute axis information.
3051        configureRawPointerAxes();
3052
3053        // Prepare input device calibration.
3054        parseCalibration();
3055        resolveCalibration();
3056    }
3057
3058    if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
3059        // Update location calibration to reflect current settings
3060        updateAffineTransformation();
3061    }
3062
3063    if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3064        // Update pointer speed.
3065        mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3066        mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3067        mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3068    }
3069
3070    bool resetNeeded = false;
3071    if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3072            | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
3073            | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3074            | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
3075        // Configure device sources, surface dimensions, orientation and
3076        // scaling factors.
3077        configureSurface(when, &resetNeeded);
3078    }
3079
3080    if (changes && resetNeeded) {
3081        // Send reset, unless this is the first time the device has been configured,
3082        // in which case the reader will call reset itself after all mappers are ready.
3083        getDevice()->notifyReset(when);
3084    }
3085}
3086
3087void TouchInputMapper::resolveExternalStylusPresence() {
3088    Vector<InputDeviceInfo> devices;
3089    mContext->getExternalStylusDevices(devices);
3090    mExternalStylusConnected = !devices.isEmpty();
3091
3092    if (!mExternalStylusConnected) {
3093        resetExternalStylus();
3094    }
3095}
3096
3097void TouchInputMapper::configureParameters() {
3098    // Use the pointer presentation mode for devices that do not support distinct
3099    // multitouch.  The spot-based presentation relies on being able to accurately
3100    // locate two or more fingers on the touch pad.
3101    mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
3102            ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
3103
3104    String8 gestureModeString;
3105    if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3106            gestureModeString)) {
3107        if (gestureModeString == "single-touch") {
3108            mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3109        } else if (gestureModeString == "multi-touch") {
3110            mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
3111        } else if (gestureModeString != "default") {
3112            ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3113        }
3114    }
3115
3116    if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3117        // The device is a touch screen.
3118        mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3119    } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3120        // The device is a pointing device like a track pad.
3121        mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3122    } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3123            || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3124        // The device is a cursor device with a touch pad attached.
3125        // By default don't use the touch pad to move the pointer.
3126        mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3127    } else {
3128        // The device is a touch pad of unknown purpose.
3129        mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3130    }
3131
3132    mParameters.hasButtonUnderPad=
3133            getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3134
3135    String8 deviceTypeString;
3136    if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3137            deviceTypeString)) {
3138        if (deviceTypeString == "touchScreen") {
3139            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3140        } else if (deviceTypeString == "touchPad") {
3141            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3142        } else if (deviceTypeString == "touchNavigation") {
3143            mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3144        } else if (deviceTypeString == "pointer") {
3145            mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3146        } else if (deviceTypeString != "default") {
3147            ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3148        }
3149    }
3150
3151    mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3152    getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3153            mParameters.orientationAware);
3154
3155    mParameters.hasAssociatedDisplay = false;
3156    mParameters.associatedDisplayIsExternal = false;
3157    if (mParameters.orientationAware
3158            || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3159            || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3160        mParameters.hasAssociatedDisplay = true;
3161        mParameters.associatedDisplayIsExternal =
3162                mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3163                        && getDevice()->isExternal();
3164    }
3165
3166    // Initial downs on external touch devices should wake the device.
3167    // Normally we don't do this for internal touch screens to prevent them from waking
3168    // up in your pocket but you can enable it using the input device configuration.
3169    mParameters.wake = getDevice()->isExternal();
3170    getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3171            mParameters.wake);
3172}
3173
3174void TouchInputMapper::dumpParameters(String8& dump) {
3175    dump.append(INDENT3 "Parameters:\n");
3176
3177    switch (mParameters.gestureMode) {
3178    case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3179        dump.append(INDENT4 "GestureMode: single-touch\n");
3180        break;
3181    case Parameters::GESTURE_MODE_MULTI_TOUCH:
3182        dump.append(INDENT4 "GestureMode: multi-touch\n");
3183        break;
3184    default:
3185        assert(false);
3186    }
3187
3188    switch (mParameters.deviceType) {
3189    case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3190        dump.append(INDENT4 "DeviceType: touchScreen\n");
3191        break;
3192    case Parameters::DEVICE_TYPE_TOUCH_PAD:
3193        dump.append(INDENT4 "DeviceType: touchPad\n");
3194        break;
3195    case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3196        dump.append(INDENT4 "DeviceType: touchNavigation\n");
3197        break;
3198    case Parameters::DEVICE_TYPE_POINTER:
3199        dump.append(INDENT4 "DeviceType: pointer\n");
3200        break;
3201    default:
3202        ALOG_ASSERT(false);
3203    }
3204
3205    dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
3206            toString(mParameters.hasAssociatedDisplay),
3207            toString(mParameters.associatedDisplayIsExternal));
3208    dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3209            toString(mParameters.orientationAware));
3210}
3211
3212void TouchInputMapper::configureRawPointerAxes() {
3213    mRawPointerAxes.clear();
3214}
3215
3216void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3217    dump.append(INDENT3 "Raw Touch Axes:\n");
3218    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3219    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3220    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3221    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3222    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3223    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3224    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3225    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3226    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3227    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3228    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3229    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3230    dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3231}
3232
3233bool TouchInputMapper::hasExternalStylus() const {
3234    return mExternalStylusConnected;
3235}
3236
3237void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3238    int32_t oldDeviceMode = mDeviceMode;
3239
3240    resolveExternalStylusPresence();
3241
3242    // Determine device mode.
3243    if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3244            && mConfig.pointerGesturesEnabled) {
3245        mSource = AINPUT_SOURCE_MOUSE;
3246        mDeviceMode = DEVICE_MODE_POINTER;
3247        if (hasStylus()) {
3248            mSource |= AINPUT_SOURCE_STYLUS;
3249        }
3250    } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3251            && mParameters.hasAssociatedDisplay) {
3252        mSource = AINPUT_SOURCE_TOUCHSCREEN;
3253        mDeviceMode = DEVICE_MODE_DIRECT;
3254        if (hasStylus()) {
3255            mSource |= AINPUT_SOURCE_STYLUS;
3256        }
3257        if (hasExternalStylus()) {
3258            mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3259        }
3260    } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3261        mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3262        mDeviceMode = DEVICE_MODE_NAVIGATION;
3263    } else {
3264        mSource = AINPUT_SOURCE_TOUCHPAD;
3265        mDeviceMode = DEVICE_MODE_UNSCALED;
3266    }
3267
3268    // Ensure we have valid X and Y axes.
3269    if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3270        ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis!  "
3271                "The device will be inoperable.", getDeviceName().string());
3272        mDeviceMode = DEVICE_MODE_DISABLED;
3273        return;
3274    }
3275
3276    // Raw width and height in the natural orientation.
3277    int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3278    int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3279
3280    // Get associated display dimensions.
3281    DisplayViewport newViewport;
3282    if (mParameters.hasAssociatedDisplay) {
3283        if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
3284            ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3285                    "display.  The device will be inoperable until the display size "
3286                    "becomes available.",
3287                    getDeviceName().string());
3288            mDeviceMode = DEVICE_MODE_DISABLED;
3289            return;
3290        }
3291    } else {
3292        newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3293    }
3294    bool viewportChanged = mViewport != newViewport;
3295    if (viewportChanged) {
3296        mViewport = newViewport;
3297
3298        if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3299            // Convert rotated viewport to natural surface coordinates.
3300            int32_t naturalLogicalWidth, naturalLogicalHeight;
3301            int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3302            int32_t naturalPhysicalLeft, naturalPhysicalTop;
3303            int32_t naturalDeviceWidth, naturalDeviceHeight;
3304            switch (mViewport.orientation) {
3305            case DISPLAY_ORIENTATION_90:
3306                naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3307                naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3308                naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3309                naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3310                naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3311                naturalPhysicalTop = mViewport.physicalLeft;
3312                naturalDeviceWidth = mViewport.deviceHeight;
3313                naturalDeviceHeight = mViewport.deviceWidth;
3314                break;
3315            case DISPLAY_ORIENTATION_180:
3316                naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3317                naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3318                naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3319                naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3320                naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3321                naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3322                naturalDeviceWidth = mViewport.deviceWidth;
3323                naturalDeviceHeight = mViewport.deviceHeight;
3324                break;
3325            case DISPLAY_ORIENTATION_270:
3326                naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3327                naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3328                naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3329                naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3330                naturalPhysicalLeft = mViewport.physicalTop;
3331                naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3332                naturalDeviceWidth = mViewport.deviceHeight;
3333                naturalDeviceHeight = mViewport.deviceWidth;
3334                break;
3335            case DISPLAY_ORIENTATION_0:
3336            default:
3337                naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3338                naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3339                naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3340                naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3341                naturalPhysicalLeft = mViewport.physicalLeft;
3342                naturalPhysicalTop = mViewport.physicalTop;
3343                naturalDeviceWidth = mViewport.deviceWidth;
3344                naturalDeviceHeight = mViewport.deviceHeight;
3345                break;
3346            }
3347
3348            mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3349            mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3350            mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3351            mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3352
3353            mSurfaceOrientation = mParameters.orientationAware ?
3354                    mViewport.orientation : DISPLAY_ORIENTATION_0;
3355        } else {
3356            mSurfaceWidth = rawWidth;
3357            mSurfaceHeight = rawHeight;
3358            mSurfaceLeft = 0;
3359            mSurfaceTop = 0;
3360            mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3361        }
3362    }
3363
3364    // If moving between pointer modes, need to reset some state.
3365    bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3366    if (deviceModeChanged) {
3367        mOrientedRanges.clear();
3368    }
3369
3370    // Create pointer controller if needed.
3371    if (mDeviceMode == DEVICE_MODE_POINTER ||
3372            (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3373        if (mPointerController == NULL) {
3374            mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3375        }
3376    } else {
3377        mPointerController.clear();
3378    }
3379
3380    if (viewportChanged || deviceModeChanged) {
3381        ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3382                "display id %d",
3383                getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3384                mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3385
3386        // Configure X and Y factors.
3387        mXScale = float(mSurfaceWidth) / rawWidth;
3388        mYScale = float(mSurfaceHeight) / rawHeight;
3389        mXTranslate = -mSurfaceLeft;
3390        mYTranslate = -mSurfaceTop;
3391        mXPrecision = 1.0f / mXScale;
3392        mYPrecision = 1.0f / mYScale;
3393
3394        mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3395        mOrientedRanges.x.source = mSource;
3396        mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3397        mOrientedRanges.y.source = mSource;
3398
3399        configureVirtualKeys();
3400
3401        // Scale factor for terms that are not oriented in a particular axis.
3402        // If the pixels are square then xScale == yScale otherwise we fake it
3403        // by choosing an average.
3404        mGeometricScale = avg(mXScale, mYScale);
3405
3406        // Size of diagonal axis.
3407        float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3408
3409        // Size factors.
3410        if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3411            if (mRawPointerAxes.touchMajor.valid
3412                    && mRawPointerAxes.touchMajor.maxValue != 0) {
3413                mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3414            } else if (mRawPointerAxes.toolMajor.valid
3415                    && mRawPointerAxes.toolMajor.maxValue != 0) {
3416                mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3417            } else {
3418                mSizeScale = 0.0f;
3419            }
3420
3421            mOrientedRanges.haveTouchSize = true;
3422            mOrientedRanges.haveToolSize = true;
3423            mOrientedRanges.haveSize = true;
3424
3425            mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3426            mOrientedRanges.touchMajor.source = mSource;
3427            mOrientedRanges.touchMajor.min = 0;
3428            mOrientedRanges.touchMajor.max = diagonalSize;
3429            mOrientedRanges.touchMajor.flat = 0;
3430            mOrientedRanges.touchMajor.fuzz = 0;
3431            mOrientedRanges.touchMajor.resolution = 0;
3432
3433            mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3434            mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3435
3436            mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3437            mOrientedRanges.toolMajor.source = mSource;
3438            mOrientedRanges.toolMajor.min = 0;
3439            mOrientedRanges.toolMajor.max = diagonalSize;
3440            mOrientedRanges.toolMajor.flat = 0;
3441            mOrientedRanges.toolMajor.fuzz = 0;
3442            mOrientedRanges.toolMajor.resolution = 0;
3443
3444            mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3445            mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3446
3447            mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3448            mOrientedRanges.size.source = mSource;
3449            mOrientedRanges.size.min = 0;
3450            mOrientedRanges.size.max = 1.0;
3451            mOrientedRanges.size.flat = 0;
3452            mOrientedRanges.size.fuzz = 0;
3453            mOrientedRanges.size.resolution = 0;
3454        } else {
3455            mSizeScale = 0.0f;
3456        }
3457
3458        // Pressure factors.
3459        mPressureScale = 0;
3460        if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3461                || mCalibration.pressureCalibration
3462                        == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3463            if (mCalibration.havePressureScale) {
3464                mPressureScale = mCalibration.pressureScale;
3465            } else if (mRawPointerAxes.pressure.valid
3466                    && mRawPointerAxes.pressure.maxValue != 0) {
3467                mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3468            }
3469        }
3470
3471        mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3472        mOrientedRanges.pressure.source = mSource;
3473        mOrientedRanges.pressure.min = 0;
3474        mOrientedRanges.pressure.max = 1.0;
3475        mOrientedRanges.pressure.flat = 0;
3476        mOrientedRanges.pressure.fuzz = 0;
3477        mOrientedRanges.pressure.resolution = 0;
3478
3479        // Tilt
3480        mTiltXCenter = 0;
3481        mTiltXScale = 0;
3482        mTiltYCenter = 0;
3483        mTiltYScale = 0;
3484        mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3485        if (mHaveTilt) {
3486            mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3487                    mRawPointerAxes.tiltX.maxValue);
3488            mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3489                    mRawPointerAxes.tiltY.maxValue);
3490            mTiltXScale = M_PI / 180;
3491            mTiltYScale = M_PI / 180;
3492
3493            mOrientedRanges.haveTilt = true;
3494
3495            mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3496            mOrientedRanges.tilt.source = mSource;
3497            mOrientedRanges.tilt.min = 0;
3498            mOrientedRanges.tilt.max = M_PI_2;
3499            mOrientedRanges.tilt.flat = 0;
3500            mOrientedRanges.tilt.fuzz = 0;
3501            mOrientedRanges.tilt.resolution = 0;
3502        }
3503
3504        // Orientation
3505        mOrientationScale = 0;
3506        if (mHaveTilt) {
3507            mOrientedRanges.haveOrientation = true;
3508
3509            mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3510            mOrientedRanges.orientation.source = mSource;
3511            mOrientedRanges.orientation.min = -M_PI;
3512            mOrientedRanges.orientation.max = M_PI;
3513            mOrientedRanges.orientation.flat = 0;
3514            mOrientedRanges.orientation.fuzz = 0;
3515            mOrientedRanges.orientation.resolution = 0;
3516        } else if (mCalibration.orientationCalibration !=
3517                Calibration::ORIENTATION_CALIBRATION_NONE) {
3518            if (mCalibration.orientationCalibration
3519                    == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3520                if (mRawPointerAxes.orientation.valid) {
3521                    if (mRawPointerAxes.orientation.maxValue > 0) {
3522                        mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3523                    } else if (mRawPointerAxes.orientation.minValue < 0) {
3524                        mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3525                    } else {
3526                        mOrientationScale = 0;
3527                    }
3528                }
3529            }
3530
3531            mOrientedRanges.haveOrientation = true;
3532
3533            mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3534            mOrientedRanges.orientation.source = mSource;
3535            mOrientedRanges.orientation.min = -M_PI_2;
3536            mOrientedRanges.orientation.max = M_PI_2;
3537            mOrientedRanges.orientation.flat = 0;
3538            mOrientedRanges.orientation.fuzz = 0;
3539            mOrientedRanges.orientation.resolution = 0;
3540        }
3541
3542        // Distance
3543        mDistanceScale = 0;
3544        if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3545            if (mCalibration.distanceCalibration
3546                    == Calibration::DISTANCE_CALIBRATION_SCALED) {
3547                if (mCalibration.haveDistanceScale) {
3548                    mDistanceScale = mCalibration.distanceScale;
3549                } else {
3550                    mDistanceScale = 1.0f;
3551                }
3552            }
3553
3554            mOrientedRanges.haveDistance = true;
3555
3556            mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3557            mOrientedRanges.distance.source = mSource;
3558            mOrientedRanges.distance.min =
3559                    mRawPointerAxes.distance.minValue * mDistanceScale;
3560            mOrientedRanges.distance.max =
3561                    mRawPointerAxes.distance.maxValue * mDistanceScale;
3562            mOrientedRanges.distance.flat = 0;
3563            mOrientedRanges.distance.fuzz =
3564                    mRawPointerAxes.distance.fuzz * mDistanceScale;
3565            mOrientedRanges.distance.resolution = 0;
3566        }
3567
3568        // Compute oriented precision, scales and ranges.
3569        // Note that the maximum value reported is an inclusive maximum value so it is one
3570        // unit less than the total width or height of surface.
3571        switch (mSurfaceOrientation) {
3572        case DISPLAY_ORIENTATION_90:
3573        case DISPLAY_ORIENTATION_270:
3574            mOrientedXPrecision = mYPrecision;
3575            mOrientedYPrecision = mXPrecision;
3576
3577            mOrientedRanges.x.min = mYTranslate;
3578            mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3579            mOrientedRanges.x.flat = 0;
3580            mOrientedRanges.x.fuzz = 0;
3581            mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3582
3583            mOrientedRanges.y.min = mXTranslate;
3584            mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3585            mOrientedRanges.y.flat = 0;
3586            mOrientedRanges.y.fuzz = 0;
3587            mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3588            break;
3589
3590        default:
3591            mOrientedXPrecision = mXPrecision;
3592            mOrientedYPrecision = mYPrecision;
3593
3594            mOrientedRanges.x.min = mXTranslate;
3595            mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3596            mOrientedRanges.x.flat = 0;
3597            mOrientedRanges.x.fuzz = 0;
3598            mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3599
3600            mOrientedRanges.y.min = mYTranslate;
3601            mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3602            mOrientedRanges.y.flat = 0;
3603            mOrientedRanges.y.fuzz = 0;
3604            mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3605            break;
3606        }
3607
3608        // Location
3609        updateAffineTransformation();
3610
3611        if (mDeviceMode == DEVICE_MODE_POINTER) {
3612            // Compute pointer gesture detection parameters.
3613            float rawDiagonal = hypotf(rawWidth, rawHeight);
3614            float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3615
3616            // Scale movements such that one whole swipe of the touch pad covers a
3617            // given area relative to the diagonal size of the display when no acceleration
3618            // is applied.
3619            // Assume that the touch pad has a square aspect ratio such that movements in
3620            // X and Y of the same number of raw units cover the same physical distance.
3621            mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3622                    * displayDiagonal / rawDiagonal;
3623            mPointerYMovementScale = mPointerXMovementScale;
3624
3625            // Scale zooms to cover a smaller range of the display than movements do.
3626            // This value determines the area around the pointer that is affected by freeform
3627            // pointer gestures.
3628            mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3629                    * displayDiagonal / rawDiagonal;
3630            mPointerYZoomScale = mPointerXZoomScale;
3631
3632            // Max width between pointers to detect a swipe gesture is more than some fraction
3633            // of the diagonal axis of the touch pad.  Touches that are wider than this are
3634            // translated into freeform gestures.
3635            mPointerGestureMaxSwipeWidth =
3636                    mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3637
3638            // Abort current pointer usages because the state has changed.
3639            abortPointerUsage(when, 0 /*policyFlags*/);
3640        }
3641
3642        // Inform the dispatcher about the changes.
3643        *outResetNeeded = true;
3644        bumpGeneration();
3645    }
3646}
3647
3648void TouchInputMapper::dumpSurface(String8& dump) {
3649    dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3650            "logicalFrame=[%d, %d, %d, %d], "
3651            "physicalFrame=[%d, %d, %d, %d], "
3652            "deviceSize=[%d, %d]\n",
3653            mViewport.displayId, mViewport.orientation,
3654            mViewport.logicalLeft, mViewport.logicalTop,
3655            mViewport.logicalRight, mViewport.logicalBottom,
3656            mViewport.physicalLeft, mViewport.physicalTop,
3657            mViewport.physicalRight, mViewport.physicalBottom,
3658            mViewport.deviceWidth, mViewport.deviceHeight);
3659
3660    dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3661    dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3662    dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3663    dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3664    dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3665}
3666
3667void TouchInputMapper::configureVirtualKeys() {
3668    Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3669    getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3670
3671    mVirtualKeys.clear();
3672
3673    if (virtualKeyDefinitions.size() == 0) {
3674        return;
3675    }
3676
3677    mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3678
3679    int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3680    int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3681    int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3682    int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3683
3684    for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3685        const VirtualKeyDefinition& virtualKeyDefinition =
3686                virtualKeyDefinitions[i];
3687
3688        mVirtualKeys.add();
3689        VirtualKey& virtualKey = mVirtualKeys.editTop();
3690
3691        virtualKey.scanCode = virtualKeyDefinition.scanCode;
3692        int32_t keyCode;
3693        int32_t dummyKeyMetaState;
3694        uint32_t flags;
3695        if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3696                                  &keyCode, &dummyKeyMetaState, &flags)) {
3697            ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3698                    virtualKey.scanCode);
3699            mVirtualKeys.pop(); // drop the key
3700            continue;
3701        }
3702
3703        virtualKey.keyCode = keyCode;
3704        virtualKey.flags = flags;
3705
3706        // convert the key definition's display coordinates into touch coordinates for a hit box
3707        int32_t halfWidth = virtualKeyDefinition.width / 2;
3708        int32_t halfHeight = virtualKeyDefinition.height / 2;
3709
3710        virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3711                * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3712        virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3713                * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3714        virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3715                * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3716        virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3717                * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3718    }
3719}
3720
3721void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3722    if (!mVirtualKeys.isEmpty()) {
3723        dump.append(INDENT3 "Virtual Keys:\n");
3724
3725        for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3726            const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
3727            dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
3728                    "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3729                    i, virtualKey.scanCode, virtualKey.keyCode,
3730                    virtualKey.hitLeft, virtualKey.hitRight,
3731                    virtualKey.hitTop, virtualKey.hitBottom);
3732        }
3733    }
3734}
3735
3736void TouchInputMapper::parseCalibration() {
3737    const PropertyMap& in = getDevice()->getConfiguration();
3738    Calibration& out = mCalibration;
3739
3740    // Size
3741    out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3742    String8 sizeCalibrationString;
3743    if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3744        if (sizeCalibrationString == "none") {
3745            out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3746        } else if (sizeCalibrationString == "geometric") {
3747            out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3748        } else if (sizeCalibrationString == "diameter") {
3749            out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3750        } else if (sizeCalibrationString == "box") {
3751            out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3752        } else if (sizeCalibrationString == "area") {
3753            out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3754        } else if (sizeCalibrationString != "default") {
3755            ALOGW("Invalid value for touch.size.calibration: '%s'",
3756                    sizeCalibrationString.string());
3757        }
3758    }
3759
3760    out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3761            out.sizeScale);
3762    out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3763            out.sizeBias);
3764    out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3765            out.sizeIsSummed);
3766
3767    // Pressure
3768    out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3769    String8 pressureCalibrationString;
3770    if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3771        if (pressureCalibrationString == "none") {
3772            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3773        } else if (pressureCalibrationString == "physical") {
3774            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3775        } else if (pressureCalibrationString == "amplitude") {
3776            out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3777        } else if (pressureCalibrationString != "default") {
3778            ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3779                    pressureCalibrationString.string());
3780        }
3781    }
3782
3783    out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3784            out.pressureScale);
3785
3786    // Orientation
3787    out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3788    String8 orientationCalibrationString;
3789    if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3790        if (orientationCalibrationString == "none") {
3791            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3792        } else if (orientationCalibrationString == "interpolated") {
3793            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3794        } else if (orientationCalibrationString == "vector") {
3795            out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3796        } else if (orientationCalibrationString != "default") {
3797            ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3798                    orientationCalibrationString.string());
3799        }
3800    }
3801
3802    // Distance
3803    out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3804    String8 distanceCalibrationString;
3805    if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3806        if (distanceCalibrationString == "none") {
3807            out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3808        } else if (distanceCalibrationString == "scaled") {
3809            out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3810        } else if (distanceCalibrationString != "default") {
3811            ALOGW("Invalid value for touch.distance.calibration: '%s'",
3812                    distanceCalibrationString.string());
3813        }
3814    }
3815
3816    out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3817            out.distanceScale);
3818
3819    out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3820    String8 coverageCalibrationString;
3821    if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
3822        if (coverageCalibrationString == "none") {
3823            out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3824        } else if (coverageCalibrationString == "box") {
3825            out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
3826        } else if (coverageCalibrationString != "default") {
3827            ALOGW("Invalid value for touch.coverage.calibration: '%s'",
3828                    coverageCalibrationString.string());
3829        }
3830    }
3831}
3832
3833void TouchInputMapper::resolveCalibration() {
3834    // Size
3835    if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
3836        if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
3837            mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3838        }
3839    } else {
3840        mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3841    }
3842
3843    // Pressure
3844    if (mRawPointerAxes.pressure.valid) {
3845        if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
3846            mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3847        }
3848    } else {
3849        mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3850    }
3851
3852    // Orientation
3853    if (mRawPointerAxes.orientation.valid) {
3854        if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
3855            mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3856        }
3857    } else {
3858        mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3859    }
3860
3861    // Distance
3862    if (mRawPointerAxes.distance.valid) {
3863        if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
3864            mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3865        }
3866    } else {
3867        mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3868    }
3869
3870    // Coverage
3871    if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
3872        mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
3873    }
3874}
3875
3876void TouchInputMapper::dumpCalibration(String8& dump) {
3877    dump.append(INDENT3 "Calibration:\n");
3878
3879    // Size
3880    switch (mCalibration.sizeCalibration) {
3881    case Calibration::SIZE_CALIBRATION_NONE:
3882        dump.append(INDENT4 "touch.size.calibration: none\n");
3883        break;
3884    case Calibration::SIZE_CALIBRATION_GEOMETRIC:
3885        dump.append(INDENT4 "touch.size.calibration: geometric\n");
3886        break;
3887    case Calibration::SIZE_CALIBRATION_DIAMETER:
3888        dump.append(INDENT4 "touch.size.calibration: diameter\n");
3889        break;
3890    case Calibration::SIZE_CALIBRATION_BOX:
3891        dump.append(INDENT4 "touch.size.calibration: box\n");
3892        break;
3893    case Calibration::SIZE_CALIBRATION_AREA:
3894        dump.append(INDENT4 "touch.size.calibration: area\n");
3895        break;
3896    default:
3897        ALOG_ASSERT(false);
3898    }
3899
3900    if (mCalibration.haveSizeScale) {
3901        dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
3902                mCalibration.sizeScale);
3903    }
3904
3905    if (mCalibration.haveSizeBias) {
3906        dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
3907                mCalibration.sizeBias);
3908    }
3909
3910    if (mCalibration.haveSizeIsSummed) {
3911        dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
3912                toString(mCalibration.sizeIsSummed));
3913    }
3914
3915    // Pressure
3916    switch (mCalibration.pressureCalibration) {
3917    case Calibration::PRESSURE_CALIBRATION_NONE:
3918        dump.append(INDENT4 "touch.pressure.calibration: none\n");
3919        break;
3920    case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3921        dump.append(INDENT4 "touch.pressure.calibration: physical\n");
3922        break;
3923    case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3924        dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
3925        break;
3926    default:
3927        ALOG_ASSERT(false);
3928    }
3929
3930    if (mCalibration.havePressureScale) {
3931        dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
3932                mCalibration.pressureScale);
3933    }
3934
3935    // Orientation
3936    switch (mCalibration.orientationCalibration) {
3937    case Calibration::ORIENTATION_CALIBRATION_NONE:
3938        dump.append(INDENT4 "touch.orientation.calibration: none\n");
3939        break;
3940    case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3941        dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
3942        break;
3943    case Calibration::ORIENTATION_CALIBRATION_VECTOR:
3944        dump.append(INDENT4 "touch.orientation.calibration: vector\n");
3945        break;
3946    default:
3947        ALOG_ASSERT(false);
3948    }
3949
3950    // Distance
3951    switch (mCalibration.distanceCalibration) {
3952    case Calibration::DISTANCE_CALIBRATION_NONE:
3953        dump.append(INDENT4 "touch.distance.calibration: none\n");
3954        break;
3955    case Calibration::DISTANCE_CALIBRATION_SCALED:
3956        dump.append(INDENT4 "touch.distance.calibration: scaled\n");
3957        break;
3958    default:
3959        ALOG_ASSERT(false);
3960    }
3961
3962    if (mCalibration.haveDistanceScale) {
3963        dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
3964                mCalibration.distanceScale);
3965    }
3966
3967    switch (mCalibration.coverageCalibration) {
3968    case Calibration::COVERAGE_CALIBRATION_NONE:
3969        dump.append(INDENT4 "touch.coverage.calibration: none\n");
3970        break;
3971    case Calibration::COVERAGE_CALIBRATION_BOX:
3972        dump.append(INDENT4 "touch.coverage.calibration: box\n");
3973        break;
3974    default:
3975        ALOG_ASSERT(false);
3976    }
3977}
3978
3979void TouchInputMapper::dumpAffineTransformation(String8& dump) {
3980    dump.append(INDENT3 "Affine Transformation:\n");
3981
3982    dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
3983    dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
3984    dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
3985    dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
3986    dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
3987    dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
3988}
3989
3990void TouchInputMapper::updateAffineTransformation() {
3991    mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
3992            mSurfaceOrientation);
3993}
3994
3995void TouchInputMapper::reset(nsecs_t when) {
3996    mCursorButtonAccumulator.reset(getDevice());
3997    mCursorScrollAccumulator.reset(getDevice());
3998    mTouchButtonAccumulator.reset(getDevice());
3999
4000    mPointerVelocityControl.reset();
4001    mWheelXVelocityControl.reset();
4002    mWheelYVelocityControl.reset();
4003
4004    mRawStatesPending.clear();
4005    mCurrentRawState.clear();
4006    mCurrentCookedState.clear();
4007    mLastRawState.clear();
4008    mLastCookedState.clear();
4009    mPointerUsage = POINTER_USAGE_NONE;
4010    mSentHoverEnter = false;
4011    mHavePointerIds = false;
4012    mCurrentMotionAborted = false;
4013    mDownTime = 0;
4014
4015    mCurrentVirtualKey.down = false;
4016
4017    mPointerGesture.reset();
4018    mPointerSimple.reset();
4019    resetExternalStylus();
4020
4021    if (mPointerController != NULL) {
4022        mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4023        mPointerController->clearSpots();
4024    }
4025
4026    InputMapper::reset(when);
4027}
4028
4029void TouchInputMapper::resetExternalStylus() {
4030    mExternalStylusState.clear();
4031    mExternalStylusId = -1;
4032    mExternalStylusFusionTimeout = LLONG_MAX;
4033    mExternalStylusDataPending = false;
4034}
4035
4036void TouchInputMapper::clearStylusDataPendingFlags() {
4037    mExternalStylusDataPending = false;
4038    mExternalStylusFusionTimeout = LLONG_MAX;
4039}
4040
4041void TouchInputMapper::process(const RawEvent* rawEvent) {
4042    mCursorButtonAccumulator.process(rawEvent);
4043    mCursorScrollAccumulator.process(rawEvent);
4044    mTouchButtonAccumulator.process(rawEvent);
4045
4046    if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4047        sync(rawEvent->when);
4048    }
4049}
4050
4051void TouchInputMapper::sync(nsecs_t when) {
4052    const RawState* last = mRawStatesPending.isEmpty() ?
4053            &mCurrentRawState : &mRawStatesPending.top();
4054
4055    // Push a new state.
4056    mRawStatesPending.push();
4057    RawState* next = &mRawStatesPending.editTop();
4058    next->clear();
4059    next->when = when;
4060
4061    // Sync button state.
4062    next->buttonState = mTouchButtonAccumulator.getButtonState()
4063            | mCursorButtonAccumulator.getButtonState();
4064
4065    // Sync scroll
4066    next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4067    next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
4068    mCursorScrollAccumulator.finishSync();
4069
4070    // Sync touch
4071    syncTouch(when, next);
4072
4073    // Assign pointer ids.
4074    if (!mHavePointerIds) {
4075        assignPointerIds(last, next);
4076    }
4077
4078#if DEBUG_RAW_EVENTS
4079    ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4080            "hovering ids 0x%08x -> 0x%08x",
4081            last->rawPointerData.pointerCount,
4082            next->rawPointerData.pointerCount,
4083            last->rawPointerData.touchingIdBits.value,
4084            next->rawPointerData.touchingIdBits.value,
4085            last->rawPointerData.hoveringIdBits.value,
4086            next->rawPointerData.hoveringIdBits.value);
4087#endif
4088
4089    processRawTouches(false /*timeout*/);
4090}
4091
4092void TouchInputMapper::processRawTouches(bool timeout) {
4093    if (mDeviceMode == DEVICE_MODE_DISABLED) {
4094        // Drop all input if the device is disabled.
4095        mCurrentRawState.clear();
4096        mRawStatesPending.clear();
4097        return;
4098    }
4099
4100    // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4101    // valid and must go through the full cook and dispatch cycle. This ensures that anything
4102    // touching the current state will only observe the events that have been dispatched to the
4103    // rest of the pipeline.
4104    const size_t N = mRawStatesPending.size();
4105    size_t count;
4106    for(count = 0; count < N; count++) {
4107        const RawState& next = mRawStatesPending[count];
4108
4109        // A failure to assign the stylus id means that we're waiting on stylus data
4110        // and so should defer the rest of the pipeline.
4111        if (assignExternalStylusId(next, timeout)) {
4112            break;
4113        }
4114
4115        // All ready to go.
4116        clearStylusDataPendingFlags();
4117        mCurrentRawState.copyFrom(next);
4118        if (mCurrentRawState.when < mLastRawState.when) {
4119            mCurrentRawState.when = mLastRawState.when;
4120        }
4121        cookAndDispatch(mCurrentRawState.when);
4122    }
4123    if (count != 0) {
4124        mRawStatesPending.removeItemsAt(0, count);
4125    }
4126
4127    if (mExternalStylusDataPending) {
4128        if (timeout) {
4129            nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4130            clearStylusDataPendingFlags();
4131            mCurrentRawState.copyFrom(mLastRawState);
4132#if DEBUG_STYLUS_FUSION
4133            ALOGD("Timeout expired, synthesizing event with new stylus data");
4134#endif
4135            cookAndDispatch(when);
4136        } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4137            mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4138            getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4139        }
4140    }
4141}
4142
4143void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4144    // Always start with a clean state.
4145    mCurrentCookedState.clear();
4146
4147    // Apply stylus buttons to current raw state.
4148    applyExternalStylusButtonState(when);
4149
4150    // Handle policy on initial down or hover events.
4151    bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4152            && mCurrentRawState.rawPointerData.pointerCount != 0;
4153
4154    uint32_t policyFlags = 0;
4155    bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4156    if (initialDown || buttonsPressed) {
4157        // If this is a touch screen, hide the pointer on an initial down.
4158        if (mDeviceMode == DEVICE_MODE_DIRECT) {
4159            getContext()->fadePointer();
4160        }
4161
4162        if (mParameters.wake) {
4163            policyFlags |= POLICY_FLAG_WAKE;
4164        }
4165    }
4166
4167    // Consume raw off-screen touches before cooking pointer data.
4168    // If touches are consumed, subsequent code will not receive any pointer data.
4169    if (consumeRawTouches(when, policyFlags)) {
4170        mCurrentRawState.rawPointerData.clear();
4171    }
4172
4173    // Cook pointer data.  This call populates the mCurrentCookedState.cookedPointerData structure
4174    // with cooked pointer data that has the same ids and indices as the raw data.
4175    // The following code can use either the raw or cooked data, as needed.
4176    cookPointerData();
4177
4178    // Apply stylus pressure to current cooked state.
4179    applyExternalStylusTouchState(when);
4180
4181    // Synthesize key down from raw buttons if needed.
4182    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
4183            policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
4184
4185    // Dispatch the touches either directly or by translation through a pointer on screen.
4186    if (mDeviceMode == DEVICE_MODE_POINTER) {
4187        for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4188                !idBits.isEmpty(); ) {
4189            uint32_t id = idBits.clearFirstMarkedBit();
4190            const RawPointerData::Pointer& pointer =
4191                    mCurrentRawState.rawPointerData.pointerForId(id);
4192            if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4193                    || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4194                mCurrentCookedState.stylusIdBits.markBit(id);
4195            } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4196                    || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4197                mCurrentCookedState.fingerIdBits.markBit(id);
4198            } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4199                mCurrentCookedState.mouseIdBits.markBit(id);
4200            }
4201        }
4202        for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4203                !idBits.isEmpty(); ) {
4204            uint32_t id = idBits.clearFirstMarkedBit();
4205            const RawPointerData::Pointer& pointer =
4206                    mCurrentRawState.rawPointerData.pointerForId(id);
4207            if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4208                    || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4209                mCurrentCookedState.stylusIdBits.markBit(id);
4210            }
4211        }
4212
4213        // Stylus takes precedence over all tools, then mouse, then finger.
4214        PointerUsage pointerUsage = mPointerUsage;
4215        if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4216            mCurrentCookedState.mouseIdBits.clear();
4217            mCurrentCookedState.fingerIdBits.clear();
4218            pointerUsage = POINTER_USAGE_STYLUS;
4219        } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4220            mCurrentCookedState.fingerIdBits.clear();
4221            pointerUsage = POINTER_USAGE_MOUSE;
4222        } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4223                isPointerDown(mCurrentRawState.buttonState)) {
4224            pointerUsage = POINTER_USAGE_GESTURES;
4225        }
4226
4227        dispatchPointerUsage(when, policyFlags, pointerUsage);
4228    } else {
4229        if (mDeviceMode == DEVICE_MODE_DIRECT
4230                && mConfig.showTouches && mPointerController != NULL) {
4231            mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4232            mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4233
4234            mPointerController->setButtonState(mCurrentRawState.buttonState);
4235            mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4236                    mCurrentCookedState.cookedPointerData.idToIndex,
4237                    mCurrentCookedState.cookedPointerData.touchingIdBits);
4238        }
4239
4240        if (!mCurrentMotionAborted) {
4241            dispatchButtonRelease(when, policyFlags);
4242            dispatchHoverExit(when, policyFlags);
4243            dispatchTouches(when, policyFlags);
4244            dispatchHoverEnterAndMove(when, policyFlags);
4245            dispatchButtonPress(when, policyFlags);
4246        }
4247
4248        if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4249            mCurrentMotionAborted = false;
4250        }
4251    }
4252
4253    // Synthesize key up from raw buttons if needed.
4254    synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
4255            policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
4256
4257    // Clear some transient state.
4258    mCurrentRawState.rawVScroll = 0;
4259    mCurrentRawState.rawHScroll = 0;
4260
4261    // Copy current touch to last touch in preparation for the next cycle.
4262    mLastRawState.copyFrom(mCurrentRawState);
4263    mLastCookedState.copyFrom(mCurrentCookedState);
4264}
4265
4266void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
4267    if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
4268        mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4269    }
4270}
4271
4272void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
4273    CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4274    const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
4275
4276    if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4277        float pressure = mExternalStylusState.pressure;
4278        if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4279            const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4280            pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4281        }
4282        PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4283        coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4284
4285        PointerProperties& properties =
4286                currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
4287        if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4288            properties.toolType = mExternalStylusState.toolType;
4289        }
4290    }
4291}
4292
4293bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4294    if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4295        return false;
4296    }
4297
4298    const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4299            && state.rawPointerData.pointerCount != 0;
4300    if (initialDown) {
4301        if (mExternalStylusState.pressure != 0.0f) {
4302#if DEBUG_STYLUS_FUSION
4303            ALOGD("Have both stylus and touch data, beginning fusion");
4304#endif
4305            mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4306        } else if (timeout) {
4307#if DEBUG_STYLUS_FUSION
4308            ALOGD("Timeout expired, assuming touch is not a stylus.");
4309#endif
4310            resetExternalStylus();
4311        } else {
4312            if (mExternalStylusFusionTimeout == LLONG_MAX) {
4313                mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
4314            }
4315#if DEBUG_STYLUS_FUSION
4316            ALOGD("No stylus data but stylus is connected, requesting timeout "
4317                    "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
4318#endif
4319            getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4320            return true;
4321        }
4322    }
4323
4324    // Check if the stylus pointer has gone up.
4325    if (mExternalStylusId != -1 &&
4326            !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4327#if DEBUG_STYLUS_FUSION
4328            ALOGD("Stylus pointer is going up");
4329#endif
4330        mExternalStylusId = -1;
4331    }
4332
4333    return false;
4334}
4335
4336void TouchInputMapper::timeoutExpired(nsecs_t when) {
4337    if (mDeviceMode == DEVICE_MODE_POINTER) {
4338        if (mPointerUsage == POINTER_USAGE_GESTURES) {
4339            dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4340        }
4341    } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
4342        if (mExternalStylusFusionTimeout < when) {
4343            processRawTouches(true /*timeout*/);
4344        } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4345            getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4346        }
4347    }
4348}
4349
4350void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
4351    mExternalStylusState.copyFrom(state);
4352    if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
4353        // We're either in the middle of a fused stream of data or we're waiting on data before
4354        // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4355        // data.
4356        mExternalStylusDataPending = true;
4357        processRawTouches(false /*timeout*/);
4358    }
4359}
4360
4361bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4362    // Check for release of a virtual key.
4363    if (mCurrentVirtualKey.down) {
4364        if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
4365            // Pointer went up while virtual key was down.
4366            mCurrentVirtualKey.down = false;
4367            if (!mCurrentVirtualKey.ignored) {
4368#if DEBUG_VIRTUAL_KEYS
4369                ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4370                        mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4371#endif
4372                dispatchVirtualKey(when, policyFlags,
4373                        AKEY_EVENT_ACTION_UP,
4374                        AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4375            }
4376            return true;
4377        }
4378
4379        if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4380            uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4381            const RawPointerData::Pointer& pointer =
4382                    mCurrentRawState.rawPointerData.pointerForId(id);
4383            const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4384            if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4385                // Pointer is still within the space of the virtual key.
4386                return true;
4387            }
4388        }
4389
4390        // Pointer left virtual key area or another pointer also went down.
4391        // Send key cancellation but do not consume the touch yet.
4392        // This is useful when the user swipes through from the virtual key area
4393        // into the main display surface.
4394        mCurrentVirtualKey.down = false;
4395        if (!mCurrentVirtualKey.ignored) {
4396#if DEBUG_VIRTUAL_KEYS
4397            ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4398                    mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4399#endif
4400            dispatchVirtualKey(when, policyFlags,
4401                    AKEY_EVENT_ACTION_UP,
4402                    AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4403                            | AKEY_EVENT_FLAG_CANCELED);
4404        }
4405    }
4406
4407    if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4408            && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
4409        // Pointer just went down.  Check for virtual key press or off-screen touches.
4410        uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4411        const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
4412        if (!isPointInsideSurface(pointer.x, pointer.y)) {
4413            // If exactly one pointer went down, check for virtual key hit.
4414            // Otherwise we will drop the entire stroke.
4415            if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4416                const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4417                if (virtualKey) {
4418                    mCurrentVirtualKey.down = true;
4419                    mCurrentVirtualKey.downTime = when;
4420                    mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4421                    mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4422                    mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4423                            when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4424
4425                    if (!mCurrentVirtualKey.ignored) {
4426#if DEBUG_VIRTUAL_KEYS
4427                        ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4428                                mCurrentVirtualKey.keyCode,
4429                                mCurrentVirtualKey.scanCode);
4430#endif
4431                        dispatchVirtualKey(when, policyFlags,
4432                                AKEY_EVENT_ACTION_DOWN,
4433                                AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4434                    }
4435                }
4436            }
4437            return true;
4438        }
4439    }
4440
4441    // Disable all virtual key touches that happen within a short time interval of the
4442    // most recent touch within the screen area.  The idea is to filter out stray
4443    // virtual key presses when interacting with the touch screen.
4444    //
4445    // Problems we're trying to solve:
4446    //
4447    // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4448    //    virtual key area that is implemented by a separate touch panel and accidentally
4449    //    triggers a virtual key.
4450    //
4451    // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4452    //    area and accidentally triggers a virtual key.  This often happens when virtual keys
4453    //    are layed out below the screen near to where the on screen keyboard's space bar
4454    //    is displayed.
4455    if (mConfig.virtualKeyQuietTime > 0 &&
4456            !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
4457        mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4458    }
4459    return false;
4460}
4461
4462void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4463        int32_t keyEventAction, int32_t keyEventFlags) {
4464    int32_t keyCode = mCurrentVirtualKey.keyCode;
4465    int32_t scanCode = mCurrentVirtualKey.scanCode;
4466    nsecs_t downTime = mCurrentVirtualKey.downTime;
4467    int32_t metaState = mContext->getGlobalMetaState();
4468    policyFlags |= POLICY_FLAG_VIRTUAL;
4469
4470    NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4471            keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4472    getListener()->notifyKey(&args);
4473}
4474
4475void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4476    BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4477    if (!currentIdBits.isEmpty()) {
4478        int32_t metaState = getContext()->getGlobalMetaState();
4479        int32_t buttonState = mCurrentCookedState.buttonState;
4480        dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4481                metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4482                mCurrentCookedState.cookedPointerData.pointerProperties,
4483                mCurrentCookedState.cookedPointerData.pointerCoords,
4484                mCurrentCookedState.cookedPointerData.idToIndex,
4485                currentIdBits, -1,
4486                mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4487        mCurrentMotionAborted = true;
4488    }
4489}
4490
4491void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
4492    BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4493    BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
4494    int32_t metaState = getContext()->getGlobalMetaState();
4495    int32_t buttonState = mCurrentCookedState.buttonState;
4496
4497    if (currentIdBits == lastIdBits) {
4498        if (!currentIdBits.isEmpty()) {
4499            // No pointer id changes so this is a move event.
4500            // The listener takes care of batching moves so we don't have to deal with that here.
4501            dispatchMotion(when, policyFlags, mSource,
4502                    AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
4503                    AMOTION_EVENT_EDGE_FLAG_NONE,
4504                    mCurrentCookedState.cookedPointerData.pointerProperties,
4505                    mCurrentCookedState.cookedPointerData.pointerCoords,
4506                    mCurrentCookedState.cookedPointerData.idToIndex,
4507                    currentIdBits, -1,
4508                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4509        }
4510    } else {
4511        // There may be pointers going up and pointers going down and pointers moving
4512        // all at the same time.
4513        BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4514        BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4515        BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4516        BitSet32 dispatchedIdBits(lastIdBits.value);
4517
4518        // Update last coordinates of pointers that have moved so that we observe the new
4519        // pointer positions at the same time as other pointers that have just gone up.
4520        bool moveNeeded = updateMovedPointers(
4521                mCurrentCookedState.cookedPointerData.pointerProperties,
4522                mCurrentCookedState.cookedPointerData.pointerCoords,
4523                mCurrentCookedState.cookedPointerData.idToIndex,
4524                mLastCookedState.cookedPointerData.pointerProperties,
4525                mLastCookedState.cookedPointerData.pointerCoords,
4526                mLastCookedState.cookedPointerData.idToIndex,
4527                moveIdBits);
4528        if (buttonState != mLastCookedState.buttonState) {
4529            moveNeeded = true;
4530        }
4531
4532        // Dispatch pointer up events.
4533        while (!upIdBits.isEmpty()) {
4534            uint32_t upId = upIdBits.clearFirstMarkedBit();
4535
4536            dispatchMotion(when, policyFlags, mSource,
4537                    AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
4538                    mLastCookedState.cookedPointerData.pointerProperties,
4539                    mLastCookedState.cookedPointerData.pointerCoords,
4540                    mLastCookedState.cookedPointerData.idToIndex,
4541                    dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4542            dispatchedIdBits.clearBit(upId);
4543        }
4544
4545        // Dispatch move events if any of the remaining pointers moved from their old locations.
4546        // Although applications receive new locations as part of individual pointer up
4547        // events, they do not generally handle them except when presented in a move event.
4548        if (moveNeeded && !moveIdBits.isEmpty()) {
4549            ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4550            dispatchMotion(when, policyFlags, mSource,
4551                    AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
4552                    mCurrentCookedState.cookedPointerData.pointerProperties,
4553                    mCurrentCookedState.cookedPointerData.pointerCoords,
4554                    mCurrentCookedState.cookedPointerData.idToIndex,
4555                    dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4556        }
4557
4558        // Dispatch pointer down events using the new pointer locations.
4559        while (!downIdBits.isEmpty()) {
4560            uint32_t downId = downIdBits.clearFirstMarkedBit();
4561            dispatchedIdBits.markBit(downId);
4562
4563            if (dispatchedIdBits.count() == 1) {
4564                // First pointer is going down.  Set down time.
4565                mDownTime = when;
4566            }
4567
4568            dispatchMotion(when, policyFlags, mSource,
4569                    AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
4570                    mCurrentCookedState.cookedPointerData.pointerProperties,
4571                    mCurrentCookedState.cookedPointerData.pointerCoords,
4572                    mCurrentCookedState.cookedPointerData.idToIndex,
4573                    dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4574        }
4575    }
4576}
4577
4578void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4579    if (mSentHoverEnter &&
4580            (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4581                    || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
4582        int32_t metaState = getContext()->getGlobalMetaState();
4583        dispatchMotion(when, policyFlags, mSource,
4584                AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
4585                mLastCookedState.cookedPointerData.pointerProperties,
4586                mLastCookedState.cookedPointerData.pointerCoords,
4587                mLastCookedState.cookedPointerData.idToIndex,
4588                mLastCookedState.cookedPointerData.hoveringIdBits, -1,
4589                mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4590        mSentHoverEnter = false;
4591    }
4592}
4593
4594void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
4595    if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4596            && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
4597        int32_t metaState = getContext()->getGlobalMetaState();
4598        if (!mSentHoverEnter) {
4599            dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
4600                    0, 0, metaState, mCurrentRawState.buttonState, 0,
4601                    mCurrentCookedState.cookedPointerData.pointerProperties,
4602                    mCurrentCookedState.cookedPointerData.pointerCoords,
4603                    mCurrentCookedState.cookedPointerData.idToIndex,
4604                    mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
4605                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4606            mSentHoverEnter = true;
4607        }
4608
4609        dispatchMotion(when, policyFlags, mSource,
4610                AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
4611                mCurrentRawState.buttonState, 0,
4612                mCurrentCookedState.cookedPointerData.pointerProperties,
4613                mCurrentCookedState.cookedPointerData.pointerCoords,
4614                mCurrentCookedState.cookedPointerData.idToIndex,
4615                mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
4616                mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4617    }
4618}
4619
4620void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4621    BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4622    const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4623    const int32_t metaState = getContext()->getGlobalMetaState();
4624    int32_t buttonState = mLastCookedState.buttonState;
4625    while (!releasedButtons.isEmpty()) {
4626        int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4627        buttonState &= ~actionButton;
4628        dispatchMotion(when, policyFlags, mSource,
4629                    AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4630                    0, metaState, buttonState, 0,
4631                    mCurrentCookedState.cookedPointerData.pointerProperties,
4632                    mCurrentCookedState.cookedPointerData.pointerCoords,
4633                    mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4634                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4635    }
4636}
4637
4638void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4639    BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4640    const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4641    const int32_t metaState = getContext()->getGlobalMetaState();
4642    int32_t buttonState = mLastCookedState.buttonState;
4643    while (!pressedButtons.isEmpty()) {
4644        int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4645        buttonState |= actionButton;
4646        dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4647                    0, metaState, buttonState, 0,
4648                    mCurrentCookedState.cookedPointerData.pointerProperties,
4649                    mCurrentCookedState.cookedPointerData.pointerCoords,
4650                    mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4651                    mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4652    }
4653}
4654
4655const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4656    if (!cookedPointerData.touchingIdBits.isEmpty()) {
4657        return cookedPointerData.touchingIdBits;
4658    }
4659    return cookedPointerData.hoveringIdBits;
4660}
4661
4662void TouchInputMapper::cookPointerData() {
4663    uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
4664
4665    mCurrentCookedState.cookedPointerData.clear();
4666    mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4667    mCurrentCookedState.cookedPointerData.hoveringIdBits =
4668            mCurrentRawState.rawPointerData.hoveringIdBits;
4669    mCurrentCookedState.cookedPointerData.touchingIdBits =
4670            mCurrentRawState.rawPointerData.touchingIdBits;
4671
4672    if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4673        mCurrentCookedState.buttonState = 0;
4674    } else {
4675        mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4676    }
4677
4678    // Walk through the the active pointers and map device coordinates onto
4679    // surface coordinates and adjust for display orientation.
4680    for (uint32_t i = 0; i < currentPointerCount; i++) {
4681        const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
4682
4683        // Size
4684        float touchMajor, touchMinor, toolMajor, toolMinor, size;
4685        switch (mCalibration.sizeCalibration) {
4686        case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4687        case Calibration::SIZE_CALIBRATION_DIAMETER:
4688        case Calibration::SIZE_CALIBRATION_BOX:
4689        case Calibration::SIZE_CALIBRATION_AREA:
4690            if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4691                touchMajor = in.touchMajor;
4692                touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4693                toolMajor = in.toolMajor;
4694                toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4695                size = mRawPointerAxes.touchMinor.valid
4696                        ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4697            } else if (mRawPointerAxes.touchMajor.valid) {
4698                toolMajor = touchMajor = in.touchMajor;
4699                toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4700                        ? in.touchMinor : in.touchMajor;
4701                size = mRawPointerAxes.touchMinor.valid
4702                        ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4703            } else if (mRawPointerAxes.toolMajor.valid) {
4704                touchMajor = toolMajor = in.toolMajor;
4705                touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4706                        ? in.toolMinor : in.toolMajor;
4707                size = mRawPointerAxes.toolMinor.valid
4708                        ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4709            } else {
4710                ALOG_ASSERT(false, "No touch or tool axes.  "
4711                        "Size calibration should have been resolved to NONE.");
4712                touchMajor = 0;
4713                touchMinor = 0;
4714                toolMajor = 0;
4715                toolMinor = 0;
4716                size = 0;
4717            }
4718
4719            if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
4720                uint32_t touchingCount =
4721                        mCurrentRawState.rawPointerData.touchingIdBits.count();
4722                if (touchingCount > 1) {
4723                    touchMajor /= touchingCount;
4724                    touchMinor /= touchingCount;
4725                    toolMajor /= touchingCount;
4726                    toolMinor /= touchingCount;
4727                    size /= touchingCount;
4728                }
4729            }
4730
4731            if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4732                touchMajor *= mGeometricScale;
4733                touchMinor *= mGeometricScale;
4734                toolMajor *= mGeometricScale;
4735                toolMinor *= mGeometricScale;
4736            } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4737                touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4738                touchMinor = touchMajor;
4739                toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4740                toolMinor = toolMajor;
4741            } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4742                touchMinor = touchMajor;
4743                toolMinor = toolMajor;
4744            }
4745
4746            mCalibration.applySizeScaleAndBias(&touchMajor);
4747            mCalibration.applySizeScaleAndBias(&touchMinor);
4748            mCalibration.applySizeScaleAndBias(&toolMajor);
4749            mCalibration.applySizeScaleAndBias(&toolMinor);
4750            size *= mSizeScale;
4751            break;
4752        default:
4753            touchMajor = 0;
4754            touchMinor = 0;
4755            toolMajor = 0;
4756            toolMinor = 0;
4757            size = 0;
4758            break;
4759        }
4760
4761        // Pressure
4762        float pressure;
4763        switch (mCalibration.pressureCalibration) {
4764        case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4765        case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4766            pressure = in.pressure * mPressureScale;
4767            break;
4768        default:
4769            pressure = in.isHovering ? 0 : 1;
4770            break;
4771        }
4772
4773        // Tilt and Orientation
4774        float tilt;
4775        float orientation;
4776        if (mHaveTilt) {
4777            float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4778            float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4779            orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4780            tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4781        } else {
4782            tilt = 0;
4783
4784            switch (mCalibration.orientationCalibration) {
4785            case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4786                orientation = in.orientation * mOrientationScale;
4787                break;
4788            case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4789                int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4790                int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4791                if (c1 != 0 || c2 != 0) {
4792                    orientation = atan2f(c1, c2) * 0.5f;
4793                    float confidence = hypotf(c1, c2);
4794                    float scale = 1.0f + confidence / 16.0f;
4795                    touchMajor *= scale;
4796                    touchMinor /= scale;
4797                    toolMajor *= scale;
4798                    toolMinor /= scale;
4799                } else {
4800                    orientation = 0;
4801                }
4802                break;
4803            }
4804            default:
4805                orientation = 0;
4806            }
4807        }
4808
4809        // Distance
4810        float distance;
4811        switch (mCalibration.distanceCalibration) {
4812        case Calibration::DISTANCE_CALIBRATION_SCALED:
4813            distance = in.distance * mDistanceScale;
4814            break;
4815        default:
4816            distance = 0;
4817        }
4818
4819        // Coverage
4820        int32_t rawLeft, rawTop, rawRight, rawBottom;
4821        switch (mCalibration.coverageCalibration) {
4822        case Calibration::COVERAGE_CALIBRATION_BOX:
4823            rawLeft = (in.toolMinor & 0xffff0000) >> 16;
4824            rawRight = in.toolMinor & 0x0000ffff;
4825            rawBottom = in.toolMajor & 0x0000ffff;
4826            rawTop = (in.toolMajor & 0xffff0000) >> 16;
4827            break;
4828        default:
4829            rawLeft = rawTop = rawRight = rawBottom = 0;
4830            break;
4831        }
4832
4833        // Adjust X,Y coords for device calibration
4834        // TODO: Adjust coverage coords?
4835        float xTransformed = in.x, yTransformed = in.y;
4836        mAffineTransform.applyTo(xTransformed, yTransformed);
4837
4838        // Adjust X, Y, and coverage coords for surface orientation.
4839        float x, y;
4840        float left, top, right, bottom;
4841
4842        switch (mSurfaceOrientation) {
4843        case DISPLAY_ORIENTATION_90:
4844            x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4845            y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4846            left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4847            right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4848            bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4849            top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4850            orientation -= M_PI_2;
4851            if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
4852                orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4853            }
4854            break;
4855        case DISPLAY_ORIENTATION_180:
4856            x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
4857            y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4858            left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
4859            right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
4860            bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4861            top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4862            orientation -= M_PI;
4863            if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
4864                orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4865            }
4866            break;
4867        case DISPLAY_ORIENTATION_270:
4868            x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
4869            y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4870            left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
4871            right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
4872            bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4873            top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4874            orientation += M_PI_2;
4875            if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
4876                orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
4877            }
4878            break;
4879        default:
4880            x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4881            y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4882            left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4883            right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
4884            bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4885            top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
4886            break;
4887        }
4888
4889        // Write output coords.
4890        PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
4891        out.clear();
4892        out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
4893        out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4894        out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4895        out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
4896        out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
4897        out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
4898        out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
4899        out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
4900        out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
4901        if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
4902            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
4903            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
4904            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
4905            out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
4906        } else {
4907            out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
4908            out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
4909        }
4910
4911        // Write output properties.
4912        PointerProperties& properties =
4913                mCurrentCookedState.cookedPointerData.pointerProperties[i];
4914        uint32_t id = in.id;
4915        properties.clear();
4916        properties.id = id;
4917        properties.toolType = in.toolType;
4918
4919        // Write id index.
4920        mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
4921    }
4922}
4923
4924void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
4925        PointerUsage pointerUsage) {
4926    if (pointerUsage != mPointerUsage) {
4927        abortPointerUsage(when, policyFlags);
4928        mPointerUsage = pointerUsage;
4929    }
4930
4931    switch (mPointerUsage) {
4932    case POINTER_USAGE_GESTURES:
4933        dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
4934        break;
4935    case POINTER_USAGE_STYLUS:
4936        dispatchPointerStylus(when, policyFlags);
4937        break;
4938    case POINTER_USAGE_MOUSE:
4939        dispatchPointerMouse(when, policyFlags);
4940        break;
4941    default:
4942        break;
4943    }
4944}
4945
4946void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
4947    switch (mPointerUsage) {
4948    case POINTER_USAGE_GESTURES:
4949        abortPointerGestures(when, policyFlags);
4950        break;
4951    case POINTER_USAGE_STYLUS:
4952        abortPointerStylus(when, policyFlags);
4953        break;
4954    case POINTER_USAGE_MOUSE:
4955        abortPointerMouse(when, policyFlags);
4956        break;
4957    default:
4958        break;
4959    }
4960
4961    mPointerUsage = POINTER_USAGE_NONE;
4962}
4963
4964void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
4965        bool isTimeout) {
4966    // Update current gesture coordinates.
4967    bool cancelPreviousGesture, finishPreviousGesture;
4968    bool sendEvents = preparePointerGestures(when,
4969            &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
4970    if (!sendEvents) {
4971        return;
4972    }
4973    if (finishPreviousGesture) {
4974        cancelPreviousGesture = false;
4975    }
4976
4977    // Update the pointer presentation and spots.
4978    if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
4979        mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
4980        if (finishPreviousGesture || cancelPreviousGesture) {
4981            mPointerController->clearSpots();
4982        }
4983
4984        if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
4985            mPointerController->setSpots(mPointerGesture.currentGestureCoords,
4986                     mPointerGesture.currentGestureIdToIndex,
4987                     mPointerGesture.currentGestureIdBits);
4988        }
4989    } else {
4990        mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
4991    }
4992
4993    // Show or hide the pointer if needed.
4994    switch (mPointerGesture.currentGestureMode) {
4995    case PointerGesture::NEUTRAL:
4996<