File: autofill_keyboard_accessory_controller_impl.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (612 lines) | stat: -rw-r--r-- 22,271 bytes parent folder | download | duplicates (3)
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// 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 "chrome/browser/ui/autofill/autofill_keyboard_accessory_controller_impl.h"

#include <algorithm>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>

#include "base/check_op.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/strings/strcat.h"
#include "base/time/time.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/keyboard_accessory/android/manual_filling_controller.h"
#include "chrome/browser/password_manager/android/access_loss/password_access_loss_warning_bridge_impl.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/autofill/autofill_keyboard_accessory_view.h"
#include "chrome/browser/ui/autofill/autofill_popup_view.h"
#include "chrome/browser/ui/autofill/autofill_suggestion_controller_utils.h"
#include "chrome/browser/ui/autofill/next_idle_barrier.h"
#include "components/autofill/core/browser/data_manager/addresses/address_data_manager.h"
#include "components/autofill/core/browser/data_manager/payments/payments_data_manager.h"
#include "components/autofill/core/browser/data_manager/personal_data_manager.h"
#include "components/autofill/core/browser/filling/filling_product.h"
#include "components/autofill/core/browser/suggestions/suggestion_hiding_reason.h"
#include "components/autofill/core/browser/suggestions/suggestion_type.h"
#include "components/autofill/core/browser/ui/autofill_suggestion_delegate.h"
#include "components/autofill/core/browser/ui/popup_open_enums.h"
#include "components/password_manager/core/browser/password_manager_metrics_util.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/l10n/l10n_util.h"

