framework 学习笔记22. input输入事件番外5(事件分发InputDispatcher)

1. InputDispatcher 的简介

在 input 输入事件番外4 中讲到事件经过获取、初步处理后最终发送给 InputtDispatcher 进行分发,那么 InputtDispatcher 是怎么进行分发的呢,首先从 InputtDispatcher 的设计思路出发,然后再进行一步步分析;
InputDispatcher 既然是要分发事件,就要搞清两个问题,发送的是什么?发送给谁?也就是下面将要展开分析的两点:
获取发送事件;
获取目标app,并将事件交由其处理;

获取发送事件:
第一步:获取事件;
第二步:放入队列前的简单处理;例如是否处于锁屏状态、有没有被 InputFilter 消费掉等;
第三步:放入队列 Queue mInboundQueue;

发送事件给目标app:
第一步:找到目标 app;
第二步:放入队列 Queue outboundQueue;
第三步:从 outboundQueue 取出事件,通过 Connection 发送给目标 app;

2. 获取发送事件:

2.1 事件从 InputReader 到 InputDispatcher:上一节中讲到 getListener()->notifyMotion(&args) 后事件就传递到 InputDispatcher 交给分发线程处理了,而且还提到 getListener() 其实就是在初始化 InputReader 时传入的参数 mDispatcher,这里就来分析一下:

(1)getListener():

// frameworks\native\services\inputflinger\InputManager.cpp
InputManager::InputManager(
        const sp& eventHub,
        const sp& readerPolicy,
        const sp& dispatcherPolicy) {
    mDispatcher = new InputDispatcher(dispatcherPolicy);
    mReader = new InputReader(eventHub, readerPolicy, mDispatcher);
    initialize();
}


// InputReader 的构造函数 frameworks\native\services\inputflinger\InputReader.cpp
InputReader::InputReader(const sp& eventHub,
        const sp& policy,
        const sp& listener) :
        mContext(this), mEventHub(eventHub), mPolicy(policy),
        mGlobalMetaState(0), mGeneration(1),
        mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
        mConfigurationChangesToRefresh(0) {
    mQueuedListener = new QueuedInputListener(listener);  // 就在这里,初始化了 mQueuedListener 

    { // acquire lock
        AutoMutex _l(mLock);

        refreshConfigurationLocked(0);
        updateGlobalMetaStateLocked();
    } // release lock
}

InputListenerInterface* InputReader::ContextImpl::getListener() {
    return mReader->mQueuedListener.get();  // 通过 get() 函数获得原生指针
}

(2)InputReader 传递事件到 InputDispatcher:

// 事件获取线程中 获取事件到事件传递 循环调用的方法:loopOnce()
void InputReader::loopOnce() {

    // ... 
    // 1. 读取事件
    size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);

    { // acquire lock
        AutoMutex _l(mLock);
        mReaderIsAliveCondition.broadcast();

        if (count) {
            // 2. 事件的简单处理;
            processEventsLocked(mEventBuffer, count);  
        }
        // ... 
    } // release lock

    // Send out a message that the describes the changed input devices.
    if (inputDevicesChanged) {
        mPolicy->notifyInputDevicesChanged(inputDevices);
    }
    
    // 3. 把事件传给 InputDispatcher 处理(也可以理解为交给分发线程处理)
    mQueuedListener->flush();  // 这个 mQueuedListener 其实就是 InputDispatcher
}

上面的代码是上一节内容的代码,还是以 SingleTouch 为例,事件简单处理最终调用 getListener()->notifyMotion(&args),然后再调用 mQueuedListener->flush();

void QueuedInputListener::notifyMotion(const NotifyMotionArgs* args) {
    // push() 方法:STL中常见的方法,向数据结构中添加元素
    mArgsQueue.push(new NotifyMotionArgs(*args));  
}
 
void QueuedInputListener::flush() {
    size_t count = mArgsQueue.size();
    for (size_t i = 0; i < count; i++) {
        NotifyArgs* args = mArgsQueue[i];
        // mInnerListener 是 QueuedInputListener 构造函数中传入的 InputDispatcher
        args->notify(mInnerListener);
        delete args;
    }
    mArgsQueue.clear();
}

