File: autofill_context_menu_manager.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (353 lines) | stat: -rw-r--r-- 12,983 bytes parent folder | download
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
// 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/ui/autofill/autofill_context_menu_manager.h"

#include <string>

#include "base/ranges/algorithm.h"
#include "base/values.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/user_education/scoped_new_badge_tracker.h"
#include "chrome/grit/generated_resources.h"
#include "components/autofill/content/browser/content_autofill_client.h"
#include "components/autofill/content/browser/content_autofill_driver.h"
#include "components/autofill/core/browser/autofill_feedback_data.h"
#include "components/autofill/core/browser/browser_autofill_manager.h"
#include "components/autofill/core/browser/data_model/autofill_profile.h"
#include "components/autofill/core/browser/form_types.h"
#include "components/autofill/core/browser/metrics/fallback_autocomplete_unrecognized_metrics.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/autofill/core/common/unique_ids.h"
#include "components/feature_engagement/public/feature_constants.h"
#include "components/variations/service/variations_service.h"
#include "components/vector_icons/vector_icons.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/menu_model.h"

namespace autofill {

namespace {

constexpr char kFeedbackPlaceholder[] =
    "What steps did you just take?\n"
    "(1)\n"
    "(2)\n"
    "(3)\n"
    "\n"
    "What was the expected result?\n"
    "\n"
    "What happened instead? (Please include the screenshot below)";

bool ShouldShowAutofillContextMenu(const content::ContextMenuParams& params) {
  if (!params.form_control_type) {
    return false;
  }
  // Return true on text fields.
  // TODO(crbug.com/1492339): Unify with functions from form_autofill_util.cc.
  switch (*params.form_control_type) {
    case blink::mojom::FormControlType::kInputEmail:
    case blink::mojom::FormControlType::kInputMonth:
    case blink::mojom::FormControlType::kInputNumber:
    case blink::mojom::FormControlType::kInputPassword:
    case blink::mojom::FormControlType::kInputSearch:
    case blink::mojom::FormControlType::kInputTelephone:
    case blink::mojom::FormControlType::kInputText:
    case blink::mojom::FormControlType::kInputUrl:
    case blink::mojom::FormControlType::kTextArea:
      return true;
    default:
      return false;
  }
}

base::Value::Dict LoadTriggerFormAndFieldLogs(
    AutofillManager& manager,
    const LocalFrameToken& frame_token,
    const content::ContextMenuParams& params) {
  if (!ShouldShowAutofillContextMenu(params)) {
    return base::Value::Dict();
  }

  FormGlobalId form_global_id = {frame_token,
                                 FormRendererId(params.form_renderer_id)};

  base::Value::Dict trigger_form_logs;
  if (FormStructure* form = manager.FindCachedFormById(form_global_id)) {
    trigger_form_logs.Set("triggerFormSignature", form->FormSignatureAsStr());

    if (params.form_control_type) {
      FieldGlobalId field_global_id = {
          frame_token, FieldRendererId(params.field_renderer_id)};
      auto field =
          base::ranges::find_if(*form, [&field_global_id](const auto& field) {
            return field->global_id() == field_global_id;
          });
      if (field != form->end()) {
        trigger_form_logs.Set("triggerFieldSignature",
                              (*field)->FieldSignatureAsStr());
      }
    }
  }
  return trigger_form_logs;
}

bool IsLikelyDogfoodClient() {
  auto* variations_service = g_browser_process->variations_service();
  if (!variations_service) {
    return false;
  }
  return variations_service->IsLikelyDogfoodClient();
}

}  // namespace

// static
bool AutofillContextMenuManager::IsAutofillCustomCommandId(
    CommandId command_id) {
  const int id = command_id.value();
  return id == IDC_CONTENT_CONTEXT_AUTOFILL_FEEDBACK ||
         id == IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_ADDRESS ||
         id == IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_PAYMENTS;
}

AutofillContextMenuManager::AutofillContextMenuManager(
    PersonalDataManager* personal_data_manager,
    RenderViewContextMenuBase* delegate,
    ui::SimpleMenuModel* menu_model)
    : personal_data_manager_(personal_data_manager),
      menu_model_(menu_model),
      delegate_(delegate) {
  DCHECK(delegate_);
  params_ = delegate_->params();
}

AutofillContextMenuManager::~AutofillContextMenuManager() = default;

void AutofillContextMenuManager::AppendItems() {
  content::RenderFrameHost* rfh = delegate_->GetRenderFrameHost();
  if (!rfh)
    return;

  ContentAutofillDriver* driver =
      ContentAutofillDriver::GetForRenderFrameHost(rfh);
  // Do not show autofill context menu options for input fields that cannot be
  // filled by the driver. See crbug.com/1367547.
  if (!driver || !driver->CanShowAutofillUi())
    return;

  if (ShouldShowAutofillContextMenu(params_)) {
    const LocalFrameToken frame_token = driver->GetFrameToken();
    // Formless fields have default form renderer id.
    driver->OnContextMenuShownInField(
        {frame_token, FormRendererId(params_.form_renderer_id)},
        {frame_token, FieldRendererId(params_.field_renderer_id)});
  }

  // Includes the option of submitting feedback on Autofill.
  if (personal_data_manager_->IsAutofillEnabled() &&
      base::FeatureList::IsEnabled(features::kAutofillFeedback) &&
      IsLikelyDogfoodClient()) {
    menu_model_->AddItemWithStringIdAndIcon(
        IDC_CONTENT_CONTEXT_AUTOFILL_FEEDBACK,
        IDS_CONTENT_CONTEXT_AUTOFILL_FEEDBACK,
        ui::ImageModel::FromVectorIcon(vector_icons::kDogfoodIcon));

    menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);
  }