namespace autofill {

namespace {

using FillingSource = ManualFillingController::FillingSource;

constexpr std::u16string_view kLabelSeparator = u" ";
constexpr size_t kMaxBulletCount = 8;

// Creates a text label used by the keyboard accessory. For password
// suggestions, constructs the label from the password stored in
// `Suggestion::additional_label` and an optional signon realm stored in
// `Suggestion::labels`. For other suggestions, constructs the label from
// `Suggestion::labels`.
Suggestion::Text CreateLabel(const Suggestion& suggestion) {
  if (suggestion.labels.empty()) {
    return Suggestion::Text();
  }
  // TODO(crbug.com/40221039): Re-consider whether using CHECK is an appropriate
  // way to explicitly regulate what information should be populated for the
  // interface.
  CHECK_EQ(suggestion.labels.size(), 1U);
  CHECK_EQ(suggestion.labels[0].size(), 1U);
  if (GetFillingProductFromSuggestionType(suggestion.type) ==
      FillingProduct::kPassword) {
    // The `Suggestion::labels` can never be empty since it must contain a
    // password.
    const std::u16string password =
        suggestion.labels[0][0].value.substr(0, kMaxBulletCount);

    // The `Suggestion::additional_label` contains the signon_realm or is empty.
    if (suggestion.additional_label.empty()) {
      return Suggestion::Text(password);
    }
    return Suggestion::Text(
        base::StrCat({suggestion.additional_label, kLabelSeparator, password}));
  }

  return Suggestion::Text(suggestion.labels[0][0].value);
}

}  // namespace

// static
base::WeakPtr<AutofillSuggestionController>
AutofillSuggestionController::GetOrCreate(
    base::WeakPtr<AutofillSuggestionController> previous,
    base::WeakPtr<AutofillSuggestionDelegate> delegate,
    content::WebContents* web_contents,
    PopupControllerCommon controller_common,
    int32_t form_control_ax_id) {
  // All controllers on Android derive from
  // `AutofillKeyboardAccessoryControllerImpl`.
  if (AutofillKeyboardAccessoryControllerImpl* previous_impl =
          static_cast<AutofillKeyboardAccessoryControllerImpl*>(previous.get());
      previous_impl && previous_impl->delegate_.get() == delegate.get() &&
      previous_impl->container_view() == controller_common.container_view) {
    if (previous_impl->self_deletion_weak_ptr_factory_.HasWeakPtrs()) {
      previous_impl->self_deletion_weak_ptr_factory_.InvalidateWeakPtrs();
    }
    previous_impl->controller_common_ = std::move(controller_common);
    previous_impl->suggestions_.clear();
    return previous_impl->GetWeakPtr();
  }

  if (previous) {
    previous->Hide(SuggestionHidingReason::kViewDestroyed);
  }
  auto* controller = new AutofillKeyboardAccessoryControllerImpl(
      delegate, web_contents, std::move(controller_common));
  return controller->GetWeakPtr();
}

AutofillKeyboardAccessoryControllerImpl::
    AutofillKeyboardAccessoryControllerImpl(
        base::WeakPtr<AutofillSuggestionDelegate> delegate,
        content::WebContents* web_contents,
        PopupControllerCommon controller_common)
    : delegate_(delegate),
      web_contents_(web_contents->GetWeakPtr()),
      controller_common_(std::move(controller_common)) {}

AutofillKeyboardAccessoryControllerImpl::
    ~AutofillKeyboardAccessoryControllerImpl() = default;

void AutofillKeyboardAccessoryControllerImpl::Hide(
    SuggestionHidingReason reason) {
  // For tests, keep open when hiding is due to external stimuli.
  if (keep_popup_open_for_testing_ &&
      (reason == SuggestionHidingReason::kWidgetChanged ||
       reason == SuggestionHidingReason::kEndEditing)) {
    // Don't close the popup because the browser window is resized or because
    // too many fields get focus one after each other (this can happen on
    // Desktop, if multiple password forms are present, and they are all
    // autofilled by default).
    return;
  }

  if (delegate_) {
    delegate_->ClearPreviewedForm();
    delegate_->OnSuggestionsHidden();
  }
  popup_hide_helper_.reset();
  AutofillMetrics::LogAutofillSuggestionHidingReason(
      suggestions_filling_product_, reason);
  HideViewAndDie();
}

void AutofillKeyboardAccessoryControllerImpl::HideViewAndDie() {
  // Invalidates in particular ChromeAutofillClient's WeakPtr to `this`, which
  // prevents recursive calls triggered by `view_->Hide()`
  // (crbug.com/1267047).
  weak_ptr_factory_.InvalidateWeakPtrs();

  // Mark the popup-like filling sources as unavailable.
  // Note: We don't invoke ManualFillingController::Hide() here, as we might
  // switch between text input fields.
  if (web_contents_) {
    if (base::WeakPtr<ManualFillingController> manual_filling_controller =
            ManualFillingController::GetOrCreate(web_contents_.get())) {
      manual_filling_controller->UpdateSourceAvailability(
          FillingSource::AUTOFILL,
          /*has_suggestions=*/false);
    }
  }

  // TODO(crbug.com/1341374, crbug.com/1277218): Move this into the asynchronous
  // call?
  if (view_) {
    view_->Hide();
    view_.reset();
  }

  if (self_deletion_weak_ptr_factory_.HasWeakPtrs()) {
    return;
  }

  // TODO: Examine whether this is really enough or revert to the one from
  // the popup controller.
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(
          [](base::WeakPtr<AutofillKeyboardAccessoryControllerImpl> weak_this) {
            delete weak_this.get();
          },
          self_deletion_weak_ptr_factory_.GetWeakPtr()));
}

void AutofillKeyboardAccessoryControllerImpl::ViewDestroyed() {
  Hide(SuggestionHidingReason::kViewDestroyed);
}

gfx::NativeView AutofillKeyboardAccessoryControllerImpl::container_view()
    const {
  return controller_common_.container_view;
}

content::WebContents* AutofillKeyboardAccessoryControllerImpl::GetWebContents()
    const {
  return web_contents_.get();
}

const gfx::RectF& AutofillKeyboardAccessoryControllerImpl::element_bounds()
    const {
  return controller_common_.element_bounds;
}

