InputChannel/Looper/InputDispatcher/InputReader

390 阅读16分钟

InputChannel.java -> NativeInputChannel(android_view_InputChannel.cpp) -> InputChannel

Java层

class InputChannel {
     private long mPtr;
     private static native InputChannel[] nativeOpenInputChannelPair(String name); // jni层打开一对socketpair
private native void nativeReadFromParcel(Parcel parcel);
 private native void nativeWriteToParcel(Parcel parcel);
public void readFromParcel(Parcel in) {
     if (in == null) {
         throw new IllegalArgumentException("in must not be null");
     }
     
     nativeReadFromParcel(in);
 }

 @Override
 public void writeToParcel(Parcel out, int flags) {
     if (out == null) {
         throw new IllegalArgumentException("out must not be null");
     }
     
     nativeWriteToParcel(out); // jni层构建传输parcel对象
     
     if ((flags & PARCELABLE_WRITE_RETURN_VALUE) != 0) {
         dispose();
     }
 }
 }

NativeInputChannel(android_view_InputChannel.cpp)

// 封装用于binder传输的InputChannel数据
// windowstate服务端传输inputchannel回viewrootImpl用到
static void android_view_InputChannel_nativeWriteToParcel(JNIEnv* env, jobject obj,
        jobject parcelObj) {
    // 获取java层InputChannel parcel对象在c++层对应的Parcel对象
    Parcel* parcel = parcelForJavaObject(env, parcelObj);
    if (parcel) {
       // 获取java层InputChannel在jni的NativeInputChannel对象
        NativeInputChannel* nativeInputChannel =
                android_view_InputChannel_getNativeInputChannel(env, obj);
        if (nativeInputChannel) {
            // 获取在c++层的InputChannel对象
            sp<InputChannel> inputChannel = nativeInputChannel->getInputChannel();
            // 写入1
            parcel->writeInt32(1);
            // 写入name
            parcel->writeString8(String8(inputChannel->getName().c_str()));
            // 写入文件描述符
            parcel->writeDupFileDescriptor(inputChannel->getFd());
        } else {
            parcel->writeInt32(0);
        }
    }
}
// 构建ViewRootImpl binder传输windowState回传的InputChannel
static void android_view_InputChannel_nativeReadFromParcel(JNIEnv* env, jobject obj,
        jobject parcelObj) {
    if (android_view_InputChannel_getNativeInputChannel(env, obj) != NULL) {
        jniThrowException(env, "java/lang/IllegalStateException",
                "This object already has a native input channel.");
        return;
    }
    
    Parcel* parcel = parcelForJavaObject(env, parcelObj);
    if (parcel) {
        // 读取整数 1
        bool isInitialized = parcel->readInt32();
        if (isInitialized) {
            // 读取名字
            String8 name = parcel->readString8();
            int rawFd = parcel->readFileDescriptor(); // binder 拥有传输fd能力
            int dupFd = dup(rawFd); // 复制传回来的socketpair接收端文件描述符
            if (dupFd < 0) {
                ALOGE("Error %d dup channel fd %d.", errno, rawFd);
                jniThrowRuntimeException(env,
                        "Could not read input channel file descriptors from parcel.");
                return;
            }
            // 建立c++层InputChannel,通过传回来的文件描述符建立socket监听
            InputChannel* inputChannel = new InputChannel(name.string(), dupFd);
            // 建立jni层NativeInputChannel
            NativeInputChannel* nativeInputChannel = new NativeInputChannel(inputChannel);
            // 设置jni层NativeInputChannel mPtr到Java层InputChannel mPtr
            android_view_InputChannel_setNativeInputChannel(env, obj, nativeInputChannel);
        }
    }
}
/**
* java层jni调用打开一对InputChannel, 名称为nameObj
**/
static jobjectArray android_view_InputChannel_nativeOpenInputChannelPair(JNIEnv* env,
        jclass clazz, jstring nameObj) {
    const char* nameChars = env->GetStringUTFChars(nameObj, NULL); // jstring -> char*
    std::string name = nameChars; // char* -> std::name
    env->ReleaseStringUTFChars(nameObj, nameChars);

    sp<InputChannel> serverChannel; // 服务端inputChannel
    sp<InputChannel> clientChannel;  // 客户端inputChannel
    status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);

    if (result) {
        String8 message;
        message.appendFormat("Could not open input channel pair.  status=%d", result);
        jniThrowRuntimeException(env, message.string());
        return NULL;
    }

    jobjectArray channelPair = env->NewObjectArray(2, gInputChannelClassInfo.clazz, NULL);
    if (env->ExceptionCheck()) {
        return NULL;
    }

    // 创建一个java层对象InputChannel.java , ptr对应 c++层serverChannel指针
    jobject serverChannelObj = android_view_InputChannel_createInputChannel(env,
            std::make_unique<NativeInputChannel>(serverChannel));
    if (env->ExceptionCheck()) {
        return NULL;
    }
    // 创建一个java层对象InputChannel.java , ptr对应 c++层clientChannel指针
    jobject clientChannelObj = android_view_InputChannel_createInputChannel(env,
            std::make_unique<NativeInputChannel>(clientChannel));
    if (env->ExceptionCheck()) {
        return NULL;
    }

    env->SetObjectArrayElement(channelPair, 0, serverChannelObj);
    env->SetObjectArrayElement(channelPair, 1, clientChannelObj);
    return channelPair; // 返回java层对象InputChannel[]
}

c++ InputChannel

/** 打开一对inputChannelPair
 *  核心是通过socketpair创建一对socket, 得到两个文件描述符(int)
 **/
status_t InputChannel::openInputChannelPair(const std::string& name,
        sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
    int sockets[2];
    if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
        status_t result = -errno;
        ALOGE("channel '%s' ~ Could not create socket pair.  errno=%d",
                name.c_str(), errno);
        outServerChannel.clear();
        outClientChannel.clear();
        return result;
    }

    int bufferSize = SOCKET_BUFFER_SIZE;
    setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
    setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
    setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
    setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));

    std::string serverChannelName = name;
    serverChannelName += " (server)";
    outServerChannel = new InputChannel(serverChannelName, sockets[0]);

    std::string clientChannelName = name;
    clientChannelName += " (client)";
    outClientChannel = new InputChannel(clientChannelName, sockets[1]);
    return OK;
}

ViewRootImpl.java

// windowstate通过openInputChannelPair得到一对InputChannel,返回一个InputChannel给 ViewRootImpl
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(), mWinFrame,
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mAttachInfo.mDisplayCutout, mInputChannel);

InputEventReceiver.java -> android_view_InputEventReceiver.cpp

