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