1 /*
2  * Copyright (C) 2010 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 "KeyEvent-JNI"
18 
19 #include <nativehelper/JNIHelp.h>
20 
21 #include <android_runtime/AndroidRuntime.h>
22 #include <android_runtime/Log.h>
23 #include <input/Input.h>
24 #include <nativehelper/ScopedPrimitiveArray.h>
25 #include <nativehelper/ScopedUtfChars.h>
26 #include <utils/Log.h>
27 #include <optional>
28 #include "android_view_KeyEvent.h"
29 
30 #include "core_jni_helpers.h"
31 
32 namespace android {
33 
34 /**
35  * Convert an std::array of bytes into a Java object.
36  */
37 template <size_t N>
toJbyteArray(JNIEnv * env,const std::array<uint8_t,N> & data)38 static ScopedLocalRef<jbyteArray> toJbyteArray(JNIEnv* env, const std::array<uint8_t, N>& data) {
39     ScopedLocalRef<jbyteArray> array(env, env->NewByteArray(N));
40     if (array.get() == nullptr) {
41         jniThrowException(env, "java/lang/OutOfMemoryError", nullptr);
42         return array;
43     }
44     static_assert(sizeof(char) == sizeof(uint8_t));
45     env->SetByteArrayRegion(array.get(), 0, N, reinterpret_cast<const signed char*>(data.data()));
46     return array;
47 }
48 
49 /**
50  * Convert a Java object into an std::array of bytes of size N.
51  * If the object is null,  or the length is unexpected, return std::nullopt.
52  */
53 template <size_t N>
fromJobject(JNIEnv * env,jobject object)54 static std::optional<std::array<uint8_t, N>> fromJobject(JNIEnv* env, jobject object) {
55     if (object == nullptr) {
56         return std::nullopt;
57     }
58     jbyteArray javaArray = reinterpret_cast<jbyteArray>(object);
59     ScopedByteArrayRO bytes(env, javaArray);
60     if (bytes.size() != N) {
61         ALOGE("Could not initialize array from java object, expected length %zu but got %zu", N,
62               bytes.size());
63         return std::nullopt;
64     }
65     std::array<uint8_t, N> array;
66     std::move(bytes.get(), bytes.get() + N, array.begin());
67     return array;
68 }
69 
70 // ----------------------------------------------------------------------------
71 
72 static struct {
73     jclass clazz;
74 
75     jmethodID obtain;
76     jmethodID recycle;
77 
78     jfieldID mId;
79     jfieldID mDeviceId;
80     jfieldID mSource;
81     jfieldID mDisplayId;
82     jfieldID mHmac;
83     jfieldID mMetaState;
84     jfieldID mAction;
85     jfieldID mKeyCode;
86     jfieldID mScanCode;
87     jfieldID mRepeatCount;
88     jfieldID mFlags;
89     jfieldID mDownTime;
90     jfieldID mEventTime;
91     jfieldID mCharacters;
92 } gKeyEventClassInfo;
93 
94 // ----------------------------------------------------------------------------
95 
android_view_KeyEvent_fromNative(JNIEnv * env,const KeyEvent * event)96 jobject android_view_KeyEvent_fromNative(JNIEnv* env, const KeyEvent* event) {
97     ScopedLocalRef<jbyteArray> hmac = toJbyteArray(env, event->getHmac());
98     jobject eventObj =
99             env->CallStaticObjectMethod(gKeyEventClassInfo.clazz, gKeyEventClassInfo.obtain,
100                                         event->getId(),
101                                         nanoseconds_to_milliseconds(event->getDownTime()),
102                                         nanoseconds_to_milliseconds(event->getEventTime()),
103                                         event->getAction(), event->getKeyCode(),
104                                         event->getRepeatCount(), event->getMetaState(),
105                                         event->getDeviceId(), event->getScanCode(),
106                                         event->getFlags(), event->getSource(),
107                                         event->getDisplayId(), hmac.get(), nullptr);
108     if (env->ExceptionCheck()) {
109         ALOGE("An exception occurred while obtaining a key event.");
110         LOGE_EX(env);
111         env->ExceptionClear();
112         return NULL;
113     }
114     return eventObj;
115 }
116 
android_view_KeyEvent_toNative(JNIEnv * env,jobject eventObj,KeyEvent * event)117 status_t android_view_KeyEvent_toNative(JNIEnv* env, jobject eventObj,
118         KeyEvent* event) {
119     jint id = env->GetIntField(eventObj, gKeyEventClassInfo.mId);
120     jint deviceId = env->GetIntField(eventObj, gKeyEventClassInfo.mDeviceId);
121     jint source = env->GetIntField(eventObj, gKeyEventClassInfo.mSource);
122     jint displayId = env->GetIntField(eventObj, gKeyEventClassInfo.mDisplayId);
123     jobject hmacObj = env->GetObjectField(eventObj, gKeyEventClassInfo.mHmac);
124     std::optional<std::array<uint8_t, 32>> hmac = fromJobject<32>(env, hmacObj);
125     if (!hmac) {
126         hmac = INVALID_HMAC;
127     }
128     jint metaState = env->GetIntField(eventObj, gKeyEventClassInfo.mMetaState);
129     jint action = env->GetIntField(eventObj, gKeyEventClassInfo.mAction);
130     jint keyCode = env->GetIntField(eventObj, gKeyEventClassInfo.mKeyCode);
131     jint scanCode = env->GetIntField(eventObj, gKeyEventClassInfo.mScanCode);
132     jint repeatCount = env->GetIntField(eventObj, gKeyEventClassInfo.mRepeatCount);
133     jint flags = env->GetIntField(eventObj, gKeyEventClassInfo.mFlags);
134     jlong downTime = env->GetLongField(eventObj, gKeyEventClassInfo.mDownTime);
135     jlong eventTime = env->GetLongField(eventObj, gKeyEventClassInfo.mEventTime);
136 
137     event->initialize(id, deviceId, source, displayId, *hmac, action, flags, keyCode, scanCode,
138                       metaState, repeatCount, milliseconds_to_nanoseconds(downTime),
139                       milliseconds_to_nanoseconds(eventTime));
140     return OK;
141 }
142 
android_view_KeyEvent_recycle(JNIEnv * env,jobject eventObj)143 status_t android_view_KeyEvent_recycle(JNIEnv* env, jobject eventObj) {
144     env->CallVoidMethod(eventObj, gKeyEventClassInfo.recycle);
145     if (env->ExceptionCheck()) {
146         ALOGW("An exception occurred while recycling a key event.");
147         LOGW_EX(env);
148         env->ExceptionClear();
149         return UNKNOWN_ERROR;
150     }
151     return OK;
152 }
153 
android_view_KeyEvent_nativeKeyCodeToString(JNIEnv * env,jobject clazz,jint keyCode)154 static jstring android_view_KeyEvent_nativeKeyCodeToString(JNIEnv* env, jobject clazz,
155         jint keyCode) {
156     return env->NewStringUTF(KeyEvent::getLabel(keyCode));
157 }
158 
android_view_KeyEvent_nativeKeyCodeFromString(JNIEnv * env,jobject clazz,jstring label)159 static jint android_view_KeyEvent_nativeKeyCodeFromString(JNIEnv* env, jobject clazz,
160         jstring label) {
161     ScopedUtfChars keyLabel(env, label);
162     return KeyEvent::getKeyCodeFromLabel(keyLabel.c_str());
163 }
164 
android_view_KeyEvent_nativeNextId()165 static jint android_view_KeyEvent_nativeNextId() {
166     return static_cast<jint>(InputEvent::nextId());
167 }
168 
169 // ----------------------------------------------------------------------------
170 
171 static const JNINativeMethod g_methods[] = {
172         {"nativeKeyCodeToString", "(I)Ljava/lang/String;",
173          (void*)android_view_KeyEvent_nativeKeyCodeToString},
174         {"nativeKeyCodeFromString", "(Ljava/lang/String;)I",
175          (void*)android_view_KeyEvent_nativeKeyCodeFromString},
176         {"nativeNextId", "()I", (void*)android_view_KeyEvent_nativeNextId},
177 };
178 
register_android_view_KeyEvent(JNIEnv * env)179 int register_android_view_KeyEvent(JNIEnv* env) {
180     jclass clazz = FindClassOrDie(env, "android/view/KeyEvent");
181     gKeyEventClassInfo.clazz = MakeGlobalRefOrDie(env, clazz);
182 
183     gKeyEventClassInfo.obtain =
184             GetStaticMethodIDOrDie(env, gKeyEventClassInfo.clazz, "obtain",
185                                    "(IJJIIIIIIIII[BLjava/lang/String;)Landroid/view/KeyEvent;");
186     gKeyEventClassInfo.recycle = GetMethodIDOrDie(env, gKeyEventClassInfo.clazz,
187             "recycle", "()V");
188 
189     gKeyEventClassInfo.mId = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mId", "I");
190     gKeyEventClassInfo.mDeviceId = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mDeviceId", "I");
191     gKeyEventClassInfo.mSource = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mSource", "I");
192     gKeyEventClassInfo.mDisplayId = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mDisplayId",
193                                                     "I");
194     gKeyEventClassInfo.mHmac = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mHmac", "[B");
195     gKeyEventClassInfo.mMetaState = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mMetaState",
196                                                     "I");
197     gKeyEventClassInfo.mAction = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mAction", "I");
198     gKeyEventClassInfo.mKeyCode = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mKeyCode", "I");
199     gKeyEventClassInfo.mScanCode = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mScanCode", "I");
200     gKeyEventClassInfo.mRepeatCount = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mRepeatCount",
201                                                       "I");
202     gKeyEventClassInfo.mFlags = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mFlags", "I");
203     gKeyEventClassInfo.mDownTime = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mDownTime", "J");
204     gKeyEventClassInfo.mEventTime = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mEventTime",
205                                                     "J");
206     gKeyEventClassInfo.mCharacters = GetFieldIDOrDie(env, gKeyEventClassInfo.clazz, "mCharacters",
207                                                      "Ljava/lang/String;");
208 
209     return RegisterMethodsOrDie(env, "android/view/KeyEvent", g_methods, NELEM(g_methods));
210 }
211 
212 } // namespace android
213