// 还是以上一节中为例 所以这里调用的时 NotifyMotionArgs 的 notify() 方法;
void NotifyMotionArgs::notify(const sp& listener) const {
    listener->notifyMotion(this);  // 终于到 InputDispatcher 中了;
}

2.2 InputDispatcher::notifyMotion():从事件获取到简单处理 mPolicy->interceptMotionBeforeQueueing(),最终通过 needWake = true 唤醒分发线程;
在 InputReader 中通过 listener->notifyMotion(this) 将事件封装成 NotifyMotionArgs 传递到 InputDispatcher;

void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
    //(1)获取发送事件:即封装的 NotifyMotionArgs* args  (上面讲到的内容)
    // ... 省略一些打印信息的代码
    // 判断是否是有效的事件
    if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {  
        return;
    }

    uint32_t policyFlags = args->policyFlags;
    policyFlags |= POLICY_FLAG_TRUSTED;
    //(2)放入队列前的简单处理  
    // 注释 /*byref*/ 表示 "引用类型的变量",说明这个方法的处理结果会保存在 policyFlags 中;并且最后根据  
    // 这个 policyFlags 构造出 newEntry;
    mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);

    bool needWake;
    { // acquire lock
        mLock.lock();

        if (shouldSendMotionToInputFilterLocked(args)) {
            mLock.unlock();

            MotionEvent event;
            event.initialize(args->deviceId, args->source, args->action, args->flags,
                    args->edgeFlags, args->metaState, args->buttonState, 0, 0,
                    args->xPrecision, args->yPrecision,
                    args->downTime, args->eventTime,
                    args->pointerCount, args->pointerProperties, args->pointerCoords);

            policyFlags |= POLICY_FLAG_FILTERED;
            /* IMS.filterInputEvent:可拦截事件,当返回值为 false 的事件都直接拦截,没有机会加入mInboundQueue队列 */
            if (!mPolicy->filterInputEvent(&event, policyFlags)) {
                return; // event 被 InputFilter 消费掉,直接返回
            }

            mLock.lock();
        }

        // Just enqueue a new motion event.
        MotionEntry* newEntry = new MotionEntry(args->eventTime,
                args->deviceId, args->source, policyFlags,
                args->action, args->flags, args->metaState, args->buttonState,
                args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
                args->displayId,
                args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);

        //(3)放入队列 Queue mInboundQueue
        needWake = enqueueInboundEventLocked(newEntry);
        mLock.unlock();
    } // release lock

    if (needWake) {
        mLooper->wake();  // 如果需要唤醒 InputDispatcher 线程, 则调用 Looper 的 wake() 方法
    }
}

(1)获取发送事件:notifyMotion() 方法中的参数,即封装的 NotifyMotionArgs* args;
(2)放入队列前的简单处理: mPolicy->interceptMotionBeforeQueueing()
要想搞明白进行了什么处理,首先得先搞明白这个 mPolicy 是什么。

// mPolicy 定义:在 InputDispatcher.h 中
class Connection : public RefBase {
  public:
    sp mPolicy;
}

// mPolicy 的初始化:InputDispatcher 的构造函数中
InputDispatcher::InputDispatcher(const sp& policy) :
    mPolicy(policy),/* mPolicy 的初始化,传入的参数 */
    mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
    mNextUnblockedEvent(NULL),
    mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
    mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
    mLooper = new Looper(false);
    mKeyRepeatState.lastKeyEntry = NULL;
    policy->getDispatcherConfiguration(&mConfig);
}

跟踪代码,结果发现是在 frameworks\base\services\core\jni\com_android_server_input_InputManagerService.cpp 中初始化 InputManager(eventHub, this, this) 中传入的 this (第三个参数),那就很容易找到 interceptMotionBeforeQueueing() 这个方法的代码了:

