InputReader与InputDispatcher关系 - android-15.0.0_r23

InputReader与InputDispatcher关系 - android-15.0.0_r23

InputManagerService启动-Android12


1、InputManager中创建

  • JNIcom_android_server_input_InputManagerService.cpp)连接 InputManagerService.javaInputManager.cpp
  • InputManager.cpp中去创建InputReaderInputDispatcher,都会持有 JNINativeInputManager
  • JNINativeInputManager 继承 InputReaderPolicyInterfaceInputDispatcherPolicyInterfacePointerControllerPolicyInterfacePointerChoreographerPolicyInterfaceInputFilterPolicyInterface

frameworks/base/services/core/java/com/android/server/input/InputManagerService.java

frameworks/base/services/core/java/com/android/server/input/NativeInputManagerService.java

java 复制代码
NativeImpl(InputManagerService service, MessageQueue messageQueue) {
    mPtr = init(service, messageQueue);
}

frameworks/base/services/core/jni/com_android_server_input_InputManagerService.cpp

cpp 复制代码
static jlong nativeInit(JNIEnv* env, jclass /* clazz */, jobject serviceObj,
                        jobject messageQueueObj) {
    sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
    if (messageQueue == nullptr) {
        jniThrowRuntimeException(env, "MessageQueue is not initialized.");
        return 0;
    }

    static std::once_flag nativeInitialize;
    NativeInputManager* im = nullptr;
    std::call_once(nativeInitialize, [&]() {
        // Create the NativeInputManager, which should not be destroyed or deallocated for the
        // lifetime of the process.
        im = new NativeInputManager(serviceObj, messageQueue->getLooper());
    });
    LOG_ALWAYS_FATAL_IF(im == nullptr, "NativeInputManager was already initialized.");
    return reinterpret_cast<jlong>(im);
}

NativeInputManager::NativeInputManager(jobject serviceObj, const sp<Looper>& looper)
      : mLooper(looper) {
    JNIEnv* env = jniEnv();

    mServiceObj = env->NewGlobalRef(serviceObj);

    InputManager* im = new InputManager(this, *this, *this, *this);
    mInputManager = im;
    defaultServiceManager()->addService(String16("inputflinger"), im);
}

frameworks/native/services/inputflinger/InputManager.cpp

cpp 复制代码
/**
 * The event flow is via the "InputListener" interface, as follows:
 *   InputReader
 *     -> UnwantedInteractionBlocker
 *     -> InputFilter
 *     -> PointerChoreographer
 *     -> InputProcessor
 *     -> InputDeviceMetricsCollector
 *     -> InputDispatcher
 */
InputManager::InputManager(const sp<InputReaderPolicyInterface>& readerPolicy,
                           InputDispatcherPolicyInterface& dispatcherPolicy,
                           PointerChoreographerPolicyInterface& choreographerPolicy,
                           InputFilterPolicyInterface& inputFilterPolicy) {
    mInputFlingerRust = createInputFlingerRust();

    mDispatcher = createInputDispatcher(dispatcherPolicy);
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("InputDispatcher", *mDispatcher));

    if (ENABLE_INPUT_FILTER_RUST) {
        mInputFilter = std::make_unique<InputFilter>(*mTracingStages.back(), *mInputFlingerRust,
                                                     inputFilterPolicy);
        mTracingStages.emplace_back(
                std::make_unique<TracedInputListener>("InputFilter", *mInputFilter));
    }

    if (ENABLE_INPUT_DEVICE_USAGE_METRICS) {
        mCollector = std::make_unique<InputDeviceMetricsCollector>(*mTracingStages.back());
        mTracingStages.emplace_back(
                std::make_unique<TracedInputListener>("MetricsCollector", *mCollector));
    }

    mProcessor = std::make_unique<InputProcessor>(*mTracingStages.back());
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("InputProcessor", *mProcessor));

    mChoreographer =
            std::make_unique<PointerChoreographer>(*mTracingStages.back(), choreographerPolicy);
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("PointerChoreographer", *mChoreographer));

    mBlocker = std::make_unique<UnwantedInteractionBlocker>(*mTracingStages.back());
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("UnwantedInteractionBlocker", *mBlocker));

    mReader = createInputReader(readerPolicy, *mTracingStages.back());
}

2、InputDispatcher

  • mPolicy(policy) 持有 JNINativeInputManager与上层IMS沟通桥梁
  • mTraceruser版本上Perfetto日志
  • mLooper = sp<Looper>::make(false) 控制线程休眠/激活;上层mNative.start()启动InputDispatcher的线程执行 dispatchOnce() ,并激活mLooper->wake()

frameworks/native/services/inputflinger/dispatcher/InputDispatcher.cpp

cpp 复制代码
InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
      : InputDispatcher(policy, createInputTracingBackendIfEnabled()) {}

InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
                                 std::unique_ptr<trace::InputTracingBackendInterface> traceBackend)
      : mPolicy(policy),
        mPendingEvent(nullptr),
        mLastDropReason(DropReason::NOT_DROPPED),
        mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
        mMinTimeBetweenUserActivityPokes(DEFAULT_USER_ACTIVITY_POKE_INTERVAL),
        mNextUnblockedEvent(nullptr),
        mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
        mDispatchEnabled(false),
        mDispatchFrozen(false),
        mInputFilterEnabled(false),
        mMaximumObscuringOpacityForTouch(1.0f),
        mFocusedDisplayId(ui::LogicalDisplayId::DEFAULT),
        mWindowTokenWithPointerCapture(nullptr),
        mAwaitedApplicationDisplayId(ui::LogicalDisplayId::INVALID),
        mInputEventTimelineProcessor(
                input_flags::enable_per_device_input_latency_metrics()
                        ? std::move(std::unique_ptr<InputEventTimelineProcessor>(
                                  new LatencyAggregatorWithHistograms()))
                        : std::move(std::unique_ptr<InputEventTimelineProcessor>(
                                  new LatencyAggregator()))),
        mLatencyTracker(*mInputEventTimelineProcessor) {
    mLooper = sp<Looper>::make(false);
    mReporter = createInputReporter();

    mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
#if defined(__ANDROID__)
    SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
#endif
    mKeyRepeatState.lastKeyEntry = nullptr;

    if (traceBackend) {
        mTracer = std::make_unique<trace::impl::InputTracer>(std::move(traceBackend));
    }

    mLastUserActivityTimes.fill(0);
}

status_t InputDispatcher::start() {
    if (mThread) {
        return ALREADY_EXISTS;
    }
    mThread = std::make_unique<InputThread>(
            "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); },
            /*isInCriticalPath=*/true);
    return OK;
}

3、InputReader

  • mPolicy(policy) 持有 JNINativeInputManager与上层IMS沟通桥梁
  • mEventHub(eventHub) 获取底层input事件;控制start()启动的线程的休眠/激活
  • mNextListener(listener) 连接InputDispatcher,并新增了 mTracingStages 链表处理

frameworks/native/services/inputflinger/reader/InputReader.cpp

cpp 复制代码
InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
                         const sp<InputReaderPolicyInterface>& policy,
                         InputListenerInterface& listener)
      : mContext(this),
        mEventHub(eventHub),
        mPolicy(policy),
        mNextListener(listener),
        mKeyboardClassifier(std::make_unique<KeyboardClassifier>()),
        mGlobalMetaState(AMETA_NONE),
        mLedMetaState(AMETA_NONE),
        mGeneration(1),
        mNextInputDeviceId(END_RESERVED_ID),
        mDisableVirtualKeysTimeout(LLONG_MIN),
        mNextTimeout(LLONG_MAX),
        mConfigurationChangesToRefresh(0) {
    refreshConfigurationLocked(/*changes=*/{});
    updateGlobalMetaStateLocked();
}

status_t InputReader::start() {
    if (mThread) {
        return ALREADY_EXISTS;
    }
    mThread = std::make_unique<InputThread>(
            "InputReader", [this]() { loopOnce(); }, [this]() { mEventHub->wake(); },
            /*isInCriticalPath=*/true);
    return OK;
}

4、mTracingStages 链表

代码注释:The event flow is via the "InputListener" interface, as follows: InputReader -> UnwantedInteractionBlocker -> InputFilter -> PointerChoreographer -> InputProcessor -> InputDeviceMetricsCollector -> InputDispatcher

  • InputReadermNextListener(listener)持有链表head UnwantedInteractionBlocker
  • 当获取到事件后 mNextListener.notify(args) 执行链表mTracingStages

实际链表:
UnwantedInteractionBlocker PointerChoreographer InputProcessor InputDeviceMetricsCollector InputFilter InputDispatcher

frameworks/native/services/inputflinger/InputManager.cpp

cpp 复制代码
/**
 * The event flow is via the "InputListener" interface, as follows:
 *   InputReader
 *     -> UnwantedInteractionBlocker
 *     -> InputFilter
 *     -> PointerChoreographer
 *     -> InputProcessor
 *     -> InputDeviceMetricsCollector
 *     -> InputDispatcher
 */
