blob: a45b8a56ce020e37be19bc359f25369b09f9c585 [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 <android-base/stringprintf.h>
#include <input/Keyboard.h>
#include <input/VirtualKeyMap.h>
#include <statslog.h>
#define INDENT " "
#define INDENT2 " "
#define INDENT3 " "
#define INDENT4 " "
#define INDENT5 " "
using android::base::StringPrintf;
namespace android {
// --- Constants ---
// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
static constexpr size_t MAX_SLOTS = 32;
// Maximum amount of latency to add to touch events while waiting for data from an
// external stylus.
static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
// Maximum amount of time to wait on touch data before pushing out new pressure data.
static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
// Artificial latency on synthetic events created from stylus data without corresponding touch
// data.
static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
// How often to report input event statistics
static constexpr nsecs_t STATISTICS_REPORT_FREQUENCY = seconds_to_nanoseconds(5 * 60);
// --- 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, int32_t displayId,
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(context->getNextSequenceNum(), when, deviceId, source, displayId,
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, int32_t displayId,
uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
lastButtonState, currentButtonState,
AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
lastButtonState, currentButtonState,
AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
}
// --- InputReader ---
InputReader::InputReader(const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& policy,
const sp<InputListenerInterface>& listener) :
mContext(this), mEventHub(eventHub), mPolicy(policy),
mNextSequenceNum(1), 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;
std::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: %zu Count: %zu", 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.c_str());
} else {
ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
identifier.name.c_str(), 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 = nullptr;
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().c_str());
} else {
ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
device->getId(), device->getName().c_str(), 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(mContext.getNextSequenceNum(), 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(std::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()) {
InputDeviceInfo info;
device->getDeviceInfo(&info);
outDevices.push_back(info);
}
}
}
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().c_str(),
(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(std::vector<InputDeviceInfo>& outInputDevices) {
AutoMutex _l(mLock);
getInputDevicesLocked(outInputDevices);
}
void InputReader::getInputDevicesLocked(std::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()) {
InputDeviceInfo info;
device->getDeviceInfo(&info);
outInputDevices.push_back(info);
}
}
}
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;
}
bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
AutoMutex _l(mLock);
ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
if (deviceIndex < 0) {
ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
return false;
}
InputDevice* device = mDevices.valueAt(deviceIndex);
std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplay();
// No associated display. By default, can dispatch to all displays.
if (!associatedDisplayId) {
return true;
}
if (*associatedDisplayId == ADISPLAY_ID_NONE) {
ALOGW("Device has associated, but no associated display id.");
return true;
}
return *associatedDisplayId == displayId;
}
void InputReader::dump(std::string& dump) {
AutoMutex _l(mLock);
mEventHub->dump(dump);
dump += "\n";
dump += "Input Reader State:\n";
for (size_t i = 0; i < mDevices.size(); i++) {
mDevices.valueAt(i)->dump(dump);
}
dump += INDENT "Configuration:\n";
dump += INDENT2 "ExcludedDeviceNames: [";
for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
if (i != 0) {
dump += ", ";
}
dump += mConfig.excludedDeviceNames[i];
}
dump += "]\n";
dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
mConfig.virtualKeyQuietTime * 0.000001f);
dump += StringPrintf(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 += StringPrintf(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 += StringPrintf(INDENT2 "PointerGesture:\n");
dump += StringPrintf(INDENT3 "Enabled: %s\n",
toString(mConfig.pointerGesturesEnabled));
dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
mConfig.pointerGestureQuietInterval * 0.000001f);
dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
mConfig.pointerGestureDragMinSwitchSpeed);
dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
mConfig.pointerGestureTapInterval * 0.000001f);
dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
mConfig.pointerGestureTapDragInterval * 0.000001f);
dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
mConfig.pointerGestureTapSlop);
dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
mConfig.pointerGestureMultitouchMinDistance);
dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
mConfig.pointerGestureSwipeTransitionAngleCosine);
dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
mConfig.pointerGestureSwipeMaxWidthRatio);
dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
mConfig.pointerGestureMovementSpeedRatio);
dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
mConfig.pointerGestureZoomSpeedRatio);
dump += 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(std::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();
}
uint32_t InputReader::ContextImpl::getNextSequenceNum() {
return (mReader->mNextSequenceNum)++;
}
// --- 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(std::string& dump) {
InputDeviceInfo deviceInfo;
getDeviceInfo(&deviceInfo);
dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
deviceInfo.getDisplayName().c_str());
dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
if (mAssociatedDisplayPort) {
dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
} else {
dump += "<none>\n";
}
dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
if (!ranges.empty()) {
dump += INDENT2 "Motion Ranges:\n";
for (size_t i = 0; i < ranges.size(); i++) {
const InputDeviceInfo::MotionRange& range = ranges[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 += StringPrintf(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.push_back(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)) {
std::string 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);
}
if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
// In most situations, no port will be specified.
mAssociatedDisplayPort = std::nullopt;
// Find the display port that corresponds to the current input port.
const std::string& inputPort = mIdentifier.location;
if (!inputPort.empty()) {
const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
const auto& displayPort = ports.find(inputPort);
if (displayPort != ports.end()) {
mAssociatedDisplayPort = std::make_optional(displayPort->second);
}
}
}
for (InputMapper* mapper : mMappers) {
mapper->configure(when, config, changes);
mSources |= mapper->getSources();
}
}
}
void InputDevice::reset(nsecs_t when) {
for (InputMapper* mapper : mMappers) {
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.
for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
#if DEBUG_RAW_EVENTS
ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
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().c_str());
mDropUntilNextSync = true;
reset(rawEvent->when);
} else {
for (InputMapper* mapper : mMappers) {
mapper->process(rawEvent);
}
}
--count;
}
}
void InputDevice::timeoutExpired(nsecs_t when) {
for (InputMapper* mapper : mMappers) {
mapper->timeoutExpired(when);
}
}
void InputDevice::updateExternalStylusState(const StylusState& state) {
for (InputMapper* mapper : mMappers) {
mapper->updateExternalStylusState(state);
}
}
void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
mIsExternal, mHasMic);
for (InputMapper* mapper : mMappers) {
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;
for (InputMapper* mapper : mMappers) {
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;
for (InputMapper* mapper : mMappers) {
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) {
for (InputMapper* mapper : mMappers) {
mapper->vibrate(pattern, patternSize, repeat, token);
}
}
void InputDevice::cancelVibrate(int32_t token) {
for (InputMapper* mapper : mMappers) {
mapper->cancelVibrate(token);
}
}
void InputDevice::cancelTouch(nsecs_t when) {
for (InputMapper* mapper : mMappers) {
mapper->cancelTouch(when);
}
}
int32_t InputDevice::getMetaState() {
int32_t result = 0;
for (InputMapper* mapper : mMappers) {
result |= mapper->getMetaState();
}
return result;
}
void InputDevice::updateMetaState(int32_t keyCode) {
for (InputMapper* mapper : mMappers) {
mapper->updateMetaState(keyCode);
}
}
void InputDevice::fadePointer() {
for (InputMapper* mapper : mMappers) {
mapper->fadePointer();
}
}
void InputDevice::bumpGeneration() {
mGeneration = mContext->bumpGeneration();
}
void InputDevice::notifyReset(nsecs_t when) {
NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
mContext->getListener()->notifyDeviceReset(&args);
}
std::optional<int32_t> InputDevice::getAssociatedDisplay() {
for (InputMapper* mapper : mMappers) {
std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplay();
if (associatedDisplayId) {
return associatedDisplayId;
}
}
return std::nullopt;
}
// --- 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(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
mHaveStylus(false), mDeviceTimestamp(0) {
}
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);
}
mDeviceTimestamp = 0;
}
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 %zd; 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;
} else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
mDeviceTimestamp = rawEvent->value;
}
}
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(std::string& 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(std::string& dump,
const RawAbsoluteAxisInfo& axis, const char* name) {
if (axis.valid) {
dump += StringPrintf(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 += StringPrintf(INDENT4 "%s: unknown range\n", name);
}
}
void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
dump += StringPrintf(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(mContext->getNextSequenceNum(), 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(std::string& dump) {
dump += INDENT2 "Switch Input Mapper:\n";
dump += StringPrintf(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
std::string patternStr;
for (size_t i = 0; i < patternSize; i++) {
if (i != 0) {
patternStr += ", ";
}
patternStr += StringPrintf("%" PRId64, pattern[i]);
}
ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
getDeviceId(), patternStr.c_str(), 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=%" PRId64, 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(std::string& dump) {
dump += INDENT2 "Vibrator Input Mapper:\n";
dump += StringPrintf(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;
}
int32_t KeyboardInputMapper::getOrientation() {
if (mViewport) {
return mViewport->orientation;
}
return DISPLAY_ORIENTATION_0;
}
int32_t KeyboardInputMapper::getDisplayId() {
if (mViewport) {
return mViewport->displayId;
}
return ADISPLAY_ID_NONE;
}
void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
InputMapper::populateDeviceInfo(info);
info->setKeyboardType(mKeyboardType);
info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
}
void KeyboardInputMapper::dump(std::string& dump) {
dump += INDENT2 "Keyboard Input Mapper:\n";
dumpParameters(dump);
dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", 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) {
mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
}
}
}
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);
if (mParameters.orientationAware) {
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(std::string& dump) {
dump += INDENT3 "Parameters:\n";
dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
toString(mParameters.orientationAware));
dump += StringPrintf(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) {
keyCode = rotateKeyCode(keyCode, getOrientation());
}
// 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[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);
}
KeyDown keyDown;
keyDown.keyCode = keyCode;
keyDown.scanCode = scanCode;
mKeyDowns.push_back(keyDown);
}
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[keyDownIndex].keyCode;
mKeyDowns.erase(mKeyDowns.begin() + (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().c_str(), 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(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
getDisplayId(), 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(std::string& dump) {
dump += INDENT2 "Cursor Input Mapper:\n";
dumpParameters(dump);
dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
toString(mCursorScrollAccumulator.haveRelativeVWheel()));
dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
toString(mCursorScrollAccumulator.haveRelativeHWheel()));
dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", 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");
mParameters.mode = Parameters::MODE_POINTER;
[[fallthrough]];
case Parameters::MODE_POINTER:
mSource = AINPUT_SOURCE_MOUSE;
mXPrecision = 1.0f;
mYPrecision = 1.0f;
mXScale = 1.0f;
mYScale = 1.0f;
mPointerController = getPolicy()->obtainPointerController(getDeviceId());
break;
case Parameters::MODE_NAVIGATION:
mSource = AINPUT_SOURCE_TRACKBALL;
mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
break;
}
mVWheelScale = 1.0f;
mHWheelScale = 1.0f;
}
if ((!changes && config->pointerCapture)
|| (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
if (config->pointerCapture) {
if (mParameters.mode == Parameters::MODE_POINTER) {
mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
// Keep PointerController around in order to preserve the pointer position.
mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
} else {
ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
}
} else {
if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
mParameters.mode = Parameters::MODE_POINTER;
mSource = AINPUT_SOURCE_MOUSE;
} else {
ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
}
}
bumpGeneration();
if (changes) {
getDevice()->notifyReset(when);
}
}
if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
}
if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
mOrientation = DISPLAY_ORIENTATION_0;
if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
std::optional<DisplayViewport> internalViewport =
config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
if (internalViewport) {
mOrientation = internalViewport->orientation;
}
}
// Update the PointerController if viewports changed.
if (mParameters.mode == Parameters::MODE_POINTER) {
getPolicy()->obtainPointerController(getDeviceId());
}
bumpGeneration();
}
}
void CursorInputMapper::configureParameters() {
mParameters.mode = Parameters::MODE_POINTER;
String8 cursorModeString;
if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
if (cursorModeString == "navigation") {
mParameters.mode = Parameters::MODE_NAVIGATION;
} else if (cursorModeString != "pointer" && cursorModeString != "default") {
ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
}
}
mParameters.orientationAware = false;
getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
mParameters.orientationAware);
mParameters.hasAssociatedDisplay = false;
if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
mParameters.hasAssociatedDisplay = true;
}
}
void CursorInputMapper::dumpParameters(std::string& dump) {
dump += INDENT3 "Parameters:\n";
dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
toString(mParameters.hasAssociatedDisplay));
switch (mParameters.mode) {
case Parameters::MODE_POINTER:
dump += INDENT4 "Mode: pointer\n";
break;
case Parameters::MODE_POINTER_RELATIVE:
dump += INDENT4 "Mode: relative pointer\n";
break;
case Parameters::MODE_NAVIGATION:
dump += INDENT4 "Mode: navigation\n";
break;
default:
ALOG_ASSERT(false);
}
dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
toString(mParameters.orientationAware));
}
void CursorInputMapper::reset(nsecs_t when) {
mButtonState = 0;
mDownTime = 0;
mPointerVelocityControl.reset();
mWheelXVelocityControl.reset();
mWheelYVelocityControl.reset();
mCursorButtonAccumulator.reset(getDevice());
mCursorMotionAccumulator.reset(getDevice());
mCursorScrollAccumulator.reset(getDevice());
InputMapper::reset(when);
}
void CursorInputMapper::process(const RawEvent* rawEvent) {
mCursorButtonAccumulator.process(rawEvent);
mCursorMotionAccumulator.process(rawEvent);
mCursorScrollAccumulator.process(rawEvent);
if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
sync(rawEvent->when);
}
}
void CursorInputMapper::sync(nsecs_t when) {
int32_t lastButtonState = mButtonState;
int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
mButtonState = currentButtonState;
bool wasDown = isPointerDown(lastButtonState);
bool down = isPointerDown(currentButtonState);
bool downChanged;
if (!wasDown && down) {
mDownTime = when;
downChanged = true;
} else if (wasDown && !down) {
downChanged = true;
} else {
downChanged = false;
}
nsecs_t downTime = mDownTime;
bool buttonsChanged = currentButtonState != lastButtonState;
int32_t buttonsPressed = currentButtonState & ~lastButtonState;
int32_t buttonsReleased = lastButtonState & ~currentButtonState;
float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
bool moved = deltaX != 0 || deltaY != 0;
// Rotate delta according to orientation if needed.
if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
&& (deltaX != 0.0f || deltaY != 0.0f)) {
rotateDelta(mOrientation, &deltaX, &deltaY);
}
// Move the pointer.
PointerProperties pointerProperties;
pointerProperties.clear();
pointerProperties.id = 0;
pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
PointerCoords pointerCoords;
pointerCoords.clear();
float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
bool scrolled = vscroll != 0 || hscroll != 0;
mWheelYVelocityControl.move(when, nullptr, &vscroll);
mWheelXVelocityControl.move(when, &hscroll, nullptr);
mPointerVelocityControl.move(when, &deltaX, &deltaY);
int32_t displayId;
if (mSource == AINPUT_SOURCE_MOUSE) {
if (moved || scrolled || buttonsChanged) {
mPointerController->setPresentation(
PointerControllerInterface::PRESENTATION_POINTER);
if (moved) {
mPointerController->move(deltaX, deltaY);
}
if (buttonsChanged) {
mPointerController->setButtonState(currentButtonState);
}
mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
}
float x, y;
mPointerController->getPosition(&x, &y);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
displayId = mPointerController->getDisplayId();
} else {
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
displayId = ADISPLAY_ID_NONE;
}
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
// Moving an external trackball or mouse should wake the device.
// We don't do this for internal cursor devices to prevent them from waking up
// the device in your pocket.
// TODO: Use the input device configuration to control this behavior more finely.
uint32_t policyFlags = 0;
if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
policyFlags |= POLICY_FLAG_WAKE;
}
// Synthesize key down from buttons if needed.
synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
displayId, policyFlags, lastButtonState, currentButtonState);
// Send motion event.
if (downChanged || moved || scrolled || buttonsChanged) {
int32_t metaState = mContext->getGlobalMetaState();
int32_t buttonState = lastButtonState;
int32_t motionEventAction;
if (downChanged) {
motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
} else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
motionEventAction = AMOTION_EVENT_ACTION_MOVE;
} else {
motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
}
if (buttonsReleased) {
BitSet32 released(buttonsReleased);
while (!released.isEmpty()) {
int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
buttonState &= ~actionButton;
NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
mSource, displayId, policyFlags,
AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
metaState, buttonState,
MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&releaseArgs);
}
}
NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
if (buttonsPressed) {
BitSet32 pressed(buttonsPressed);
while (!pressed.isEmpty()) {
int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
buttonState |= actionButton;
NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
actionButton, 0, metaState, buttonState,
MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&pressArgs);
}
}
ALOG_ASSERT(buttonState == currentButtonState);
// Send hover move after UP to tell the application that the mouse is hovering now.
if (motionEventAction == AMOTION_EVENT_ACTION_UP
&& (mSource == AINPUT_SOURCE_MOUSE)) {
NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
metaState, currentButtonState,
MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&hoverArgs);
}
// Send scroll events.
if (scrolled) {
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
mSource, displayId, policyFlags,
AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&scrollArgs);
}
}