从 InputManagerService: 创立与启动 可知,Input 体系的主要功用,主要会集在 native 层,而且Input 体系的 native 层又包含 InputReader, InputClassifer, InputDispatcher 三个子模块。本文来剖析 InputReader 从创立到启动的基本流程,为后续剖析 InputReader 的每一个功用打好基础。

InputReader 的创立

从 InputManagerService: 创立与启动 可知,
InputReader 的创立进程如下

// InputReaderFactory.cpp
sp<InputReaderInterface> createInputReader(const sp<InputReaderPolicyInterface>& policy,
                                           const sp<InputListenerInterface>& listener) {
    return new InputReader(std::make_unique<EventHub>(), policy, listener);
}

InputReader 依靠 EventHub,因而首先要看下 EventHub 的创立进程

EventHub::EventHub(void)
      : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
        mNextDeviceId(1),
        mControllerNumbers(),
        mNeedToSendFinishedDeviceScan(false),
        mNeedToReopenDevices(false),
        mNeedToScanDevices(true), // mNeedToScanDevices 初始化为 true,标明需求扫描输入设备
        mPendingEventCount(0),
        mPendingEventIndex(0),
        mPendingINotify(false) {
    ensureProcessCanBlockSuspend();
    // 1. 创立 epoll
    mEpollFd = epoll_create1(EPOLL_CLOEXEC);
    // 2. 初始化 inotify
    mINotifyFd = inotify_init();
    // 监听 /dev/input/ 目录项的创立与删去,其实便是监听输入设备的创立与删去
    mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
    // ...
    // 3. epoll 监听 inotify 事情
    // 可读事情,标明有输入设备的创立与删去
    struct epoll_event eventItem = {};
    eventItem.events = EPOLLIN | EPOLLWAKEUP;
    eventItem.data.fd = mINotifyFd;
    int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
    // 4. 创立管道
    int wakeFds[2];
    result = pipe(wakeFds);
    mWakeReadPipeFd = wakeFds[0];
    mWakeWritePipeFd = wakeFds[1];
    // 设置管道两端为非堵塞
    result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
    result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
    // 5. epoll 监听管道读端的事情
    // 可读事情,标明需求唤醒 InputReader 线程,触发条件一般为装备更新
    eventItem.data.fd = mWakeReadPipeFd;
    result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
}

EventHub 创立进程如下

  1. 创立 epoll 实例。
  2. 初始化 inotify 实例,并用 epoll 监听它的事情。当输入设备添加/删去时,epoll 就会收到 inotify 的可读事情,因而 EventHub 和 InputReader 就可以动态地处理输入设备的添加/删去。
  3. 创立管道。
  4. epoll 监听管道的读端的事情。当装备更新时,会向管道的写端写入数据,epoll 就会收到管道的可读事情,假如此时 InputReader 线程处于休眠状态,那么 InputReader 将被唤醒来处于装备更新。

epoll, inotify, pipe,它们的效果和使用方法,请读者自行查阅 Unix/Linux 材料。

现在让咱们持续看下 InputReader 的创立进程

InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
                         const sp<InputReaderPolicyInterface>& policy,
                         const sp<InputListenerInterface>& listener)
      : mContext(this), // mContext 代表 InputReader 的环境
        mEventHub(eventHub),
        mPolicy(policy),
        mGlobalMetaState(0),
        mLedMetaState(AMETA_NUM_LOCK_ON),
        mGeneration(1),
        mNextInputDeviceId(END_RESERVED_ID),
        mDisableVirtualKeysTimeout(LLONG_MIN),
        mNextTimeout(LLONG_MAX),
        mConfigurationChangesToRefresh(0) {
    // InputReader 会把加工后的事情添加到 QueuedInputListener 行列中,之后一起分发给 InputClassifier
    mQueuedListener = new QueuedInputListener(listener);
    { // acquire lock
        std::scoped_lock _l(mLock);
        // 改写装备
        // 其实便是更新 InputReader::mConfig
        refreshConfigurationLocked(0);
        // 更新 InputReader::mGlobalMetaState
        // 与键盘输入设备的meta按键相关
        updateGlobalMetaStateLocked();
    } // release lock
}

