blob: d4266f6df9625b2ff9f403538d02377e272eb977 [file] [log] [blame]
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "InputReader"
//#define LOG_NDEBUG 0
// Log debug messages for each raw event received from the EventHub.
#define DEBUG_RAW_EVENTS 0
// Log debug messages about touch screen filtering hacks.
#define DEBUG_HACKS 0
// Log debug messages about virtual key processing.
#define DEBUG_VIRTUAL_KEYS 0
// Log debug messages about pointers.
#define DEBUG_POINTERS 0
// Log debug messages about pointer assignment calculations.
#define DEBUG_POINTER_ASSIGNMENT 0
// Log debug messages about gesture detection.
#define DEBUG_GESTURES 0
// Log debug messages about the vibrator.
#define DEBUG_VIBRATOR 0
// Log debug messages about fusing stylus data.
#define DEBUG_STYLUS_FUSION 0
#include "InputReader.h"
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <log/log.h>
#include <input/Keyboard.h>
#include <input/VirtualKeyMap.h>
#define INDENT " "
#define INDENT2 " "
#define INDENT3 " "
#define INDENT4 " "
#define INDENT5 " "
namespace android {
// --- Constants ---
// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
static const size_t MAX_SLOTS = 32;
// Maximum amount of latency to add to touch events while waiting for data from an
// external stylus.
static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
// Maximum amount of time to wait on touch data before pushing out new pressure data.
static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
// Artificial latency on synthetic events created from stylus data without corresponding touch
// data.
static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
// --- Static Functions ---
template<typename T>
inline static T abs(const T& value) {
return value < 0 ? - value : value;
}
template<typename T>
inline static T min(const T& a, const T& b) {
return a < b ? a : b;
}
template<typename T>
inline static void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
inline static float avg(float x, float y) {
return (x + y) / 2;
}
inline static float distance(float x1, float y1, float x2, float y2) {
return hypotf(x1 - x2, y1 - y2);
}
inline static int32_t signExtendNybble(int32_t value) {
return value >= 8 ? value - 16 : value;
}
static inline const char* toString(bool value) {
return value ? "true" : "false";
}
static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
const int32_t map[][4], size_t mapSize) {
if (orientation != DISPLAY_ORIENTATION_0) {
for (size_t i = 0; i < mapSize; i++) {
if (value == map[i][0]) {
return map[i][orientation];
}
}
}
return value;
}
static const int32_t keyCodeRotationMap[][4] = {
// key codes enumerated counter-clockwise with the original (unrotated) key first
// no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
{ AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
{ AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
{ AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
{ AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
{ AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
{ AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
{ AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
{ AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
};
static const size_t keyCodeRotationMapSize =
sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
static int32_t rotateStemKey(int32_t value, int32_t orientation,
const int32_t map[][2], size_t mapSize) {
if (orientation == DISPLAY_ORIENTATION_180) {
for (size_t i = 0; i < mapSize; i++) {
if (value == map[i][0]) {
return map[i][1];
}
}
}
return value;
}
// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
static int32_t stemKeyRotationMap[][2] = {
// key codes enumerated with the original (unrotated) key first
// no rotation, 180 degree rotation
{ AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
{ AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
{ AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
{ AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
};
static const size_t stemKeyRotationMapSize =
sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
keyCode = rotateStemKey(keyCode, orientation,
stemKeyRotationMap, stemKeyRotationMapSize);
return rotateValueUsingRotationMap(keyCode, orientation,
keyCodeRotationMap, keyCodeRotationMapSize);
}
static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
float temp;
switch (orientation) {
case DISPLAY_ORIENTATION_90:
temp = *deltaX;
*deltaX = *deltaY;
*deltaY = -temp;
break;
case DISPLAY_ORIENTATION_180:
*deltaX = -*deltaX;
*deltaY = -*deltaY;
break;
case DISPLAY_ORIENTATION_270:
temp = *deltaX;
*deltaX = -*deltaY;
*deltaY = temp;
break;
}
}
static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
}
// Returns true if the pointer should be reported as being down given the specified
// button states. This determines whether the event is reported as a touch event.
static bool isPointerDown(int32_t buttonState) {
return buttonState &
(AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
| AMOTION_EVENT_BUTTON_TERTIARY);
}
static float calculateCommonVector(float a, float b) {
if (a > 0 && b > 0) {
return a < b ? a : b;
} else if (a < 0 && b < 0) {
return a > b ? a : b;
} else {
return 0;
}
}
static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
nsecs_t when, int32_t deviceId, uint32_t source,
uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
int32_t buttonState, int32_t keyCode) {
if (
(action == AKEY_EVENT_ACTION_DOWN
&& !(lastButtonState & buttonState)
&& (currentButtonState & buttonState))
|| (action == AKEY_EVENT_ACTION_UP
&& (lastButtonState & buttonState)
&& !(currentButtonState & buttonState))) {
NotifyKeyArgs args(when, deviceId, source, policyFlags,
action, 0, keyCode, 0, context->getGlobalMetaState(), when);
context->getListener()->notifyKey(&args);
}
}
static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
nsecs_t when, int32_t deviceId, uint32_t source,
uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
lastButtonState, currentButtonState,
AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
lastButtonState, currentButtonState,
AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
}
// --- InputReaderConfiguration ---
bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType,
const String8* uniqueDisplayId, DisplayViewport* outViewport) const {
const DisplayViewport* viewport = NULL;
if (viewportType == ViewportType::VIEWPORT_VIRTUAL && uniqueDisplayId != NULL) {
for (const DisplayViewport& currentViewport : mVirtualDisplays) {
if (currentViewport.uniqueId == *uniqueDisplayId) {
viewport = &currentViewport;
break;
}
}
} else if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
viewport = &mExternalDisplay;
} else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
viewport = &mInternalDisplay;
}
if (viewport != NULL && viewport->displayId >= 0) {
*outViewport = *viewport;
return true;
}
return false;
}
void InputReaderConfiguration::setPhysicalDisplayViewport(ViewportType viewportType,
const DisplayViewport& viewport) {
if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
mExternalDisplay = viewport;
} else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
mInternalDisplay = viewport;
}
}
void InputReaderConfiguration::setVirtualDisplayViewports(
const Vector<DisplayViewport>& viewports) {
mVirtualDisplays = viewports;
}
void InputReaderConfiguration::dump(String8& dump) const {
dump.append(INDENT4 "ViewportInternal:\n");
dumpViewport(dump, mInternalDisplay);
dump.append(INDENT4 "ViewportExternal:\n");
dumpViewport(dump, mExternalDisplay);
dump.append(INDENT4 "ViewportVirtual:\n");
for (const DisplayViewport& viewport : mVirtualDisplays) {
dumpViewport(dump, viewport);
}
}
void InputReaderConfiguration::dumpViewport(String8& dump, const DisplayViewport& viewport) const {
dump.appendFormat(INDENT5 "Viewport: displayId=%d, orientation=%d, uniqueId='%s', "
"logicalFrame=[%d, %d, %d, %d], "
"physicalFrame=[%d, %d, %d, %d], "
"deviceSize=[%d, %d]\n",
viewport.displayId, viewport.orientation, viewport.uniqueId.c_str(),
viewport.logicalLeft, viewport.logicalTop,
viewport.logicalRight, viewport.logicalBottom,
viewport.physicalLeft, viewport.physicalTop,
viewport.physicalRight, viewport.physicalBottom,
viewport.deviceWidth, viewport.deviceHeight);
}
// -- TouchAffineTransformation --
void TouchAffineTransformation::applyTo(float& x, float& y) const {
float newX, newY;
newX = x * x_scale + y * x_ymix + x_offset;
newY = x * y_xmix + y * y_scale + y_offset;
x = newX;
y = newY;
}
// --- InputReader ---
InputReader::InputReader(const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& policy,
const sp<InputListenerInterface>& listener) :
mContext(this), mEventHub(eventHub), mPolicy(policy),
mGlobalMetaState(0), mGeneration(1),
mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
mConfigurationChangesToRefresh(0) {
mQueuedListener = new QueuedInputListener(listener);
{ // acquire lock
AutoMutex _l(mLock);
refreshConfigurationLocked(0);
updateGlobalMetaStateLocked();
} // release lock
}
InputReader::~InputReader() {
for (size_t i = 0; i < mDevices.size(); i++) {
delete mDevices.valueAt(i);
}
}
void InputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
Vector<InputDeviceInfo> inputDevices;
{ // acquire lock
AutoMutex _l(mLock);
oldGeneration = mGeneration;
timeoutMillis = -1;
uint32_t changes = mConfigurationChangesToRefresh;
if (changes) {
mConfigurationChangesToRefresh = 0;
timeoutMillis = 0;
refreshConfigurationLocked(changes);
} else if (mNextTimeout != LLONG_MAX) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
}
} // release lock
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
{ // acquire lock
AutoMutex _l(mLock);
mReaderIsAliveCondition.broadcast();
if (count) {
processEventsLocked(mEventBuffer, count);
}
if (mNextTimeout != LLONG_MAX) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
if (now >= mNextTimeout) {
#if DEBUG_RAW_EVENTS
ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
#endif
mNextTimeout = LLONG_MAX;
timeoutExpiredLocked(now);
}
}
if (oldGeneration != mGeneration) {
inputDevicesChanged = true;
getInputDevicesLocked(inputDevices);
}
} // release lock
// Send out a message that the describes the changed input devices.
if (inputDevicesChanged) {
mPolicy->notifyInputDevicesChanged(inputDevices);
}
// Flush queued events out to the listener.
// This must happen outside of the lock because the listener could potentially call
// back into the InputReader's methods, such as getScanCodeState, or become blocked
// on another thread similarly waiting to acquire the InputReader lock thereby
// resulting in a deadlock. This situation is actually quite plausible because the
// listener is actually the input dispatcher, which calls into the window manager,
// which occasionally calls into the input reader.
mQueuedListener->flush();
}
void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
for (const RawEvent* rawEvent = rawEvents; count;) {
int32_t type = rawEvent->type;
size_t batchSize = 1;
if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
int32_t deviceId = rawEvent->deviceId;
while (batchSize < count) {
if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
|| rawEvent[batchSize].deviceId != deviceId) {
break;
}
batchSize += 1;
}
#if DEBUG_RAW_EVENTS
ALOGD("BatchSize: %d Count: %d", batchSize, count);
#endif
processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
} else {
switch (rawEvent->type) {
case EventHubInterface::DEVICE_ADDED:
addDeviceLocked(rawEvent->when, rawEvent->deviceId);
break;
case EventHubInterface::DEVICE_REMOVED:
removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
break;
case EventHubInterface::FINISHED_DEVICE_SCAN:
handleConfigurationChangedLocked(rawEvent->when);
break;
default:
ALOG_ASSERT(false); // can't happen
break;
}
}
count -= batchSize;
rawEvent += batchSize;
}
}
void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex >= 0) {
ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
return;
}
InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
uint32_t classes = mEventHub->getDeviceClasses(deviceId);
int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
device->configure(when, &mConfig, 0);
device->reset(when);
if (device->isIgnored()) {
ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
identifier.name.string());
} else {
ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
identifier.name.string(), device->getSources());
}
mDevices.add(deviceId, device);
bumpGenerationLocked();
if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
notifyExternalStylusPresenceChanged();
}
}
void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
InputDevice* device = NULL;
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex < 0) {
ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
return;
}
device = mDevices.valueAt(deviceIndex);
mDevices.removeItemsAt(deviceIndex, 1);
bumpGenerationLocked();
if (device->isIgnored()) {
ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
device->getId(), device->getName().string());
} else {
ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
device->getId(), device->getName().string(), device->getSources());
}
if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
notifyExternalStylusPresenceChanged();
}
device->reset(when);
delete device;
}
InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
const InputDeviceIdentifier& identifier, uint32_t classes) {
InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
controllerNumber, identifier, classes);
// External devices.
if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
device->setExternal(true);
}
// Devices with mics.
if (classes & INPUT_DEVICE_CLASS_MIC) {
device->setMic(true);
}
// Switch-like devices.
if (classes & INPUT_DEVICE_CLASS_SWITCH) {
device->addMapper(new SwitchInputMapper(device));
}
// Scroll wheel-like devices.
if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
device->addMapper(new RotaryEncoderInputMapper(device));
}
// Vibrator-like devices.
if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
device->addMapper(new VibratorInputMapper(device));
}
// Keyboard-like devices.
uint32_t keyboardSource = 0;
int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
keyboardSource |= AINPUT_SOURCE_KEYBOARD;
}
if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
}
if (classes & INPUT_DEVICE_CLASS_DPAD) {
keyboardSource |= AINPUT_SOURCE_DPAD;
}
if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
keyboardSource |= AINPUT_SOURCE_GAMEPAD;
}
if (keyboardSource != 0) {
device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
}
// Cursor-like devices.
if (classes & INPUT_DEVICE_CLASS_CURSOR) {
device->addMapper(new CursorInputMapper(device));
}
// Touchscreens and touchpad devices.
if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
device->addMapper(new MultiTouchInputMapper(device));
} else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
device->addMapper(new SingleTouchInputMapper(device));
}
// Joystick-like devices.
if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
device->addMapper(new JoystickInputMapper(device));
}
// External stylus-like devices.
if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
device->addMapper(new ExternalStylusInputMapper(device));
}
return device;
}
void InputReader::processEventsForDeviceLocked(int32_t deviceId,
const RawEvent* rawEvents, size_t count) {
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex < 0) {
ALOGW("Discarding event for unknown deviceId %d.", deviceId);
return;
}
InputDevice* device = mDevices.valueAt(deviceIndex);
if (device->isIgnored()) {
//ALOGD("Discarding event for ignored deviceId %d.", deviceId);
return;
}
device->process(rawEvents, count);
}
void InputReader::timeoutExpiredLocked(nsecs_t when) {
for (size_t i = 0; i < mDevices.size(); i++) {
InputDevice* device = mDevices.valueAt(i);
if (!device->isIgnored()) {
device->timeoutExpired(when);
}
}
}
void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
// Reset global meta state because it depends on the list of all configured devices.
updateGlobalMetaStateLocked();
// Enqueue configuration changed.
NotifyConfigurationChangedArgs args(when);
mQueuedListener->notifyConfigurationChanged(&args);
}
void InputReader::refreshConfigurationLocked(uint32_t changes) {
mPolicy->getReaderConfiguration(&mConfig);
mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
if (changes) {
ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
mEventHub->requestReopenDevices();
} else {
for (size_t i = 0; i < mDevices.size(); i++) {
InputDevice* device = mDevices.valueAt(i);
device->configure(now, &mConfig, changes);
}
}
}
}
void InputReader::updateGlobalMetaStateLocked() {
mGlobalMetaState = 0;
for (size_t i = 0; i < mDevices.size(); i++) {
InputDevice* device = mDevices.valueAt(i);
mGlobalMetaState |= device->getMetaState();
}
}
int32_t InputReader::getGlobalMetaStateLocked() {
return mGlobalMetaState;
}
void InputReader::notifyExternalStylusPresenceChanged() {
refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
}
void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
for (size_t i = 0; i < mDevices.size(); i++) {
InputDevice* device = mDevices.valueAt(i);
if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
outDevices.push();
device->getDeviceInfo(&outDevices.editTop());
}
}
}
void InputReader::dispatchExternalStylusState(const StylusState& state) {
for (size_t i = 0; i < mDevices.size(); i++) {
InputDevice* device = mDevices.valueAt(i);
device->updateExternalStylusState(state);
}
}
void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
mDisableVirtualKeysTimeout = time;
}
bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
InputDevice* device, int32_t keyCode, int32_t scanCode) {
if (now < mDisableVirtualKeysTimeout) {
ALOGI("Dropping virtual key from device %s because virtual keys are "
"temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
device->getName().string(),
(mDisableVirtualKeysTimeout - now) * 0.000001,
keyCode, scanCode);
return true;
} else {
return false;
}
}
void InputReader::fadePointerLocked() {
for (size_t i = 0; i < mDevices.size(); i++) {
InputDevice* device = mDevices.valueAt(i);
device->fadePointer();
}
}
void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
if (when < mNextTimeout) {
mNextTimeout = when;
mEventHub->wake();
}
}
int32_t InputReader::bumpGenerationLocked() {
return ++mGeneration;
}
void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
AutoMutex _l(mLock);
getInputDevicesLocked(outInputDevices);
}
void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
outInputDevices.clear();
size_t numDevices = mDevices.size();
for (size_t i = 0; i < numDevices; i++) {
InputDevice* device = mDevices.valueAt(i);
if (!device->isIgnored()) {
outInputDevices.push();
device->getDeviceInfo(&outInputDevices.editTop());
}
}
}
int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
int32_t keyCode) {
AutoMutex _l(mLock);
return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
}
int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
int32_t scanCode) {
AutoMutex _l(mLock);
return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
}
int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
AutoMutex _l(mLock);
return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
}
int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
GetStateFunc getStateFunc) {
int32_t result = AKEY_STATE_UNKNOWN;
if (deviceId >= 0) {
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex >= 0) {
InputDevice* device = mDevices.valueAt(deviceIndex);
if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
result = (device->*getStateFunc)(sourceMask, code);
}
}
} else {
size_t numDevices = mDevices.size();
for (size_t i = 0; i < numDevices; i++) {
InputDevice* device = mDevices.valueAt(i);
if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
// If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
// value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
if (currentResult >= AKEY_STATE_DOWN) {
return currentResult;
} else if (currentResult == AKEY_STATE_UP) {
result = currentResult;
}
}
}
}
return result;
}
void InputReader::toggleCapsLockState(int32_t deviceId) {
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex < 0) {
ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
return;
}
InputDevice* device = mDevices.valueAt(deviceIndex);
if (device->isIgnored()) {
return;
}
device->updateMetaState(AKEYCODE_CAPS_LOCK);
}
bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
AutoMutex _l(mLock);
memset(outFlags, 0, numCodes);
return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
}
bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
bool result = false;
if (deviceId >= 0) {
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex >= 0) {
InputDevice* device = mDevices.valueAt(deviceIndex);
if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
result = device->markSupportedKeyCodes(sourceMask,
numCodes, keyCodes, outFlags);
}
}
} else {
size_t numDevices = mDevices.size();
for (size_t i = 0; i < numDevices; i++) {
InputDevice* device = mDevices.valueAt(i);
if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
result |= device->markSupportedKeyCodes(sourceMask,
numCodes, keyCodes, outFlags);
}
}
}
return result;
}
void InputReader::requestRefreshConfiguration(uint32_t changes) {
AutoMutex _l(mLock);
if (changes) {
bool needWake = !mConfigurationChangesToRefresh;
mConfigurationChangesToRefresh |= changes;
if (needWake) {
mEventHub->wake();
}
}
}
void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
ssize_t repeat, int32_t token) {
AutoMutex _l(mLock);
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex >= 0) {
InputDevice* device = mDevices.valueAt(deviceIndex);
device->vibrate(pattern, patternSize, repeat, token);
}
}
void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
AutoMutex _l(mLock);
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex >= 0) {
InputDevice* device = mDevices.valueAt(deviceIndex);
device->cancelVibrate(token);
}
}
bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
AutoMutex _l(mLock);
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex >= 0) {
InputDevice* device = mDevices.valueAt(deviceIndex);
return device->isEnabled();
}
ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
return false;
}
void InputReader::dump(String8& dump) {
AutoMutex _l(mLock);
mEventHub->dump(dump);
dump.append("\n");
dump.append("Input Reader State:\n");
for (size_t i = 0; i < mDevices.size(); i++) {
mDevices.valueAt(i)->dump(dump);
}
dump.append(INDENT "Configuration:\n");
dump.append(INDENT2 "ExcludedDeviceNames: [");
for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
if (i != 0) {
dump.append(", ");
}
dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
}
dump.append("]\n");
dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
mConfig.virtualKeyQuietTime * 0.000001f);
dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
"scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
mConfig.pointerVelocityControlParameters.scale,
mConfig.pointerVelocityControlParameters.lowThreshold,
mConfig.pointerVelocityControlParameters.highThreshold,
mConfig.pointerVelocityControlParameters.acceleration);
dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
"scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
mConfig.wheelVelocityControlParameters.scale,
mConfig.wheelVelocityControlParameters.lowThreshold,
mConfig.wheelVelocityControlParameters.highThreshold,
mConfig.wheelVelocityControlParameters.acceleration);
dump.appendFormat(INDENT2 "PointerGesture:\n");
dump.appendFormat(INDENT3 "Enabled: %s\n",
toString(mConfig.pointerGesturesEnabled));
dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
mConfig.pointerGestureQuietInterval * 0.000001f);
dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
mConfig.pointerGestureDragMinSwitchSpeed);
dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
mConfig.pointerGestureTapInterval * 0.000001f);
dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
mConfig.pointerGestureTapDragInterval * 0.000001f);
dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
mConfig.pointerGestureTapSlop);
dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
mConfig.pointerGestureMultitouchMinDistance);
dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
mConfig.pointerGestureSwipeTransitionAngleCosine);
dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
mConfig.pointerGestureSwipeMaxWidthRatio);
dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
mConfig.pointerGestureMovementSpeedRatio);
dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
mConfig.pointerGestureZoomSpeedRatio);
dump.append(INDENT3 "Viewports:\n");
mConfig.dump(dump);
}
void InputReader::monitor() {
// Acquire and release the lock to ensure that the reader has not deadlocked.
mLock.lock();
mEventHub->wake();
mReaderIsAliveCondition.wait(mLock);
mLock.unlock();
// Check the EventHub
mEventHub->monitor();
}
// --- InputReader::ContextImpl ---
InputReader::ContextImpl::ContextImpl(InputReader* reader) :
mReader(reader) {
}
void InputReader::ContextImpl::updateGlobalMetaState() {
// lock is already held by the input loop
mReader->updateGlobalMetaStateLocked();
}
int32_t InputReader::ContextImpl::getGlobalMetaState() {
// lock is already held by the input loop
return mReader->getGlobalMetaStateLocked();
}
void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
// lock is already held by the input loop
mReader->disableVirtualKeysUntilLocked(time);
}
bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
InputDevice* device, int32_t keyCode, int32_t scanCode) {
// lock is already held by the input loop
return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
}
void InputReader::ContextImpl::fadePointer() {
// lock is already held by the input loop
mReader->fadePointerLocked();
}
void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
// lock is already held by the input loop
mReader->requestTimeoutAtTimeLocked(when);
}
int32_t InputReader::ContextImpl::bumpGeneration() {
// lock is already held by the input loop
return mReader->bumpGenerationLocked();
}
void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
// lock is already held by whatever called refreshConfigurationLocked
mReader->getExternalStylusDevicesLocked(outDevices);
}
void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
mReader->dispatchExternalStylusState(state);
}
InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
return mReader->mPolicy.get();
}
InputListenerInterface* InputReader::ContextImpl::getListener() {
return mReader->mQueuedListener.get();
}
EventHubInterface* InputReader::ContextImpl::getEventHub() {
return mReader->mEventHub.get();
}
// --- InputReaderThread ---
InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
Thread(/*canCallJava*/ true), mReader(reader) {
}
InputReaderThread::~InputReaderThread() {
}
bool InputReaderThread::threadLoop() {
mReader->loopOnce();
return true;
}
// --- InputDevice ---
InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
mIdentifier(identifier), mClasses(classes),
mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
}
InputDevice::~InputDevice() {
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
delete mMappers[i];
}
mMappers.clear();
}
bool InputDevice::isEnabled() {
return getEventHub()->isDeviceEnabled(mId);
}
void InputDevice::setEnabled(bool enabled, nsecs_t when) {
if (isEnabled() == enabled) {
return;
}
if (enabled) {
getEventHub()->enableDevice(mId);
reset(when);
} else {
reset(when);
getEventHub()->disableDevice(mId);
}
// Must change generation to flag this device as changed
bumpGeneration();
}
void InputDevice::dump(String8& dump) {
InputDeviceInfo deviceInfo;
getDeviceInfo(& deviceInfo);
dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
deviceInfo.getDisplayName().string());
dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
dump.appendFormat(INDENT2 "HasMic: %s\n", toString(mHasMic));
dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
if (!ranges.isEmpty()) {
dump.append(INDENT2 "Motion Ranges:\n");
for (size_t i = 0; i < ranges.size(); i++) {
const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
const char* label = getAxisLabel(range.axis);
char name[32];
if (label) {
strncpy(name, label, sizeof(name));
name[sizeof(name) - 1] = '\0';
} else {
snprintf(name, sizeof(name), "%d", range.axis);
}
dump.appendFormat(INDENT3 "%s: source=0x%08x, "
"min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
name, range.source, range.min, range.max, range.flat, range.fuzz,
range.resolution);
}
}
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->dump(dump);
}
}
void InputDevice::addMapper(InputMapper* mapper) {
mMappers.add(mapper);
}
void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
mSources = 0;
if (!isIgnored()) {
if (!changes) { // first time only
mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
}
if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
sp<KeyCharacterMap> keyboardLayout =
mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
bumpGeneration();
}
}
}
if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
if (mAlias != alias) {
mAlias = alias;
bumpGeneration();
}
}
}
if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
ssize_t index = config->disabledDevices.indexOf(mId);
bool enabled = index < 0;
setEnabled(enabled, when);
}
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->configure(when, config, changes);
mSources |= mapper->getSources();
}
}
}
void InputDevice::reset(nsecs_t when) {
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->reset(when);
}
mContext->updateGlobalMetaState();
notifyReset(when);
}
void InputDevice::process(const RawEvent* rawEvents, size_t count) {
// Process all of the events in order for each mapper.
// We cannot simply ask each mapper to process them in bulk because mappers may
// have side-effects that must be interleaved. For example, joystick movement events and
// gamepad button presses are handled by different mappers but they should be dispatched
// in the order received.
size_t numMappers = mMappers.size();
for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
#if DEBUG_RAW_EVENTS
ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
rawEvent->when);
#endif
if (mDropUntilNextSync) {
if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
mDropUntilNextSync = false;
#if DEBUG_RAW_EVENTS
ALOGD("Recovered from input event buffer overrun.");
#endif
} else {
#if DEBUG_RAW_EVENTS
ALOGD("Dropped input event while waiting for next input sync.");
#endif
}
} else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
ALOGI("Detected input event buffer overrun for device %s.", getName().string());
mDropUntilNextSync = true;
reset(rawEvent->when);
} else {
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->process(rawEvent);
}
}
}
}
void InputDevice::timeoutExpired(nsecs_t when) {
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->timeoutExpired(when);
}
}
void InputDevice::updateExternalStylusState(const StylusState& state) {
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->updateExternalStylusState(state);
}
}
void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
mIsExternal, mHasMic);
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->populateDeviceInfo(outDeviceInfo);
}
}
int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
}
int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
}
int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
}
int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
int32_t result = AKEY_STATE_UNKNOWN;
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
// If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
// value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
if (currentResult >= AKEY_STATE_DOWN) {
return currentResult;
} else if (currentResult == AKEY_STATE_UP) {
result = currentResult;
}
}
}
return result;
}
bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
const int32_t* keyCodes, uint8_t* outFlags) {
bool result = false;
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
}
}
return result;
}
void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
int32_t token) {
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->vibrate(pattern, patternSize, repeat, token);
}
}
void InputDevice::cancelVibrate(int32_t token) {
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->cancelVibrate(token);
}
}
void InputDevice::cancelTouch(nsecs_t when) {
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->cancelTouch(when);
}
}
int32_t InputDevice::getMetaState() {
int32_t result = 0;
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
result |= mapper->getMetaState();
}
return result;
}
void InputDevice::updateMetaState(int32_t keyCode) {
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
mMappers[i]->updateMetaState(keyCode);
}
}
void InputDevice::fadePointer() {
size_t numMappers = mMappers.size();
for (size_t i = 0; i < numMappers; i++) {
InputMapper* mapper = mMappers[i];
mapper->fadePointer();
}
}
void InputDevice::bumpGeneration() {
mGeneration = mContext->bumpGeneration();
}
void InputDevice::notifyReset(nsecs_t when) {
NotifyDeviceResetArgs args(when, mId);
mContext->getListener()->notifyDeviceReset(&args);
}
// --- CursorButtonAccumulator ---
CursorButtonAccumulator::CursorButtonAccumulator() {
clearButtons();
}
void CursorButtonAccumulator::reset(InputDevice* device) {
mBtnLeft = device->isKeyPressed(BTN_LEFT);
mBtnRight = device->isKeyPressed(BTN_RIGHT);
mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
mBtnBack = device->isKeyPressed(BTN_BACK);
mBtnSide = device->isKeyPressed(BTN_SIDE);
mBtnForward = device->isKeyPressed(BTN_FORWARD);
mBtnExtra = device->isKeyPressed(BTN_EXTRA);
mBtnTask = device->isKeyPressed(BTN_TASK);
}
void CursorButtonAccumulator::clearButtons() {
mBtnLeft = 0;
mBtnRight = 0;
mBtnMiddle = 0;
mBtnBack = 0;
mBtnSide = 0;
mBtnForward = 0;
mBtnExtra = 0;
mBtnTask = 0;
}
void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
if (rawEvent->type == EV_KEY) {
switch (rawEvent->code) {
case BTN_LEFT:
mBtnLeft = rawEvent->value;
break;
case BTN_RIGHT:
mBtnRight = rawEvent->value;
break;
case BTN_MIDDLE:
mBtnMiddle = rawEvent->value;
break;
case BTN_BACK:
mBtnBack = rawEvent->value;
break;
case BTN_SIDE:
mBtnSide = rawEvent->value;
break;
case BTN_FORWARD:
mBtnForward = rawEvent->value;
break;
case BTN_EXTRA:
mBtnExtra = rawEvent->value;
break;
case BTN_TASK:
mBtnTask = rawEvent->value;
break;
}
}
}
uint32_t CursorButtonAccumulator::getButtonState() const {
uint32_t result = 0;
if (mBtnLeft) {
result |= AMOTION_EVENT_BUTTON_PRIMARY;
}
if (mBtnRight) {
result |= AMOTION_EVENT_BUTTON_SECONDARY;
}
if (mBtnMiddle) {
result |= AMOTION_EVENT_BUTTON_TERTIARY;
}
if (mBtnBack || mBtnSide) {
result |= AMOTION_EVENT_BUTTON_BACK;
}
if (mBtnForward || mBtnExtra) {
result |= AMOTION_EVENT_BUTTON_FORWARD;
}
return result;
}
// --- CursorMotionAccumulator ---
CursorMotionAccumulator::CursorMotionAccumulator() {
clearRelativeAxes();
}
void CursorMotionAccumulator::reset(InputDevice* device) {
clearRelativeAxes();
}
void CursorMotionAccumulator::clearRelativeAxes() {
mRelX = 0;
mRelY = 0;
}
void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
if (rawEvent->type == EV_REL) {
switch (rawEvent->code) {
case REL_X:
mRelX = rawEvent->value;
break;
case REL_Y:
mRelY = rawEvent->value;
break;
}
}
}
void CursorMotionAccumulator::finishSync() {
clearRelativeAxes();
}
// --- CursorScrollAccumulator ---
CursorScrollAccumulator::CursorScrollAccumulator() :
mHaveRelWheel(false), mHaveRelHWheel(false) {
clearRelativeAxes();
}
void CursorScrollAccumulator::configure(InputDevice* device) {
mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
}
void CursorScrollAccumulator::reset(InputDevice* device) {
clearRelativeAxes();
}
void CursorScrollAccumulator::clearRelativeAxes() {
mRelWheel = 0;
mRelHWheel = 0;
}
void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
if (rawEvent->type == EV_REL) {
switch (rawEvent->code) {
case REL_WHEEL:
mRelWheel = rawEvent->value;
break;
case REL_HWHEEL:
mRelHWheel = rawEvent->value;
break;
}
}
}
void CursorScrollAccumulator::finishSync() {
clearRelativeAxes();
}
// --- TouchButtonAccumulator ---
TouchButtonAccumulator::TouchButtonAccumulator() :
mHaveBtnTouch(false), mHaveStylus(false) {
clearButtons();
}
void TouchButtonAccumulator::configure(InputDevice* device) {
mHaveBtnTouch = device->hasKey(BTN_TOUCH);
mHaveStylus = device->hasKey(BTN_TOOL_PEN)
|| device->hasKey(BTN_TOOL_RUBBER)
|| device->hasKey(BTN_TOOL_BRUSH)
|| device->hasKey(BTN_TOOL_PENCIL)
|| device->hasKey(BTN_TOOL_AIRBRUSH);
}
void TouchButtonAccumulator::reset(InputDevice* device) {
mBtnTouch = device->isKeyPressed(BTN_TOUCH);
mBtnStylus = device->isKeyPressed(BTN_STYLUS);
// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
mBtnStylus2 =
device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
}
void TouchButtonAccumulator::clearButtons() {
mBtnTouch = 0;
mBtnStylus = 0;
mBtnStylus2 = 0;
mBtnToolFinger = 0;
mBtnToolPen = 0;
mBtnToolRubber = 0;
mBtnToolBrush = 0;
mBtnToolPencil = 0;
mBtnToolAirbrush = 0;
mBtnToolMouse = 0;
mBtnToolLens = 0;
mBtnToolDoubleTap = 0;
mBtnToolTripleTap = 0;
mBtnToolQuadTap = 0;
}
void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
if (rawEvent->type == EV_KEY) {
switch (rawEvent->code) {
case BTN_TOUCH:
mBtnTouch = rawEvent->value;
break;
case BTN_STYLUS:
mBtnStylus = rawEvent->value;
break;
case BTN_STYLUS2:
case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
mBtnStylus2 = rawEvent->value;
break;
case BTN_TOOL_FINGER:
mBtnToolFinger = rawEvent->value;
break;
case BTN_TOOL_PEN:
mBtnToolPen = rawEvent->value;
break;
case BTN_TOOL_RUBBER:
mBtnToolRubber = rawEvent->value;
break;
case BTN_TOOL_BRUSH:
mBtnToolBrush = rawEvent->value;
break;
case BTN_TOOL_PENCIL:
mBtnToolPencil = rawEvent->value;
break;
case BTN_TOOL_AIRBRUSH:
mBtnToolAirbrush = rawEvent->value;
break;
case BTN_TOOL_MOUSE:
mBtnToolMouse = rawEvent->value;
break;
case BTN_TOOL_LENS:
mBtnToolLens = rawEvent->value;
break;
case BTN_TOOL_DOUBLETAP:
mBtnToolDoubleTap = rawEvent->value;
break;
case BTN_TOOL_TRIPLETAP:
mBtnToolTripleTap = rawEvent->value;
break;
case BTN_TOOL_QUADTAP:
mBtnToolQuadTap = rawEvent->value;
break;
}
}
}
uint32_t TouchButtonAccumulator::getButtonState() const {
uint32_t result = 0;
if (mBtnStylus) {
result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
}
if (mBtnStylus2) {
result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
}
return result;
}
int32_t TouchButtonAccumulator::getToolType() const {
if (mBtnToolMouse || mBtnToolLens) {
return AMOTION_EVENT_TOOL_TYPE_MOUSE;
}
if (mBtnToolRubber) {
return AMOTION_EVENT_TOOL_TYPE_ERASER;
}
if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
return AMOTION_EVENT_TOOL_TYPE_STYLUS;
}
if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
return AMOTION_EVENT_TOOL_TYPE_FINGER;
}
return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
}
bool TouchButtonAccumulator::isToolActive() const {
return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
|| mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
|| mBtnToolMouse || mBtnToolLens
|| mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
}
bool TouchButtonAccumulator::isHovering() const {
return mHaveBtnTouch && !mBtnTouch;
}
bool TouchButtonAccumulator::hasStylus() const {
return mHaveStylus;
}
// --- RawPointerAxes ---
RawPointerAxes::RawPointerAxes() {
clear();
}
void RawPointerAxes::clear() {
x.clear();
y.clear();
pressure.clear();
touchMajor.clear();
touchMinor.clear();
toolMajor.clear();
toolMinor.clear();
orientation.clear();
distance.clear();
tiltX.clear();
tiltY.clear();
trackingId.clear();
slot.clear();
}
// --- RawPointerData ---
RawPointerData::RawPointerData() {
clear();
}
void RawPointerData::clear() {
pointerCount = 0;
clearIdBits();
}
void RawPointerData::copyFrom(const RawPointerData& other) {
pointerCount = other.pointerCount;
hoveringIdBits = other.hoveringIdBits;
touchingIdBits = other.touchingIdBits;
for (uint32_t i = 0; i < pointerCount; i++) {
pointers[i] = other.pointers[i];
int id = pointers[i].id;
idToIndex[id] = other.idToIndex[id];
}
}
void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
float x = 0, y = 0;
uint32_t count = touchingIdBits.count();
if (count) {
for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
uint32_t id = idBits.clearFirstMarkedBit();
const Pointer& pointer = pointerForId(id);
x += pointer.x;
y += pointer.y;
}
x /= count;
y /= count;
}
*outX = x;
*outY = y;
}
// --- CookedPointerData ---
CookedPointerData::CookedPointerData() {
clear();
}
void CookedPointerData::clear() {
pointerCount = 0;
hoveringIdBits.clear();
touchingIdBits.clear();
}
void CookedPointerData::copyFrom(const CookedPointerData& other) {
pointerCount = other.pointerCount;
hoveringIdBits = other.hoveringIdBits;
touchingIdBits = other.touchingIdBits;
for (uint32_t i = 0; i < pointerCount; i++) {
pointerProperties[i].copyFrom(other.pointerProperties[i]);
pointerCoords[i].copyFrom(other.pointerCoords[i]);
int id = pointerProperties[i].id;
idToIndex[id] = other.idToIndex[id];
}
}
// --- SingleTouchMotionAccumulator ---
SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
clearAbsoluteAxes();
}
void SingleTouchMotionAccumulator::reset(InputDevice* device) {
mAbsX = device->getAbsoluteAxisValue(ABS_X);
mAbsY = device->getAbsoluteAxisValue(ABS_Y);
mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
}
void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
mAbsX = 0;
mAbsY = 0;
mAbsPressure = 0;
mAbsToolWidth = 0;
mAbsDistance = 0;
mAbsTiltX = 0;
mAbsTiltY = 0;
}
void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
if (rawEvent->type == EV_ABS) {
switch (rawEvent->code) {
case ABS_X:
mAbsX = rawEvent->value;
break;
case ABS_Y:
mAbsY = rawEvent->value;
break;
case ABS_PRESSURE:
mAbsPressure = rawEvent->value;
break;
case ABS_TOOL_WIDTH:
mAbsToolWidth = rawEvent->value;
break;
case ABS_DISTANCE:
mAbsDistance = rawEvent->value;
break;
case ABS_TILT_X:
mAbsTiltX = rawEvent->value;
break;
case ABS_TILT_Y:
mAbsTiltY = rawEvent->value;
break;
}
}
}
// --- MultiTouchMotionAccumulator ---
MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
mHaveStylus(false) {
}
MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
delete[] mSlots;
}
void MultiTouchMotionAccumulator::configure(InputDevice* device,
size_t slotCount, bool usingSlotsProtocol) {
mSlotCount = slotCount;
mUsingSlotsProtocol = usingSlotsProtocol;
mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
delete[] mSlots;
mSlots = new Slot[slotCount];
}
void MultiTouchMotionAccumulator::reset(InputDevice* device) {
// Unfortunately there is no way to read the initial contents of the slots.
// So when we reset the accumulator, we must assume they are all zeroes.
if (mUsingSlotsProtocol) {
// Query the driver for the current slot index and use it as the initial slot
// before we start reading events from the device. It is possible that the
// current slot index will not be the same as it was when the first event was
// written into the evdev buffer, which means the input mapper could start
// out of sync with the initial state of the events in the evdev buffer.
// In the extremely unlikely case that this happens, the data from
// two slots will be confused until the next ABS_MT_SLOT event is received.
// This can cause the touch point to "jump", but at least there will be
// no stuck touches.
int32_t initialSlot;
status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
ABS_MT_SLOT, &initialSlot);
if (status) {
ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
initialSlot = -1;
}
clearSlots(initialSlot);
} else {
clearSlots(-1);
}
}
void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
if (mSlots) {
for (size_t i = 0; i < mSlotCount; i++) {
mSlots[i].clear();
}
}
mCurrentSlot = initialSlot;
}
void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
if (rawEvent->type == EV_ABS) {
bool newSlot = false;
if (mUsingSlotsProtocol) {
if (rawEvent->code == ABS_MT_SLOT) {
mCurrentSlot = rawEvent->value;
newSlot = true;
}
} else if (mCurrentSlot < 0) {
mCurrentSlot = 0;
}
if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
#if DEBUG_POINTERS
if (newSlot) {
ALOGW("MultiTouch device emitted invalid slot index %d but it "
"should be between 0 and %d; ignoring this slot.",
mCurrentSlot, mSlotCount - 1);
}
#endif
} else {
Slot* slot = &mSlots[mCurrentSlot];
switch (rawEvent->code) {
case ABS_MT_POSITION_X:
slot->mInUse = true;
slot->mAbsMTPositionX = rawEvent->value;
break;
case ABS_MT_POSITION_Y:
slot->mInUse = true;
slot->mAbsMTPositionY = rawEvent->value;
break;
case ABS_MT_TOUCH_MAJOR:
slot->mInUse = true;
slot->mAbsMTTouchMajor = rawEvent->value;
break;
case ABS_MT_TOUCH_MINOR:
slot->mInUse = true;
slot->mAbsMTTouchMinor = rawEvent->value;
slot->mHaveAbsMTTouchMinor = true;
break;
case ABS_MT_WIDTH_MAJOR:
slot->mInUse = true;
slot->mAbsMTWidthMajor = rawEvent->value;
break;
case ABS_MT_WIDTH_MINOR:
slot->mInUse = true;
slot->mAbsMTWidthMinor = rawEvent->value;
slot->mHaveAbsMTWidthMinor = true;
break;
case ABS_MT_ORIENTATION:
slot->mInUse = true;
slot->mAbsMTOrientation = rawEvent->value;
break;
case ABS_MT_TRACKING_ID:
if (mUsingSlotsProtocol && rawEvent->value < 0) {
// The slot is no longer in use but it retains its previous contents,
// which may be reused for subsequent touches.
slot->mInUse = false;
} else {
slot->mInUse = true;
slot->mAbsMTTrackingId = rawEvent->value;
}
break;
case ABS_MT_PRESSURE:
slot->mInUse = true;
slot->mAbsMTPressure = rawEvent->value;
break;
case ABS_MT_DISTANCE:
slot->mInUse = true;
slot->mAbsMTDistance = rawEvent->value;
break;
case ABS_MT_TOOL_TYPE:
slot->mInUse = true;
slot->mAbsMTToolType = rawEvent->value;
slot->mHaveAbsMTToolType = true;
break;
}
}
} else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
// MultiTouch Sync: The driver has returned all data for *one* of the pointers.
mCurrentSlot += 1;
}
}
void MultiTouchMotionAccumulator::finishSync() {
if (!mUsingSlotsProtocol) {
clearSlots(-1);
}
}
bool MultiTouchMotionAccumulator::hasStylus() const {
return mHaveStylus;
}
// --- MultiTouchMotionAccumulator::Slot ---
MultiTouchMotionAccumulator::Slot::Slot() {
clear();
}
void MultiTouchMotionAccumulator::Slot::clear() {
mInUse = false;
mHaveAbsMTTouchMinor = false;
mHaveAbsMTWidthMinor = false;
mHaveAbsMTToolType = false;
mAbsMTPositionX = 0;
mAbsMTPositionY = 0;
mAbsMTTouchMajor = 0;
mAbsMTTouchMinor = 0;
mAbsMTWidthMajor = 0;
mAbsMTWidthMinor = 0;
mAbsMTOrientation = 0;
mAbsMTTrackingId = -1;
mAbsMTPressure = 0;
mAbsMTDistance = 0;
mAbsMTToolType = 0;
}
int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
if (mHaveAbsMTToolType) {
switch (mAbsMTToolType) {
case MT_TOOL_FINGER:
return AMOTION_EVENT_TOOL_TYPE_FINGER;
case MT_TOOL_PEN:
return AMOTION_EVENT_TOOL_TYPE_STYLUS;
}
}
return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
}
// --- InputMapper ---
InputMapper::InputMapper(InputDevice* device) :
mDevice(device), mContext(device->getContext()) {
}
InputMapper::~InputMapper() {
}
void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
info->addSource(getSources());
}
void InputMapper::dump(String8& dump) {
}
void InputMapper::configure(nsecs_t when,
const InputReaderConfiguration* config, uint32_t changes) {
}
void InputMapper::reset(nsecs_t when) {
}
void InputMapper::timeoutExpired(nsecs_t when) {
}
int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
return AKEY_STATE_UNKNOWN;
}
int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
return AKEY_STATE_UNKNOWN;
}
int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
return AKEY_STATE_UNKNOWN;
}
bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
const int32_t* keyCodes, uint8_t* outFlags) {
return false;
}
void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
int32_t token) {
}
void InputMapper::cancelVibrate(int32_t token) {
}
void InputMapper::cancelTouch(nsecs_t when) {
}
int32_t InputMapper::getMetaState() {
return 0;
}
void InputMapper::updateMetaState(int32_t keyCode) {
}
void InputMapper::updateExternalStylusState(const StylusState& state) {
}
void InputMapper::fadePointer() {
}
status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
}
void InputMapper::bumpGeneration() {
mDevice->bumpGeneration();
}
void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
const RawAbsoluteAxisInfo& axis, const char* name) {
if (axis.valid) {
dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
} else {
dump.appendFormat(INDENT4 "%s: unknown range\n", name);
}
}
void InputMapper::dumpStylusState(String8& dump, const StylusState& state) {
dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when);
dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure);
dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons);
dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
}
// --- SwitchInputMapper ---
SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
}
SwitchInputMapper::~SwitchInputMapper() {
}
uint32_t SwitchInputMapper::getSources() {
return AINPUT_SOURCE_SWITCH;
}
void SwitchInputMapper::process(const RawEvent* rawEvent) {
switch (rawEvent->type) {
case EV_SW:
processSwitch(rawEvent->code, rawEvent->value);
break;
case EV_SYN:
if (rawEvent->code == SYN_REPORT) {
sync(rawEvent->when);
}
}
}
void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
if (switchCode >= 0 && switchCode < 32) {
if (switchValue) {
mSwitchValues |= 1 << switchCode;
} else {
mSwitchValues &= ~(1 << switchCode);
}
mUpdatedSwitchMask |= 1 << switchCode;
}
}
void SwitchInputMapper::sync(nsecs_t when) {
if (mUpdatedSwitchMask) {
uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
getListener()->notifySwitch(&args);
mUpdatedSwitchMask = 0;
}
}
int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
return getEventHub()->getSwitchState(getDeviceId(), switchCode);
}
void SwitchInputMapper::dump(String8& dump) {
dump.append(INDENT2 "Switch Input Mapper:\n");
dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
}
// --- VibratorInputMapper ---
VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
InputMapper(device), mVibrating(false) {
}
VibratorInputMapper::~VibratorInputMapper() {
}
uint32_t VibratorInputMapper::getSources() {
return 0;
}
void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
InputMapper::populateDeviceInfo(info);
info->setVibrator(true);
}
void VibratorInputMapper::process(const RawEvent* rawEvent) {
// TODO: Handle FF_STATUS, although it does not seem to be widely supported.
}
void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
int32_t token) {
#if DEBUG_VIBRATOR
String8 patternStr;
for (size_t i = 0; i < patternSize; i++) {
if (i != 0) {
patternStr.append(", ");
}
patternStr.appendFormat("%lld", pattern[i]);
}
ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
getDeviceId(), patternStr.string(), repeat, token);
#endif
mVibrating = true;
memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
mPatternSize = patternSize;
mRepeat = repeat;
mToken = token;
mIndex = -1;
nextStep();
}
void VibratorInputMapper::cancelVibrate(int32_t token) {
#if DEBUG_VIBRATOR
ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
#endif
if (mVibrating && mToken == token) {
stopVibrating();
}
}
void VibratorInputMapper::timeoutExpired(nsecs_t when) {
if (mVibrating) {
if (when >= mNextStepTime) {
nextStep();
} else {
getContext()->requestTimeoutAtTime(mNextStepTime);
}
}
}
void VibratorInputMapper::nextStep() {
mIndex += 1;
if (size_t(mIndex) >= mPatternSize) {
if (mRepeat < 0) {
// We are done.
stopVibrating();
return;
}
mIndex = mRepeat;
}
bool vibratorOn = mIndex & 1;
nsecs_t duration = mPattern[mIndex];
if (vibratorOn) {
#if DEBUG_VIBRATOR
ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
getDeviceId(), duration);
#endif
getEventHub()->vibrate(getDeviceId(), duration);
} else {
#if DEBUG_VIBRATOR
ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
#endif
getEventHub()->cancelVibrate(getDeviceId());
}
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
mNextStepTime = now + duration;
getContext()->requestTimeoutAtTime(mNextStepTime);
#if DEBUG_VIBRATOR
ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
#endif
}
void VibratorInputMapper::stopVibrating() {
mVibrating = false;
#if DEBUG_VIBRATOR
ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
#endif
getEventHub()->cancelVibrate(getDeviceId());
}
void VibratorInputMapper::dump(String8& dump) {
dump.append(INDENT2 "Vibrator Input Mapper:\n");
dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
}
// --- KeyboardInputMapper ---
KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
uint32_t source, int32_t keyboardType) :
InputMapper(device), mSource(source),
mKeyboardType(keyboardType) {
}
KeyboardInputMapper::~KeyboardInputMapper() {
}
uint32_t KeyboardInputMapper::getSources() {
return mSource;
}
void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
InputMapper::populateDeviceInfo(info);
info->setKeyboardType(mKeyboardType);
info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
}
void KeyboardInputMapper::dump(String8& dump) {
dump.append(INDENT2 "Keyboard Input Mapper:\n");
dumpParameters(dump);
dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
}
void KeyboardInputMapper::configure(nsecs_t when,
const InputReaderConfiguration* config, uint32_t changes) {
InputMapper::configure(when, config, changes);
if (!changes) { // first time only
// Configure basic parameters.
configureParameters();
}
if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
DisplayViewport v;
if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
mOrientation = v.orientation;
} else {
mOrientation = DISPLAY_ORIENTATION_0;
}
} else {
mOrientation = DISPLAY_ORIENTATION_0;
}
}
}
static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
int32_t mapped = 0;
if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
if (stemKeyRotationMap[i][0] == keyCode) {
stemKeyRotationMap[i][1] = mapped;
return;
}
}
}
}
void KeyboardInputMapper::configureParameters() {
mParameters.orientationAware = false;
const PropertyMap& config = getDevice()->getConfiguration();
config.tryGetProperty(String8("keyboard.orientationAware"),
mParameters.orientationAware);
mParameters.hasAssociatedDisplay = false;
if (mParameters.orientationAware) {
mParameters.hasAssociatedDisplay = true;
mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
}
mParameters.handlesKeyRepeat = false;
config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
mParameters.handlesKeyRepeat);
}
void KeyboardInputMapper::dumpParameters(String8& dump) {
dump.append(INDENT3 "Parameters:\n");
dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
toString(mParameters.hasAssociatedDisplay));
dump.appendFormat(INDENT4 "OrientationAware: %s\n",
toString(mParameters.orientationAware));
dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
toString(mParameters.handlesKeyRepeat));
}
void KeyboardInputMapper::reset(nsecs_t when) {
mMetaState = AMETA_NONE;
mDownTime = 0;
mKeyDowns.clear();
mCurrentHidUsage = 0;
resetLedState();
InputMapper::reset(when);
}
void KeyboardInputMapper::process(const RawEvent* rawEvent) {
switch (rawEvent->type) {
case EV_KEY: {
int32_t scanCode = rawEvent->code;
int32_t usageCode = mCurrentHidUsage;
mCurrentHidUsage = 0;
if (isKeyboardOrGamepadKey(scanCode)) {
processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
}
break;
}
case EV_MSC: {
if (rawEvent->code == MSC_SCAN) {
mCurrentHidUsage = rawEvent->value;
}
break;
}
case EV_SYN: {
if (rawEvent->code == SYN_REPORT) {
mCurrentHidUsage = 0;
}
}
}
}
bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
return scanCode < BTN_MOUSE
|| scanCode >= KEY_OK
|| (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
|| (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
}
bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
switch (keyCode) {
case AKEYCODE_MEDIA_PLAY:
case AKEYCODE_MEDIA_PAUSE:
case AKEYCODE_MEDIA_PLAY_PAUSE:
case AKEYCODE_MUTE:
case AKEYCODE_HEADSETHOOK:
case AKEYCODE_MEDIA_STOP:
case AKEYCODE_MEDIA_NEXT:
case AKEYCODE_MEDIA_PREVIOUS:
case AKEYCODE_MEDIA_REWIND:
case AKEYCODE_MEDIA_RECORD:
case AKEYCODE_MEDIA_FAST_FORWARD:
case AKEYCODE_MEDIA_SKIP_FORWARD:
case AKEYCODE_MEDIA_SKIP_BACKWARD:
case AKEYCODE_MEDIA_STEP_FORWARD:
case AKEYCODE_MEDIA_STEP_BACKWARD:
case AKEYCODE_MEDIA_AUDIO_TRACK:
case AKEYCODE_VOLUME_UP:
case AKEYCODE_VOLUME_DOWN:
case AKEYCODE_VOLUME_MUTE:
case AKEYCODE_TV_AUDIO_DESCRIPTION:
case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
return true;
}
return false;
}
void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
int32_t usageCode) {
int32_t keyCode;
int32_t keyMetaState;
uint32_t policyFlags;
if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
&keyCode, &keyMetaState, &policyFlags)) {
keyCode = AKEYCODE_UNKNOWN;
keyMetaState = mMetaState;
policyFlags = 0;
}
if (down) {
// Rotate key codes according to orientation if needed.
if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
keyCode = rotateKeyCode(keyCode, mOrientation);
}
// Add key down.
ssize_t keyDownIndex = findKeyDown(scanCode);
if (keyDownIndex >= 0) {
// key repeat, be sure to use same keycode as before in case of rotation
keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
} else {
// key down
if ((policyFlags & POLICY_FLAG_VIRTUAL)
&& mContext->shouldDropVirtualKey(when,
getDevice(), keyCode, scanCode)) {
return;
}
if (policyFlags & POLICY_FLAG_GESTURE) {
mDevice->cancelTouch(when);
}
mKeyDowns.push();
KeyDown& keyDown = mKeyDowns.editTop();
keyDown.keyCode = keyCode;
keyDown.scanCode = scanCode;
}
mDownTime = when;
} else {
// Remove key down.
ssize_t keyDownIndex = findKeyDown(scanCode);
if (keyDownIndex >= 0) {
// key up, be sure to use same keycode as before in case of rotation
keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
mKeyDowns.removeAt(size_t(keyDownIndex));
} else {
// key was not actually down
ALOGI("Dropping key up from device %s because the key was not down. "
"keyCode=%d, scanCode=%d",
getDeviceName().string(), keyCode, scanCode);
return;
}
}
if (updateMetaStateIfNeeded(keyCode, down)) {
// If global meta state changed send it along with the key.
// If it has not changed then we'll use what keymap gave us,
// since key replacement logic might temporarily reset a few
// meta bits for given key.
keyMetaState = mMetaState;
}
nsecs_t downTime = mDownTime;
// Key down on external an keyboard should wake the device.
// We don't do this for internal keyboards to prevent them from waking up in your pocket.
// For internal keyboards, the key layout file should specify the policy flags for
// each wake key individually.
// TODO: Use the input device configuration to control this behavior more finely.
if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
policyFlags |= POLICY_FLAG_WAKE;
}
if (mParameters.handlesKeyRepeat) {
policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
}
NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
getListener()->notifyKey(&args);
}
ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
size_t n = mKeyDowns.size();
for (size_t i = 0; i < n; i++) {
if (mKeyDowns[i].scanCode == scanCode) {
return i;
}
}
return -1;
}
int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
}
int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
}
bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
const int32_t* keyCodes, uint8_t* outFlags) {
return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
}
int32_t KeyboardInputMapper::getMetaState() {
return mMetaState;
}
void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
updateMetaStateIfNeeded(keyCode, false);
}
bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
int32_t oldMetaState = mMetaState;
int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
bool metaStateChanged = oldMetaState != newMetaState;
if (metaStateChanged) {
mMetaState = newMetaState;
updateLedState(false);
getContext()->updateGlobalMetaState();
}
return metaStateChanged;
}
void KeyboardInputMapper::resetLedState() {
initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
updateLedState(true);
}
void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
ledState.on = false;
}
void KeyboardInputMapper::updateLedState(bool reset) {
updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
AMETA_CAPS_LOCK_ON, reset);
updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
AMETA_NUM_LOCK_ON, reset);
updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
AMETA_SCROLL_LOCK_ON, reset);
}
void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
int32_t led, int32_t modifier, bool reset) {
if (ledState.avail) {
bool desiredState = (mMetaState & modifier) != 0;
if (reset || ledState.on != desiredState) {
getEventHub()->setLedState(getDeviceId(), led, desiredState);
ledState.on = desiredState;
}
}
}
// --- CursorInputMapper ---
CursorInputMapper::CursorInputMapper(InputDevice* device) :
InputMapper(device) {
}
CursorInputMapper::~CursorInputMapper() {
}
uint32_t CursorInputMapper::getSources() {
return mSource;
}
void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
InputMapper::populateDeviceInfo(info);
if (mParameters.mode == Parameters::MODE_POINTER) {
float minX, minY, maxX, maxY;
if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
}
} else {
info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
}
info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
if (mCursorScrollAccumulator.haveRelativeVWheel()) {
info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
}
if (mCursorScrollAccumulator.haveRelativeHWheel()) {
info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
}
}
void CursorInputMapper::dump(String8& dump) {
dump.append(INDENT2 "Cursor Input Mapper:\n");
dumpParameters(dump);
dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
toString(mCursorScrollAccumulator.haveRelativeVWheel()));
dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
toString(mCursorScrollAccumulator.haveRelativeHWheel()));
dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
}
void CursorInputMapper::configure(nsecs_t when,
const InputReaderConfiguration* config, uint32_t changes) {
InputMapper::configure(when, config, changes);
if (!changes) { // first time only
mCursorScrollAccumulator.configure(getDevice());
// Configure basic parameters.
configureParameters();
// Configure device mode.
switch (mParameters.mode) {
case Parameters::MODE_POINTER_RELATIVE:
// Should not happen during first time configuration.
ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");