InputManager::InputManager(const sp<InputReaderPolicyInterface>& readerPolicy,
                           InputDispatcherPolicyInterface& dispatcherPolicy,
                           PointerChoreographerPolicyInterface& choreographerPolicy,
                           InputFilterPolicyInterface& inputFilterPolicy) {
    mInputFlingerRust = createInputFlingerRust();

    mDispatcher = createInputDispatcher(dispatcherPolicy);
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("InputDispatcher", *mDispatcher));

    if (ENABLE_INPUT_FILTER_RUST) {
        mInputFilter = std::make_unique<InputFilter>(*mTracingStages.back(), *mInputFlingerRust,
                                                     inputFilterPolicy);
        mTracingStages.emplace_back(
                std::make_unique<TracedInputListener>("InputFilter", *mInputFilter));
    }

    if (ENABLE_INPUT_DEVICE_USAGE_METRICS) {
        mCollector = std::make_unique<InputDeviceMetricsCollector>(*mTracingStages.back());
        mTracingStages.emplace_back(
                std::make_unique<TracedInputListener>("MetricsCollector", *mCollector));
    }

    mProcessor = std::make_unique<InputProcessor>(*mTracingStages.back());
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("InputProcessor", *mProcessor));

    mChoreographer =
            std::make_unique<PointerChoreographer>(*mTracingStages.back(), choreographerPolicy);
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("PointerChoreographer", *mChoreographer));

    mBlocker = std::make_unique<UnwantedInteractionBlocker>(*mTracingStages.back());
    mTracingStages.emplace_back(
            std::make_unique<TracedInputListener>("UnwantedInteractionBlocker", *mBlocker));

    mReader = createInputReader(readerPolicy, *mTracingStages.back());
}

4.1 链表执行

  • 根据 NotifyArgs 事件类型调用对应方法。这里使用 std::visit 配合 lambda 访问者(Visitor) 来处理 std::variant 类型的事件分发。实质就是检查generalArgs 参数类型调用对应方法。
  • 按照任务链表mTracingStages依次执行。

frameworks/native/services/inputflinger/include/InputListener.h

frameworks/native/services/inputflinger/InputListener.cpp

cpp 复制代码
// Helper to std::visit with lambdas.
template <typename... V>
struct Visitor : V... { using V::operator()...; };
// explicit deduction guide (not needed as of C++20)
template <typename... V>
Visitor(V...) -> Visitor<V...>;

void InputListenerInterface::notify(const NotifyArgs& generalArgs) {
    Visitor v{
            [&](const NotifyInputDevicesChangedArgs& args) { notifyInputDevicesChanged(args); },
            [&](const NotifyKeyArgs& args) { notifyKey(args); },
            [&](const NotifyMotionArgs& args) { notifyMotion(args); },
            [&](const NotifySwitchArgs& args) { notifySwitch(args); },
            [&](const NotifySensorArgs& args) { notifySensor(args); },
            [&](const NotifyVibratorStateArgs& args) { notifyVibratorState(args); },
            [&](const NotifyDeviceResetArgs& args) { notifyDeviceReset(args); },
            [&](const NotifyPointerCaptureChangedArgs& args) { notifyPointerCaptureChanged(args); },
    };
    std::visit(v, generalArgs);
}

4.2 不同InputListenerInterface功能

InputListenerInterface 功能
UnwantedInteractionBlocker UnwantedInteractionBlocker接口的实现。表示输入处理的一个单独阶段。所有输入事件都经过这个阶段。充当除运动事件之外的所有输入事件的直通。运动类型的事件被发送到PalmRejectorsPalmRejector检测不需要的触摸,并在删除错误指针的情况下发出输入流。
PointerChoreographer PointerChrographer管理系统显示的用于输入交互的图标。这包括显示鼠标光标、手写笔悬停图标和触摸点。它负责累积鼠标光标的位置,并在必要时为传入事件填充光标位置。
InputProcessor InputProcessor接口的实现。表示输入处理的一个单独阶段。所有输入事件都经过这个阶段。充当除运动事件之外的所有输入事件的直通。运动类型的事件被发送到MotionClassifier。
InputDeviceMetricsCollector 为测试而注入的度量收集器的日志接口。ENABLE_INPUT_DEVICE_USAGE_METRICS开关控制
InputFilter InputFilterC++组件被设计为rust实现的包装器。ENABLE_INPUT_FILTER_RUST开关控制
InputDispatcher InputEvent 分发给目标窗口
相关推荐
CIb0la2 小时前
安卓16系统升级后(Google pixel 8/8pro 9/9pro xl 10/10pro xl)救砖及Root方法
android·运维·生活
Ya-Jun2 小时前
项目实战Now in Android:项目模块说明
android·架构·kotlin
@Aurora.3 小时前
【MySQL】基础
android
ooooooctober3 小时前
PHP代码审计框架性思维的建立
android·开发语言·php
q***82914 小时前
图文详述:MySQL的下载、安装、配置、使用
android·mysql·adb
沐怡旸5 小时前
【底层机制】Ashmem匿名共享内存:原理与应用深度解析
android·面试
用户2018792831676 小时前
Activity结束动画与System.exit(0)的黑屏之谜
android
Proud lion7 小时前
Apipost 脚本高频场景最佳实践:搞定接口签名验证、登录令牌刷新、动态参数生成等
android
介一安全7 小时前
【Frida Android】实战篇5:SSL Pinning 证书绑定绕过 Hook 教程(二)
android·网络安全·逆向·安全性测试·frida
2501_937193147 小时前
PLB-TV 影视!无广告 + 4K 高清
android·源码·源代码管理·机顶盒