  MaybeAddAutofillManualFallbackItems(*driver);
}

bool AutofillContextMenuManager::IsCommandIdSupported(int command_id) {
  return IsAutofillCustomCommandId(CommandId(command_id));
}

bool AutofillContextMenuManager::IsCommandIdEnabled(int command_id) {
  return true;
}

void AutofillContextMenuManager::ExecuteCommand(int command_id) {
  content::RenderFrameHost* rfh = delegate_->GetRenderFrameHost();
  if (!rfh) {
    return;
  }
  ContentAutofillDriver* driver =
      ContentAutofillDriver::GetForRenderFrameHost(rfh);
  if (!driver) {
    return;
  }
  AutofillManager& manager = driver->GetAutofillManager();

  CHECK(IsAutofillCustomCommandId(CommandId(command_id)));

  if (command_id == IDC_CONTENT_CONTEXT_AUTOFILL_FEEDBACK) {
    ExecuteAutofillFeedbackCommand(driver->GetFrameToken(), manager);
    return;
  }

  if (command_id == IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_ADDRESS) {
    ExecuteFallbackForAutocompleteUnrecognizedCommand(manager);
    return;
  }

  if (command_id == IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_PAYMENTS) {
    // TODO(crbug.com/1493361): Render payments suggestions.
    NOTIMPLEMENTED();
    return;
  }
}

void AutofillContextMenuManager::ExecuteAutofillFeedbackCommand(
    const LocalFrameToken& frame_token,
    AutofillManager& manager) {
  // The cast is safe since the context menu is only available on Desktop.
  auto& client = static_cast<ContentAutofillClient&>(manager.client());
  Browser* browser = chrome::FindBrowserWithTab(&client.GetWebContents());
  chrome::ShowFeedbackPage(
      browser, chrome::kFeedbackSourceAutofillContextMenu,
      /*description_template=*/std::string(),
      /*description_placeholder_text=*/kFeedbackPlaceholder,
      /*category_tag=*/"dogfood_autofill_feedback",
      /*extra_diagnostics=*/std::string(),
      /*autofill_metadata=*/
      data_logs::FetchAutofillFeedbackData(
          &manager,
          LoadTriggerFormAndFieldLogs(manager, frame_token, params_)));
}

void AutofillContextMenuManager::
    ExecuteFallbackForAutocompleteUnrecognizedCommand(
        AutofillManager& manager) {
  auto& driver = static_cast<ContentAutofillDriver&>(manager.driver());
  if (!ShouldAddAddressManualFallbackForAutocompleteUnrecognized(driver)) {
    // Do nothing if the target field is not on address form field with
    // unrecognized autocomplete attribute fillable with available data.
    // TODO(crbug.com/1493361): Render suggestions for unclassified fields.
    return;
  }
  AutofillField* field = GetAutofillField(manager, driver.GetFrameToken());
  if (!field) {
    // The field should generally exist, since the fallback option is only shown
    // when the field can be retrieved. But if the website removed the field
    // before the entry was select, it might not be available anymore.
    return;
  }
  driver.browser_events().RendererShouldTriggerSuggestions(
      field->global_id(),
      AutofillSuggestionTriggerSource::kManualFallbackAddress);
  static_cast<BrowserAutofillManager&>(manager)
      .GetAutocompleteUnrecognizedFallbackEventLogger()
      .ContextMenuEntryAccepted(
          /*address_field_has_ac_unrecognized=*/field
              ->ShouldSuppressSuggestionsAndFillingByDefault());
}