// InputChannel是windowstate返回的socketpair一端
public InputEventReceiver(InputChannel inputChannel, Looper looper) {
        if (inputChannel == null) {
            throw new IllegalArgumentException("inputChannel must not be null");
        }
        if (looper == null) {
            throw new IllegalArgumentException("looper must not be null");
        }

        mInputChannel = inputChannel;
        mMessageQueue = looper.getQueue();
        mReceiverPtr = nativeInit(new WeakReference<InputEventReceiver>(this),
                inputChannel, mMessageQueue); // 将inputChannel中的socketpair一端socket fd 加入到messageQueue epoll监听

        mCloseGuard.open("dispose");
    }
// android_view_InputEventReceiver  nativeInit
static jlong nativeInit(JNIEnv* env, jclass clazz, jobject receiverWeak,
        jobject inputChannelObj, jobject messageQueueObj) {
    // java层inputChannelObj对应c++层InputChannel对象
    sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
            inputChannelObj);
    if (inputChannel == NULL) {
        jniThrowRuntimeException(env, "InputChannel is not initialized.");
        return 0;
    }
    // java层messageQueue对应c++层MessageQueue
    sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
    if (messageQueue == NULL) {
        jniThrowRuntimeException(env, "MessageQueue is not initialized.");
        return 0;
    }
    // 新建一个本地层c++ NativeInputEventReceiver对象,对应java层InputEventReceiver
    sp<NativeInputEventReceiver> receiver = new NativeInputEventReceiver(env,
            receiverWeak, inputChannel, messageQueue);
    // 初始化,将该NativeInputEventReceiver(LooperCallback)加入 Looper epoll监听InputChannel fd
    status_t status = receiver->initialize();
    if (status) {
        String8 message;
        message.appendFormat("Failed to initialize input event receiver.  status=%d", status);
        jniThrowRuntimeException(env, message.string());
        return 0;
    }

    receiver->incStrong(gInputEventReceiverClassInfo.clazz); // retain a reference for the object
    return reinterpret_cast<jlong>(receiver.get());
}

android_view_InputEventReceiver initialize

void NativeInputEventReceiver::setFdEvents(int events) {
    if (mFdEvents != events) {
        mFdEvents = events;
        // 将接收端InputChannel的文件描述符加入到Looper epoll监听,事件来临时回调handleEvent
        int fd = mInputConsumer.getChannel()->getFd();
        if (events) {
            mMessageQueue->getLooper()->addFd(fd, 0, events, this, NULL);
        } else {
            mMessageQueue->getLooper()->removeFd(fd);
        }
    }
}
int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
    if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
        // This error typically occurs when the publisher has closed the input channel
        // as part of removing a window or finishing an IME session, in which case
        // the consumer will soon be disposed as well.
        if (kDebugDispatchCycle) {
            ALOGD("channel '%s' ~ Publisher closed input channel or an error occurred.  "
                    "events=0x%x", getInputChannelName().c_str(), events);
        }
        return 0; // remove the callback
    }

    if (events & ALOOPER_EVENT_INPUT) {
        JNIEnv* env = AndroidRuntime::getJNIEnv();
        status_t status = consumeEvents(env, false /*consumeBatches*/, -1, NULL);
        mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
        return status == OK || status == NO_MEMORY ? 1 : 0;
    }

    if (events & ALOOPER_EVENT_OUTPUT) {
        for (size_t i = 0; i < mFinishQueue.size(); i++) {
            const Finish& finish = mFinishQueue.itemAt(i);
            status_t status = mInputConsumer.sendFinishedSignal(finish.seq, finish.handled);
            if (status) {
                mFinishQueue.removeItemsAt(0, i);

                if (status == WOULD_BLOCK) {
                    if (kDebugDispatchCycle) {
                        ALOGD("channel '%s' ~ Sent %zu queued finish events; %zu left.",
                                getInputChannelName().c_str(), i, mFinishQueue.size());
                    }
                    return 1; // keep the callback, try again later
                }

                ALOGW("Failed to send finished signal on channel '%s'.  status=%d",
                        getInputChannelName().c_str(), status);
                if (status != DEAD_OBJECT) {
                    JNIEnv* env = AndroidRuntime::getJNIEnv();
                    String8 message;
                    message.appendFormat("Failed to finish input event.  status=%d", status);
                    jniThrowRuntimeException(env, message.string());
                    mMessageQueue->raiseAndClearException(env, "finishInputEvent");
                }
                return 0; // remove the callback
            }
        }
        if (kDebugDispatchCycle) {
            ALOGD("channel '%s' ~ Sent %zu queued finish events; none left.",
                    getInputChannelName().c_str(), mFinishQueue.size());
        }
        mFinishQueue.clear();
        setFdEvents(ALOOPER_EVENT_INPUT);
        return 1;
    }

    ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event.  "
            "events=0x%x", getInputChannelName().c_str(), events);
    return 1;
}

Looper.Java -> Looper.cpp

/**
* 计算超时时间(由java层最新消息和c++层最新消息共同决定),
 epoll_wait等待事件,事件来临后先处理epoll事件, 然后处理c++层消息队列到时消息, 处理完该方法返回, Java层Looper接下来处理java层消息队列到时消息, 循环往复
**/
int Looper::pollInner(int timeoutMillis) {
#if DEBUG_POLL_AND_WAKE
    ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
#endif

    // Adjust the timeout based on when the next message is due.
    // java层下一个消息到来时间间隔timeoutMillis
    // 本地层消息队列头部消息时间 mNextMessageUptime
    if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
        // 计算本地层头部消息还有多久时间到来
        int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
        if (messageTimeoutMillis >= 0
                && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
                // 如果本地层也有新消息,本地层新消息比上层新消息超时时间还要小, 即本地层新消息发生时间小于上层新消息发生时间
                // 超时时间采用本地层消息超时时间
            timeoutMillis = messageTimeoutMillis;
        }
#if DEBUG_POLL_AND_WAKE
        ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
                this, mNextMessageUptime - now, timeoutMillis);
#endif
    }

    // Poll.
    int result = POLL_WAKE;
    mResponses.clear();
    mResponseIndex = 0;

    // We are about to idle.
    mPolling = true;

    struct epoll_event eventItems[EPOLL_MAX_EVENTS];
    // epoll_wait等待监听事件的到来,阻塞主线程
    // Java层/本地层到来新消息会唤醒主线程, InputChannel触摸事件也会唤醒
    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);

    // No longer idling.
    mPolling = false;

    // Acquire lock.
    mLock.lock();

    // Rebuild epoll set if needed.
    if (mEpollRebuildRequired) {
        mEpollRebuildRequired = false;
        rebuildEpollLocked();
        goto Done;
    }

    // Check for poll error.
    if (eventCount < 0) {
        if (errno == EINTR) {
            goto Done;
        }
        ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
        result = POLL_ERROR;
        goto Done;
    }

    // Check for poll timeout.
    if (eventCount == 0) {
#if DEBUG_POLL_AND_WAKE
        ALOGD("%p ~ pollOnce - timeout", this);
#endif
        result = POLL_TIMEOUT;
        goto Done;
    }

    // Handle all events.