void NativeInputManager::interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) {
    if (mInteractive) {
        policyFlags |= POLICY_FLAG_INTERACTIVE;
    }
    if ((policyFlags & POLICY_FLAG_TRUSTED) && !(policyFlags & POLICY_FLAG_INJECTED)) {
        if (policyFlags & POLICY_FLAG_INTERACTIVE) {
            policyFlags |= POLICY_FLAG_PASS_TO_USER;
        } else {
            JNIEnv* env = jniEnv();
            // 这是 JNI 回调 Java 中的代码:interceptMotionBeforeQueueingNonInteractive 的同名函数 */
            // 在这里直接说明这个同名函数 PhoneWindowManger.java 中,后续单独一节来讲 JNI 系统
            jint wmActions = env->CallIntMethod(mServiceObj,
                        gServiceClassInfo.interceptMotionBeforeQueueingNonInteractive,
                        when, policyFlags);
            if (checkAndClearExceptionFromCallback(env,
                    "interceptMotionBeforeQueueingNonInteractive")) {
                wmActions = 0;
            }
            // 根据回调 Java 中的方法得到的结果 wmActions 来设置 policyFlags
            handleInterceptActions(wmActions, when, /*byref*/ policyFlags);
        }
    } else {
        if (mInteractive) {
            policyFlags |= POLICY_FLAG_PASS_TO_USER;
        }
    }
}

PhoneWindowManger.java 中:interceptMotionBeforeQueueingNonInteractive()

   @Override
    public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
        if ((policyFlags & FLAG_WAKE) != 0) {
            mPowerManager.wakeUp(whenNanos / 1000000);
            return 0;
        }
        if (shouldDispatchInputWhenNonInteractive()) {  // 有没有锁屏之类的
            return ACTION_PASS_TO_USER;  // 发送给 USER
        }
        return 0;
    }

    private boolean shouldDispatchInputWhenNonInteractive() {
        return keyguardIsShowingTq() && mDisplay != null &&
                mDisplay.getState() != Display.STATE_OFF;  // 屏幕不是熄屏状态
    }

(3)将事件放入队列 Queue mInboundQueue:enqueueInboundEventLocked()

bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
    bool needWake = mInboundQueue.isEmpty();  // 如果队列为空 , 则需要唤醒
    mInboundQueue.enqueueAtTail(entry);  // 插入到mInboundQueue队列尾部
    traceInboundQueueLengthLocked();

    switch (entry->type) {

    // 这里会优化App切换的事件,如果上一个App还有事件没处理完,也没反馈事件处理完毕消息
    // 则清空之前的事件,切换下一个应用
    case EventEntry::TYPE_KEY: {
        KeyEntry* keyEntry = static_cast(entry);
        if (isAppSwitchKeyEventLocked(keyEntry)) {
            if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
                mAppSwitchSawKeyDown = true;
            } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
                if (mAppSwitchSawKeyDown) {
                    mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
                    mAppSwitchSawKeyDown = false;
                    needWake = true;
                }
            }
        }
        break;
    }

    // 当一个非当前激活app的点击事件发生,会清空之前的事件
    // 从这个新的点击事件开始
    case EventEntry::TYPE_MOTION: {
        MotionEntry* motionEntry = static_cast(entry);
        if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
                && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
                && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
                && mInputTargetWaitApplicationHandle != NULL) {
            int32_t displayId = motionEntry->displayId;
            int32_t x = int32_t(motionEntry->pointerCoords[0].
                    getAxisValue(AMOTION_EVENT_AXIS_X));
            int32_t y = int32_t(motionEntry->pointerCoords[0].
                    getAxisValue(AMOTION_EVENT_AXIS_Y));
            sp touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
            if (touchedWindowHandle != NULL
                    && touchedWindowHandle->inputApplicationHandle
                            != mInputTargetWaitApplicationHandle) {

                mNextUnblockedEvent = motionEntry;
                needWake = true;
            }
        }
        break;
    }

    return needWake;
}
/*
这里做了两种优化,主要是在当前App窗口处理事件过慢,同时你又触发其他App的事件时,Dispatcher就会
丢弃先前的事件,从这个开始唤醒Dispatcher。这样做很合情合理,用户在使用时,会遇到App由于开发者水
平有限导致处理事件过慢情况,这时用户等的不耐烦,则应该让用户轻松的切换到其它 App,而不是阻塞在
那。所以,事件无法响应只会发生在App内部,而不会影响应用的切换,从而提升用户体验。App的质量问题
不会影响系统的运转。
*/

