• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "InputEventSender"
18 
19 //#define LOG_NDEBUG 0
20 
21 #include <nativehelper/JNIHelp.h>
22 
23 #include <android_runtime/AndroidRuntime.h>
24 #include <log/log.h>
25 #include <utils/Looper.h>
26 #include <input/InputTransport.h>
27 #include "android_os_MessageQueue.h"
28 #include "android_view_InputChannel.h"
29 #include "android_view_KeyEvent.h"
30 #include "android_view_MotionEvent.h"
31 
32 #include <nativehelper/ScopedLocalRef.h>
33 #include <unordered_map>
34 
35 #include "core_jni_helpers.h"
36 
37 namespace android {
38 
39 // Log debug messages about the dispatch cycle.
40 static const bool kDebugDispatchCycle = false;
41 
42 static struct {
43     jclass clazz;
44 
45     jmethodID dispatchInputEventFinished;
46 } gInputEventSenderClassInfo;
47 
48 
49 class NativeInputEventSender : public LooperCallback {
50 public:
51     NativeInputEventSender(JNIEnv* env,
52             jobject senderWeak, const sp<InputChannel>& inputChannel,
53             const sp<MessageQueue>& messageQueue);
54 
55     status_t initialize();
56     void dispose();
57     status_t sendKeyEvent(uint32_t seq, const KeyEvent* event);
58     status_t sendMotionEvent(uint32_t seq, const MotionEvent* event);
59 
60 protected:
61     virtual ~NativeInputEventSender();
62 
63 private:
64     jobject mSenderWeakGlobal;
65     InputPublisher mInputPublisher;
66     sp<MessageQueue> mMessageQueue;
67     std::unordered_map<uint32_t, uint32_t> mPublishedSeqMap;
68 
69     uint32_t mNextPublishedSeq;
70 
getInputChannelName()71     const std::string getInputChannelName() {
72         return mInputPublisher.getChannel()->getName();
73     }
74 
75     virtual int handleEvent(int receiveFd, int events, void* data);
76     status_t receiveFinishedSignals(JNIEnv* env);
77 };
78 
79 
NativeInputEventSender(JNIEnv * env,jobject senderWeak,const sp<InputChannel> & inputChannel,const sp<MessageQueue> & messageQueue)80 NativeInputEventSender::NativeInputEventSender(JNIEnv* env,
81         jobject senderWeak, const sp<InputChannel>& inputChannel,
82         const sp<MessageQueue>& messageQueue) :
83         mSenderWeakGlobal(env->NewGlobalRef(senderWeak)),
84         mInputPublisher(inputChannel), mMessageQueue(messageQueue),
85         mNextPublishedSeq(1) {
86     if (kDebugDispatchCycle) {
87         ALOGD("channel '%s' ~ Initializing input event sender.", getInputChannelName().c_str());
88     }
89 }
90 
~NativeInputEventSender()91 NativeInputEventSender::~NativeInputEventSender() {
92     JNIEnv* env = AndroidRuntime::getJNIEnv();
93     env->DeleteGlobalRef(mSenderWeakGlobal);
94 }
95 
initialize()96 status_t NativeInputEventSender::initialize() {
97     int receiveFd = mInputPublisher.getChannel()->getFd();
98     mMessageQueue->getLooper()->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, this, NULL);
99     return OK;
100 }
101 
dispose()102 void NativeInputEventSender::dispose() {
103     if (kDebugDispatchCycle) {
104         ALOGD("channel '%s' ~ Disposing input event sender.", getInputChannelName().c_str());
105     }
106 
107     mMessageQueue->getLooper()->removeFd(mInputPublisher.getChannel()->getFd());
108 }
109 
sendKeyEvent(uint32_t seq,const KeyEvent * event)110 status_t NativeInputEventSender::sendKeyEvent(uint32_t seq, const KeyEvent* event) {
111     if (kDebugDispatchCycle) {
112         ALOGD("channel '%s' ~ Sending key event, seq=%u.", getInputChannelName().c_str(), seq);
113     }
114 
115     uint32_t publishedSeq = mNextPublishedSeq++;
116     status_t status =
117             mInputPublisher.publishKeyEvent(publishedSeq, event->getId(), event->getDeviceId(),
118                                             event->getSource(), event->getDisplayId(),
119                                             event->getHmac(), event->getAction(), event->getFlags(),
120                                             event->getKeyCode(), event->getScanCode(),
121                                             event->getMetaState(), event->getRepeatCount(),
122                                             event->getDownTime(), event->getEventTime());
123     if (status) {
124         ALOGW("Failed to send key event on channel '%s'.  status=%d",
125                 getInputChannelName().c_str(), status);
126         return status;
127     }
128     mPublishedSeqMap.emplace(publishedSeq, seq);
129     return OK;
130 }
131 
sendMotionEvent(uint32_t seq,const MotionEvent * event)132 status_t NativeInputEventSender::sendMotionEvent(uint32_t seq, const MotionEvent* event) {
133     if (kDebugDispatchCycle) {
134         ALOGD("channel '%s' ~ Sending motion event, seq=%u.", getInputChannelName().c_str(), seq);
135     }
136 
137     uint32_t publishedSeq;
138     for (size_t i = 0; i <= event->getHistorySize(); i++) {
139         publishedSeq = mNextPublishedSeq++;
140         status_t status =
141                 mInputPublisher.publishMotionEvent(publishedSeq, event->getId(),
142                                                    event->getDeviceId(), event->getSource(),
143                                                    event->getDisplayId(), event->getHmac(),
144                                                    event->getAction(), event->getActionButton(),
145                                                    event->getFlags(), event->getEdgeFlags(),
146                                                    event->getMetaState(), event->getButtonState(),
147                                                    event->getClassification(), event->getXScale(),
148                                                    event->getYScale(), event->getXOffset(),
149                                                    event->getYOffset(), event->getXPrecision(),
150                                                    event->getYPrecision(),
151                                                    event->getRawXCursorPosition(),
152                                                    event->getRawYCursorPosition(),
153                                                    event->getDownTime(),
154                                                    event->getHistoricalEventTime(i),
155                                                    event->getPointerCount(),
156                                                    event->getPointerProperties(),
157                                                    event->getHistoricalRawPointerCoords(0, i));
158         if (status) {
159             ALOGW("Failed to send motion event sample on channel '%s'.  status=%d",
160                     getInputChannelName().c_str(), status);
161             return status;
162         }
163     }
164     mPublishedSeqMap.emplace(publishedSeq, seq);
165     return OK;
166 }
167 
handleEvent(int receiveFd,int events,void * data)168 int NativeInputEventSender::handleEvent(int receiveFd, int events, void* data) {
169     if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
170         // This error typically occurs when the consumer has closed the input channel
171         // as part of finishing an IME session, in which case the publisher will
172         // soon be disposed as well.
173         if (kDebugDispatchCycle) {
174             ALOGD("channel '%s' ~ Consumer closed input channel or an error occurred.  "
175                     "events=0x%x", getInputChannelName().c_str(), events);
176         }
177 
178         return 0; // remove the callback
179     }
180 
181     if (!(events & ALOOPER_EVENT_INPUT)) {
182         ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event.  "
183                 "events=0x%x", getInputChannelName().c_str(), events);
184         return 1;
185     }
186 
187     JNIEnv* env = AndroidRuntime::getJNIEnv();
188     status_t status = receiveFinishedSignals(env);
189     mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
190     return status == OK || status == NO_MEMORY ? 1 : 0;
191 }
192 
receiveFinishedSignals(JNIEnv * env)193 status_t NativeInputEventSender::receiveFinishedSignals(JNIEnv* env) {
194     if (kDebugDispatchCycle) {
195         ALOGD("channel '%s' ~ Receiving finished signals.", getInputChannelName().c_str());
196     }
197 
198     ScopedLocalRef<jobject> senderObj(env, NULL);
199     bool skipCallbacks = false;
200     for (;;) {
201         uint32_t publishedSeq;
202         bool handled;
203         status_t status = mInputPublisher.receiveFinishedSignal(&publishedSeq, &handled);
204         if (status) {
205             if (status == WOULD_BLOCK) {
206                 return OK;
207             }
208             ALOGE("channel '%s' ~ Failed to consume finished signals.  status=%d",
209                     getInputChannelName().c_str(), status);
210             return status;
211         }
212 
213         auto it = mPublishedSeqMap.find(publishedSeq);
214         if (it == mPublishedSeqMap.end()) {
215             continue;
216         }
217 
218         uint32_t seq = it->second;
219         mPublishedSeqMap.erase(it);
220 
221         if (kDebugDispatchCycle) {
222             ALOGD("channel '%s' ~ Received finished signal, seq=%u, handled=%s, "
223                     "pendingEvents=%zu.",
224                     getInputChannelName().c_str(), seq, handled ? "true" : "false",
225                     mPublishedSeqMap.size());
226         }
227 
228         if (!skipCallbacks) {
229             if (!senderObj.get()) {
230                 senderObj.reset(jniGetReferent(env, mSenderWeakGlobal));
231                 if (!senderObj.get()) {
232                     ALOGW("channel '%s' ~ Sender object was finalized "
233                             "without being disposed.", getInputChannelName().c_str());
234                     return DEAD_OBJECT;
235                 }
236             }
237 
238             env->CallVoidMethod(senderObj.get(),
239                     gInputEventSenderClassInfo.dispatchInputEventFinished,
240                     jint(seq), jboolean(handled));
241             if (env->ExceptionCheck()) {
242                 ALOGE("Exception dispatching finished signal.");
243                 skipCallbacks = true;
244             }
245         }
246     }
247 }
248 
249 
nativeInit(JNIEnv * env,jclass clazz,jobject senderWeak,jobject inputChannelObj,jobject messageQueueObj)250 static jlong nativeInit(JNIEnv* env, jclass clazz, jobject senderWeak,
251         jobject inputChannelObj, jobject messageQueueObj) {
252     sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
253             inputChannelObj);
254     if (inputChannel == NULL) {
255         jniThrowRuntimeException(env, "InputChannel is not initialized.");
256         return 0;
257     }
258 
259     sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
260     if (messageQueue == NULL) {
261         jniThrowRuntimeException(env, "MessageQueue is not initialized.");
262         return 0;
263     }
264 
265     sp<NativeInputEventSender> sender = new NativeInputEventSender(env,
266             senderWeak, inputChannel, messageQueue);
267     status_t status = sender->initialize();
268     if (status) {
269         String8 message;
270         message.appendFormat("Failed to initialize input event sender.  status=%d", status);
271         jniThrowRuntimeException(env, message.string());
272         return 0;
273     }
274 
275     sender->incStrong(gInputEventSenderClassInfo.clazz); // retain a reference for the object
276     return reinterpret_cast<jlong>(sender.get());
277 }
278 
nativeDispose(JNIEnv * env,jclass clazz,jlong senderPtr)279 static void nativeDispose(JNIEnv* env, jclass clazz, jlong senderPtr) {
280     sp<NativeInputEventSender> sender =
281             reinterpret_cast<NativeInputEventSender*>(senderPtr);
282     sender->dispose();
283     sender->decStrong(gInputEventSenderClassInfo.clazz); // drop reference held by the object
284 }
285 
nativeSendKeyEvent(JNIEnv * env,jclass clazz,jlong senderPtr,jint seq,jobject eventObj)286 static jboolean nativeSendKeyEvent(JNIEnv* env, jclass clazz, jlong senderPtr,
287         jint seq, jobject eventObj) {
288     sp<NativeInputEventSender> sender =
289             reinterpret_cast<NativeInputEventSender*>(senderPtr);
290     KeyEvent event;
291     android_view_KeyEvent_toNative(env, eventObj, &event);
292     status_t status = sender->sendKeyEvent(seq, &event);
293     return !status;
294 }
295 
nativeSendMotionEvent(JNIEnv * env,jclass clazz,jlong senderPtr,jint seq,jobject eventObj)296 static jboolean nativeSendMotionEvent(JNIEnv* env, jclass clazz, jlong senderPtr,
297         jint seq, jobject eventObj) {
298     sp<NativeInputEventSender> sender =
299             reinterpret_cast<NativeInputEventSender*>(senderPtr);
300     MotionEvent* event = android_view_MotionEvent_getNativePtr(env, eventObj);
301     status_t status = sender->sendMotionEvent(seq, event);
302     return !status;
303 }
304 
305 
306 static const JNINativeMethod gMethods[] = {
307     /* name, signature, funcPtr */
308     { "nativeInit",
309             "(Ljava/lang/ref/WeakReference;Landroid/view/InputChannel;Landroid/os/MessageQueue;)J",
310             (void*)nativeInit },
311     { "nativeDispose", "(J)V",
312             (void*)nativeDispose },
313     { "nativeSendKeyEvent", "(JILandroid/view/KeyEvent;)Z",
314             (void*)nativeSendKeyEvent },
315     { "nativeSendMotionEvent", "(JILandroid/view/MotionEvent;)Z",
316             (void*)nativeSendMotionEvent },
317 };
318 
register_android_view_InputEventSender(JNIEnv * env)319 int register_android_view_InputEventSender(JNIEnv* env) {
320     int res = RegisterMethodsOrDie(env, "android/view/InputEventSender", gMethods, NELEM(gMethods));
321 
322     jclass clazz = FindClassOrDie(env, "android/view/InputEventSender");
323     gInputEventSenderClassInfo.clazz = MakeGlobalRefOrDie(env, clazz);
324 
325     gInputEventSenderClassInfo.dispatchInputEventFinished = GetMethodIDOrDie(
326             env, gInputEventSenderClassInfo.clazz, "dispatchInputEventFinished", "(IZ)V");
327 
328     return res;
329 }
330 
331 } // namespace android
332