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

base / android / input_hint_checker.cc [blame]

// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/android/input_hint_checker.h"

#include <jni.h>
#include <pthread.h>

#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/feature_list.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
#include "base/time/time.h"

// Must come after all headers that specialize FromJniType() / ToJniType().
#include "base/base_jni/InputHintChecker_jni.h"

namespace base::android {

enum class InputHintChecker::InitState {
  kNotStarted,
  kInProgress,
  kInitialized,
  kFailedToInitialize
};

namespace {

bool g_input_hint_enabled;
base::TimeDelta g_poll_interval;
InputHintChecker* g_test_instance;

}  // namespace

// Whether to fetch the input hint from the system. When disabled, pretends
// that no input is ever queued.
BASE_EXPORT
BASE_FEATURE(kYieldWithInputHint,
             "YieldWithInputHint",
             base::FEATURE_ENABLED_BY_DEFAULT);

// Min time delta between checks for the input hint. Must be a smaller than
// time to produce a frame, but a bit longer than the time it takes to retrieve
// the hint.
const base::FeatureParam<int> kPollIntervalMillisParam{&kYieldWithInputHint,
                                                       "poll_interval_ms", 1};

// Class calling a private method of InputHintChecker.
// This allows not to declare the method called by pthread_create in the public
// header.
class InputHintChecker::OffThreadInitInvoker {
 public:
  // Called by pthread_create().
  static void* Run(void* opaque) {
    InputHintChecker::GetInstance().RunOffThreadInitialization();
    return nullptr;
  }
};

InputHintChecker::InputHintChecker() : init_state_(InitState::kNotStarted) {}

InputHintChecker::~InputHintChecker() = default;

// static
void InputHintChecker::InitializeFeatures() {
  bool is_enabled = base::FeatureList::IsEnabled(kYieldWithInputHint);
  g_input_hint_enabled = is_enabled;
  if (is_enabled) {
    g_poll_interval = Milliseconds(kPollIntervalMillisParam.Get());
  }
}

void InputHintChecker::SetView(
    JNIEnv* env,
    const jni_zero::JavaParamRef<jobject>& root_view) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  InitState state = FetchState();
  if (state == InitState::kFailedToInitialize) {
    return;
  }
  view_ = JavaObjectWeakGlobalRef(env, root_view);
  if (!root_view) {
    return;
  }
  if (state == InitState::kNotStarted) {
    // Store the View.class and continue initialization on another thread. A
    // separate non-Java thread is required to obtain a reference to
    // j.l.reflect.Method via double-reflection.
    TransitionToState(InitState::kInProgress);
    view_class_ =
        ScopedJavaGlobalRef<jobject>(env, env->GetObjectClass(root_view.obj()));
    pthread_t new_thread;
    if (pthread_create(&new_thread, nullptr, OffThreadInitInvoker::Run,
                       nullptr) != 0) {
      PLOG(ERROR) << "pthread_create";
      TransitionToState(InitState::kFailedToInitialize);
    }
  }
}

// static
bool InputHintChecker::HasInput() {
  if (!g_input_hint_enabled) {
    return false;
  }
  return GetInstance().HasInputImplWithThrottling();
}

bool InputHintChecker::IsInitializedForTesting() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return FetchState() == InitState::kInitialized;
}

bool InputHintChecker::FailedToInitializeForTesting() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return FetchState() == InitState::kFailedToInitialize;
}

bool InputHintChecker::HasInputImplWithThrottling() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  // Early return if off-thread initialization has not succeeded yet.
  InitState state = FetchState();
  if (state != InitState::kInitialized) {
    return false;
  }

  // Input processing is associated with the root view. Early return when the
  // root view is not available. It can happen in cases like multi-window.
  JNIEnv* env = AttachCurrentThread();
  ScopedJavaLocalRef<jobject> scoped_view = view_.get(env);
  if (!scoped_view) {
    return false;
  }

  // Throttle.
  auto now = base::TimeTicks::Now();
  if (last_checked_.is_null() || (now - last_checked_) >= g_poll_interval) {
    last_checked_ = now;
  } else {
    return false;
  }

  return HasInputImpl(env, scoped_view.obj());
}