在这里 needWake 置为 true 后,结合上面的内容,唤醒了事件分发线程,接下来就分析一下这个事件分发线程。

3. 发送事件给目标app

InputDispatcherThread 与 前一节的中的 InputReader 线程一样,直接进入它的 threadLoop() 方法:

bool InputDispatcherThread::threadLoop() {
    mDispatcher->dispatchOnce();  //调用了 InputDispatcher 的 dispatchOnce() 
    return true;
}

void InputDispatcher::dispatchOnce() {
    nsecs_t nextWakeupTime = LONG_LONG_MAX;
    { // acquire lock
        AutoMutex _l(mLock);
        mDispatcherIsAliveCondition.broadcast();


        // 第一次进来时 mCommandQueue 为空,能进入此分支;
        // 然后在 dispatchOnceInnerLocked() 方法中 return;
        // 最终在 mLooper->pollOnce(timeoutMillis) 休眠等待;
        if (!haveCommandsLocked()) {  // 为空则开始处理事件
            // 会创建一个 commandEntry,并 mCommandQueue.enqueueAtTail(commandEntry)
            dispatchOnceInnerLocked(&nextWakeupTime);
        }

        // Run all pending commands if there are any.
        // If any commands were run then force the next poll to wake up immediately.
        // 如果 mCommandQueue 不为空,消费掉队列中的 commandEntry,直到为空
        if (runCommandsLockedInterruptible()) {  // mCommandQueue.isEmpty() 时返回 false
            nextWakeupTime = LONG_LONG_MIN;  // 如果有命令时立刻唤醒分发线程;
        }
    } // release lock

    // Wait for callback or timeout or wake.  (make sure we round up, not down)
    nsecs_t currentTime = now();
    int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
    // looper进入休眠等待,wake() 方法唤醒(向fd中写入数据就会唤醒)
    mLooper->pollOnce(timeoutMillis);
}

dispatchOnceInnerLocked() -> pokeUserActivityLocked() -> postCommandLocked(),在此过程中从事件队列中取出事件,调用 pokeUserActivityLocked() 最终连接 PowerMangerService 保持屏幕唤醒;

// 传递流程 这个分支纪录一下,暂时不跟进;

// 向 mCommandQueue 中添加 commandEntry:postCommandLocked() 方法中
(1)CommandEntry* commandEntry = postCommandLocked(
            & InputDispatcher::doPokeUserActivityLockedInterruptible)
