blob: effeed6b2af6840c41977ad523045eaa5f7ec9d1 [file] [log] [blame]
Jeff Brownc28867a2013-03-26 15:42:39 -07001/*
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
Steven Moreland2279b252017-07-19 09:50:45 -070021#include <nativehelper/JNIHelp.h>
Jeff Brownc28867a2013-03-26 15:42:39 -070022
23#include <android_runtime/AndroidRuntime.h>
24#include <utils/Log.h>
25#include <utils/Looper.h>
26#include <utils/threads.h>
27#include <utils/KeyedVector.h>
Jeff Brown9d3b1a42013-07-01 19:07:15 -070028#include <input/InputTransport.h>
Jeff Brownc28867a2013-03-26 15:42:39 -070029#include "android_os_MessageQueue.h"
30#include "android_view_InputChannel.h"
31#include "android_view_KeyEvent.h"
32#include "android_view_MotionEvent.h"
33
Steven Moreland2279b252017-07-19 09:50:45 -070034#include <nativehelper/ScopedLocalRef.h>
Jeff Browna4ca8ea2013-04-02 18:01:38 -070035
Andreas Gampe987f79f2014-11-18 17:29:46 -080036#include "core_jni_helpers.h"
37
Jeff Brownc28867a2013-03-26 15:42:39 -070038namespace android {
39
Andreas Gampeed6b9df2014-11-20 22:02:20 -080040// Log debug messages about the dispatch cycle.
41static const bool kDebugDispatchCycle = false;
Tarandeep Singhe1cfcf42017-07-10 18:50:00 -070042// Display id for default(primary) display.
43static const int32_t kDefaultDisplayId = 0;
Andreas Gampeed6b9df2014-11-20 22:02:20 -080044
Jeff Brownc28867a2013-03-26 15:42:39 -070045static struct {
46 jclass clazz;
47
48 jmethodID dispatchInputEventFinished;
49} gInputEventSenderClassInfo;
50
51
52class NativeInputEventSender : public LooperCallback {
53public:
54 NativeInputEventSender(JNIEnv* env,
Jeff Browna4ca8ea2013-04-02 18:01:38 -070055 jobject senderWeak, const sp<InputChannel>& inputChannel,
Jeff Brownc28867a2013-03-26 15:42:39 -070056 const sp<MessageQueue>& messageQueue);
57
58 status_t initialize();
59 void dispose();
60 status_t sendKeyEvent(uint32_t seq, const KeyEvent* event);
61 status_t sendMotionEvent(uint32_t seq, const MotionEvent* event);
62
63protected:
64 virtual ~NativeInputEventSender();
65
66private:
Jeff Browna4ca8ea2013-04-02 18:01:38 -070067 jobject mSenderWeakGlobal;
Jeff Brownc28867a2013-03-26 15:42:39 -070068 InputPublisher mInputPublisher;
69 sp<MessageQueue> mMessageQueue;
70 KeyedVector<uint32_t, uint32_t> mPublishedSeqMap;
71 uint32_t mNextPublishedSeq;
72
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -080073 const std::string getInputChannelName() {
74 return mInputPublisher.getChannel()->getName();
Jeff Brownc28867a2013-03-26 15:42:39 -070075 }
76
77 virtual int handleEvent(int receiveFd, int events, void* data);
78 status_t receiveFinishedSignals(JNIEnv* env);
79};
80
81
82NativeInputEventSender::NativeInputEventSender(JNIEnv* env,
Jeff Browna4ca8ea2013-04-02 18:01:38 -070083 jobject senderWeak, const sp<InputChannel>& inputChannel,
Jeff Brownc28867a2013-03-26 15:42:39 -070084 const sp<MessageQueue>& messageQueue) :
Jeff Browna4ca8ea2013-04-02 18:01:38 -070085 mSenderWeakGlobal(env->NewGlobalRef(senderWeak)),
Jeff Brownc28867a2013-03-26 15:42:39 -070086 mInputPublisher(inputChannel), mMessageQueue(messageQueue),
Michael Wright10f9b092013-04-01 13:11:34 -070087 mNextPublishedSeq(1) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -080088 if (kDebugDispatchCycle) {
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -080089 ALOGD("channel '%s' ~ Initializing input event sender.", getInputChannelName().c_str());
Andreas Gampeed6b9df2014-11-20 22:02:20 -080090 }
Jeff Brownc28867a2013-03-26 15:42:39 -070091}
92
93NativeInputEventSender::~NativeInputEventSender() {
94 JNIEnv* env = AndroidRuntime::getJNIEnv();
Jeff Browna4ca8ea2013-04-02 18:01:38 -070095 env->DeleteGlobalRef(mSenderWeakGlobal);
Jeff Brownc28867a2013-03-26 15:42:39 -070096}
97
98status_t NativeInputEventSender::initialize() {
99 int receiveFd = mInputPublisher.getChannel()->getFd();
100 mMessageQueue->getLooper()->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, this, NULL);
101 return OK;
102}
103
104void NativeInputEventSender::dispose() {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800105 if (kDebugDispatchCycle) {
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800106 ALOGD("channel '%s' ~ Disposing input event sender.", getInputChannelName().c_str());
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800107 }
Jeff Brownc28867a2013-03-26 15:42:39 -0700108
109 mMessageQueue->getLooper()->removeFd(mInputPublisher.getChannel()->getFd());
110}
111
112status_t NativeInputEventSender::sendKeyEvent(uint32_t seq, const KeyEvent* event) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800113 if (kDebugDispatchCycle) {
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800114 ALOGD("channel '%s' ~ Sending key event, seq=%u.", getInputChannelName().c_str(), seq);
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800115 }
Jeff Brownc28867a2013-03-26 15:42:39 -0700116
117 uint32_t publishedSeq = mNextPublishedSeq++;
118 status_t status = mInputPublisher.publishKeyEvent(publishedSeq,
119 event->getDeviceId(), event->getSource(), event->getAction(), event->getFlags(),
120 event->getKeyCode(), event->getScanCode(), event->getMetaState(),
121 event->getRepeatCount(), event->getDownTime(), event->getEventTime());
122 if (status) {
123 ALOGW("Failed to send key event on channel '%s'. status=%d",
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800124 getInputChannelName().c_str(), status);
Jeff Brownc28867a2013-03-26 15:42:39 -0700125 return status;
126 }
127 mPublishedSeqMap.add(publishedSeq, seq);
128 return OK;
129}
130
131status_t NativeInputEventSender::sendMotionEvent(uint32_t seq, const MotionEvent* event) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800132 if (kDebugDispatchCycle) {
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800133 ALOGD("channel '%s' ~ Sending motion event, seq=%u.", getInputChannelName().c_str(), seq);
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800134 }
Jeff Brownc28867a2013-03-26 15:42:39 -0700135
136 uint32_t publishedSeq;
137 for (size_t i = 0; i <= event->getHistorySize(); i++) {
138 publishedSeq = mNextPublishedSeq++;
139 status_t status = mInputPublisher.publishMotionEvent(publishedSeq,
Michael Wright5bd69e62015-05-14 14:48:08 +0100140 event->getDeviceId(), event->getSource(),
Tarandeep Singhe1cfcf42017-07-10 18:50:00 -0700141 kDefaultDisplayId /* TODO(multi-display): propagate display id */,
Michael Wright5bd69e62015-05-14 14:48:08 +0100142 event->getAction(), event->getActionButton(), event->getFlags(),
Jeff Brownc28867a2013-03-26 15:42:39 -0700143 event->getEdgeFlags(), event->getMetaState(), event->getButtonState(),
144 event->getXOffset(), event->getYOffset(),
145 event->getXPrecision(), event->getYPrecision(),
146 event->getDownTime(), event->getHistoricalEventTime(i),
147 event->getPointerCount(), event->getPointerProperties(),
148 event->getHistoricalRawPointerCoords(0, i));
149 if (status) {
150 ALOGW("Failed to send motion event sample on channel '%s'. status=%d",
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800151 getInputChannelName().c_str(), status);
Jeff Brownc28867a2013-03-26 15:42:39 -0700152 return status;
153 }
154 }
155 mPublishedSeqMap.add(publishedSeq, seq);
156 return OK;
157}
158
159int NativeInputEventSender::handleEvent(int receiveFd, int events, void* data) {
160 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Brown44e13ef2013-03-27 12:34:30 -0700161 // This error typically occurs when the consumer has closed the input channel
162 // as part of finishing an IME session, in which case the publisher will
163 // soon be disposed as well.
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800164 if (kDebugDispatchCycle) {
165 ALOGD("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800166 "events=0x%x", getInputChannelName().c_str(), events);
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800167 }
168
Jeff Brownc28867a2013-03-26 15:42:39 -0700169 return 0; // remove the callback
170 }
171
172 if (!(events & ALOOPER_EVENT_INPUT)) {
173 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800174 "events=0x%x", getInputChannelName().c_str(), events);
Jeff Brownc28867a2013-03-26 15:42:39 -0700175 return 1;
176 }
177
178 JNIEnv* env = AndroidRuntime::getJNIEnv();
179 status_t status = receiveFinishedSignals(env);
180 mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
181 return status == OK || status == NO_MEMORY ? 1 : 0;
182}
183
184status_t NativeInputEventSender::receiveFinishedSignals(JNIEnv* env) {
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800185 if (kDebugDispatchCycle) {
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800186 ALOGD("channel '%s' ~ Receiving finished signals.", getInputChannelName().c_str());
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800187 }
Jeff Brownc28867a2013-03-26 15:42:39 -0700188
Jeff Browna4ca8ea2013-04-02 18:01:38 -0700189 ScopedLocalRef<jobject> senderObj(env, NULL);
Jeff Brownc28867a2013-03-26 15:42:39 -0700190 bool skipCallbacks = false;
191 for (;;) {
192 uint32_t publishedSeq;
193 bool handled;
194 status_t status = mInputPublisher.receiveFinishedSignal(&publishedSeq, &handled);
195 if (status) {
196 if (status == WOULD_BLOCK) {
197 return OK;
198 }
199 ALOGE("channel '%s' ~ Failed to consume finished signals. status=%d",
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800200 getInputChannelName().c_str(), status);
Jeff Brownc28867a2013-03-26 15:42:39 -0700201 return status;
202 }
203
204 ssize_t index = mPublishedSeqMap.indexOfKey(publishedSeq);
205 if (index >= 0) {
206 uint32_t seq = mPublishedSeqMap.valueAt(index);
207 mPublishedSeqMap.removeItemsAt(index);
208
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800209 if (kDebugDispatchCycle) {
210 ALOGD("channel '%s' ~ Received finished signal, seq=%u, handled=%s, "
Bernhard Rosenkränzer46c82b42014-11-30 11:04:10 +0100211 "pendingEvents=%zu.",
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800212 getInputChannelName().c_str(), seq, handled ? "true" : "false",
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800213 mPublishedSeqMap.size());
214 }
Jeff Brownc28867a2013-03-26 15:42:39 -0700215
216 if (!skipCallbacks) {
Jeff Browna4ca8ea2013-04-02 18:01:38 -0700217 if (!senderObj.get()) {
218 senderObj.reset(jniGetReferent(env, mSenderWeakGlobal));
219 if (!senderObj.get()) {
220 ALOGW("channel '%s' ~ Sender object was finalized "
Siarhei Vishniakoud6058f42018-01-04 13:00:48 -0800221 "without being disposed.", getInputChannelName().c_str());
Jeff Browna4ca8ea2013-04-02 18:01:38 -0700222 return DEAD_OBJECT;
223 }
224 }
225
226 env->CallVoidMethod(senderObj.get(),
Jeff Brownc28867a2013-03-26 15:42:39 -0700227 gInputEventSenderClassInfo.dispatchInputEventFinished,
228 jint(seq), jboolean(handled));
229 if (env->ExceptionCheck()) {
230 ALOGE("Exception dispatching finished signal.");
231 skipCallbacks = true;
232 }
233 }
234 }
235 }
236}
237
238
Ashok Bhata931d5212014-01-08 14:04:51 +0000239static jlong nativeInit(JNIEnv* env, jclass clazz, jobject senderWeak,
Jeff Brownc28867a2013-03-26 15:42:39 -0700240 jobject inputChannelObj, jobject messageQueueObj) {
241 sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
242 inputChannelObj);
243 if (inputChannel == NULL) {
244 jniThrowRuntimeException(env, "InputChannel is not initialized.");
245 return 0;
246 }
247
248 sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
249 if (messageQueue == NULL) {
250 jniThrowRuntimeException(env, "MessageQueue is not initialized.");
251 return 0;
252 }
253
254 sp<NativeInputEventSender> sender = new NativeInputEventSender(env,
Jeff Browna4ca8ea2013-04-02 18:01:38 -0700255 senderWeak, inputChannel, messageQueue);
Jeff Brownc28867a2013-03-26 15:42:39 -0700256 status_t status = sender->initialize();
257 if (status) {
258 String8 message;
259 message.appendFormat("Failed to initialize input event sender. status=%d", status);
260 jniThrowRuntimeException(env, message.string());
261 return 0;
262 }
263
264 sender->incStrong(gInputEventSenderClassInfo.clazz); // retain a reference for the object
Ashok Bhata931d5212014-01-08 14:04:51 +0000265 return reinterpret_cast<jlong>(sender.get());
Jeff Brownc28867a2013-03-26 15:42:39 -0700266}
267
Ashok Bhata931d5212014-01-08 14:04:51 +0000268static void nativeDispose(JNIEnv* env, jclass clazz, jlong senderPtr) {
Jeff Brownc28867a2013-03-26 15:42:39 -0700269 sp<NativeInputEventSender> sender =
270 reinterpret_cast<NativeInputEventSender*>(senderPtr);
271 sender->dispose();
272 sender->decStrong(gInputEventSenderClassInfo.clazz); // drop reference held by the object
273}
274
Ashok Bhata931d5212014-01-08 14:04:51 +0000275static jboolean nativeSendKeyEvent(JNIEnv* env, jclass clazz, jlong senderPtr,
Jeff Brownc28867a2013-03-26 15:42:39 -0700276 jint seq, jobject eventObj) {
277 sp<NativeInputEventSender> sender =
278 reinterpret_cast<NativeInputEventSender*>(senderPtr);
279 KeyEvent event;
280 android_view_KeyEvent_toNative(env, eventObj, &event);
281 status_t status = sender->sendKeyEvent(seq, &event);
282 return !status;
283}
284
Ashok Bhata931d5212014-01-08 14:04:51 +0000285static jboolean nativeSendMotionEvent(JNIEnv* env, jclass clazz, jlong senderPtr,
Jeff Brownc28867a2013-03-26 15:42:39 -0700286 jint seq, jobject eventObj) {
287 sp<NativeInputEventSender> sender =
288 reinterpret_cast<NativeInputEventSender*>(senderPtr);
289 MotionEvent* event = android_view_MotionEvent_getNativePtr(env, eventObj);
290 status_t status = sender->sendMotionEvent(seq, event);
291 return !status;
292}
293
294
Daniel Micay76f6a862015-09-19 17:31:01 -0400295static const JNINativeMethod gMethods[] = {
Jeff Brownc28867a2013-03-26 15:42:39 -0700296 /* name, signature, funcPtr */
297 { "nativeInit",
Ashok Bhata931d5212014-01-08 14:04:51 +0000298 "(Ljava/lang/ref/WeakReference;Landroid/view/InputChannel;Landroid/os/MessageQueue;)J",
Jeff Brownc28867a2013-03-26 15:42:39 -0700299 (void*)nativeInit },
Ashok Bhata931d5212014-01-08 14:04:51 +0000300 { "nativeDispose", "(J)V",
Jeff Brownc28867a2013-03-26 15:42:39 -0700301 (void*)nativeDispose },
Ashok Bhata931d5212014-01-08 14:04:51 +0000302 { "nativeSendKeyEvent", "(JILandroid/view/KeyEvent;)Z",
Jeff Brownc28867a2013-03-26 15:42:39 -0700303 (void*)nativeSendKeyEvent },
Ashok Bhata931d5212014-01-08 14:04:51 +0000304 { "nativeSendMotionEvent", "(JILandroid/view/MotionEvent;)Z",
Jeff Brownc28867a2013-03-26 15:42:39 -0700305 (void*)nativeSendMotionEvent },
306};
307
Jeff Brownc28867a2013-03-26 15:42:39 -0700308int register_android_view_InputEventSender(JNIEnv* env) {
Andreas Gampe987f79f2014-11-18 17:29:46 -0800309 int res = RegisterMethodsOrDie(env, "android/view/InputEventSender", gMethods, NELEM(gMethods));
Jeff Brownc28867a2013-03-26 15:42:39 -0700310
Andreas Gampe987f79f2014-11-18 17:29:46 -0800311 jclass clazz = FindClassOrDie(env, "android/view/InputEventSender");
312 gInputEventSenderClassInfo.clazz = MakeGlobalRefOrDie(env, clazz);
Jeff Brownc28867a2013-03-26 15:42:39 -0700313
Andreas Gampe987f79f2014-11-18 17:29:46 -0800314 gInputEventSenderClassInfo.dispatchInputEventFinished = GetMethodIDOrDie(
315 env, gInputEventSenderClassInfo.clazz, "dispatchInputEventFinished", "(IZ)V");
316
317 return res;
Jeff Brownc28867a2013-03-26 15:42:39 -0700318}
319
320} // namespace android