InputReader 的结构函数很简单,便是成员变量的初始化。其中需求重点看下 refreshConfigurationLocked(0) 是怎么改写 InputReader 装备

// 留意,此时参数 changes 为 0
void InputReader::refreshConfigurationLocked(uint32_t changes) {
    // 经过 InputReaderPolicyInterface 获取装备,保存到 InputReader::mConfig 中
    mPolicy->getReaderConfiguration(&mConfig);
    // EventHub 保存扫除的设备
    mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
    if (!changes) return;
    // ...
}

原来 InputReader::mConfig 代表的便是 InputReader 的装备,而且是经过 InputReaderPolicyInterface mPolicy 获取装备的。

从 InputManagerService: 创立与启动 可知,InputReaderPolicyInterface 接口的实现者是 NativeInputManager ,而 NativeInputManager 是 Input 体系的上层与底层交流的桥梁,因而 InputReader 必定是经过 NativeInputManager 向上层获取装备

void NativeInputManager::getReaderConfiguration(InputReaderConfiguration* outConfig) {
    ATRACE_CALL();
    JNIEnv* env = jniEnv();
    // 1. 经过JNI,向上层 InputManagerService 获取装备,并保存到 outConfig 中
    jint virtualKeyQuietTime = env->CallIntMethod(mServiceObj,
            gServiceClassInfo.getVirtualKeyQuietTimeMillis);
    if (!checkAndClearExceptionFromCallback(env, "getVirtualKeyQuietTimeMillis")) {
        outConfig->virtualKeyQuietTime = milliseconds_to_nanoseconds(virtualKeyQuietTime);
    }
    outConfig->excludedDeviceNames.clear();
    jobjectArray excludedDeviceNames = jobjectArray(env->CallStaticObjectMethod(
            gServiceClassInfo.clazz, gServiceClassInfo.getExcludedDeviceNames));
    if (!checkAndClearExceptionFromCallback(env, "getExcludedDeviceNames") && excludedDeviceNames) {
        jsize length = env->GetArrayLength(excludedDeviceNames);
        for (jsize i = 0; i < length; i++) {
            std::string deviceName = getStringElementFromJavaArray(env, excludedDeviceNames, i);
            outConfig->excludedDeviceNames.push_back(deviceName);
        }
        env->DeleteLocalRef(excludedDeviceNames);
    }
    // Associations between input ports and display ports
    // The java method packs the information in the following manner:
    // Original data: [{'inputPort1': '1'}, {'inputPort2': '2'}]
    // Received data: ['inputPort1', '1', 'inputPort2', '2']
    // So we unpack accordingly here.
    outConfig->portAssociations.clear();
    jobjectArray portAssociations = jobjectArray(env->CallObjectMethod(mServiceObj,
            gServiceClassInfo.getInputPortAssociations));
    if (!checkAndClearExceptionFromCallback(env, "getInputPortAssociations") && portAssociations) {
        jsize length = env->GetArrayLength(portAssociations);
        for (jsize i = 0; i < length / 2; i++) {
            std::string inputPort = getStringElementFromJavaArray(env, portAssociations, 2 * i);
            std::string displayPortStr =
                    getStringElementFromJavaArray(env, portAssociations, 2 * i + 1);
            uint8_t displayPort;
            // Should already have been validated earlier, but do it here for safety.
            bool success = ParseUint(displayPortStr, &displayPort);
            if (!success) {
                ALOGE("Could not parse entry in port configuration file, received: %s",
                    displayPortStr.c_str());
                continue;
            }
            outConfig->portAssociations.insert({inputPort, displayPort});
        }
        env->DeleteLocalRef(portAssociations);
    }
    outConfig->uniqueIdAssociations.clear();
    jobjectArray uniqueIdAssociations = jobjectArray(
            env->CallObjectMethod(mServiceObj, gServiceClassInfo.getInputUniqueIdAssociations));
    if (!checkAndClearExceptionFromCallback(env, "getInputUniqueIdAssociations") &&
        uniqueIdAssociations) {
        jsize length = env->GetArrayLength(uniqueIdAssociations);
        for (jsize i = 0; i < length / 2; i++) {
            std::string inputDeviceUniqueId =
                    getStringElementFromJavaArray(env, uniqueIdAssociations, 2 * i);
            std::string displayUniqueId =
                    getStringElementFromJavaArray(env, uniqueIdAssociations, 2 * i + 1);
            outConfig->uniqueIdAssociations.insert({inputDeviceUniqueId, displayUniqueId});
        }
        env->DeleteLocalRef(uniqueIdAssociations);
    }
    jint hoverTapTimeout = env->CallIntMethod(mServiceObj,
            gServiceClassInfo.getHoverTapTimeout);
    if (!checkAndClearExceptionFromCallback(env, "getHoverTapTimeout")) {
        jint doubleTapTimeout = env->CallIntMethod(mServiceObj,
                gServiceClassInfo.getDoubleTapTimeout);
        if (!checkAndClearExceptionFromCallback(env, "getDoubleTapTimeout")) {
            jint longPressTimeout = env->CallIntMethod(mServiceObj,
                    gServiceClassInfo.getLongPressTimeout);
            if (!checkAndClearExceptionFromCallback(env, "getLongPressTimeout")) {
                outConfig->pointerGestureTapInterval = milliseconds_to_nanoseconds(hoverTapTimeout);
                // We must ensure that the tap-drag interval is significantly shorter than
                // the long-press timeout because the tap is held down for the entire duration
                // of the double-tap timeout.
                jint tapDragInterval = max(min(longPressTimeout - 100,
                        doubleTapTimeout), hoverTapTimeout);
                outConfig->pointerGestureTapDragInterval =
                        milliseconds_to_nanoseconds(tapDragInterval);
            }
        }
    }
    jint hoverTapSlop = env->CallIntMethod(mServiceObj,
            gServiceClassInfo.getHoverTapSlop);
    if (!checkAndClearExceptionFromCallback(env, "getHoverTapSlop")) {
        outConfig->pointerGestureTapSlop = hoverTapSlop;
    }
    // 2. 从 NativeInputManager::mLocked 更新装备,保存到 outConfig 中
    // NativeInputManager::mLocked 的数据是上层经由 InputManagerService 传入的
    { // acquire lock
        AutoMutex _l(mLock);
        outConfig->pointerVelocityControlParameters.scale = exp2f(mLocked.pointerSpeed
                * POINTER_SPEED_EXPONENT);
        outConfig->pointerGesturesEnabled = mLocked.pointerGesturesEnabled;
        outConfig->showTouches = mLocked.showTouches;
        outConfig->pointerCapture = mLocked.pointerCapture;
        outConfig->setDisplayViewports(mLocked.viewports);
        outConfig->defaultPointerDisplayId = mLocked.pointerDisplayId;
        outConfig->disabledDevices = mLocked.disabledInputDevices;
    } // release lock
}