bool InputHintChecker::HasInputImplNoThrottlingForTesting(_JNIEnv* env) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (FetchState() != InitState::kInitialized) {
    return false;
  }
  ScopedJavaLocalRef<jobject> scoped_view = view_.get(env);
  CHECK(scoped_view.obj());
  return HasInputImpl(env, scoped_view.obj());
}

bool InputHintChecker::HasInputImplWithThrottlingForTesting(_JNIEnv* env) {
  if (FetchState() != InitState::kInitialized) {
    return false;
  }
  return HasInputImplWithThrottling();
}

bool InputHintChecker::HasInputImpl(JNIEnv* env, jobject o) {
  auto has_input_result = ScopedJavaLocalRef<jobject>::Adopt(
      env, env->CallObjectMethod(reflect_method_for_has_input_.obj(),
                                 invoke_id_, o, nullptr));
  if (ClearException(env)) {
    LOG(ERROR) << "Exception when calling reflect_method_for_has_input_";
    TransitionToState(InitState::kFailedToInitialize);
    return false;
  }
  if (!has_input_result) {
    LOG(ERROR) << "Returned null from reflection call";
    TransitionToState(InitState::kFailedToInitialize);
    return false;
  }

  // Convert result to bool and return.
  bool value = static_cast<bool>(
      env->CallBooleanMethod(has_input_result.obj(), boolean_value_id_));
  if (ClearException(env)) {
    LOG(ERROR) << "Exception when converting to boolean";
    TransitionToState(InitState::kFailedToInitialize);
    return false;
  }
  return value;
}

InputHintChecker::InitState InputHintChecker::FetchState() const {
  return init_state_.load(std::memory_order_acquire);
}

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class InitializationResult {
  kSuccess = 0,
  kFailure = 1,
  kMaxValue = kFailure,
};

void InputHintChecker::TransitionToState(InitState new_state) {
  DCHECK_NE(new_state, FetchState());
  if (new_state == InitState::kInitialized ||
      new_state == InitState::kFailedToInitialize) {
    InitializationResult r = (new_state == InitState::kInitialized)
                                 ? InitializationResult::kSuccess
                                 : InitializationResult::kFailure;
    UmaHistogramEnumeration("Android.InputHintChecker.InitializationResult", r);
  }
  init_state_.store(new_state, std::memory_order_release);
}

void InputHintChecker::RunOffThreadInitialization() {
  JNIEnv* env = AttachCurrentThread();
  InitGlobalRefsAndMethodIds(env);
  DetachFromVM();
}