PopupAnchorType AutofillKeyboardAccessoryControllerImpl::anchor_type() const {
  return controller_common_.anchor_type;
}

base::i18n::TextDirection
AutofillKeyboardAccessoryControllerImpl::GetElementTextDirection() const {
  return controller_common_.text_direction;
}

void AutofillKeyboardAccessoryControllerImpl::OnSuggestionsChanged() {
  // Assume that suggestions are (still) available. If this is wrong, the method
  // `HideViewAndDie` will be called soon after and will hide all suggestions.
  if (base::WeakPtr<ManualFillingController> manual_filling_controller =
          ManualFillingController::GetOrCreate(web_contents_.get())) {
    manual_filling_controller->UpdateSourceAvailability(
        FillingSource::AUTOFILL,
        /*has_suggestions=*/true);
  }
  if (view_) {
    view_->Show();
  }
}

void AutofillKeyboardAccessoryControllerImpl::AcceptSuggestion(int index) {
  // Ignore clicks immediately after the popup was shown. This is to prevent
  // users accidentally accepting suggestions (crbug.com/1279268).
  if (!barrier_for_accepting_.value() && !disable_threshold_for_testing_) {
    return;
  }

  if (base::checked_cast<size_t>(index) >= suggestions_.size() ||
      !IsAcceptableSuggestionType(suggestions_[index].type)) {
    // Prevents crashes from crbug.com/521133. It seems that in rare cases or
    // races the suggestions_ and the user-selected index may be out of sync.
    // If the index points out of bounds, Chrome will crash. Prevent this by
    // ignoring the selection and wait for another signal from the user.
    return;
  }
  if (IsPointerLocked(web_contents_.get())) {
    Hide(SuggestionHidingReason::kMouseLocked);
    return;
  }

  // Use a copy instead of a reference here. Under certain circumstances,
  // `DidAcceptSuggestion()` invalidate the reference.
  Suggestion suggestion = suggestions_[index];
  if (!suggestion.IsAcceptable()) {
    return;
  }

  if (base::WeakPtr<ManualFillingController> manual_filling_controller =
          ManualFillingController::GetOrCreate(web_contents_.get())) {
    // Accepting a suggestion should hide all suggestions. To prevent them from
    // coming up in Multi-Window mode, mark the source as unavailable.
    manual_filling_controller->UpdateSourceAvailability(
        FillingSource::AUTOFILL,
        /*has_suggestions=*/false);
    manual_filling_controller->Hide();
  }

  NotifyUserEducationAboutAcceptedSuggestion(web_contents_.get(), suggestion);
  if (suggestion.acceptance_a11y_announcement && view_) {
    view_->AxAnnounce(*suggestion.acceptance_a11y_announcement);
  }

  delegate_->DidAcceptSuggestion(
      suggestion, AutofillSuggestionDelegate::SuggestionMetadata{.row = index});

  if (suggestion.type != SuggestionType::kPasswordEntry) {
    // Returning early because the code below triggers the UI which is shown
    // after accepting passwords.
    return;
  }

  Profile* profile =
      Profile::FromBrowserContext(web_contents_->GetBrowserContext());
  if (!access_loss_warning_bridge_) {
    access_loss_warning_bridge_ =
        std::make_unique<PasswordAccessLossWarningBridgeImpl>();
  }
  if (profile && access_loss_warning_bridge_->ShouldShowAccessLossNoticeSheet(
                     profile->GetPrefs(), /*called_at_startup=*/false)) {
    access_loss_warning_bridge_->MaybeShowAccessLossNoticeSheet(
        profile->GetPrefs(), web_contents_->GetTopLevelNativeWindow(), profile,
        /*called_at_startup=*/false,
        password_manager_android_util::PasswordAccessLossWarningTriggers::
            kKeyboardAcessoryBar);
  }
}

