Android 11.0源码系列之IMSInputReader
Posted bubbleben
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 11.0源码系列之IMSInputReader相关的知识,希望对你有一定的参考价值。
本篇涉及到的主要代码:
frameworks/native/services/inputflinger/
上一篇我们介绍了InputChannel
以及InputConnection
的创建以及它们在事件分发流程中的作用,至此输入事件从native层的InputDispatcher
传递到了位于应用进程空间的ViewRootImpl
,但是InputDispatcher的输入事件又从何而来呢?本篇将会为大家解答第三篇中留下的这个疑问。
1.1 InputReader的创建
[-> InputManager.cpp]
InputManager::InputManager(
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
mDispatcher = createInputDispatcher(dispatcherPolicy);
mClassifier = new InputClassifier(mDispatcher);
// 将NativeInputManager作为InputReaderPolicyInterface传递给InputReader
// 将InputClassfier作为InputListenerInterface传递给InputReader
mReader = createInputReader(readerPolicy, mClassifier);
}
[-> InputReaderFactory.cpp]
sp<InputReaderInterface> createInputReader(const sp<InputReaderPolicyInterface>& policy,
const sp<InputListenerInterface>& listener) {
// 创建InputReader[见1.2小节
// 创建EventHub[见1.5小节]
return new InputReader(std::make_unique<EventHub>(), policy, listener);
}
回顾一下第二篇提到的InputDispatcher和InputReader的创建过程:NativeInputManager继承于InputReaderPolicyInterface和InputDispatcherPolicyInterface,它会被传递为InputReader构造函数的第二个参数;InputClassfier继承于InputClassifierInterface,而InputClassifierInterface又继承于InputListenerInterface,所以它会被传递为InputReader构造函数的第三个参数;
1.2 InputReader构造函数
[-> InputReader.cpp]
// --- InputReader ---
InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
const sp<InputReaderPolicyInterface>& policy,
const sp<InputListenerInterface>& listener)
: mContext(this),
// 初始化EventHub
mEventHub(eventHub),
// 初始化mPolicy
mPolicy(policy),
mGlobalMetaState(0),
mGeneration(1),
mNextInputDeviceId(END_RESERVED_ID),
mDisableVirtualKeysTimeout(LLONG_MIN),
mNextTimeout(LLONG_MAX),
mConfigurationChangesToRefresh(0) {
// 创建QueuedInputListener
mQueuedListener = new QueuedInputListener(listener);
{ // acquire lock
AutoMutex _l(mLock);
// 通过mPolicy即NativeManager调用JNI方法getReaderConfiguration获取配置,
// 而它最终会调到Java层IMS的一些方法获取保存在文件中的一些系统配置项
refreshConfigurationLocked(0);
updateGlobalMetaStateLocked();
} // release lock
}
[-> InputListener.cpp]
QueuedInputListener::QueuedInputListener(const sp<InputListenerInterface>& innerListener) :
// 初始化mInnerListener
mInnerListener(innerListener) {
}
InputReader构造函数中,创建了一个非常重要的对象mQueuedListener,它将在InputReader线程启动后将读取到的输入事件传递给InputDispatcher;
1.3 InputReader线程启动
[-> InputReader.cpp]
status_t InputReader::start() {
// 只能启动一次
if (mThread) {
return ALREADY_EXISTS;
}
mEventHub->wake
// 创建名为"InputReader"的线程,其loop方法和wake方法分别为loopOnce()[见1.4小节]和mEventHub->wake()
mThread = std::make_unique<InputThread>(
"InputReader", [this]() { loopOnce(); }, [this]() { mEventHub->wake(); });
return OK;
}
在第三篇中我们分析过"InputThread只是对InputThreadImpl的封装,InputThreadImpl才是一个真正的线程",同InputDispatcher一样:在调用InputThreadImpl.run方法之后,线程就开始运行起来并调用threadLoop方法开始消息队列的循环处理,这样也就回到了InputReader.loopOnce()方法;
1.4 消息循环loopOnce()
[-> InputReader.cpp]
void InputReader::loopOnce() {
int32_t oldGeneration;
int32_t timeoutMillis;
bool inputDevicesChanged = false;
std::vector<InputDeviceInfo> inputDevices;
// 通过EventHub获取输入事件[见1.6小节]
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
{ // acquire lock
AutoMutex _l(mLock);
mReaderIsAliveCondition.broadcast();
if (count) {
// 处理输入事件[见1.7小节]
processEventsLocked(mEventBuffer, count);
}
} // release lock
......
// 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.
// 将输入事件传递给InputDispatcher[见1.13小节]
mQueuedListener->flush();
}
loopOnce()方法通过EventHub.getEvents源源不断的获取RawEvent事件,然后交由processEventsLocked作预处理,最后通过QueuedListener->flush方法将输入事件传递给InputDispatcher,在这之前我们首先要看看EventHub是什么,它在构造函数中又做了些什么;
1.5 EventHub构造函数
[-> EventHub.cpp]
EventHub::EventHub(void)
: mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
mNextDeviceId(1),
mControllerNumbers(),
mOpeningDevices(nullptr),
mClosingDevices(nullptr),
mNeedToSendFinishedDeviceScan(false),
mNeedToReopenDevices(false),
mNeedToScanDevices(true),
mPendingEventCount(0),
mPendingEventIndex(0),
mPendingINotify(false) {
ensureProcessCanBlockSuspend();
// 创建epoll并保存生成的文件描述符mEpollFd
mEpollFd = epoll_create1(EPOLL_CLOEXEC);
// 创建inotify并保存生成的文件描述符mINotifyFd
mINotifyFd = inotify_init();
// 此处DEVICE_PATH为"/dev/input",利用mINotifyFd监听该设备结点
mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
struct epoll_event eventItem = {};
eventItem.events = EPOLLIN | EPOLLWAKEUP;
eventItem.data.fd = mINotifyFd;
//添加iNotify到epoll实例
int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
int wakeFds[2];
// 创建管道
result = pipe(wakeFds);
// 读管道
mWakeReadPipeFd = wakeFds[0];
// 写管道
mWakeWritePipeFd = wakeFds[1];
//将pipe的读和写都设置为非阻塞方式
result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
//添加管道的读端到epoll实例
eventItem.data.fd = mWakeReadPipeFd;
result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
}
EventHub在构造函数中主要完成了以下几项工作:创建epoll实例;初始化iNotify监听/dev/input设备结点,并添加到epoll实例;创建非阻塞模式的管道,并将管道的读端添加到epoll;
1.6 EventHub.getEvents
[-> EventHub.cpp]
size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
ALOG_ASSERT(bufferSize >= 1);
AutoMutex _l(mLock);
// 读取到的input_event
struct input_event readBuffer[bufferSize];
// 原始事件,容量大小为256
RawEvent* event = buffer;
size_t capacity = bufferSize;
bool awoken = false;
for (;;) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
......
// Report any devices that had last been added/removed.
while (mClosingDevices) {
Device* device = mClosingDevices;
ALOGV("Reporting device closed: id=%d, name=%s\\n", device->id, device->path.c_str());
mClosingDevices = device->next;
event->when = now;
event->deviceId = (device->id == mBuiltInKeyboardId)
? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
: device->id;
// 移除设备的事件
event->type = DEVICE_REMOVED;
event += 1;
delete device;
mNeedToSendFinishedDeviceScan = true;
if (--capacity == 0) {
break;
}
}
......
while (mOpeningDevices != nullptr) {
Device* device = mOpeningDevices;
ALOGV("Reporting device opened: id=%d, name=%s\\n", device->id, device->path.c_str());
mOpeningDevices = device->next;
event->when = now;
event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
// 添加设备的事件
event->type = DEVICE_ADDED;
event += 1;
mNeedToSendFinishedDeviceScan = true;
if (--capacity == 0) {
break;
}
}
if (mNeedToSendFinishedDeviceScan) {
mNeedToSendFinishedDeviceScan = false;
event->when = now;
// 结束设备扫描的事件
event->type = FINISHED_DEVICE_SCAN;
event += 1;
if (--capacity == 0) {
break;
}
}
// Grab the next input event.
bool deviceChanged = false;
// mPendingEventIndex和mPendingEventCount分别代表待处理事件的索引和待处理事件的个数
// 当通过epoll读取到epoll_event事件之后就会循环处理所有的mPendingEventItems
while (mPendingEventIndex < mPendingEventCount) {
// 根据索引取出一个epoll_event事件
const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
......
// 根据epoll_data.fd获取对应的设备
Device* device = getDeviceByFdLocked(eventItem.data.fd);
......
// This must be an input event
if (eventItem.events & EPOLLIN) {
// 从输入设备中读取输入事件,放入到readBuffer
int32_t readSize =
read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
// Device was removed before INotify noticed.
ALOGW("could not get event, removed? (fd: %d size: %" PRId32
" bufferSize: %zu capacity: %zu errno: %d)\\n",
device->fd, readSize, bufferSize, capacity, errno);
deviceChanged = true;
// 设备已被移除则执行关闭操作
closeDeviceLocked(device);
} else if (readSize < 0) {
......
} else if ((readSize % sizeof(struct input_event)) != 0) {
......
} else {
int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
size_t count = size_t(readSize) / sizeof(struct input_event);
// 将读取到的所有input_event转换成RawEvent
for (size_t i = 0; i < count; i++) {
struct input_event& iev = readBuffer[i];
event->when = processEventTimestamp(iev);
event->deviceId = deviceId;
event->type = iev.type;
event->code = iev.code;
event->value = iev.value;
event += 1;
capacity -= 1;
}
// 传入的buffer已经填满,将mPendingEventIndex索引减一后退出while循环
if (capacity == 0) {
// The result buffer is full. Reset the pending event index
// so we will try to read the device again on the next iteration.
mPendingEventIndex -= 1;
break;
}
}
}
}
......
// Poll for events.
// When a device driver has pending (unread) events, it acquires
// a kernel wake lock. Once the last pending event has been read, the device
// driver will release the kernel wake lock, but the epoll will hold the wakelock,
// since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
// is called again for the same fd that produced the event.
// Thus the system can only sleep if there are no events pending or
// currently being processed.
//
// The timeout is advisory only. If the device is asleep, it will not wake just to
// service the timeout.
// 重置输入事件的索引为0
mPendingEventIndex = 0;
mLock.unlock(); // release lock before poll
// 等待input事件的到来,并将获取到的epoll_event事件填充到mPendingEventItems
int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
mLock.lock(); // reacquire lock after poll
if (pollResult == 0) {
// Timed out.
mPendingEventCount = 0;
break;
}
if (pollResult < 0) {
// An error occurred.
mPendingEventCount = 0;
// Sleep after errors to avoid locking up the system.
// Hopefully the error is transient.
if (errno != EINTR) {
ALOGW("poll failed (errno=%d)\\n", errno);
// 系统出现错误则休眠1s
usleep(100000);
}
} else {
// Some events occurred.
// epoll_wait的返回值为input事件的个数
mPendingEventCount = size_t(pollResult);
}
}
// All done, return the number of events we read.
return event - buffer;
}
EventHub采用iNotify + epoll机制实现监听目录/dev/input
下的设备节点,在getEvents方法中将input_event结构体 + deviceId 转换成RawEvent结构体;
1.7 InputReader.processEventsLocked
[-> InputReader.cpp]
void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
// 循环处理每一个RawEvent
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;
}
// 真正处理RawEvent的逻辑[见1.8小节]
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;
}
}
这里会根据RawEvent的type来分别处理:如果是真正的input输入事件则单独处理,否则再继续细分处理方案(包括输入设备的添加,删除和扫描不是本篇的重点,这里不作讨论);
1.8 InputReader.processEventsForDeviceLocked
[-> InputReader.cpp]
void InputReader::processEventsForDeviceLocked(int32_t eventHubId, const RawEvent* rawEvents,
size_t count) {
auto deviceIt = mDevices.find(eventHubId);
// 没找到输入设备
if (deviceIt == mDevices.end()) {
ALOGW("Discarding event for unknown eventHubId %d.", eventHubId);
return;
}
std::shared_ptr<InputDevice>& device = deviceIt->second;
if (device->isIgnored()) {
// ALOGD("Discarding event for ignored deviceId %d.", deviceId);
return;
}
// 直接调用输入设备的proesss方法[见1.9小节]
device->process(rawEvents, count);
}
1.9 InputDevice.process
[-> InputDevice.cpp]
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 (mDropUntilNextSync) {
if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
mDropUntilNextSync = false;
}
} 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 {
// 根据RawEvent的deviceId查找对应的InputMapper,并继续执行其process方法[1.10方法]
for_each_mapper_in_subdevice(rawEvent->deviceId, [rawEvent](InputMapper& mapper) {
mapper.process(rawEvent);
});
}
--count;
}
}
// run a function against every mapper on a specific subdevice
inline void for_each_mapper_in_subdevice(int32_t eventHubDevice,
std::function<void(InputMapper&)> f) {
// mDevices是一个map:key为deviceId,value为DevicePair
auto deviceIt = mDevices.find(eventHubDevice);
if (deviceIt != mDevices.end()) {
// mDevices的second是一个DevicePair
auto& devicePair = deviceIt->second;
// DevicePair的second是一个InputMapper
auto& mappers = devicePair.second;
for (auto& mapperPtr : mappers) {
f(*mapperPtr);
}
}
}
在添加输入设备的过程中,InputReader会根据输入设备的class类型添加不同的InputMapper,一种或者多种class可能对应一个InputMapper,比如代表按键事件的KeyboardInputMapper,代表单点触摸的SingleTouchInputMapper和代表多点触摸的MultiTouchInputMapper,它们都是InputMapper的子类:
void InputDevice::addEventHubDevice(int32_t eventHubId, bool populateMappers) {
// 已经添加过的就不再重复添加
if (mDevices.find(eventHubId) != mDevices.end()) {
return;
}
// 初始化InputDeviceContext,this代表InputDevice
std::unique_ptr<InputDeviceContext> contextPtr(new InputDeviceContext(*this, eventHubId));
uint32_t classes = contextPtr->getDeviceClasses();
std::vector<std::unique_ptr<InputMapper>> mappers;
......
// 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;
}
// 根据class获取不同的keyboardSource
if (keyboardSource != 0) {
mappers.push_back(
std::make_unique<KeyboardInputMapper>(*contextPtr, keyboardSource, keyboardType));
}
// Touchscreens and touchpad devices.
if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
// 多点触摸则添加MultiTouchInputMapper
mappers.push_back(std::make_unique<MultiTouchInputMapper>(*contextPtr));
} else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
// 单点触摸则添加SingleTouchInputMapper
mappers.push_back(std::make_unique<SingleTouchInputMapper>(*contextPtr));
}
......
// insert the context into the devices set
mDevices.insert({eventHubId, std::make_pair(std::move(contextPtr), std::move(mappers))});
}
接下来我们将以KeyboardInputMapper为例来展开说明;
1.10 KeyboardInputMapper.process
[-> KeyboardInputMapper.cpp]
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)) {
// procesKey[见1.11小节]
processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
}
break;
}
case EV_MSC: {
......
}
case EV_SYN: {
......
}
}
}
1.11 KeyboardInputMapper.processKey
[-> KeyboardInputMapper.cpp]
void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, int32_t usageCode) {
int32_t keyCode;
int32_t keyMetaState;
uint32_t policyFlags;
// 根据scanCode找到对应的keyCode
if (getDeviceContext().mapKey(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
// mKeyDowns记录着所有按下的键
keyCode = mKeyDowns[keyDownIndex].keyCode;
} else {
// key down
if ((policyFlags & POLICY_FLAG_VIRTUAL) &&
getContext()->shouldDropVirtualKey(when, keyCode, scanCode)) {
return;
}
if (policyFlags & POLICY_FLAG_GESTURE) {
getDeviceContext().cancelTouch(when);
}
KeyDown keyDown;
keyDown.keyCode = keyCode;
keyDown.scanCode = scanCode;
// 将此次down事件压入栈顶
mKeyDowns.push_back(keyDown);
}
// 同时记录down事件时间
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;
// 按键抬起,则移除down事件
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;
}
}
nsecs_t downTime = mDownTime;
// 创建NotifyKeyArgs对象, when记录eventTime, downTime记录按下时间;
NotifyKeyArgs args(getContext()->getNextId(), 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将事件通知出去,这里的getListener指谁呢?[见1.12小节]
getListener()->notifyKey(&args);
}
[-> InputMapper.h]
// KeyboardInputMapper调用父类InputMapper.getListener
inline InputListenerInterface* getListener() { return getContext()->getListener(); }
// InputMapper.getContext又调用了mDeviceContext.getContext()
inline InputReaderContext* getContext() { return mDeviceContext.getContext(); }
// mDeviceContext是在InputMapper构造函数中通过传入的InputDeviceContext初始化的,在1.9节中的addEventHubDevice中可以看
// 到这里的deviceContext是指InputDevice,继续调用InputDevice.getContext()
InputMapper::InputMapper(InputDeviceContext& deviceContext) : mDeviceContext(deviceContext) {}
// InputDevice的mContext也是在构造函数中传入的
inline InputReaderContext* getContext() { return mContext; }
[-> InputDevice.cpp]
InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
const InputDeviceIdentifier& identifier)
: mContext(context),
mId(id),
mGeneration(generation),
mControllerNumber(0),
mIdentifier(identifier),
mClasses(0),
mSources(0),
mIsExternal(false),
mHasMic(false),
mDropUntilNextSync(false) {}
[-> InputReader.cpp]
std::shared_ptr<InputDevice> InputReader::createDeviceLocked(
int32_t eventHubId, const InputDeviceIdentifier& identifier) {
auto deviceIt = std::find_if(mDevices.begin(), mDevices.end(), [identifier](auto& devicePair) {
return devicePair.second->getDescriptor().size() && identifier.descriptor.size() &&
devicePair.second->getDescriptor() == identifier.descriptor;
});
std::shared_ptr<InputDevice> device;
if (deviceIt != mDevices.end()) {
device = deviceIt->second;
} else {
int32_t deviceId = (eventHubId < END_RESERVED_ID) ? eventHubId : nextInputDeviceIdLocked();
// InputDevice在createDeviceLocked中创建,其mContext也是在InputReader的构造函数中赋值的即InputReader
device = std::make_shared<InputDevice>(&mContext, deviceId, bumpGenerationLocked(),
identifier);
}
device->addEventHubDevice(eventHubId);
return device;
}
// 最终getListener()指向的还是QueuedListener
InputListenerInterface* InputReader::ContextImpl::getListener() {
return mReader->mQueuedListener.get();
}
通过一级级的往上回溯,最终我们找到了getListener()返回值即在InputReader构造函数中创建的QueuedListener;
1.12 QueuedListener.notifyKey
[-> InputListener.cpp]
std::vector<NotifyArgs*> mArgsQueue;
void QueuedInputListener::notifyKey(const NotifyKeyArgs* args) {
traceEvent(__func__, args->id);
mArgsQueue.push_back(new NotifyKeyArgs(*args));
}
void QueuedInputListener::notifyMotion(const NotifyMotionArgs* args) {
traceEvent(__func__, args->id);
mArgsQueue.push_back(new NotifyMotionArgs(*args));
}
不管是NotifyKeyArgs(按键事件)还是NotifyMotionArgs(触摸事件),它们都继承于NotifyArgs,这里都会把它们压栈到mArgsQueue中,等待下一步的处理;
1.13 QueuedListener.flush()
[-> InputListener.cpp]
void QueuedInputListener::flush() {
size_t count = mArgsQueue.size();
for (size_t i = 0; i < count; i++) {
NotifyArgs* args = mArgsQueue[i];
// 依次从mArgsQueue中取出每一个NotifyArgs,并执行其notify方法[见1.14小节]
args->notify(mInnerListener);
delete args;
}
mArgsQueue.clear();
}
// notify方法又调用了mInnerListener.notifyKey[见1.14小节]
void NotifyKeyArgs::notify(const sp<InputListenerInterface>& listener) const {
listener->notifyKey(this);
}
根据1.1和1.2小节的分析,mInnerListener就是传入InputReader的InputClassifier;
1.14 InputClassifier.notifyKey
[-> InputClassifier.cpp]
void InputClassifier::notifyKey(const NotifyKeyArgs* args) {
// pass through
// 直接调用mListener->notifyKey[见1.15小节]
mListener->notifyKey(args);
}
同样根据前几篇文章的分析,这里的mListener就是传入InputClassfier构造函数中的InputDispatcher;
1.15 InputDispatcher.notifyKey
[-> InputDispatcher.cpp]
void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
// 按键事件只支持KEY_DOWN和KEY_UP
if (!validateKeyEvent(args->action)) {
return;
}
......
KeyEvent event;
// 将NotifyKeyArgs转换为KeyEvent
event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
args->downTime, args->eventTime);
android::base::Timer t;
// 由NativeInputManager经IMS->WMS->InputManagerCallback将按键消息交由PhoneWindowManager确认是否提前处理
mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
// 处理时间是否超过50ms
if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
std::to_string(t.duration().count()).c_str());
}
bool needWake;
{ // acquire lock
mLock.lock();
// 是否需要拦截输入事件
if (shouldSendKeyToInputFilterLocked(args)) {
mLock.unlock();
policyFlags |= POLICY_FLAG_FILTERED;
if (!mPolicy->filterInputEvent(&event, policyFlags)) {
// 输入事件被InputFilter消费就不再往下传递
return; // event was consumed by the filter
}
mLock.lock();
}
// 构造KeyEntry
KeyEntry* newEntry =
new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
args->displayId, policyFlags, args->action, flags, keyCode,
args->scanCode, metaState, repeatCount, args->downTime);
// 将KeyEntry添加到mInboundQueue队列
needWake = enqueueInboundEventLocked(newEntry);
mLock.unlock();
} // release lock
if (needWake) {
// 唤醒InputDispatcher的线程
mLooper->wake();
}
}
首先将NotifyKeyArgs转换成KeyEvent,然后交由mPolicy(在第一篇文章中我们分析过这里的mPolicy是经由JNI层的NativeManager指向Java层的IMS)分别经过interceptKeyBeforeQueueing和filterInputEvent的处理;如果事件不被拦截的话最终会入队到mInboundQueue中,这里的mInboundQueue正是我们在第三篇中分析的InputDispatcher处理输入事件的来源:有了它InputDispatcher就可以不断的从中取出事件并通过InputChannel的socket发送给应用端去处理了。
以上是关于Android 11.0源码系列之IMSInputReader的主要内容,如果未能解决你的问题,请参考以下文章
Android 11.0源码系列之IMSInputManagerService
Android 11.0源码系列之IMSInputManager
Android 11.0源码系列之IMSInputDispatcher