1 /*
2 * Copyright (C) 2011 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 "InputEventReceiver"
18
19 //#define LOG_NDEBUG 0
20
21 #include <inttypes.h>
22
23 #include <nativehelper/JNIHelp.h>
24
25 #include <android_runtime/AndroidRuntime.h>
26 #include <log/log.h>
27 #include <utils/Looper.h>
28 #include <utils/Vector.h>
29 #include <input/InputTransport.h>
30 #include "android_os_MessageQueue.h"
31 #include "android_view_InputChannel.h"
32 #include "android_view_KeyEvent.h"
33 #include "android_view_MotionEvent.h"
34
35 #include <nativehelper/ScopedLocalRef.h>
36
37 #include "core_jni_helpers.h"
38
39 namespace android {
40
41 static const bool kDebugDispatchCycle = false;
42
toString(bool value)43 static const char* toString(bool value) {
44 return value ? "true" : "false";
45 }
46
47 static struct {
48 jclass clazz;
49
50 jmethodID dispatchInputEvent;
51 jmethodID onFocusEvent;
52 jmethodID onBatchedInputEventPending;
53 } gInputEventReceiverClassInfo;
54
55
56 class NativeInputEventReceiver : public LooperCallback {
57 public:
58 NativeInputEventReceiver(JNIEnv* env,
59 jobject receiverWeak, const sp<InputChannel>& inputChannel,
60 const sp<MessageQueue>& messageQueue);
61
62 status_t initialize();
63 void dispose();
64 status_t finishInputEvent(uint32_t seq, bool handled);
65 status_t consumeEvents(JNIEnv* env, bool consumeBatches, nsecs_t frameTime,
66 bool* outConsumedBatch);
67
68 protected:
69 virtual ~NativeInputEventReceiver();
70
71 private:
72 struct Finish {
73 uint32_t seq;
74 bool handled;
75 };
76
77 jobject mReceiverWeakGlobal;
78 InputConsumer mInputConsumer;
79 sp<MessageQueue> mMessageQueue;
80 PreallocatedInputEventFactory mInputEventFactory;
81 bool mBatchedInputEventPending;
82 int mFdEvents;
83 Vector<Finish> mFinishQueue;
84
85 void setFdEvents(int events);
86
getInputChannelName()87 const std::string getInputChannelName() {
88 return mInputConsumer.getChannel()->getName();
89 }
90
91 virtual int handleEvent(int receiveFd, int events, void* data) override;
92 };
93
94
NativeInputEventReceiver(JNIEnv * env,jobject receiverWeak,const sp<InputChannel> & inputChannel,const sp<MessageQueue> & messageQueue)95 NativeInputEventReceiver::NativeInputEventReceiver(JNIEnv* env,
96 jobject receiverWeak, const sp<InputChannel>& inputChannel,
97 const sp<MessageQueue>& messageQueue) :
98 mReceiverWeakGlobal(env->NewGlobalRef(receiverWeak)),
99 mInputConsumer(inputChannel), mMessageQueue(messageQueue),
100 mBatchedInputEventPending(false), mFdEvents(0) {
101 if (kDebugDispatchCycle) {
102 ALOGD("channel '%s' ~ Initializing input event receiver.", getInputChannelName().c_str());
103 }
104 }
105
~NativeInputEventReceiver()106 NativeInputEventReceiver::~NativeInputEventReceiver() {
107 JNIEnv* env = AndroidRuntime::getJNIEnv();
108 env->DeleteGlobalRef(mReceiverWeakGlobal);
109 }
110
initialize()111 status_t NativeInputEventReceiver::initialize() {
112 setFdEvents(ALOOPER_EVENT_INPUT);
113 return OK;
114 }
115
dispose()116 void NativeInputEventReceiver::dispose() {
117 if (kDebugDispatchCycle) {
118 ALOGD("channel '%s' ~ Disposing input event receiver.", getInputChannelName().c_str());
119 }
120
121 setFdEvents(0);
122 }
123
finishInputEvent(uint32_t seq,bool handled)124 status_t NativeInputEventReceiver::finishInputEvent(uint32_t seq, bool handled) {
125 if (kDebugDispatchCycle) {
126 ALOGD("channel '%s' ~ Finished input event.", getInputChannelName().c_str());
127 }
128
129 status_t status = mInputConsumer.sendFinishedSignal(seq, handled);
130 if (status) {
131 if (status == WOULD_BLOCK) {
132 if (kDebugDispatchCycle) {
133 ALOGD("channel '%s' ~ Could not send finished signal immediately. "
134 "Enqueued for later.", getInputChannelName().c_str());
135 }
136 Finish finish;
137 finish.seq = seq;
138 finish.handled = handled;
139 mFinishQueue.add(finish);
140 if (mFinishQueue.size() == 1) {
141 setFdEvents(ALOOPER_EVENT_INPUT | ALOOPER_EVENT_OUTPUT);
142 }
143 return OK;
144 }
145 ALOGW("Failed to send finished signal on channel '%s'. status=%d",
146 getInputChannelName().c_str(), status);
147 }
148 return status;
149 }
150
setFdEvents(int events)151 void NativeInputEventReceiver::setFdEvents(int events) {
152 if (mFdEvents != events) {
153 mFdEvents = events;
154 int fd = mInputConsumer.getChannel()->getFd();
155 if (events) {
156 mMessageQueue->getLooper()->addFd(fd, 0, events, this, nullptr);
157 } else {
158 mMessageQueue->getLooper()->removeFd(fd);
159 }
160 }
161 }
162
handleEvent(int receiveFd,int events,void * data)163 int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
164 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
165 // This error typically occurs when the publisher has closed the input channel
166 // as part of removing a window or finishing an IME session, in which case
167 // the consumer will soon be disposed as well.
168 if (kDebugDispatchCycle) {
169 ALOGD("channel '%s' ~ Publisher closed input channel or an error occurred. "
170 "events=0x%x", getInputChannelName().c_str(), events);
171 }
172 return 0; // remove the callback
173 }
174
175 if (events & ALOOPER_EVENT_INPUT) {
176 JNIEnv* env = AndroidRuntime::getJNIEnv();
177 status_t status = consumeEvents(env, false /*consumeBatches*/, -1, nullptr);
178 mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
179 return status == OK || status == NO_MEMORY ? 1 : 0;
180 }
181
182 if (events & ALOOPER_EVENT_OUTPUT) {
183 for (size_t i = 0; i < mFinishQueue.size(); i++) {
184 const Finish& finish = mFinishQueue.itemAt(i);
185 status_t status = mInputConsumer.sendFinishedSignal(finish.seq, finish.handled);
186 if (status) {
187 mFinishQueue.removeItemsAt(0, i);
188
189 if (status == WOULD_BLOCK) {
190 if (kDebugDispatchCycle) {
191 ALOGD("channel '%s' ~ Sent %zu queued finish events; %zu left.",
192 getInputChannelName().c_str(), i, mFinishQueue.size());
193 }
194 return 1; // keep the callback, try again later
195 }
196
197 ALOGW("Failed to send finished signal on channel '%s'. status=%d",
198 getInputChannelName().c_str(), status);
199 if (status != DEAD_OBJECT) {
200 JNIEnv* env = AndroidRuntime::getJNIEnv();
201 String8 message;
202 message.appendFormat("Failed to finish input event. status=%d", status);
203 jniThrowRuntimeException(env, message.string());
204 mMessageQueue->raiseAndClearException(env, "finishInputEvent");
205 }
206 return 0; // remove the callback
207 }
208 }
209 if (kDebugDispatchCycle) {
210 ALOGD("channel '%s' ~ Sent %zu queued finish events; none left.",
211 getInputChannelName().c_str(), mFinishQueue.size());
212 }
213 mFinishQueue.clear();
214 setFdEvents(ALOOPER_EVENT_INPUT);
215 return 1;
216 }
217
218 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
219 "events=0x%x", getInputChannelName().c_str(), events);
220 return 1;
221 }
222
consumeEvents(JNIEnv * env,bool consumeBatches,nsecs_t frameTime,bool * outConsumedBatch)223 status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env,
224 bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) {
225 if (kDebugDispatchCycle) {
226 ALOGD("channel '%s' ~ Consuming input events, consumeBatches=%s, frameTime=%" PRId64,
227 getInputChannelName().c_str(), toString(consumeBatches), frameTime);
228 }
229
230 if (consumeBatches) {
231 mBatchedInputEventPending = false;
232 }
233 if (outConsumedBatch) {
234 *outConsumedBatch = false;
235 }
236
237 ScopedLocalRef<jobject> receiverObj(env, nullptr);
238 bool skipCallbacks = false;
239 for (;;) {
240 uint32_t seq;
241 InputEvent* inputEvent;
242
243 status_t status = mInputConsumer.consume(&mInputEventFactory,
244 consumeBatches, frameTime, &seq, &inputEvent);
245 if (status != OK && status != WOULD_BLOCK) {
246 ALOGE("channel '%s' ~ Failed to consume input event. status=%d",
247 getInputChannelName().c_str(), status);
248 return status;
249 }
250
251 if (status == WOULD_BLOCK) {
252 if (!skipCallbacks && !mBatchedInputEventPending && mInputConsumer.hasPendingBatch()) {
253 // There is a pending batch. Come back later.
254 if (!receiverObj.get()) {
255 receiverObj.reset(jniGetReferent(env, mReceiverWeakGlobal));
256 if (!receiverObj.get()) {
257 ALOGW("channel '%s' ~ Receiver object was finalized "
258 "without being disposed.",
259 getInputChannelName().c_str());
260 return DEAD_OBJECT;
261 }
262 }
263
264 mBatchedInputEventPending = true;
265 if (kDebugDispatchCycle) {
266 ALOGD("channel '%s' ~ Dispatching batched input event pending notification.",
267 getInputChannelName().c_str());
268 }
269
270 env->CallVoidMethod(receiverObj.get(),
271 gInputEventReceiverClassInfo.onBatchedInputEventPending,
272 mInputConsumer.getPendingBatchSource());
273 if (env->ExceptionCheck()) {
274 ALOGE("Exception dispatching batched input events.");
275 mBatchedInputEventPending = false; // try again later
276 }
277 }
278 return OK;
279 }
280 assert(inputEvent);
281
282 if (!skipCallbacks) {
283 if (!receiverObj.get()) {
284 receiverObj.reset(jniGetReferent(env, mReceiverWeakGlobal));
285 if (!receiverObj.get()) {
286 ALOGW("channel '%s' ~ Receiver object was finalized "
287 "without being disposed.", getInputChannelName().c_str());
288 return DEAD_OBJECT;
289 }
290 }
291
292 jobject inputEventObj;
293 switch (inputEvent->getType()) {
294 case AINPUT_EVENT_TYPE_KEY:
295 if (kDebugDispatchCycle) {
296 ALOGD("channel '%s' ~ Received key event.", getInputChannelName().c_str());
297 }
298 inputEventObj = android_view_KeyEvent_fromNative(env,
299 static_cast<KeyEvent*>(inputEvent));
300 break;
301
302 case AINPUT_EVENT_TYPE_MOTION: {
303 if (kDebugDispatchCycle) {
304 ALOGD("channel '%s' ~ Received motion event.", getInputChannelName().c_str());
305 }
306 MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
307 if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
308 *outConsumedBatch = true;
309 }
310 inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
311 break;
312 }
313 case AINPUT_EVENT_TYPE_FOCUS: {
314 FocusEvent* focusEvent = static_cast<FocusEvent*>(inputEvent);
315 if (kDebugDispatchCycle) {
316 ALOGD("channel '%s' ~ Received focus event: hasFocus=%s, inTouchMode=%s.",
317 getInputChannelName().c_str(), toString(focusEvent->getHasFocus()),
318 toString(focusEvent->getInTouchMode()));
319 }
320 env->CallVoidMethod(receiverObj.get(), gInputEventReceiverClassInfo.onFocusEvent,
321 jboolean(focusEvent->getHasFocus()),
322 jboolean(focusEvent->getInTouchMode()));
323 finishInputEvent(seq, true /* handled */);
324 continue;
325 }
326
327 default:
328 assert(false); // InputConsumer should prevent this from ever happening
329 inputEventObj = nullptr;
330 }
331
332 if (inputEventObj) {
333 if (kDebugDispatchCycle) {
334 ALOGD("channel '%s' ~ Dispatching input event.", getInputChannelName().c_str());
335 }
336 env->CallVoidMethod(receiverObj.get(),
337 gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);
338 if (env->ExceptionCheck()) {
339 ALOGE("Exception dispatching input event.");
340 skipCallbacks = true;
341 }
342 env->DeleteLocalRef(inputEventObj);
343 } else {
344 ALOGW("channel '%s' ~ Failed to obtain event object.",
345 getInputChannelName().c_str());
346 skipCallbacks = true;
347 }
348 }
349
350 if (skipCallbacks) {
351 mInputConsumer.sendFinishedSignal(seq, false);
352 }
353 }
354 }
355
356
nativeInit(JNIEnv * env,jclass clazz,jobject receiverWeak,jobject inputChannelObj,jobject messageQueueObj)357 static jlong nativeInit(JNIEnv* env, jclass clazz, jobject receiverWeak,
358 jobject inputChannelObj, jobject messageQueueObj) {
359 sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
360 inputChannelObj);
361 if (inputChannel == nullptr) {
362 jniThrowRuntimeException(env, "InputChannel is not initialized.");
363 return 0;
364 }
365
366 sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
367 if (messageQueue == nullptr) {
368 jniThrowRuntimeException(env, "MessageQueue is not initialized.");
369 return 0;
370 }
371
372 sp<NativeInputEventReceiver> receiver = new NativeInputEventReceiver(env,
373 receiverWeak, inputChannel, messageQueue);
374 status_t status = receiver->initialize();
375 if (status) {
376 String8 message;
377 message.appendFormat("Failed to initialize input event receiver. status=%d", status);
378 jniThrowRuntimeException(env, message.string());
379 return 0;
380 }
381
382 receiver->incStrong(gInputEventReceiverClassInfo.clazz); // retain a reference for the object
383 return reinterpret_cast<jlong>(receiver.get());
384 }
385
nativeDispose(JNIEnv * env,jclass clazz,jlong receiverPtr)386 static void nativeDispose(JNIEnv* env, jclass clazz, jlong receiverPtr) {
387 sp<NativeInputEventReceiver> receiver =
388 reinterpret_cast<NativeInputEventReceiver*>(receiverPtr);
389 receiver->dispose();
390 receiver->decStrong(gInputEventReceiverClassInfo.clazz); // drop reference held by the object
391 }
392
nativeFinishInputEvent(JNIEnv * env,jclass clazz,jlong receiverPtr,jint seq,jboolean handled)393 static void nativeFinishInputEvent(JNIEnv* env, jclass clazz, jlong receiverPtr,
394 jint seq, jboolean handled) {
395 sp<NativeInputEventReceiver> receiver =
396 reinterpret_cast<NativeInputEventReceiver*>(receiverPtr);
397 status_t status = receiver->finishInputEvent(seq, handled);
398 if (status && status != DEAD_OBJECT) {
399 String8 message;
400 message.appendFormat("Failed to finish input event. status=%d", status);
401 jniThrowRuntimeException(env, message.string());
402 }
403 }
404
nativeConsumeBatchedInputEvents(JNIEnv * env,jclass clazz,jlong receiverPtr,jlong frameTimeNanos)405 static jboolean nativeConsumeBatchedInputEvents(JNIEnv* env, jclass clazz, jlong receiverPtr,
406 jlong frameTimeNanos) {
407 sp<NativeInputEventReceiver> receiver =
408 reinterpret_cast<NativeInputEventReceiver*>(receiverPtr);
409 bool consumedBatch;
410 status_t status = receiver->consumeEvents(env, true /*consumeBatches*/, frameTimeNanos,
411 &consumedBatch);
412 if (status && status != DEAD_OBJECT && !env->ExceptionCheck()) {
413 String8 message;
414 message.appendFormat("Failed to consume batched input event. status=%d", status);
415 jniThrowRuntimeException(env, message.string());
416 return JNI_FALSE;
417 }
418 return consumedBatch ? JNI_TRUE : JNI_FALSE;
419 }
420
421
422 static const JNINativeMethod gMethods[] = {
423 /* name, signature, funcPtr */
424 { "nativeInit",
425 "(Ljava/lang/ref/WeakReference;Landroid/view/InputChannel;Landroid/os/MessageQueue;)J",
426 (void*)nativeInit },
427 { "nativeDispose", "(J)V",
428 (void*)nativeDispose },
429 { "nativeFinishInputEvent", "(JIZ)V",
430 (void*)nativeFinishInputEvent },
431 { "nativeConsumeBatchedInputEvents", "(JJ)Z",
432 (void*)nativeConsumeBatchedInputEvents },
433 };
434
register_android_view_InputEventReceiver(JNIEnv * env)435 int register_android_view_InputEventReceiver(JNIEnv* env) {
436 int res = RegisterMethodsOrDie(env, "android/view/InputEventReceiver",
437 gMethods, NELEM(gMethods));
438
439 jclass clazz = FindClassOrDie(env, "android/view/InputEventReceiver");
440 gInputEventReceiverClassInfo.clazz = MakeGlobalRefOrDie(env, clazz);
441
442 gInputEventReceiverClassInfo.dispatchInputEvent = GetMethodIDOrDie(env,
443 gInputEventReceiverClassInfo.clazz,
444 "dispatchInputEvent", "(ILandroid/view/InputEvent;)V");
445 gInputEventReceiverClassInfo.onFocusEvent =
446 GetMethodIDOrDie(env, gInputEventReceiverClassInfo.clazz, "onFocusEvent", "(ZZ)V");
447 gInputEventReceiverClassInfo.onBatchedInputEventPending =
448 GetMethodIDOrDie(env, gInputEventReceiverClassInfo.clazz, "onBatchedInputEventPending",
449 "(I)V");
450
451 return res;
452 }
453
454 } // namespace android
455