(2)InputDispatcher.doPokeUserActivityLockedInterruptible ->
(3)com_android_server_input_InputManagerService.pokeUserActivit ->
(4)com_android_server_power_PowerManagerService.android_server_PowerManagerService_userActivity ->
(5)PowerManagerService.userActivityFromNative ->
(6)PowerManagerService.userActivityInternal ->
(7)PowerManagerService.userActivityNoUpdateLocked{ updatePowerStateLocked(); }
void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
    nsecs_t currentTime = now();
    // 判断事件分发是否允许,也就是在 IMS 未成功启动、非交互状态下等是不可用的,默认值是 false
    if (!mDispatchEnabled) {
        resetKeyRepeatLocked();
    }
    //判断分发线程是否被冻结,是否可以配发,默认值是false
    if (mDispatchFrozen) {
        return;
    }
    // 当事件分发的事件点距离该事件加入 mInboundQueue 的时间超过500ms时,则判定 app 切换过期;
    // isAppSwitchDue 为 true;
    bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
    if (mAppSwitchDueTime < *nextWakeupTime) {
        *nextWakeupTime = mAppSwitchDueTime;
    }

    //mPendingEvent是即将要被配发的事件,派发完成置为null,此处是判断是否正在配发事件
    if (! mPendingEvent) {
        if (mInboundQueue.isEmpty()) {  // 如果Event队列为空的话
            if (isAppSwitchDue) {
                // The inbound queue is empty so the app switch key we were waiting
                // for will never arrive.  Stop waiting for it.
                resetPendingAppSwitchLocked(false);
                isAppSwitchDue = false;
            }

            // Synthesize a key repeat if appropriate.
            if (mKeyRepeatState.lastKeyEntry) {
                if (currentTime >= mKeyRepeatState.nextRepeatTime) {
                    mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
                } else {
                    if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
                        *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
                    }
                }
            }

            // Nothing to do if there is no pending event.
            if (!mPendingEvent) {  // 如果没有要处理的事件 , 则返回
                return;
            }
        } else {// 有Event时,取出第一个Event;
            // Inbound queue has at least one entry.
            mPendingEvent = mInboundQueue.dequeueAtHead();
            traceInboundQueueLengthLocked();
        }

        // Poke user activity for this event.
        if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
            pokeUserActivityLocked(mPendingEvent);
        }

        // Get ready to dispatch the event.
       // 重置此次事件分发的ANR超时时间,如果超过5秒,就会产生ANR
        resetANRTimeoutsLocked();
    }

    // Now we have an event to dispatch.
    // All events are eventually dequeued and processed this way, even if we intend to drop them.
    ALOG_ASSERT(mPendingEvent != NULL);
    bool done = false;
    DropReason dropReason = DROP_REASON_NOT_DROPPED;
    if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
        dropReason = DROP_REASON_POLICY;
    } else if (!mDispatchEnabled) {
        dropReason = DROP_REASON_DISABLED;
    }

    if (mNextUnblockedEvent == mPendingEvent) {
        mNextUnblockedEvent = NULL;
    }

    switch (mPendingEvent->type) {
     // 处理 Configuration Change消息 , 即屏幕旋转等等
    case EventEntry::TYPE_CONFIGURATION_CHANGED: {
        ConfigurationChangedEntry* typedEntry =
                static_cast(mPendingEvent);
        done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
        dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
        break;
    }
    // 处理设备重置消息 
    case EventEntry::TYPE_DEVICE_RESET: {
        DeviceResetEntry* typedEntry =
                static_cast(mPendingEvent);
        done = dispatchDeviceResetLocked(currentTime, typedEntry);
        dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
        break;
    }
    // 处理Key按键消息
    case EventEntry::TYPE_KEY: {
        KeyEntry* typedEntry = static_cast(mPendingEvent);
        if (isAppSwitchDue) {
            if (isAppSwitchKeyEventLocked(typedEntry)) {
                resetPendingAppSwitchLocked(true);
                isAppSwitchDue = false;
            } else if (dropReason == DROP_REASON_NOT_DROPPED) {
                dropReason = DROP_REASON_APP_SWITCH;
            }
        }
        if (dropReason == DROP_REASON_NOT_DROPPED
                && isStaleEventLocked(currentTime, typedEntry)) {
            dropReason = DROP_REASON_STALE;
        }
        if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
            dropReason = DROP_REASON_BLOCKED;
        }
        done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
        break;
    }
    // 判断时触屏事件时:
    case EventEntry::TYPE_MOTION: {
        MotionEntry* typedEntry = static_cast(mPendingEvent);
        if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
            dropReason = DROP_REASON_APP_SWITCH;
        }
        if (dropReason == DROP_REASON_NOT_DROPPED
                && isStaleEventLocked(currentTime, typedEntry)) {
            dropReason = DROP_REASON_STALE;
        }
        if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
            dropReason = DROP_REASON_BLOCKED;
        }
        done = dispatchMotionLocked(currentTime, typedEntry,
                &dropReason, nextWakeupTime);  // 分发事件
        break;
    }

    default:
        ALOG_ASSERT(false);
        break;
    }

    if (done) {
        if (dropReason != DROP_REASON_NOT_DROPPED) {
            dropInboundEventLocked(mPendingEvent, dropReason);  // 从配发队列里面丢弃事件
        }

        releasePendingEventLocked();
        *nextWakeupTime = LONG_LONG_MIN;  // force next poll to wake up immediately
    }
}

(关键代码1)分发事件:done = dispatchMotionLocked();

