File: tab_interaction_recorder_android.cc

package info (click to toggle)
chromium 135.0.7049.95-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 5,959,392 kB
  • sloc: cpp: 34,198,526; ansic: 7,100,035; javascript: 3,985,800; python: 1,395,489; asm: 896,754; xml: 722,891; pascal: 180,504; sh: 94,909; perl: 88,388; objc: 79,739; sql: 53,020; cs: 41,358; fortran: 24,137; makefile: 22,501; php: 13,699; tcl: 10,142; yacc: 8,822; ruby: 7,350; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; awk: 197; sed: 36
file content (315 lines) | stat: -rw-r--r-- 10,888 bytes parent folder | download | duplicates (5)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/android/customtabs/tab_interaction_recorder_android.h"

#include <memory>
#include <string>

#include "base/android/jni_android.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "chrome/browser/android/customtabs/custom_tab_session_state_tracker.h"
#include "chrome/browser/android/tab_android.h"
#include "chrome/browser/flags/android/chrome_feature_list.h"
#include "components/autofill/content/browser/content_autofill_driver.h"
#include "components/autofill/core/browser/foundations/autofill_manager.h"
#include "components/autofill/core/common/unique_ids.h"
#include "content/public/browser/document_user_data.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"

// Must come after all headers that specialize FromJniType() / ToJniType().
#include "chrome/android/chrome_jni_headers/TabInteractionRecorder_jni.h"