#if DEBUG_POLL_AND_WAKE
    ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
#endif
    // 处理epoll到来的所有事件
    for (int i = 0; i < eventCount; i++) {
        int fd = eventItems[i].data.fd;
        uint32_t epollEvents = eventItems[i].events;
        if (fd == mWakeEventFd) {
        // 管道输入事件,即上层java 消息队列加入了消息,往管道写了数据
            if (epollEvents & EPOLLIN) {
                awoken(); // 读管道int 1数据,唤醒主线程
            } else {
                ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
            }
        } else {
        // 其他注册fd事件则回调handleEvent,如InputChannel socketPair
            ssize_t requestIndex = mRequests.indexOfKey(fd);
            if (requestIndex >= 0) {
                int events = 0;
                if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
                if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
                if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
                if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
                pushResponse(events, mRequests.valueAt(requestIndex));
            } else {
                ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
                        "no longer registered.", epollEvents, fd);
            }
        }
    }
Done: ;

    // 处理c++层消息队列消息
    // Invoke pending message callbacks.
    mNextMessageUptime = LLONG_MAX;
    while (mMessageEnvelopes.size() != 0) {
        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
        const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
        if (messageEnvelope.uptime <= now) {
            // Remove the envelope from the list.
            // We keep a strong reference to the handler until the call to handleMessage
            // finishes.  Then we drop it so that the handler can be deleted *before*
            // we reacquire our lock.
            { // obtain handler
                sp<MessageHandler> handler = messageEnvelope.handler; // 该消息处理函数指针
                Message message = messageEnvelope.message;
                mMessageEnvelopes.removeAt(0); // 移除该消息
                mSendingMessage = true;
                mLock.unlock();

#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
                ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
                        this, handler.get(), message.what);
#endif
                handler->handleMessage(message); // 处理该消息
            } // release handler

            mLock.lock();
            mSendingMessage = false;
            result = POLL_CALLBACK;
        } else {
            // The last message left at the head of the queue determines the next wakeup time.
            mNextMessageUptime = messageEnvelope.uptime;
            break;
        }
    }

    // Release lock.
    mLock.unlock();

    // Invoke all response callbacks.
    for (size_t i = 0; i < mResponses.size(); i++) {
        Response& response = mResponses.editItemAt(i);
        if (response.request.ident == POLL_CALLBACK) {
            int fd = response.request.fd;
            int events = response.events;
            void* data = response.request.data;
#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
            ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
                    this, response.request.callback.get(), fd, events, data);
#endif
            // Invoke the callback.  Note that the file descriptor may be closed by
            // the callback (and potentially even reused) before the function returns so
            // we need to be a little careful when removing the file descriptor afterwards.
            int callbackResult = response.request.callback->handleEvent(fd, events, data);
            if (callbackResult == 0) {
                removeFd(fd, response.request.seq);
            }

            // Clear the callback reference in the response structure promptly because we
            // will not clear the response vector itself until the next poll.
            response.request.callback.clear();
            result = POLL_CALLBACK;
        }
    }
    return result;
}
//用于Java层/c++层消息队列进入消息,往管道写入1,唤醒主线程
void Looper::wake() {
#if DEBUG_POLL_AND_WAKE
    ALOGD("%p ~ wake", this);
#endif

    uint64_t inc = 1; // 写入1
    ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
    if (nWrite != sizeof(uint64_t)) {
        if (errno != EAGAIN) {
            LOG_ALWAYS_FATAL("Could not write wake signal to fd %d: %s",
                    mWakeEventFd, strerror(errno));
        }
    }
}

void Looper::awoken() {
#if DEBUG_POLL_AND_WAKE
    ALOGD("%p ~ awoken", this);
#endif

    uint64_t counter;
    // 读uint64_t类型数据1, 读事件唤醒主线程
    TEMP_FAILURE_RETRY(read(mWakeEventFd, &counter, sizeof(uint64_t)));
}
// Looper epoll增加感兴趣文件描述符事件
int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
#if DEBUG_CALLBACKS
    ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
            events, callback.get(), data);
#endif

    if (!callback.get()) {
        if (! mAllowNonCallbacks) {
            ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
            return -1;
        }

        if (ident < 0) {
            ALOGE("Invalid attempt to set NULL callback with ident < 0.");
            return -1;
        }
    } else {
        ident = POLL_CALLBACK;
    }

    { // acquire lock
        AutoMutex _l(mLock);

        Request request;
        request.fd = fd;
        request.ident = ident;
        request.events = events;
        request.seq = mNextRequestSeq++;
        request.callback = callback;
        request.data = data;
        if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1

        struct epoll_event eventItem;
        request.initEventItem(&eventItem);

        ssize_t requestIndex = mRequests.indexOfKey(fd);
        if (requestIndex < 0) {
            int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
            if (epollResult < 0) {
                ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
                return -1;
            }
            mRequests.add(fd, request);
        } else {
            int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);
            if (epollResult < 0) {
                if (errno == ENOENT) {
                    // Tolerate ENOENT because it means that an older file descriptor was
                    // closed before its callback was unregistered and meanwhile a new
                    // file descriptor with the same number has been created and is now
                    // being registered for the first time.  This error may occur naturally
                    // when a callback has the side-effect of closing the file descriptor
                    // before returning and unregistering itself.  Callback sequence number
                    // checks further ensure that the race is benign.
                    //
                    // Unfortunately due to kernel limitations we need to rebuild the epoll
                    // set from scratch because it may contain an old file handle that we are
                    // now unable to remove since its file descriptor is no longer valid.
                    // No such problem would have occurred if we were using the poll system
                    // call instead, but that approach carries others disadvantages.
#if DEBUG_CALLBACKS
                    ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
                            "being recycled, falling back on EPOLL_CTL_ADD: %s",
                            this, strerror(errno));
#endif
                    epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
                    if (epollResult < 0) {
                        ALOGE("Error modifying or adding epoll events for fd %d: %s",
                                fd, strerror(errno));
                        return -1;
                    }
                    scheduleEpollRebuildLocked();
                } else {
                    ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
                    return -1;
                }
            }
            mRequests.replaceValueAt(requestIndex, request);
        }
    } // release lock
    return 1;
}