bool AutofillKeyboardAccessoryControllerImpl::RemoveSuggestion(
    int index,
    AutofillMetrics::SingleEntryRemovalMethod removal_method) {
  CHECK_EQ(removal_method,
           AutofillMetrics::SingleEntryRemovalMethod::kKeyboardAccessory);
  std::u16string title;
  std::u16string body;
  if (!GetRemovalConfirmationText(index, &title, &body)) {
    return false;
  }

  view_->ConfirmDeletion(
      title, body,
      base::BindOnce(
          &AutofillKeyboardAccessoryControllerImpl::OnDeletionDialogClosed,
          GetWeakPtr(), index));
  return true;
}

void AutofillKeyboardAccessoryControllerImpl::OnDeletionDialogClosed(
    int index,
    bool confirmed) {
  // This function might be called in a callback, so ensure the list index is
  // still in bounds. If not, terminate the removing and consider it failed.
  // TODO(crbug.com/40766704): Replace these checks with a stronger identifier.
  if (base::checked_cast<size_t>(index) >= suggestions_.size()) {
    return;
  }
  CHECK_EQ(suggestions_.size(), labels_.size());

  const FillingProduct filling_product =
      GetFillingProductFromSuggestionType(GetSuggestionAt(index).type);
  if (!confirmed) {
    return;
  }

  if (!delegate_->RemoveSuggestion(suggestions_[index])) {
    return;
  }
  switch (filling_product) {
    case FillingProduct::kAddress:
      AutofillMetrics::LogDeleteAddressProfileFromKeyboardAccessory();
      break;
    case FillingProduct::kAutocomplete:
      AutofillMetrics::OnAutocompleteSuggestionDeleted(
          AutofillMetrics::SingleEntryRemovalMethod::kKeyboardAccessory);
      if (view_) {
        view_->AxAnnounce(l10n_util::GetStringFUTF16(
            IDS_AUTOFILL_AUTOCOMPLETE_ENTRY_DELETED_A11Y_HINT,
            suggestions_[index].main_text.value));
      }
      break;
    case FillingProduct::kCreditCard:
      // TODO(crbug.com/41482065): Add metrics for credit cards.
      break;
    case FillingProduct::kNone:
    case FillingProduct::kMerchantPromoCode:
    case FillingProduct::kIban:
    case FillingProduct::kPassword:
    case FillingProduct::kCompose:
    case FillingProduct::kPlusAddresses:
    case FillingProduct::kAutofillAi:
    case FillingProduct::kLoyaltyCard:
    case FillingProduct::kIdentityCredential:
      break;
  }

  // Remove the deleted element.
  suggestions_.erase(suggestions_.begin() + index);
  labels_.erase(labels_.begin() + index);

  if (HasSuggestions()) {
    delegate_->ClearPreviewedForm();
    OnSuggestionsChanged();
  } else {
    Hide(SuggestionHidingReason::kNoSuggestions);
  }
}

int AutofillKeyboardAccessoryControllerImpl::GetLineCount() const {
  return suggestions_.size();
}

const std::vector<Suggestion>&
AutofillKeyboardAccessoryControllerImpl::GetSuggestions() const {
  return suggestions_;
}

const Suggestion& AutofillKeyboardAccessoryControllerImpl::GetSuggestionAt(
    int row) const {
  return suggestions_[row];
}

FillingProduct AutofillKeyboardAccessoryControllerImpl::GetMainFillingProduct()
    const {
  return delegate_->GetMainFillingProduct();
}

std::optional<AutofillClient::PopupScreenLocation>
AutofillKeyboardAccessoryControllerImpl::GetPopupScreenLocation() const {
  return std::nullopt;
}

