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