Input事件框架

读取线程循环读取驱动数据----原始数据处理,不同来源不同处理方式(多态策略)----封装数据进入mInboundQueue队列

分发线程循环读取队列数据-----找到对应目标窗体(包含服务端socket)------封装数据进入socket连接Connection mOutboundQueue输出队列----socket发送数据

读取/分发线程利用Loop.poolOnce/Loop.wait阻塞/唤醒,防止cpu空转

应用进程窗口(包含客户端socket)------- InputManagerService(事件对应目标窗体包含服务端socket)

InputChannel包含对socketPair的描述

应用窗口和InputManagerService建立一对socket对象,即建立inputChannel/outputChannel

#WindowManagerService
public int addWindow(Session session, IWindow client, int seq,
            LayoutParams attrs, int viewVisibility, int displayId, Rect outFrame,
            Rect outContentInsets, Rect outStableInsets, Rect outOutsets,
            DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel) {
               ...
                 final WindowState win = new WindowState(this, session, client, token, parentWindow,
                    appOp[0], seq, attrs, viewVisibility, session.mUid,
                    session.mCanAddInternalSystemWindow);
               ...
               final boolean openInputChannels = (outInputChannel != null
                    && (attrs.inputFeatures & INPUT_FEATURE_NO_INPUT_CHANNEL) == 0);
            if  (openInputChannels) {
            // windowState打开一对InputChannel, 其中一个InputChannel填充到outInputChannel返回给应用进程
                win.openInputChannel(outInputChannel);
            }
             ...
            }
            
#WindowState 打开一对InputChannel
void openInputChannel(InputChannel outInputChannel) {
        if (mInputChannel != null) {
            throw new IllegalStateException("Window already has an input channel.");
        }
        String name = getName();
        InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
        mInputChannel = inputChannels[0];
        mClientChannel = inputChannels[1];
        mInputWindowHandle.inputChannel = inputChannels[0];
        if (outInputChannel != null) {
            // 其中一个传输至outInputChannel返回给应用进程窗口
            mClientChannel.transferTo(outInputChannel);
            mClientChannel.dispose();
            mClientChannel = null;
        } else {
            // If the window died visible, we setup a dummy input channel, so that taps
            // can still detected by input monitor channel, and we can relaunch the app.
            // Create dummy event receiver that simply reports all events as handled.
            mDeadWindowEventReceiver = new DeadWindowEventReceiver(mClientChannel);
        }
        // 令一个注册到InputManagerService
        mService.mInputManager.registerInputChannel(mInputChannel, mInputWindowHandle);
    }
    
#InputManagerService
public void registerInputChannel(InputChannel inputChannel,
            InputWindowHandle inputWindowHandle) {
        if (inputChannel == null) {
            throw new IllegalArgumentException("inputChannel must not be null.");
        }

        nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
}


#com_android_server_input_InputManagerService.cpp
static void nativeRegisterInputChannel(JNIEnv* env, jclass /* clazz */,
        jlong ptr, jobject inputChannelObj, jobject inputWindowHandleObj, jboolean monitor) {
    NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);

    sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
            inputChannelObj);
    if (inputChannel == NULL) {
        throwInputChannelNotInitialized(env);
        return;
    }

    sp<InputWindowHandle> inputWindowHandle =
            android_server_InputWindowHandle_getHandle(env, inputWindowHandleObj);

    status_t status = im->registerInputChannel(
            env, inputChannel, inputWindowHandle, monitor);
    if (status) {
        std::string message;
        message += StringPrintf("Failed to register input channel.  status=%d", status);
        jniThrowRuntimeException(env, message.c_str());
        return;
    }

    if (! monitor) {
        android_view_InputChannel_setDisposeCallback(env, inputChannelObj,
                handleInputChannelDisposed, im);
    }
}


status_t NativeInputManager::registerInputChannel(JNIEnv* /* env */,
        const sp<InputChannel>& inputChannel,
        const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
    ATRACE_CALL();
    // dispatch.cpp registerInputChannel
    return mInputManager->getDispatcher()->registerInputChannel(
            inputChannel, inputWindowHandle, monitor);
}


## InputDispatcher.cpp 
建立服务端socket连接对象并保存到mConnectionsByFd集合中
status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
        const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
#if DEBUG_REGISTRATION
    ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
            toString(monitor));
#endif

    { // acquire lock
        AutoMutex _l(mLock);

        if (getConnectionIndexLocked(inputChannel) >= 0) {
            ALOGW("Attempted to register already registered input channel '%s'",
                    inputChannel->getName().c_str());
            return BAD_VALUE;
        }
        // 封装该inputChannel到Connection对象中
        sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
        
        int fd = inputChannel->getFd(); // socket fd
        // 将该连接加入到mConnectionsByFd集合中
        mConnectionsByFd.add(fd, connection);

        if (monitor) {
            mMonitoringChannels.push(inputChannel);
        }

        // soketpair一端文件描述符 fd加入looper messagequeu epoll监听,
        // 回调处理handleReceiveCallback,监听客户端socket发送的finish信号
        mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
    } // release lock

    // Wake the looper because some connections have changed.
    mLooper->wake();
    return OK;
}