从全体看,获取 InputReader 装备的方法有两种

  1. 经过 JNI 向上层的 InputManagerService 获取装备。
  2. NativeInputManager::mLocked 获取装备。

从 InputManagerService: 创立与启动 可知,NativeInputManager::mLocked 是在 NativeInputManager 的结构函数中进行初始化的,可是它并不是不变的,而是上层经由 InputManagerService 进行控制的。

例如,mLocked.showTouches 对应开发者模式下的 Show taps 功用,InputManagerService 会监听这个开关的状态,相应地改动 mLocked.showTouches,而且会通知 InputReader 装备改动了,InputReader 在处理装备改动的进程时,会从头获取 mLocked.showTouches 这个装备。

一部分 的装备是可以经过 adb shell dumpsys input 指令进行查看的

Input Manager State:
  Interactive: true
  System UI Lights Out: false
  Pointer Speed: 0
  Pointer Gestures Enabled: true
  Show Touches: false
  Pointer Capture: Disabled, seq=0

而别的一部分装备,由于会对输入设备进行装备,因而可以从 dump 出的输入设备的信息中查看。

InputReader 的运转

从 InputManagerService: 创立与启动 可知,InputReader 经过线程,循环调用 InputReader::loopOnce() 执行任务

void InputReader::loopOnce() {
    int32_t oldGeneration;
    int32_t timeoutMillis;
    bool inputDevicesChanged = false;
    std::vector<InputDeviceInfo> inputDevices;
    { // acquire lock
        std::scoped_lock _l(mLock);
        oldGeneration = mGeneration;
        timeoutMillis = -1;
        // 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
    // 2. 从 EventHub 获取事情
    size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
    { // acquire lock
        std::scoped_lock _l(mLock);
        mReaderIsAliveCondition.notify_all();
        // 3. 处理事情
        if (count) {
            processEventsLocked(mEventBuffer, count);
        }
        if (mNextTimeout != LLONG_MAX) {
            nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
            if (now >= mNextTimeout) {
                mNextTimeout = LLONG_MAX;
                timeoutExpiredLocked(now);
            }
        }
        // 4. 处理输入设备改动
        // 4.1 输入设备改动,从头获取输入设备信息
        if (oldGeneration != mGeneration) {
            inputDevicesChanged = true;
            inputDevices = getInputDevicesLocked();
        }
    } // release lock
    // 4.2 通知监听者,输入设备改动了
    if (inputDevicesChanged) {
        mPolicy->notifyInputDevicesChanged(inputDevices);
    }
    // 5. 改写行列中缓存的事情
    // 其实便是把事情分发给 InputClassifier
    mQueuedListener->flush();
}

InputReader 所做的事情如下

  1. 假如装备改动了,那么就更新装备。
  2. 从 EventHub 获取事情,并处理获取到的事情。在处理事情的进程中,InputReader 会对事情进行加工,然后保存到 QueuedInputListener 缓存行列中。
  3. 假如设备产生改动,那么从头获取新的设备信息,并通知监听者。
  4. QueuedInputListener 改写缓存的事情,其实便是把 InputReader 加工后的事情分发给 InputClassifer。

EventHub 供给事情

InputReader 的实质便是处理从 EventHub 获取的事情,然后分发给下一环。由于咱们有必要了解 EventHub::getEvents() 是怎么为 InputReader 供给事情的

// EventHub.cpp
size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
    ALOG_ASSERT(bufferSize >= 1);
    std::scoped_lock _l(mLock);
    struct input_event readBuffer[bufferSize];
    RawEvent* event = buffer;
    size_t capacity = bufferSize;
    bool awoken = false;
    for (;;) {
        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
        // Reopen input devices if needed.
        if (mNeedToReopenDevices) {
            // ...
        }
        // Report any devices that had last been added/removed.
        for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
            // ...
        }
        // 扫描输入设备
        if (mNeedToScanDevices) {
            mNeedToScanDevices = false;
            scanDevicesLocked();
            mNeedToSendFinishedDeviceScan = true;
        }
        // 为扫描后翻开的每一个输入设备,填充一个类型为 DEVICE_ADDED 的事情
        while (!mOpeningDevices.empty()) {
            std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
            mOpeningDevices.pop_back();
            event->when = now;
            event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
            event->type = DEVICE_ADDED;
            event += 1;
            // Try to find a matching video device by comparing device names
            for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
                 it++) {
                // ...
            }
            // 每次填充完事情,就把设备 Device 保存到 mDevices 中
            auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
            if (!inserted) {
                ALOGW("Device id %d exists, replaced.", device->id);
            }
            // 标明你需求发送设备扫描完结事情
            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;
        // 处理 epoll 事情
        while (mPendingEventIndex < mPendingEventCount) {
            // 处理 inotify 事情,标明输入设备新增或者删去
            const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
            if (eventItem.data.fd == mINotifyFd) {
                if (eventItem.events & EPOLLIN) {
                    mPendingINotify = true;
                } else {
                    ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
                }
                continue;
            }
            // 处理管道事情,这是用来唤醒 InputReader 线程
            if (eventItem.data.fd == mWakeReadPipeFd) {
                if (eventItem.events & EPOLLIN) {
                    ALOGV("awoken after wake()");
                    awoken = true;
                    char wakeReadBuffer[16];
                    ssize_t nRead;
                    do {
                        nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
                    } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
                } else {
                    ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
                          eventItem.events);
                }
                continue;
            }
            // 接下来是处理设备的输入事情
            Device* device = getDeviceByFdLocked(eventItem.data.fd);
            if (device == nullptr) {
                continue;
            }
            if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
                // ...
            }
            if (eventItem.events & EPOLLIN) {
                // 读取输入事情以及数量
                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) {
                    if (errno != EAGAIN && errno != EINTR) {
                        ALOGW("could not get event (errno=%d)", errno);
                    }
                } else if ((readSize % sizeof(struct input_event)) != 0) {
                    ALOGE("could not get event (wrong size: %d)", readSize);
                } else {
                    int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
                    // 为每一个输入事情,填充一个事情
                    size_t count = size_t(readSize) / sizeof(struct input_event);
                    for (size_t i = 0; i < count; i++) {
                        struct input_event& iev = readBuffer[i];
                        event->when = processEventTimestamp(iev);
                        event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
                        event->deviceId = deviceId;
                        event->type = iev.type;
                        event->code = iev.code;
                        event->value = iev.value;
                        event += 1;
                        capacity -= 1;
                    }
                    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;
                    }
                }
            } else if (eventItem.events & EPOLLHUP) {
                ALOGI("Removing device %s due to epoll hang-up event.",
                      device->identifier.name.c_str());
                deviceChanged = true;
                closeDeviceLocked(*device);
            } else {
                ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
                      device->identifier.name.c_str());
            }
        }
        // 处理设备改动
        // mPendingEventIndex >= mPendingEventCount 标明处理完一切的输入事情后,再处理设备的改动
        if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
            mPendingINotify = false;
            readNotifyLocked();
            deviceChanged = true;
        }
        // 设备产生改动,那么越过当时循环,鄙人一个循环的开头处理设备改动
        if (deviceChanged) {
            continue;
        }
        // 假如有事情,或者被唤醒,那么停止循环,接下来 InputReader 会处理事情或者更新装备
        if (event != buffer || awoken) {
            break;
        }
        mPendingEventIndex = 0;
        mLock.unlock(); // release lock before poll
        // 此时没有事情,而且也没有被唤醒,那么超时等候 epoll 事情
        int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
        mLock.lock(); // reacquire lock after poll
        if (pollResult == 0) {
            // 处理超时...
        }
        if (pollResult < 0) {
            // 处理过错...
        } else {
            // 保存待处理事情的数量
            mPendingEventCount = size_t(pollResult);
        }
    }
    // 回来事情的数量
    return event - buffer;
}

EventHub::getEvent() 供给事情的进程很长,可是现在咱们不用去了解一切的细节,咱们要有从全体看局部的眼光。EventHub 其实只生成了两类事情

  1. 设备的添加/删去事情。这种事情不是经过操作设备而产生的,体系称之为合成事情。
  2. 输入事情。这种事情是经过操作设备产生的,例如手指在触摸屏上滑动,体系称之为元输入事情。

看来咱们得分两部分来剖析这两类事情的生成以及处理进程,因而下一篇文章,咱们剖析合成事情的生成以及处理进程。