bool InputDispatcher::dispatchMotionLocked(
        nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
    //...
    bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;

    // 定义 targets(存储窗口的集合)  找到目标窗口
    Vector inputTargets;

    bool conflictingPointerActions = false;
    int32_t injectionResult;
    if (isPointerEvent) {  
        // Pointer event.  (eg. touchscreen)
      // 如果是手指事件的话 ,则找到 Touch 窗口:关键代码1
        injectionResult = findTouchedWindowTargetsLocked(currentTime,
                entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
    } else {
        // Non touch event.  (eg. trackball)
        // 如果不是手指触摸事件 , 比如轨迹球事件的话 , 则找到Focus窗口;这个分支不是重点
        injectionResult = findFocusedWindowTargetsLocked(currentTime,
                entry, inputTargets, nextWakeupTime);
    }
    // 如果找到窗口失败, 返回
    if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
        return false;
    }

    setInjectionResultLocked(entry, injectionResult);
    if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
        return true;
    }

    // TODO: support sending secondary display events to input monitors
    if (isMainDisplay(entry->displayId)) {
        addMonitoringTargetsLocked(inputTargets);
    }

    // Dispatch the motion.
    if (conflictingPointerActions) {
        CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
                "conflicting pointer actions");
        synthesizeCancelationEventsForAllConnectionsLocked(options);
    }
    // 开始向窗口分发事件:关键代码2
    dispatchEventLocked(currentTime, entry, inputTargets);
    return true;
}

3.1 找到目标 app (也就是找到目标窗口):findTouchedWindowTargetsLocked(),也是这个方法限制了不同app在不同窗口层级时,上面的app不能把触屏事件分发给下面的app;先挖一个坑吧,后续写一章节来讲这里的目标窗口和 app 的绑定。

int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
        const MotionEntry* entry, Vector& inputTargets, nsecs_t* nextWakeupTime,
        bool* outConflictingPointerActions) {
    // ...
    if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
       //从 MotionEntry 中获取坐标点
        int32_t pointerIndex = getMotionEventActionPointerIndex(action);
        int32_t x = int32_t(entry->pointerCoords[pointerIndex].
                getAxisValue(AMOTION_EVENT_AXIS_X));
        int32_t y = int32_t(entry->pointerCoords[pointerIndex].
                getAxisValue(AMOTION_EVENT_AXIS_Y));        
        sp newTouchedWindowHandle;
        bool isTouchModal = false;
        size_t numWindows = mWindowHandles.size();//1
        // 遍历窗口,找到触摸过的窗口和窗口之外的外部目标
        for (size_t i = 0; i < numWindows; i++) {//2
            //获取InputDispatcher中代表窗口的windowHandle 
            sp windowHandle = mWindowHandles.itemAt(i);
            //得到窗口信息windowInfo 
            const InputWindowInfo* windowInfo = windowHandle->getInfo();
            if (windowInfo->displayId != displayId) {
            //如果displayId不匹配,开始下一次循环
                continue; 
            }
            //获取窗口的 flag
            int32_t flags = windowInfo->layoutParamsFlags;
            //如果窗口时可见的
            if (windowInfo->visible) {
               //如果窗口的 flag 不为FLAG_NOT_TOUCHABLE(窗口是 touchable)
                if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
                   // 如果窗口是 focusable 或者 flag 不为FLAG_NOT_FOCUSABLE,则说明该窗口是"可触摸模式"
                    isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
                            | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;//3
                   //如果窗口是可触摸模式或者坐标点落在窗口之上(找到目标窗口)
                    if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
                        newTouchedWindowHandle = windowHandle;//4
                        break; // found touched window, exit window loop
                    }
                }
                if (maskedAction == AMOTION_EVENT_ACTION_DOWN
                        && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
                    //将符合条件的窗口放入TempTouchState中,以便后续处理。
                    mTempTouchState.addOrUpdateWindow(
                            windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));//5
                }
            }
        // ...
        }
    } else{
        // ...
    }
    // ...
    // 把临时存放窗口的 TempTouchState 加入到全局的 inputTargets 中
    for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
        const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
        addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
                touchedWindow.pointerIds, inputTargets);
    }
   // ...
}

(关键代码2)开始向窗口分发事件:dispatchEventLocked(currentTime, entry, inputTargets)