InputReader.cpp单线程循环读取驱动数据包含各种设备事件(鼠标/触摸/键盘等等)

    // eventHub驱动设备接口读取事件
    // InputReaderPolicyInterface 策略接口拦截处理事件
    // InputListenerInterface输入监听接口,负责分发事件即InputDispatch
    InputReader::InputReader(const sp <EventHubInterface> &eventHub,
                             const sp <InputReaderPolicyInterface> &policy,
                             const sp <InputListenerInterface> &listener) :
            mContext(this), mEventHub(eventHub), mPolicy(policy),
            mGlobalMetaState(0), mGeneration(1),
            mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
            mConfigurationChangesToRefresh(0) {
        mQueuedListener = new QueuedInputListener(listener);

        { // acquire lock
            AutoMutex _l(mLock);

            refreshConfigurationLocked(0);
            updateGlobalMetaStateLocked();
        } // release lock
    }
    
    // InputReader线程入口函数,循环处理
    bool InputReaderThread::threadLoop() {
        mReader->loopOnce();
        return true;
    }
    
    struct RawEvent {
        nsecs_t when;     // 时间
        int32_t deviceId; // 设备节点
        int32_t type;    // type
        int32_t code;    // code
        int32_t value;    // value
    };

    // 读取驱动原始数据, RawEvent mEventBuffer[EVENT_BUFFER_SIZE]
    void InputReader::loopOnce() {
        int32_t oldGeneration;
        int32_t timeoutMillis;
        bool inputDevicesChanged = false;
        Vector <InputDeviceInfo> inputDevices;
        { // acquire lock
            AutoMutex _l(mLock);

            oldGeneration = mGeneration;
            timeoutMillis = -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
        //0003 0039 00000032
        //0003 0035 000000cb
        //0003 0036 00000076
        //0000 0000 00000000
        //0003 0035 000000ca
        //0000 0000 00000000
        //0003 0039 ffffffff
        //0000 0000 00000000
        // eventhub获取events事件
        size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);

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

            if (count) {
                // 处理原始数据
                processEventsLocked(mEventBuffer, count);
            }

            if (mNextTimeout != LLONG_MAX) {
                nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
                if (now >= mNextTimeout) {
#if DEBUG_RAW_EVENTS
                    ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
#endif
                    mNextTimeout = LLONG_MAX;
                    timeoutExpiredLocked(now);
                }
            }

            if (oldGeneration != mGeneration) {
                inputDevicesChanged = true;
                getInputDevicesLocked(inputDevices);
            }
        } // release lock

        // Send out a message that the describes the changed input devices.
        if (inputDevicesChanged) {
            mPolicy->notifyInputDevicesChanged(inputDevices);
        }

        // 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.
        // flush所有原始数据已经处理过的数据
        mQueuedListener->flush();
    }
    
    processEventsLocked(mEventBuffer, count) {
                     ...
                    processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
                   ...
    }
    
    void InputReader::processEventsForDeviceLocked(int32_t deviceId,
                                                   const RawEvent *rawEvents, size_t count) {
        ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
        if (deviceIndex < 0) {
            ALOGW("Discarding event for unknown deviceId %d.", deviceId);
            return;
        }

        InputDevice *device = mDevices.valueAt(deviceIndex);
        if (device->isIgnored()) {
            //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
            return;
        }

        device->process(rawEvents, count);
    }
    
    // 不同设备数据不同处理,多态策略
    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.
        size_t numMappers = mMappers.size();
        for (const RawEvent *rawEvent = rawEvents; count != 0; rawEvent++) {
#if DEBUG_RAW_EVENTS
            ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
                    rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
                    rawEvent->when);
#endif

            if (mDropUntilNextSync) {
                if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
                    mDropUntilNextSync = false;
#if DEBUG_RAW_EVENTS
                    ALOGD("Recovered from input event buffer overrun.");
#endif
                } else {
#if DEBUG_RAW_EVENTS
                    ALOGD("Dropped input event while waiting for next input sync.");
#endif
                }
            } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
                ALOGI("Detected input event buffer overrun for device %s.", getName().string());
                mDropUntilNextSync = true;
                reset(rawEvent->when);
            } else {
                for (size_t i = 0; i < numMappers; i++) {
                    InputMapper *mapper = mMappers[i];
                    mapper->process(rawEvent);
                }
            }
            --count;
        }
    }
    
    InputMapper-CursorInputMapper-SwitchInputMapper-TouchInputMapper等等
    
    void SwitchInputMapper::process(const RawEvent* rawEvent) {
        switch (rawEvent->type) {
        case EV_SW:
            processSwitch(rawEvent->code, rawEvent->value);
            break;
    
        case EV_SYN:
            if (rawEvent->code == SYN_REPORT) {
                sync(rawEvent->when);
            }
        }
    }
    
    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)) {
                processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
            }
            break;
        }
        case EV_MSC: {
            if (rawEvent->code == MSC_SCAN) {
                mCurrentHidUsage = rawEvent->value;
            }
            break;
        }
        case EV_SYN: {
            if (rawEvent->code == SYN_REPORT) {
                mCurrentHidUsage = 0;
            }
        }
        }
    }
    
   # processXXX -  sync(rawEvent->when); 处理完毕之后同步通知inputDispatcher进行分发
   # 鼠标
   void CursorInputMapper::sync(nsecs_t when) {
        ...
         NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
                motionEventAction, 0, 0, metaState, currentButtonState,
                AMOTION_EVENT_EDGE_FLAG_NONE,
                displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
                mXPrecision, mYPrecision, downTime);
        getListener()->notifyMotion(&args); // 处理之后的数据通知到inputDispatcher
        ...
   }
   
   # 原始数据处理之后的数据进一步封装 原始数据rawEvent - NotifyMotionArgs - MotionEvent加入到mInboundQueue队列
   void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
#if DEBUG_INBOUND_EVENT_DETAILS
    ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
            "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
            "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
            args->eventTime, args->deviceId, args->source, args->policyFlags,
            args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
            args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
    for (uint32_t i = 0; i < args->pointerCount; i++) {
        ALOGD("  Pointer %d: id=%d, toolType=%d, "
                "x=%f, y=%f, pressure=%f, size=%f, "
                "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
                "orientation=%f",
                i, args->pointerProperties[i].id,
                args->pointerProperties[i].toolType,
                args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
                args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
                args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
                args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
                args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
                args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
                args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
                args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
                args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
    }
#endif
    if (!validateMotionEvent(args->action, args->actionButton,
                args->pointerCount, args->pointerProperties)) {
        return;
    }

    uint32_t policyFlags = args->policyFlags;
    policyFlags |= POLICY_FLAG_TRUSTED;

    android::base::Timer t;
    mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
    if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
        ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
                std::to_string(t.duration().count()).c_str());
    }

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

        if (shouldSendMotionToInputFilterLocked(args)) {
            mLock.unlock();
            // 原始数据rawEvent - NotifyMotionArgs - MotionEvent
            MotionEvent event;
            event.initialize(args->deviceId, args->source, args->action, args->actionButton,
                    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;
            if (!mPolicy->filterInputEvent(&event, policyFlags)) {
                return; // event was consumed by the filter
            }

            mLock.lock();
        }

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

        needWake = enqueueInboundEventLocked(newEntry);
        mLock.unlock();
    } // release lock

    if (needWake) {
        mLooper->wake();
    }
    
    bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
        ...
        bool needWake = mInboundQueue.isEmpty();
        mInboundQueue.enqueueAtTail(entry); // MotionEntry进入mInboundQueue队列尾部
        ...
    }
   

InputDispatcher.cpp单线程循环读取mInboundQueue队列数据进行分发

InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
    mPolicy(policy),
    mPendingEvent(NULL), mLastDropReason(DROP_REASON_NOT_DROPPED),
    mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
    mNextUnblockedEvent(NULL),
    mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
    mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
    mLooper = new Looper(false); // c++层Looper提供epoll能力,阻塞/唤醒线程,监听socket数据

    mKeyRepeatState.lastKeyEntry = NULL;

    policy->getDispatcherConfiguration(&mConfig);
}