namespace customtabs {

using autofill::AutofillManager;
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
using content::GlobalRenderFrameHostId;
using content::RenderFrameHost;

namespace {

AutofillManager* GetAutofillManager(RenderFrameHost* render_frame_host) {
  auto* autofill_driver =
      autofill::ContentAutofillDriver::GetForRenderFrameHost(render_frame_host);
  if (!autofill_driver)
    return nullptr;
  return &autofill_driver->GetAutofillManager();
}
}  // namespace

AutofillObserverImpl::AutofillObserverImpl(
    GlobalRenderFrameHostId id,
    autofill::AutofillManager* autofill_manager,
    OnFormInteractionCallback form_interaction_callback)
    : global_id_(id),
      autofill_manager_(autofill_manager),
      form_interaction_callback_(std::move(form_interaction_callback)) {
  autofill_manager->AddObserver(this);
}

AutofillObserverImpl::~AutofillObserverImpl() {
  Invalidate();
}

void AutofillObserverImpl::OnFormSubmitted(autofill::AutofillManager&,
                                           const autofill::FormData&) {
  OnFormInteraction();
}

void AutofillObserverImpl::OnAfterSelectControlSelectionChanged(
    autofill::AutofillManager&,
    autofill::FormGlobalId,
    autofill::FieldGlobalId) {
  OnFormInteraction();
}

void AutofillObserverImpl::OnAfterTextFieldValueChanged(
    autofill::AutofillManager&,
    autofill::FormGlobalId,
    autofill::FieldGlobalId,
    const std::u16string&) {
  OnFormInteraction();
}

void AutofillObserverImpl::OnAfterTextFieldDidScroll(autofill::AutofillManager&,
                                                     autofill::FormGlobalId,
                                                     autofill::FieldGlobalId) {
  OnFormInteraction();
}

void AutofillObserverImpl::OnAfterFormsSeen(
    AutofillManager& manager,
    base::span<const autofill::FormGlobalId> updated_forms,
    base::span<const autofill::FormGlobalId> removed_forms) {
  RenderFrameHost* rfh = RenderFrameHost::FromID(global_id_);
  // Only mark has form associated data for the RFH observed. This is to
  // metigate the fact that AutofillManager will dispatch |OnAfterFormsSeen| to
  // *all* observers regardless where the RFH the observer lives in has a form.
  if (!rfh) {
    return;
  }

  // Check whether the form seen lives in the observed RFH.
  bool forms_in_rfh = false;
  for (auto form_id : updated_forms) {
    if (form_id.frame_token ==
        autofill::LocalFrameToken(rfh->GetFrameToken().value())) {
      forms_in_rfh = true;
      break;
    }
  }
  if (!forms_in_rfh) {
    return;
  }

  // Set the had form data associated value in the page's
  // BackForwardCacheMetrics. Note that this means that if |rfh| is a subframe
  // it's possible that the page will still be marked as having a form data
  // associated with it even though |rfh| had navigated to another document and
  // there is no longer any document with forms in the page.
  content::BackForwardCache::SetHadFormDataAssociated(rfh->GetPage());

  // Create the form interaction user data meaning the page has seen a form
  // attached.
  FormInteractionData::GetOrCreateForCurrentDocument(
      rfh->GetOutermostMainFrame());
}

void AutofillObserverImpl::Invalidate() {
  if (IsInObserverList()) {
    DCHECK(autofill_manager_);
    autofill_manager_->RemoveObserver(this);
    autofill_manager_ = nullptr;
  }
}

void AutofillObserverImpl::OnFormInteraction() {
  Invalidate();
  std::move(form_interaction_callback_).Run(global_id_);
}

DOCUMENT_USER_DATA_KEY_IMPL(FormInteractionData);

FormInteractionData::~FormInteractionData() = default;

FormInteractionData::FormInteractionData(RenderFrameHost* rfh)
    : DocumentUserData<FormInteractionData>(rfh) {}

void FormInteractionData::SetHasFormInteractionData() {
  had_form_interaction_data_ = true;
}

bool FormInteractionData::GetHasFormInteractionData() {
  return had_form_interaction_data_;
}

TabInteractionRecorderAndroid::~TabInteractionRecorderAndroid() = default;

TabInteractionRecorderAndroid::TabInteractionRecorderAndroid(
    content::WebContents* web_contents)
    : content::WebContentsObserver(web_contents),
      content::WebContentsUserData<TabInteractionRecorderAndroid>(
          *web_contents) {}

bool TabInteractionRecorderAndroid::HasNavigatedFromFirstPage() const {
  return web_contents()->GetController().CanGoBack() ||
         web_contents()->GetController().CanGoForward();
}

bool TabInteractionRecorderAndroid::HasActiveFormInteraction() const {
  bool interaction = false;
  web_contents()->GetPrimaryMainFrame()->ForEachRenderFrameHostWithAction(
      [&interaction](RenderFrameHost* rfh) {
        if (!FormInteractionData::GetForCurrentDocument(rfh)) {
          return RenderFrameHost::FrameIterationAction::kContinue;
        }
        if (FormInteractionData::GetForCurrentDocument(rfh)
                ->GetHasFormInteractionData()) {
          interaction = true;
          return RenderFrameHost::FrameIterationAction::kStop;
        }
        return RenderFrameHost::FrameIterationAction::kContinue;
      });
  return interaction;
}

void TabInteractionRecorderAndroid::ResetImpl() {
  has_form_interactions_in_session_ = false;
  did_get_user_interaction_ = false;
  web_contents()->GetPrimaryMainFrame()->ForEachRenderFrameHost(
      [](RenderFrameHost* rfh) {
        if (FormInteractionData::GetForCurrentDocument(rfh)) {
          FormInteractionData::DeleteForCurrentDocument(rfh);
        }
      });
}

// content::WebContentsObserver:
void TabInteractionRecorderAndroid::RenderFrameHostStateChanged(
    RenderFrameHost* render_frame_host,
    RenderFrameHost::LifecycleState old_state,
    RenderFrameHost::LifecycleState new_state) {
  if (old_state == RenderFrameHost::LifecycleState::kActive) {
    rfh_observer_map_.erase(render_frame_host->GetGlobalId());
  } else if (new_state == RenderFrameHost::LifecycleState::kActive) {
    StartObservingFrame(render_frame_host);
  }
}

void TabInteractionRecorderAndroid::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  if (!navigation_handle->IsSameDocument() &&
      navigation_handle->HasCommitted() &&
      navigation_handle->GetRenderFrameHost()->IsActive())
    StartObservingFrame(navigation_handle->GetRenderFrameHost());
}