void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
        EventEntry* eventEntry, const Vector& inputTargets) {

    ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true

    pokeUserActivityLocked(eventEntry);

    for (size_t i = 0; i < inputTargets.size(); i++) {  // 遍历 inputTargets
        const InputTarget& inputTarget = inputTargets.itemAt(i);
        
        ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
        if (connectionIndex >= 0) {
            // 获取跨进程通讯的连接;
            sp connection = mConnectionsByFd.valueAt(connectionIndex);
            // 通过拿到的连接进行分发;
            prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
        } else {
            // ...
        }
    }
}

调用流程:
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget) ->
enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget) ->
startDispatchCycleLocked(currentTime, connection)

void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
        const sp& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
    // ...
    enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
}

void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
        const sp& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
    bool wasEmpty = connection->outboundQueue.isEmpty();

    // Enqueue dispatch entries for the requested modes.
    // 以下方法会调用 connection->outboundQueue.enqueueAtTail(dispatchEntry),
    // 将事件放入队列 Queue outboundQueue;
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
            InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
            InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
            InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
            InputTarget::FLAG_DISPATCH_AS_IS);
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
            InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
    enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
            InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);

    // If the outbound queue was previously empty, start the dispatch cycle going.
    if (wasEmpty && !connection->outboundQueue.isEmpty()) {
        // 从 outboundQueue 取出事件,通过 Connection 发送给目标 app;        
        startDispatchCycleLocked(currentTime, connection);  
    }
}

3.2 将事件放入队列 Queue outboundQueue:

void InputDispatcher::enqueueDispatchEntryLocked(
        const sp& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
        int32_t dispatchMode) {
    int32_t inputTargetFlags = inputTarget->flags;
    if (!(inputTargetFlags & dispatchMode)) {
        return;
    }
    inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;

    // This is a new event.
    // Enqueue a new dispatch entry onto the outbound queue for this connection.
    DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
            inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
            inputTarget->scaleFactor);

    // Apply target flags and update the connection's input state.
    switch (eventEntry->type) {
    case EventEntry::TYPE_KEY: {
        KeyEntry* keyEntry = static_cast(eventEntry);
        dispatchEntry->resolvedAction = keyEntry->action;
        dispatchEntry->resolvedFlags = keyEntry->flags;

        if (!connection->inputState.trackKey(keyEntry,
                dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
            delete dispatchEntry;
            return; // skip the inconsistent event
        }
        break;
    }

    case EventEntry::TYPE_MOTION: {
        MotionEntry* motionEntry = static_cast(eventEntry);
        if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
            dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
        } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
            dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
        } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
            dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
        } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
            dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
        } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
            dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
        } else {
            dispatchEntry->resolvedAction = motionEntry->action;
        }
        if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
                && !connection->inputState.isHovering(
                        motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
            dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
        }

        dispatchEntry->resolvedFlags = motionEntry->flags;
        if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
            dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
        }

        if (!connection->inputState.trackMotion(motionEntry,
                dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
            delete dispatchEntry;
            return; // skip the inconsistent event
        }
        break;
    }
    }

    // Remember that we are waiting for this dispatch to complete.
    if (dispatchEntry->hasForegroundTarget()) {
        incrementPendingForegroundDispatchesLocked(eventEntry);
    }

    // Enqueue the dispatch entry.
    connection->outboundQueue.enqueueAtTail(dispatchEntry);
    traceOutboundQueueLengthLocked(connection);
}

3.3 从 outboundQueue 取出事件,通过 Connection 发送给目标 app:

void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
        const sp& connection) {

    while (connection->status == Connection::STATUS_NORMAL&& !connection->outboundQueue.isEmpty()) {
        DispatchEntry* dispatchEntry = connection->outboundQueue.head;
        dispatchEntry->deliveryTime = currentTime;

        // Publish the event.
        status_t status;
        EventEntry* eventEntry = dispatchEntry->eventEntry;
        switch (eventEntry->type) {
        case EventEntry::TYPE_KEY: {
            // ... key 事件
            break;
        }

        case EventEntry::TYPE_MOTION: {
            MotionEntry* motionEntry = static_cast(eventEntry);

            PointerCoords scaledCoords[MAX_POINTERS];
            const PointerCoords* usingCoords = motionEntry->pointerCoords;

            // Set the X and Y offset depending on the input source.
            float xOffset, yOffset, scaleFactor;
            if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
                    && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
                scaleFactor = dispatchEntry->scaleFactor;
                xOffset = dispatchEntry->xOffset * scaleFactor;
                yOffset = dispatchEntry->yOffset * scaleFactor;
                if (scaleFactor != 1.0f) {
                    for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
                        scaledCoords[i] = motionEntry->pointerCoords[i];
                        scaledCoords[i].scale(scaleFactor);
                    }
                    usingCoords = scaledCoords;
                }
            } else {
                xOffset = 0.0f;
                yOffset = 0.0f;
                scaleFactor = 1.0f;

                // We don't want the dispatch target to know.
                if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
                    for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
                        scaledCoords[i].clear();
                    }
                    usingCoords = scaledCoords;
                }
            }

            // Publish the motion event. 
            // 通过连接分发给远程端;
            status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
                    motionEntry->deviceId, motionEntry->source,
                    dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
                    motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
                    xOffset, yOffset,
                    motionEntry->xPrecision, motionEntry->yPrecision,
                    motionEntry->downTime, motionEntry->eventTime,
                    motionEntry->pointerCount, motionEntry->pointerProperties,
                    usingCoords);
            break;
        }

        // Check the result.
        if (status) {
            // ...
            return;
        }

        // Re-enqueue the event on the wait queue.
        connection->outboundQueue.dequeue(dispatchEntry);
        traceOutboundQueueLengthLocked(connection);
        connection->waitQueue.enqueueAtTail(dispatchEntry);
        traceWaitQueueLengthLocked(connection);
    }
}

从 outboundQueue 中取出需要处理的事件,交给 connection 的 inputPublisher 去分发,将事件加入到 connection 的 waitQueue 中。到这里,事件就从 InputDispatcher 中分发出去了。

4. 最后的补充

过调用 inputPublisher.publishMotionEvent(),将事件从 InputDispatcher 分发出去,那这个方法里到底做了些什么呢?
(1)inputPublisher.publishMotionEvent():封装 InputMessage,并通过 InputChannel 的 sendMessage() 发送出去;

status_t InputPublisher::publishMotionEvent( // ... 一系列参数 ) {

    if (!seq) {
        ALOGE("Attempted to publish a motion event with sequence number 0.");
        return BAD_VALUE;
    }

    if (pointerCount > MAX_POINTERS || pointerCount < 1) {
        ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
                mChannel->getName().string(), pointerCount);
        return BAD_VALUE;
    }

    InputMessage msg;
    msg.header.type = InputMessage::TYPE_MOTION;
    msg.body.motion.seq = seq;
    msg.body.motion.deviceId = deviceId;
    msg.body.motion.source = source;
    msg.body.motion.action = action;
    // ... msg.body.motion 一系列赋值

    for (uint32_t i = 0; i < pointerCount; i++) {
        msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
        msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
    }
    return mChannel->sendMessage(&msg);  // 调用了 InputChannel 的 sendMessage() 方法;
}

(2)sendMessage():通过系统的 send() 函数向 fd 中写入上面封装的 InputMessage

status_t InputChannel::sendMessage(const InputMessage* msg) {
    size_t msgLength = msg->size();
    ssize_t nWrite;
    do {
        // send:是一个系统调用函数,用来发送消息到一个套接字中
        // end()函数只能在套接字处于连接状态的时候才能使用。(只有这样才知道接受者是谁)
        nWrite = ::send(mFd, msg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
    } while (nWrite == -1 && errno == EINTR);

    if (nWrite < 0) {
        int error = errno;
        if (error == EAGAIN || error == EWOULDBLOCK) {
            return WOULD_BLOCK;
        }
        if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
            return DEAD_OBJECT;
        }
        return -error;
    }

    if (size_t(nWrite) != msgLength) {
        return DEAD_OBJECT;
    }
    return OK;
}

你可能感兴趣的:(framework 学习笔记22. input输入事件番外5(事件分发InputDispatcher))