bool InputDispatcherThread::threadLoop() {
    mDispatcher->dispatchOnce();
    return true; // threadLoop返回false,执行一次;返回true,循环执行
}


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

        // Run a dispatch loop if there are no pending commands.
        // The dispatch loop might enqueue commands to run afterwards.
        if (!haveCommandsLocked()) {
            dispatchOnceInnerLocked(&nextWakeupTime); // 分发一次
        }

        // Run all pending commands if there are any.
        // If any commands were run then force the next poll to wake up immediately.
        if (runCommandsLockedInterruptible()) {
            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);
    mLooper->pollOnce(timeoutMillis); //pollOnce阻塞线程wait等待timeoutMillis 
}


void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
    ...
    // Inbound queue has at least one entry.
    mPendingEvent = mInboundQueue.dequeueAtHead(); //从mInboundQueue队列中获取头部数据
    ...
    // Get ready to dispatch the event. 准备开发分发事件,开启ANR超时机制
    resetANRTimeoutsLocked();
    switch  {
        ...
        dispatchKeyLocked 不同类型数据不同处理逻辑
        ...
        dispatchMotionLocked
        ...
        
    }
}

// 找到目标应用窗口对应的服务端socket即InputChanel,封装成InputTarget对象
bool InputDispatcher::dispatchMotionLocked(
        nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
        
        ...
        // Identify targets.
        Vector<InputTarget> inputTargets;
        ...
        // 找到目标应用窗口对应的服务端socket即InputChanel,封装成InputTarget对象
         injectionResult = findFocusedWindowTargetsLocked(currentTime,
                entry, inputTargets, nextWakeupTime);
        ...
}

// 通过对应socket连接对象connection对应inputChannel发送数据
void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
        EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
#if DEBUG_DISPATCH_CYCLE
    ALOGD("dispatchEventToCurrentInputTargets");
#endif

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

    pokeUserActivityLocked(eventEntry);

    for (size_t i = 0; i < inputTargets.size(); i++) {
        const InputTarget& inputTarget = inputTargets.itemAt(i);

        ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
        if (connectionIndex >= 0) {
        // 先前应用进程通过windowState注册到InputDispatcher的inputChannel封装成Connection对象
            sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
            prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
        } else {
#if DEBUG_FOCUS
            ALOGD("Dropping event delivery to target with channel '%s' because it "
                    "is no longer registered with the input dispatcher.",
                    inputTarget.inputChannel->getName().c_str());
#endif
        }
    }
}

// 进入socket连接队列
void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
        const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
        ...
         enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
         ...
      }
      
      
void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
        const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
    bool wasEmpty = connection->outboundQueue.isEmpty();

    // Enqueue dispatch entries for the requested modes.
    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()) {
        startDispatchCycleLocked(currentTime, connection);
    }
}


void InputDispatcher::enqueueDispatchEntryLocked(
        const sp<Connection>& 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);
            
     ...
       // Enqueue the dispatch entry.
    connection->outboundQueue.enqueueAtTail(dispatchEntry);
    ...
}

// Connection socket连接发送outboundQueue队列中所有数据
void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
        const sp<Connection>& connection) {
#if DEBUG_DISPATCH_CYCLE
    ALOGD("channel '%s' ~ startDispatchCycle",
            connection->getInputChannelName().c_str());
#endif
    // 循环分发socket连接中输出队列outboundQueue
    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;
        ...
         // Publish the motion event.
         // socket发送数据
            status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
                    motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
                    dispatchEntry->resolvedAction, motionEntry->actionButton,
                    dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
                    motionEntry->metaState, motionEntry->buttonState,
                    xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
                    motionEntry->downTime, motionEntry->eventTime,
                    motionEntry->pointerCount, motionEntry->pointerProperties,
                    usingCoords);
         ...
         // 将数据从outboundQueue队列中移除
         connection->outboundQueue.dequeue(dispatchEntry);
         // 将数据加入到waitQueue队列
        connection->waitQueue.enqueueAtTail(dispatchEntry);
}      

查找应用进程窗口对应服务端inputChannel,找到目标应用窗口对应的服务端socket即InputChanel,封装成InputTarget对象

findFocusedWindowTargetsLocked(currentTime,
                entry, inputTargets, nextWakeupTime) {
                 ...
                  addWindowTargetLocked(mFocusedWindowHandle,
            InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
            inputTargets);
            ...
                }


void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
        int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
    inputTargets.push();

    const InputWindowInfo* windowInfo = windowHandle->getInfo();
    InputTarget& target = inputTargets.editTop();
    target.inputChannel = windowInfo->inputChannel;
    target.flags = targetFlags;
    target.xOffset = - windowInfo->frameLeft;
    target.yOffset = - windowInfo->frameTop;
    target.scaleFactor = windowInfo->scaleFactor;
    target.pointerIds = pointerIds;
}

Connection

// inputChannel socket
// inputPublisher 发送数据接口
InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
        const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
        status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
        monitor(monitor),
        inputPublisher(inputChannel), inputPublisherBlocked(false) {
}

InputDispatcher::Connection::~Connection() {
}


#InputTransport.cpp
// --- InputPublisher --- 服务端socket发送数据

InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
        mChannel(channel) {
}

InputPublisher::~InputPublisher() {
}

status_t InputPublisher::publishKeyEvent(
        uint32_t seq,
        int32_t deviceId,
        int32_t source,
        int32_t action,
        int32_t flags,
        int32_t keyCode,
        int32_t scanCode,
        int32_t metaState,
        int32_t repeatCount,
        nsecs_t downTime,
        nsecs_t eventTime) {
#if DEBUG_TRANSPORT_ACTIONS
    ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
            "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
            "downTime=%" PRId64 ", eventTime=%" PRId64,
            mChannel->getName().c_str(), seq,
            deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
            downTime, eventTime);
#endif

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

    InputMessage msg;
    msg.header.type = InputMessage::TYPE_KEY;
    msg.body.key.seq = seq;
    msg.body.key.deviceId = deviceId;
    msg.body.key.source = source;
    msg.body.key.action = action;
    msg.body.key.flags = flags;
    msg.body.key.keyCode = keyCode;
    msg.body.key.scanCode = scanCode;
    msg.body.key.metaState = metaState;
    msg.body.key.repeatCount = repeatCount;
    msg.body.key.downTime = downTime;
    msg.body.key.eventTime = eventTime;
    return mChannel->sendMessage(&msg); // inputChannel发送数据
}

// 服务端接受客户端socket finish信号
status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
#if DEBUG_TRANSPORT_ACTIONS
    ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
            mChannel->getName().c_str());