void TabInteractionRecorderAndroid::DidGetUserInteraction(
    const blink::WebInputEvent& event) {
  // We already reported the interaction for this Tab and the lifetime of
  // this object is the same as the CCT, so we will only report once.
  if (did_get_user_interaction_)
    return;

  did_get_user_interaction_ = true;
  chrome::android::CustomTabSessionStateTracker::GetInstance()
      .OnUserInteraction();
}

void TabInteractionRecorderAndroid::SetHasFormInteractions(
    GlobalRenderFrameHostId id) {
  if (RenderFrameHost::FromID(id)) {
    FormInteractionData::GetOrCreateForCurrentDocument(
        RenderFrameHost::FromID(id))
        ->SetHasFormInteractionData();
  }

  has_form_interactions_in_session_ = true;
  rfh_observer_map_.clear();
}

void TabInteractionRecorderAndroid::StartObservingFrame(
    RenderFrameHost* render_frame_host) {
  // Do not observe the same frame more than once.
  if (rfh_observer_map_[render_frame_host->GetGlobalId()])
    return;

  AutofillManager* autofill_manager =
      test_autofill_manager_ ? test_autofill_manager_.get()
                             : GetAutofillManager(render_frame_host);
  if (!autofill_manager)
    return;

  rfh_observer_map_[render_frame_host->GetGlobalId()] =
      std::make_unique<AutofillObserverImpl>(
          render_frame_host->GetGlobalId(), autofill_manager,
          base::BindOnce(&TabInteractionRecorderAndroid::SetHasFormInteractions,
                         weak_factory_.GetWeakPtr()));
}

WEB_CONTENTS_USER_DATA_KEY_IMPL(TabInteractionRecorderAndroid);

// JNI methods
jboolean TabInteractionRecorderAndroid::DidGetUserInteraction(
    JNIEnv* env) const {
  return did_get_user_interaction_;
}

jboolean TabInteractionRecorderAndroid::HadFormInteractionInSession(
    JNIEnv* env) const {
  return has_form_interactions_in_session();
}

jboolean TabInteractionRecorderAndroid::HadNavigationInteraction(
    JNIEnv* env) const {
  return did_get_user_interaction_ && HasNavigatedFromFirstPage();
}

jboolean TabInteractionRecorderAndroid::HadFormInteractionInActivePage(
    JNIEnv* env) const {
  return HasActiveFormInteraction();
}

void TabInteractionRecorderAndroid::Reset(JNIEnv* env) {
  ResetImpl();
}

ScopedJavaLocalRef<jobject> JNI_TabInteractionRecorder_GetFromTab(
    JNIEnv* env,
    const JavaParamRef<jobject>& jtab) {
  TabAndroid* tab = TabAndroid::GetNativeTab(env, jtab);
  if (!tab || !tab->web_contents() || tab->web_contents()->IsBeingDestroyed()) {
    return ScopedJavaLocalRef<jobject>(env, nullptr);
  }

  auto* recorder =
      TabInteractionRecorderAndroid::FromWebContents(tab->web_contents());
  return Java_TabInteractionRecorder_create(
      env, reinterpret_cast<int64_t>(recorder));
}

ScopedJavaLocalRef<jobject> JNI_TabInteractionRecorder_CreateForTab(
    JNIEnv* env,
    const JavaParamRef<jobject>& jtab) {
  TabAndroid* tab = TabAndroid::GetNativeTab(env, jtab);
  if (!tab || !tab->web_contents() || tab->web_contents()->IsBeingDestroyed()) {
    return ScopedJavaLocalRef<jobject>(env, nullptr);
  }

  TabInteractionRecorderAndroid::CreateForWebContents(tab->web_contents());

  auto* recorder =
      TabInteractionRecorderAndroid::FromWebContents(tab->web_contents());
  return Java_TabInteractionRecorder_create(
      env, reinterpret_cast<int64_t>(recorder));
}

}  // namespace customtabs