void InputHintChecker::InitGlobalRefsAndMethodIds(JNIEnv* env) {
  // Obtain j.l.reflect.Method using View.class.getMethod("probablyHasInput",
  // "...").
  jclass view_class = env->GetObjectClass(view_class_.obj());
  if (ClearException(env)) {
    LOG(ERROR) << "exception on GetObjectClass(view)";
    TransitionToState(InitState::kFailedToInitialize);
    return;
  }
  jmethodID get_method_id = env->GetMethodID(
      view_class, "getMethod",
      "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;");
  if (ClearException(env)) {
    LOG(ERROR) << "exception when looking for method getMethod()";
    TransitionToState(InitState::kFailedToInitialize);
    return;
  }
  ScopedJavaLocalRef<jstring> has_input_string =
      ConvertUTF8ToJavaString(env, "probablyHasInput");
  auto method = ScopedJavaLocalRef<jobject>::Adopt(
      env, env->CallObjectMethod(view_class_.obj(), get_method_id,
                                 has_input_string.obj(), nullptr));
  if (ClearException(env)) {
    LOG(ERROR) << "exception when calling getMethod(probablyHasInput)";
    TransitionToState(InitState::kFailedToInitialize);
    return;
  }
  if (!method) {
    LOG(ERROR) << "got null from getMethod(probablyHasInput)";
    TransitionToState(InitState::kFailedToInitialize);
    return;
  }

  // Cache useful members for further calling Method.invoke(view).
  reflect_method_for_has_input_ = ScopedJavaGlobalRef<jobject>(method);
  jclass method_class =
      env->GetObjectClass(reflect_method_for_has_input_.obj());
  if (ClearException(env) || !method_class) {
    LOG(ERROR) << "exception on GetObjectClass(getMethod) or null returned";
    TransitionToState(InitState::kFailedToInitialize);
    return;
  }
  invoke_id_ = env->GetMethodID(
      method_class, "invoke",
      "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
  if (ClearException(env)) {
    LOG(ERROR) << "exception when looking for invoke() of getMethod()";
    TransitionToState(InitState::kFailedToInitialize);
    return;
  }
  jclass boolean_class = env->FindClass("java/lang/Boolean");
  if (ClearException(env) || !boolean_class) {
    LOG(ERROR) << "exception when looking for class Boolean or null returned";
    TransitionToState(InitState::kFailedToInitialize);
    return;
  }
  boolean_value_id_ = env->GetMethodID(boolean_class, "booleanValue", "()Z");
  if (ClearException(env)) {
    LOG(ERROR) << "exception when looking for method booleanValue";
    TransitionToState(InitState::kFailedToInitialize);
    return;
  }

  // Publish the obtained members to the thread observing kInitialized.
  TransitionToState(InitState::kInitialized);
}

InputHintChecker& InputHintChecker::GetInstance() {
  static NoDestructor<InputHintChecker> checker;
  if (g_test_instance) {
    return *g_test_instance;
  }
  return *checker.get();
}

InputHintChecker::ScopedOverrideInstance::ScopedOverrideInstance(
    InputHintChecker* checker) {
  g_test_instance = checker;
}

InputHintChecker::ScopedOverrideInstance::~ScopedOverrideInstance() {
  g_test_instance = nullptr;
}

// static
void InputHintChecker::RecordInputHintResult(InputHintResult result) {
  UMA_HISTOGRAM_ENUMERATION("Android.InputHintChecker.InputHintResult", result);
}

void JNI_InputHintChecker_SetView(_JNIEnv* env,
                                  const jni_zero::JavaParamRef<jobject>& v) {
  InputHintChecker::GetInstance().SetView(env, v);
}

void JNI_InputHintChecker_OnCompositorViewHolderTouchEvent(_JNIEnv* env) {
  auto& checker = InputHintChecker::GetInstance();
  if (checker.is_after_input_yield()) {
    InputHintChecker::RecordInputHintResult(
        InputHintResult::kCompositorViewTouchEvent);
  }
  checker.set_is_after_input_yield(false);
}

jboolean JNI_InputHintChecker_IsInitializedForTesting(_JNIEnv* env) {
  return InputHintChecker::GetInstance().IsInitializedForTesting();  // IN-TEST
}

jboolean JNI_InputHintChecker_FailedToInitializeForTesting(_JNIEnv* env) {
  return InputHintChecker::GetInstance()
      .FailedToInitializeForTesting();  // IN-TEST
}

jboolean JNI_InputHintChecker_HasInputForTesting(_JNIEnv* env) {
  InputHintChecker& checker = InputHintChecker::GetInstance();
  return checker.HasInputImplNoThrottlingForTesting(env);  // IN-TEST
}

jboolean JNI_InputHintChecker_HasInputWithThrottlingForTesting(_JNIEnv* env) {
  InputHintChecker& checker = InputHintChecker::GetInstance();
  return checker.HasInputImplWithThrottlingForTesting(env);  // IN-TEST
}

void JNI_InputHintChecker_SetIsAfterInputYieldForTesting(  // IN-TEST
    _JNIEnv* env,
    jboolean after) {
  InputHintChecker::GetInstance().set_is_after_input_yield(after);
}

}  // namespace base::android