void AutofillContextMenuManager::MaybeAddAutofillManualFallbackItems(
    ContentAutofillDriver& driver) {
  if (!ShouldShowAutofillContextMenu(params_)) {
    // Autofill entries are only available in input or text area fields
    return;
  }
  const bool add_address_fallback = ShouldAddAddressManualFallbackItem(driver);
  const bool add_payments_fallback =
      !personal_data_manager_->GetCreditCardsToSuggest().empty() &&
      base::FeatureList::IsEnabled(
          features::kAutofillForUnclassifiedFieldsAvailable);

  if (!add_address_fallback && !add_payments_fallback) {
    return;
  }
  menu_model_->AddTitle(
      l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_AUTOFILL_FALLBACK_TITLE));

  if (add_address_fallback) {
    menu_model_->AddItemWithStringId(
        IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_ADDRESS,
        IDS_CONTENT_CONTEXT_AUTOFILL_FALLBACK_ADDRESS);
    LogManualFallbackContextMenuEntryShown(driver);
  }
  if (add_payments_fallback) {
    menu_model_->AddItemWithStringId(
        IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_PAYMENTS,
        IDS_CONTENT_CONTEXT_AUTOFILL_FALLBACK_PAYMENTS);
  }
  menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);
}

bool AutofillContextMenuManager::ShouldAddAddressManualFallbackItem(
    ContentAutofillDriver& driver) {
  if (personal_data_manager_->GetProfilesToSuggest().empty()) {
    return false;
  }

  return ShouldAddAddressManualFallbackForAutocompleteUnrecognized(driver) ||
         base::FeatureList::IsEnabled(
             features::kAutofillForUnclassifiedFieldsAvailable);
}

bool AutofillContextMenuManager::
    ShouldAddAddressManualFallbackForAutocompleteUnrecognized(
        ContentAutofillDriver& driver) {
  if (!base::FeatureList::IsEnabled(
          features::kAutofillFallbackForAutocompleteUnrecognized)) {
    return false;
  }

  AutofillField* field =
      GetAutofillField(driver.GetAutofillManager(), driver.GetFrameToken());

  if (!field || FieldTypeGroupToFormType(field->Type().group()) !=
                    FormType::kAddressForm) {
    return false;
  }

  // Only show the context menu entry for address fields, which can be filled
  // with at least one of the user's profiles.
  CHECK(personal_data_manager_);
  if (base::ranges::none_of(personal_data_manager_->GetProfiles(),
                            [field](AutofillProfile* profile) {
                              return profile->HasInfo(
                                  field->Type().GetStorableType());
                            })) {
    return false;
  }

  // Depending on the Finch parameter, only show the context menu entry for
  // ac=unrecognized fields.
  return field->ShouldSuppressSuggestionsAndFillingByDefault() ||
         features::kAutofillFallForAutocompleteUnrecognizedOnAllAddressField
             .Get();
}

void AutofillContextMenuManager::LogManualFallbackContextMenuEntryShown(
    ContentAutofillDriver& driver) {
  AutofillField* field =
      GetAutofillField(driver.GetAutofillManager(), driver.GetFrameToken());
  CHECK(field);

  static_cast<BrowserAutofillManager&>(driver.GetAutofillManager())
      .GetAutocompleteUnrecognizedFallbackEventLogger()
      .ContextMenuEntryShown(
          /*address_field_has_ac_unrecognized=*/field
              ->ShouldSuppressSuggestionsAndFillingByDefault());
}

AutofillField* AutofillContextMenuManager::GetAutofillField(
    AutofillManager& manager,
    const LocalFrameToken& frame_token) const {
  CHECK(ShouldShowAutofillContextMenu(params_));
  FormStructure* form = manager.FindCachedFormById(
      {frame_token, FormRendererId(params_.form_renderer_id)});
  return form ? form->GetFieldById(
                    {frame_token, FieldRendererId(params_.field_renderer_id)})
              : nullptr;
}

}  // namespace autofill