#endif

    InputMessage msg;
    status_t result = mChannel->receiveMessage(&msg);
    if (result) {
        *outSeq = 0;
        *outHandled = false;
        return result;
    }
    if (msg.header.type != InputMessage::TYPE_FINISHED) {
        ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
                mChannel->getName().c_str(), msg.header.type);
        return UNKNOWN_ERROR;
    }
    *outSeq = msg.body.finished.seq;
    *outHandled = msg.body.finished.handled;
    return OK;
}

客户端socket接收数据

 #Java#InputEventReceiver.java 
  private static native long nativeInit(WeakReference<InputEventReceiver> receiver,
           InputChannel inputChannel, MessageQueue messageQueue);
   private static native void nativeDispose(long receiverPtr);
   private static native void nativeFinishInputEvent(long receiverPtr, int seq, boolean handled);
   private static native boolean nativeConsumeBatchedInputEvents(long receiverPtr,
           long frameTimeNanos);
       
 // windowstate生成返回的其中一个InputChannel作为客户端socket
 public InputEventReceiver(InputChannel inputChannel, Looper looper) {
       if (inputChannel == null) {
           throw new IllegalArgumentException("inputChannel must not be null");
       }
       if (looper == null) {
           throw new IllegalArgumentException("looper must not be null");
       }

       mInputChannel = inputChannel;
       mMessageQueue = looper.getQueue();
       mReceiverPtr = nativeInit(new WeakReference<InputEventReceiver>(this),
               inputChannel, mMessageQueue); // 将inputChannel中的socketpair一端fd 加入到messageQueue epoll监听

       mCloseGuard.open("dispose");
   }
   
   
   #ViewRootImpl.java
   /**
    * WindowInputEventReceiver接收输入事件
    */
   final class WindowInputEventReceiver extends InputEventReceiver {
       public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
           super(inputChannel, looper);
       }

       // 收到输入事件
       @Override
       public void onInputEvent(InputEvent event, int displayId) {
           enqueueInputEvent(event, this, 0, true);
       }

       @Override
       public void onBatchedInputEventPending() {
           if (mUnbufferedInputDispatch) {
               super.onBatchedInputEventPending();
           } else {
               scheduleConsumeBatchedInput();
           }
       }

       @Override
       public void dispose() {
           unscheduleConsumeBatchedInput();
           super.dispose();
       }
   }
   
   setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
         ...
           mInputChannel = new InputChannel();
           ...
          // windowState openInputChannel打开了一对socketpair,一个返回给应用进程封装到了mInputChannel
          // 一个注册到了InputManagerService InputDispatch.cpp
           res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                           getHostVisibility(), mDisplay.getDisplayId(), mWinFrame,
                           mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                           mAttachInfo.mOutsets, mAttachInfo.mDisplayCutout, mInputChannel);       
          ...   
           if (mInputChannel != null) {
                   if (mInputQueueCallback != null) {
                       mInputQueue = new InputQueue();
                       mInputQueueCallback.onInputQueueCreated(mInputQueue);
                   }
                   // inputChannel封装到WindowInputEventReceiver
                   mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
                           Looper.myLooper());
               }
          ...
   }
  # c++层
  android_view_InputEventReceiver.cpp
  
  static jlong nativeInit(JNIEnv* env, jclass clazz, jobject receiverWeak,
       jobject inputChannelObj, jobject messageQueueObj) {
       // java层inputChannelObj对应c++层InputChannel对象
   sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
           inputChannelObj);
   if (inputChannel == NULL) {
       jniThrowRuntimeException(env, "InputChannel is not initialized.");
       return 0;
   }
   // java层messageQueue对应c++层MessageQueue
   sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
   if (messageQueue == NULL) {
       jniThrowRuntimeException(env, "MessageQueue is not initialized.");
       return 0;
   }
   // 新建一个本地层c++ NativeInputEventReceiver对象,对应java层InputEventReceiver
   sp<NativeInputEventReceiver> receiver = new NativeInputEventReceiver(env,
           receiverWeak, inputChannel, messageQueue);
   // 初始化,将该NativeInputEventReceiver(LooperCallback)加入 Looper epoll监听InputChannel fd
   status_t status = receiver->initialize();
   if (status) {
       String8 message;
       message.appendFormat("Failed to initialize input event receiver.  status=%d", status);
       jniThrowRuntimeException(env, message.string());
       return 0;
   }

   receiver->incStrong(gInputEventReceiverClassInfo.clazz); // retain a reference for the object
   return reinterpret_cast<jlong>(receiver.get());
}


  class NativeInputEventReceiver : public LooperCallback {
public:
   NativeInputEventReceiver(JNIEnv* env,
           jobject receiverWeak, const sp<InputChannel>& inputChannel,
           const sp<MessageQueue>& messageQueue);

   status_t initialize();
   void dispose();
   status_t finishInputEvent(uint32_t seq, bool handled);
   status_t consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime,
           bool* outConsumedBatch);

protected:
   virtual ~NativeInputEventReceiver();

private:
   struct Finish {
       uint32_t seq;
       bool handled;
   };

   jobject mReceiverWeakGlobal;
   InputConsumer mInputConsumer;
   sp<MessageQueue> mMessageQueue;
   PreallocatedInputEventFactory mInputEventFactory;
   bool mBatchedInputEventPending;
   int mFdEvents;
   Vector<Finish> mFinishQueue;

   void setFdEvents(int events);

   const std::string getInputChannelName() {
       return mInputConsumer.getChannel()->getName();
   }

   virtual int handleEvent(int receiveFd, int events, void* data);
};


  // 初始化mInputConsumer输入事件消费者
  // 初始化mMessageQueue c++层消息队列
  NativeInputEventReceiver::NativeInputEventReceiver(JNIEnv* env,
       jobject receiverWeak, const sp<InputChannel>& inputChannel,
       const sp<MessageQueue>& messageQueue) :
       mReceiverWeakGlobal(env->NewGlobalRef(receiverWeak)),
       mInputConsumer(inputChannel), mMessageQueue(messageQueue),
       mBatchedInputEventPending(false), mFdEvents(0) {
   if (kDebugDispatchCycle) {
       ALOGD("channel '%s' ~ Initializing input event receiver.", getInputChannelName().c_str());
   }
   
   // 将socket加入looper epoll进行监听
   status_t NativeInputEventReceiver::initialize() {
       setFdEvents(ALOOPER_EVENT_INPUT);
       return OK;
   }
   
   // socket fd加入looper
    void NativeInputEventReceiver::setFdEvents(int events) {
       if (mFdEvents != events) {
           mFdEvents = events;
           int fd = mInputConsumer.getChannel()->getFd();
           if (events) {
               mMessageQueue->getLooper()->addFd(fd, 0, events, this, NULL);
           } else {
               mMessageQueue->getLooper()->removeFd(fd);
           }
       }
   }
}

