1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/android/jni_string.h"
6 #include "base/bind.h"
7 #include "base/callback.h"
8 #include "base/metrics/user_metrics.h"
9 #include "jni/RecordUserAction_jni.h"
10 
11 namespace {
12 
13 struct ActionCallbackWrapper {
14   base::ActionCallback action_callback;
15 };
16 
17 }  // namespace
18 
19 namespace base {
20 namespace android {
21 
JNI_RecordUserAction_RecordUserAction(JNIEnv * env,const JavaParamRef<jclass> & clazz,const JavaParamRef<jstring> & j_action)22 static void JNI_RecordUserAction_RecordUserAction(
23     JNIEnv* env,
24     const JavaParamRef<jclass>& clazz,
25     const JavaParamRef<jstring>& j_action) {
26   RecordComputedAction(ConvertJavaStringToUTF8(env, j_action));
27 }
28 
OnActionRecorded(const JavaRef<jobject> & callback,const std::string & action)29 static void OnActionRecorded(const JavaRef<jobject>& callback,
30                              const std::string& action) {
31   JNIEnv* env = AttachCurrentThread();
32   Java_UserActionCallback_onActionRecorded(
33       env, callback, ConvertUTF8ToJavaString(env, action));
34 }
35 
JNI_RecordUserAction_AddActionCallbackForTesting(JNIEnv * env,const JavaParamRef<jclass> & clazz,const JavaParamRef<jobject> & callback)36 static jlong JNI_RecordUserAction_AddActionCallbackForTesting(
37     JNIEnv* env,
38     const JavaParamRef<jclass>& clazz,
39     const JavaParamRef<jobject>& callback) {
40   // Create a wrapper for the ActionCallback, so it can life on the heap until
41   // RemoveActionCallbackForTesting() is called.
42   auto* wrapper = new ActionCallbackWrapper{base::Bind(
43       &OnActionRecorded, ScopedJavaGlobalRef<jobject>(env, callback))};
44   base::AddActionCallback(wrapper->action_callback);
45   return reinterpret_cast<intptr_t>(wrapper);
46 }
47 
JNI_RecordUserAction_RemoveActionCallbackForTesting(JNIEnv * env,const JavaParamRef<jclass> & clazz,jlong callback_id)48 static void JNI_RecordUserAction_RemoveActionCallbackForTesting(
49     JNIEnv* env,
50     const JavaParamRef<jclass>& clazz,
51     jlong callback_id) {
52   DCHECK(callback_id);
53   auto* wrapper = reinterpret_cast<ActionCallbackWrapper*>(callback_id);
54   base::RemoveActionCallback(wrapper->action_callback);
55   delete wrapper;
56 }
57 
58 }  // namespace android
59 }  // namespace base
60