void AutofillKeyboardAccessoryControllerImpl::Show(
    UiSessionId ui_session_id,
    std::vector<Suggestion> suggestions,
    AutofillSuggestionTriggerSource trigger_source,
    AutoselectFirstSuggestion autoselect_first_suggestion) {
  ui_session_id_ = ui_session_id;
  suggestions_filling_product_ =
      !suggestions.empty() && IsStandaloneSuggestionType(suggestions[0].type)
          ? GetFillingProductFromSuggestionType(suggestions[0].type)
          : FillingProduct::kNone;
  if (auto* rwhv = web_contents_->GetRenderWidgetHostView();
      !rwhv || !rwhv->HasFocus()) {
    Hide(SuggestionHidingReason::kNoFrameHasFocus);
    return;
  }

  // The focused frame may be a different frame than the one the delegate is
  // associated with. This happens in two scenarios:
  // - With frame-transcending forms: the focused frame is subframe, whose
  //   form has been flattened into an ancestor form.
  // - With race conditions: while Autofill parsed the form, the focused may
  //   have moved to another frame.
  // We support the case where the focused frame is a descendant of the
  // `delegate_`'s frame. We observe the focused frame's RenderFrameDeleted()
  // event.
  content::RenderFrameHost* rfh = web_contents_->GetFocusedFrame();
  if (!rfh || !delegate_ ||
      !IsAncestorOf(GetRenderFrameHost(*delegate_), rfh)) {
    Hide(SuggestionHidingReason::kNoFrameHasFocus);
    return;
  }

  if (IsPointerLocked(web_contents_.get())) {
    Hide(SuggestionHidingReason::kMouseLocked);
    return;
  }

  AutofillPopupHideHelper::HidingParams hiding_params = {
      .hide_on_web_contents_lost_focus = true};
  AutofillPopupHideHelper::HidingCallback hiding_callback = base::BindRepeating(
      &AutofillKeyboardAccessoryControllerImpl::Hide, base::Unretained(this));
  // TODO(crbug.com/40280362): Implement PIP hiding for Android.
  popup_hide_helper_.emplace(
      web_contents_.get(), rfh->GetGlobalId(), std::move(hiding_params),
      std::move(hiding_callback),
      /*pip_detection_callback=*/base::BindRepeating([] { return false; }));

  suggestions_ = std::move(suggestions);
  OrderSuggestionsAndCreateLabels();
  trigger_source_ = trigger_source;

  if (view_) {
    OnSuggestionsChanged();
  } else {
    view_ = AutofillKeyboardAccessoryView::Create(GetWeakPtr());
    // It is possible to fail to create the accessory view.
    if (!view_) {
      Hide(SuggestionHidingReason::kViewDestroyed);
      return;
    }

    if (base::WeakPtr<ManualFillingController> manual_filling_controller =
            ManualFillingController::GetOrCreate(web_contents_.get())) {
      manual_filling_controller->UpdateSourceAvailability(
          FillingSource::AUTOFILL, !suggestions_.empty());
    }
    if (view_) {
      view_->Show();
    }
  }

  barrier_for_accepting_ = NextIdleBarrier::CreateNextIdleBarrierWithDelay(
      kIgnoreEarlyClicksOnSuggestionsDuration);
  // TODO(crbug.com/364165357): Use actually shown suggestions.
  delegate_->OnSuggestionsShown(suggestions_);
}

std::optional<AutofillSuggestionController::UiSessionId>
AutofillKeyboardAccessoryControllerImpl::GetUiSessionId() const {
  return view_ ? std::make_optional(ui_session_id_) : std::nullopt;
}

void AutofillKeyboardAccessoryControllerImpl::SetKeepPopupOpenForTesting(
    bool keep_popup_open_for_testing) {
  keep_popup_open_for_testing_ = keep_popup_open_for_testing;
}

void AutofillKeyboardAccessoryControllerImpl::UpdateDataListValues(
    base::span<const SelectOption> options) {
  suggestions_ =
      UpdateSuggestionsFromDataList(options, std::move(suggestions_));
  OrderSuggestionsAndCreateLabels();
  if (HasSuggestions()) {
    OnSuggestionsChanged();
  } else {
    Hide(SuggestionHidingReason::kNoSuggestions);
  }
}

