InputReader与InputDispatcher关系 - android-15.0.0_r23

InputReader与InputDispatcher关系 - android-15.0.0_r23

InputManagerService启动-Android12


1、InputManager中创建

  • JNI (com_android_server_input_InputManagerService.cpp)连接 InputManagerService.java 与 InputManager.cpp
  • InputManager.cpp中去创建InputReader与InputDispatcher,都会持有 JNI 中 NativeInputManager
  • JNI 中 NativeInputManager 继承 InputReaderPolicyInterface、InputDispatcherPolicyInterface、PointerControllerPolicyInterface、 PointerChoreographerPolicyInterface、InputFilterPolicyInterface

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) 持有 JNI 中 NativeInputManager与上层IMS沟通桥梁
  • mTracer 非user版本上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) 持有 JNI 中 NativeInputManager与上层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

  • InputReader中mNextListener(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接口的实现。表示输入处理的一个单独阶段。所有输入事件都经过这个阶段。充当除运动事件之外的所有输入事件的直通。运动类型的事件被发送到PalmRejectors。PalmRejector检测不需要的触摸,并在删除错误指针的情况下发出输入流。
PointerChoreographer PointerChrographer管理系统显示的用于输入交互的图标。这包括显示鼠标光标、手写笔悬停图标和触摸点。它负责累积鼠标光标的位置,并在必要时为传入事件填充光标位置。
InputProcessor InputProcessor接口的实现。表示输入处理的一个单独阶段。所有输入事件都经过这个阶段。充当除运动事件之外的所有输入事件的直通。运动类型的事件被发送到MotionClassifier。
InputDeviceMetricsCollector 为测试而注入的度量收集器的日志接口。ENABLE_INPUT_DEVICE_USAGE_METRICS开关控制
InputFilter InputFilter的C++组件被设计为rust实现的包装器。ENABLE_INPUT_FILTER_RUST开关控制
InputDispatcher 将 InputEvent 分发给目标窗口
相关推荐
千里马学框架5 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台5 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
AFinalStone5 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
致远ccc5 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
ttyyttemo5 天前
Kotlin 协程中的 Job 结构化并发与取消
android
sun0077005 天前
tbox 4g/5g切换,导致wan ip 改变,导致车机旧网络不可用。需要重启车机才行
android
其实防守也摸鱼5 天前
内网穿透与反向代理:原理、工具与实战指南
android·大数据·运维·安全·网络安全·自动化·渗透
AFinalStone6 天前
Android7 SystemUI 源码解析(四)NavigationBar 导航栏与 SystemBars
android·systemui
JMchen6 天前
属性动画原理与高级动画实现
android·kotlin·canvas
AFinalStone6 天前
Android7 SystemUI 源码解析(二)启动流程深度解析
android·systemui