// epoll 监听socket fd有消息
int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
   ...
     status_t status = consumeEvents(env, false /*consumeBatches*/, -1, NULL);
    ...
   status_t status = mInputConsumer.sendFinishedSignal(finish.seq, finish.handled);
  ...
}

// 消化事件, jni层将数据回传到java层InputEventReceiver.java
status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env,
       bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) {
          ...
           // inputConsumer消费
            status_t status = mInputConsumer.consume(&mInputEventFactory,
               consumeBatches, frameTime, &seq, &inputEvent, &displayId);
         ...
         // java层
          env->CallVoidMethod(receiverObj.get(),
                           gInputEventReceiverClassInfo.dispatchBatchedInputEventPending)
        ...                  
     }
     
 #InputEventReceiver.java 
 private void dispatchInputEvent(int seq, InputEvent event, int displayId) {
       mSeqMap.put(event.getSequenceNumber(), seq);
       onInputEvent(event, displayId);
   }
   
   #ViewRootImpl.WindowInputEventReceiver
   // 收到输入事件
       @Override
       public void onInputEvent(InputEvent event, int displayId) {
           enqueueInputEvent(event, this, 0, true);
       }


  # ViewRootImpl
  InputEventReceiver.dispatchInputEvent -> ViewRootImpl$WindowInputEventReceiver.onInputEvent -> ViewRootImpl.enqueueInputEvent -> ViewRootImpl.doProcessInputEvents -> ViewRootImpl.deliverInputEvent ->
  ViewRootImpl$InputStage.deliver -> ViewRootImpl$InputStage.apply -> ViewRootImpl$InputStage.forward -> ViewRootImpl$InputStage.onDeliverToNext ->
  ViewRootImpl$InputStage.deliver -> ViewRootImpl$AsyncInputStage.apply -> ViewRootImpl$InputStage.apply ->
  ViewRootImpl$AsyncInputStage.forward -> ViewRootImpl$InputStage.forward -> ViewRootImpl$InputStage.onDeliverToNext ->
  ViewRootImpl$InputStage.deliver -> ViewRootImpl$ViewPostImeInputStage.onProcess -> ViewRootImpl$ViewPostImeInputStage.processPointerEvent ->
  View.dispatchPointerEvent -> DecorView.dispatchTouchEvent -> WindowCallbackWrapper.dispatchTouchEvent ->
  Activity.dispatchTouchEvent -> PhoneWindow.superDispatchTouchEvent -> DecorView.superDispatchTouchEvent ->
  ViewGroup.dispatchTouchEvent -> View.dispatchTouchEvent -> onTouch -> OnTouchEvent -> handler.post(PerformClick) {mOnClickListener.onClick(this)}
   
   
# InputTransport.cpp
status_t InputConsumer::consume(InputEventFactoryInterface* factory,
       bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent,
       int32_t* displayId) {
#if DEBUG_TRANSPORT_ACTIONS
   ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
           mChannel->getName().c_str(), consumeBatches ? "true" : "false", frameTime);
#endif

   *outSeq = 0;
   *outEvent = NULL;
   *displayId = -1;  // Invalid display.

   // Fetch the next input message.
   // Loop until an event can be returned or no additional events are received.
   while (!*outEvent) {
       if (mMsgDeferred) {
           // mMsg contains a valid input message from the previous call to consume
           // that has not yet been processed.
           mMsgDeferred = false;
       } else {
           // Receive a fresh message.
           status_t result = mChannel->receiveMessage(&mMsg);
           if (result) {
               // Consume the next batched event unless batches are being held for later.
               if (consumeBatches || result != WOULD_BLOCK) {
                   result = consumeBatch(factory, frameTime, outSeq, outEvent, displayId);
                   if (*outEvent) {
#if DEBUG_TRANSPORT_ACTIONS
                       ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
                               mChannel->getName().c_str(), *outSeq);
#endif
                       break;
                   }
               }
               return result;
           }
       }

       switch (mMsg.header.type) {
       case InputMessage::TYPE_KEY: {
           KeyEvent* keyEvent = factory->createKeyEvent();
           if (!keyEvent) return NO_MEMORY;

           initializeKeyEvent(keyEvent, &mMsg);
           *outSeq = mMsg.body.key.seq;
           *outEvent = keyEvent;
#if DEBUG_TRANSPORT_ACTIONS
           ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
                   mChannel->getName().c_str(), *outSeq);
#endif
           break;
       }

       case InputMessage::TYPE_MOTION: {
           ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
           if (batchIndex >= 0) {
               Batch& batch = mBatches.editItemAt(batchIndex);
               if (canAddSample(batch, &mMsg)) {
                   batch.samples.push(mMsg);
#if DEBUG_TRANSPORT_ACTIONS
                   ALOGD("channel '%s' consumer ~ appended to batch event",
                           mChannel->getName().c_str());
#endif
                   break;
               } else {
                   // We cannot append to the batch in progress, so we need to consume
                   // the previous batch right now and defer the new message until later.
                   mMsgDeferred = true;
                   status_t result = consumeSamples(factory,
                           batch, batch.samples.size(), outSeq, outEvent, displayId);
                   mBatches.removeAt(batchIndex);
                   if (result) {
                       return result;
                   }
#if DEBUG_TRANSPORT_ACTIONS
                   ALOGD("channel '%s' consumer ~ consumed batch event and "
                           "deferred current event, seq=%u",
                           mChannel->getName().c_str(), *outSeq);
#endif
                   break;
               }
           }

           // Start a new batch if needed.
           if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
                   || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
               mBatches.push();
               Batch& batch = mBatches.editTop();
               batch.samples.push(mMsg);
#if DEBUG_TRANSPORT_ACTIONS
               ALOGD("channel '%s' consumer ~ started batch event",
                       mChannel->getName().c_str());
#endif
               break;
           }

           MotionEvent* motionEvent = factory->createMotionEvent();
           if (! motionEvent) return NO_MEMORY;

           updateTouchState(mMsg);
           initializeMotionEvent(motionEvent, &mMsg);
           *outSeq = mMsg.body.motion.seq;
           *outEvent = motionEvent;
           *displayId = mMsg.body.motion.displayId;
#if DEBUG_TRANSPORT_ACTIONS
           ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
                   mChannel->getName().c_str(), *outSeq);
#endif
           break;
       }

       default:
           ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
                   mChannel->getName().c_str(), mMsg.header.type);
           return UNKNOWN_ERROR;
       }
   }
   return OK;
}