bool AutofillKeyboardAccessoryControllerImpl::HasSuggestions() const {
  return !suggestions_.empty() &&
         IsStandaloneSuggestionType(suggestions_[0].type);
}

// AutofillKeyboardAccessoryController implementation:

std::vector<std::vector<Suggestion::Text>>
AutofillKeyboardAccessoryControllerImpl::GetSuggestionLabelsAt(int row) const {
  CHECK_LT(base::checked_cast<size_t>(row), labels_.size());
  return {{labels_[row]}};
}

bool AutofillKeyboardAccessoryControllerImpl::GetRemovalConfirmationText(
    int index,
    std::u16string* title,
    std::u16string* body) {
  CHECK_LT(base::checked_cast<size_t>(index), suggestions_.size());
  const std::u16string& value = suggestions_[index].main_text.value;
  const SuggestionType type = suggestions_[index].type;
  const Suggestion::Payload& payload = suggestions_[index].payload;

  if (type == SuggestionType::kAutocompleteEntry) {
    if (title) {
      title->assign(value);
    }
    if (body) {
      body->assign(l10n_util::GetStringUTF16(
          IDS_AUTOFILL_DELETE_AUTOCOMPLETE_SUGGESTION_CONFIRMATION_BODY));
    }
    return true;
  }

  if (type != SuggestionType::kAddressEntry &&
      type != SuggestionType::kCreditCardEntry) {
    return false;
  }
  PersonalDataManager* pdm = PersonalDataManagerFactory::GetForBrowserContext(
      web_contents_->GetBrowserContext());

  if (std::holds_alternative<Suggestion::Guid>(payload)) {
    if (const CreditCard* credit_card =
            pdm->payments_data_manager().GetCreditCardByGUID(
                std::get<Suggestion::Guid>(payload).value())) {
      if (!CreditCard::IsLocalCard(credit_card)) {
        return false;
      }
      if (title) {
        title->assign(credit_card->CardNameAndLastFourDigits());
      }
      if (body) {
        body->assign(l10n_util::GetStringUTF16(
            IDS_AUTOFILL_DELETE_CREDIT_CARD_SUGGESTION_CONFIRMATION_BODY));
      }
      return true;
    }
    return false;
  }

  if (std::holds_alternative<Suggestion::AutofillProfilePayload>(payload)) {
    if (const AutofillProfile* profile =
            pdm->address_data_manager().GetProfileByGUID(
                std::get<Suggestion::AutofillProfilePayload>(payload)
                    .guid.value())) {
      // Home & Work addresses can't be deleted through the chrome UI.
      switch (profile->record_type()) {
        case AutofillProfile::RecordType::kAccountHome:
        case AutofillProfile::RecordType::kAccountWork:
          return false;
        case AutofillProfile::RecordType::kLocalOrSyncable:
        case AutofillProfile::RecordType::kAccount:
          break;
      }

      if (title) {
        std::u16string street_address = profile->GetRawInfo(ADDRESS_HOME_CITY);
        if (!street_address.empty()) {
          title->swap(street_address);
        } else {
          title->assign(value);
        }
      }
      if (body) {
        body->assign(l10n_util::GetStringUTF16(
            IDS_AUTOFILL_DELETE_PROFILE_SUGGESTION_CONFIRMATION_BODY));
      }

      return true;
    }
    return false;
  }

  return false;  // The ID was valid. The entry may have been deleted in a race.
}

void AutofillKeyboardAccessoryControllerImpl::
    OrderSuggestionsAndCreateLabels() {
  // If there is an Undo suggestion, move it to the front.
  if (auto it = std::ranges::find(suggestions_, SuggestionType::kUndoOrClear,
                                  &Suggestion::type);
      it != suggestions_.end()) {
    std::rotate(suggestions_.begin(), it, it + 1);
  }

  labels_.clear();
  labels_.reserve(suggestions_.size());
  for (const Suggestion& suggestion : suggestions_) {
    labels_.push_back(CreateLabel(suggestion));
  }
}

}  // namespace autofill