File: save_card_bubble_controller_impl.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (857 lines) | stat: -rw-r--r-- 31,825 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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
// Copyright 2015 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/payments/save_card_bubble_controller_impl.h"

#include <stddef.h>

#include <optional>
#include <string>
#include <utility>

#include "base/auto_reset.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/account_consistency_mode_manager.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/ui/autofill/autofill_bubble_base.h"
#include "chrome/browser/ui/autofill/autofill_bubble_controller_base.h"
#include "chrome/browser/ui/autofill/autofill_bubble_handler.h"
#include "chrome/browser/ui/autofill/payments/payments_ui_constants.h"
#include "chrome/browser/ui/autofill/payments/save_card_ui.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/hats/trust_safety_sentiment_service.h"
#include "chrome/browser/ui/hats/trust_safety_sentiment_service_factory.h"
#include "chrome/browser/ui/location_bar/location_bar.h"
#include "chrome/browser/ui/page_action/page_action_icon_type.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.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/metrics/autofill_metrics.h"
#include "components/autofill/core/browser/metrics/payments/credit_card_save_metrics.h"
#include "components/autofill/core/browser/metrics/payments/manage_cards_prompt_metrics.h"
#include "components/autofill/core/browser/payments/payments_autofill_client.h"
#include "components/autofill/core/browser/studies/autofill_experiments.h"
#include "components/autofill/core/browser/ui/payments/payments_ui_closed_reasons.h"
#include "components/autofill/core/browser/ui/payments/save_payment_method_and_virtual_card_enroll_confirmation_ui_params.h"
#include "components/autofill/core/common/autofill_clock.h"
#include "components/autofill/core/common/autofill_constants.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/autofill/core/common/autofill_payments_features.h"
#include "components/signin/public/base/signin_buildflags.h"
#include "components/signin/public/base/signin_pref_names.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/strings/grit/components_strings.h"
#include "components/sync/service/sync_service.h"
#include "content/public/browser/navigation_handle.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"

namespace autofill {

static bool g_ignore_window_activation_for_testing = false;

SaveCardBubbleControllerImpl::SaveCardBubbleControllerImpl(
    content::WebContents* web_contents)
    : AutofillBubbleControllerBase(web_contents),
      content::WebContentsUserData<SaveCardBubbleControllerImpl>(*web_contents),
      payments_data_manager_(PersonalDataManagerFactory::GetForBrowserContext(
                                 web_contents->GetBrowserContext())
                                 ->payments_data_manager()),
      sync_service_(SyncServiceFactory::GetForProfile(
          Profile::FromBrowserContext(web_contents->GetBrowserContext()))) {}

SaveCardBubbleControllerImpl::~SaveCardBubbleControllerImpl() = default;

// static
SaveCardBubbleController* SaveCardBubbleController::GetOrCreate(
    content::WebContents* web_contents) {
  if (!web_contents) {
    return nullptr;
  }

  SaveCardBubbleControllerImpl::CreateForWebContents(web_contents);
  return SaveCardBubbleControllerImpl::FromWebContents(web_contents);
}

void SaveCardBubbleControllerImpl::OfferLocalSave(
    const CreditCard& card,
    payments::PaymentsAutofillClient::SaveCreditCardOptions options,
    payments::PaymentsAutofillClient::LocalSaveCardPromptCallback
        save_card_prompt_callback) {
  // If the confirmation view is still showing, close it before showing the new
  // offer.
  if (current_bubble_type_ == BubbleType::UPLOAD_COMPLETED) {
    HideBubble();
  }

  // Don't show the bubble if it's already visible.
  if (bubble_view()) {
    return;
  }

  is_upload_save_ = false;
  is_reshow_ = false;
  is_triggered_by_user_gesture_ = false;
  options_ = options;
  card_ = card;
  local_save_card_prompt_callback_ = std::move(save_card_prompt_callback);
  legal_message_lines_.clear();
  current_bubble_type_ =
      options.card_save_type ==
              payments::PaymentsAutofillClient::CardSaveType::kCvcSaveOnly
          ? BubbleType::LOCAL_CVC_SAVE
          : BubbleType::LOCAL_SAVE;

  if (options.show_prompt) {
    ShowBubble();
  } else {
    ShowIconOnly();
  }
}

void SaveCardBubbleControllerImpl::OfferUploadSave(
    const CreditCard& card,
    const LegalMessageLines& legal_message_lines,
    payments::PaymentsAutofillClient::SaveCreditCardOptions options,
    payments::PaymentsAutofillClient::UploadSaveCardPromptCallback
        save_card_prompt_callback) {
  // If the confirmation view is still showing, close it before showing the new
  // offer.
  if (current_bubble_type_ == BubbleType::UPLOAD_COMPLETED) {
    HideBubble();
  }

  // Don't show the bubble if it's already visible.
  if (bubble_view()) {
    return;
  }

  is_upload_save_ = true;
  is_reshow_ = false;
  is_triggered_by_user_gesture_ = false;
  options_ = options;
  card_ = card;
  upload_save_card_prompt_callback_ = std::move(save_card_prompt_callback);
  current_bubble_type_ =
      options.card_save_type ==
              payments::PaymentsAutofillClient::CardSaveType::kCvcSaveOnly
          ? BubbleType::UPLOAD_CVC_SAVE
          : BubbleType::UPLOAD_SAVE;

  // Reset legal_message_lines for CVC only upload as there is no legal message
  // for this case.
  // TODO(crbug.com/40931101): Refactor ShowSaveCreditCardToCloud to change
  // legal_message_lines_ to optional.
  if (current_bubble_type_ == BubbleType::UPLOAD_CVC_SAVE) {
    legal_message_lines_.clear();
  } else {
    legal_message_lines_ = legal_message_lines;
  }

  if (options_.show_prompt) {
    ShowBubble();
  } else {
    ShowIconOnly();
  }
}

// Exists for testing purposes only.
void SaveCardBubbleControllerImpl::ShowBubbleForManageCardsForTesting(
    const CreditCard& card) {
  card_ = card;
  current_bubble_type_ = BubbleType::MANAGE_CARDS;
  ShowBubble();
}

void SaveCardBubbleControllerImpl::ReshowBubble(
    bool is_triggered_by_user_gesture) {
  // Don't show the bubble if it's already visible.
  if (bubble_view()) {
    return;
  }

  is_reshow_ = true;
  is_triggered_by_user_gesture_ = is_triggered_by_user_gesture;
  ShowBubble();
}

void SaveCardBubbleControllerImpl::ShowConfirmationBubbleView(
    bool card_saved,
    std::optional<
        payments::PaymentsAutofillClient::OnConfirmationClosedCallback>
        on_confirmation_closed_callback) {
  // Hide the current bubble if still showing.
  HideBubble();

  is_reshow_ = false;
  is_triggered_by_user_gesture_ = false;
  current_bubble_type_ = BubbleType::UPLOAD_COMPLETED;
  confirmation_ui_params_ =
      card_saved ? SavePaymentMethodAndVirtualCardEnrollConfirmationUiParams::
                       CreateForSaveCardSuccess()
                 : SavePaymentMethodAndVirtualCardEnrollConfirmationUiParams::
                       CreateForSaveCardFailure();
  on_confirmation_closed_callback_ = std::move(on_confirmation_closed_callback);

  // Show upload confirmation bubble.
  ShowBubble();

  // Auto close confirmation bubble when card saved is successful.
  if (card_saved) {
    auto_close_confirmation_timer_.Start(
        FROM_HERE, kAutoCloseConfirmationBubbleWaitSec,
        base::BindOnce(&SaveCardBubbleControllerImpl::HideSaveCardBubble,
                       weak_ptr_factory_.GetWeakPtr()));
  }
}

base::OnceClosure SaveCardBubbleControllerImpl::
    GetShowConfirmationForCardSuccessfullySavedCallback() {
  return base::BindOnce(
      &SaveCardBubbleControllerImpl::ShowConfirmationBubbleView,
      weak_ptr_factory_.GetWeakPtr(), true, std::nullopt);
}

base::OnceClosure
SaveCardBubbleControllerImpl::GetEndSaveCardPromptFlowCallback() {
  return base::BindOnce(&SaveCardBubbleControllerImpl::EndSaveCardPromptFlow,
                        weak_ptr_factory_.GetWeakPtr());
}

std::u16string SaveCardBubbleControllerImpl::GetWindowTitle() const {
  switch (current_bubble_type_) {
    case BubbleType::LOCAL_SAVE:
      return l10n_util::GetStringUTF16(
          IDS_AUTOFILL_SAVE_CARD_PROMPT_TITLE_LOCAL);
    case BubbleType::LOCAL_CVC_SAVE:
      return l10n_util::GetStringUTF16(
          IDS_AUTOFILL_SAVE_CVC_PROMPT_TITLE_LOCAL);
    case BubbleType::UPLOAD_SAVE:
    case BubbleType::UPLOAD_IN_PROGRESS:
      return l10n_util::GetStringUTF16(
          IDS_AUTOFILL_SAVE_CARD_PROMPT_TITLE_TO_CLOUD_SECURITY);
    case BubbleType::UPLOAD_CVC_SAVE:
      return l10n_util::GetStringUTF16(
          IDS_AUTOFILL_SAVE_CVC_PROMPT_TITLE_TO_CLOUD);
    case BubbleType::MANAGE_CARDS:
      return l10n_util::GetStringUTF16(
          options_.card_save_type ==
                  payments::PaymentsAutofillClient::CardSaveType::kCvcSaveOnly
              ? IDS_AUTOFILL_CVC_SAVED
              : IDS_AUTOFILL_CARD_SAVED);
    case BubbleType::UPLOAD_COMPLETED:
    case BubbleType::INACTIVE:
      NOTREACHED();
  }
}

std::u16string SaveCardBubbleControllerImpl::GetExplanatoryMessage() const {
  if (current_bubble_type_ == BubbleType::LOCAL_SAVE &&
      base::FeatureList::IsEnabled(
          features::kAutofillEnableCvcStorageAndFilling)) {
    CHECK_NE(options_.card_save_type,
             payments::PaymentsAutofillClient::CardSaveType::kCvcSaveOnly);
    return l10n_util::GetStringUTF16(
        options_.card_save_type ==
                payments::PaymentsAutofillClient::CardSaveType::kCardSaveOnly
            ? IDS_AUTOFILL_SAVE_CARD_ONLY_PROMPT_EXPLANATION_LOCAL
            : IDS_AUTOFILL_SAVE_CARD_WITH_CVC_PROMPT_EXPLANATION_LOCAL);
  }

  if (current_bubble_type_ == BubbleType::LOCAL_CVC_SAVE) {
    return l10n_util::GetStringUTF16(
        IDS_AUTOFILL_SAVE_CVC_PROMPT_EXPLANATION_LOCAL);
  }

  if (current_bubble_type_ == BubbleType::UPLOAD_CVC_SAVE) {
    return l10n_util::GetStringUTF16(
        IDS_AUTOFILL_SAVE_CVC_PROMPT_EXPLANATION_UPLOAD);
  }

  if (current_bubble_type_ != BubbleType::UPLOAD_SAVE &&
      current_bubble_type_ != BubbleType::UPLOAD_IN_PROGRESS) {
    return std::u16string();
  }

  return l10n_util::GetStringUTF16(
      IDS_AUTOFILL_SAVE_CARD_PROMPT_UPLOAD_EXPLANATION_SECURITY);
}

std::u16string SaveCardBubbleControllerImpl::GetAcceptButtonText() const {
  switch (current_bubble_type_) {
    case BubbleType::LOCAL_SAVE:
    case BubbleType::LOCAL_CVC_SAVE:
      return l10n_util::GetStringUTF16(
          IDS_AUTOFILL_SAVE_CARD_BUBBLE_LOCAL_SAVE_ACCEPT);
    case BubbleType::UPLOAD_SAVE:
    case BubbleType::UPLOAD_CVC_SAVE:
      return l10n_util::GetStringUTF16(
          IDS_AUTOFILL_SAVE_CARD_BUBBLE_UPLOAD_SAVE_ACCEPT);
    case BubbleType::MANAGE_CARDS:
      return l10n_util::GetStringUTF16(IDS_AUTOFILL_DONE);
    case BubbleType::UPLOAD_IN_PROGRESS:
    case BubbleType::UPLOAD_COMPLETED:
    case BubbleType::INACTIVE:
      return std::u16string();
  }
}

std::u16string SaveCardBubbleControllerImpl::GetDeclineButtonText() const {
  switch (current_bubble_type_) {
    case BubbleType::LOCAL_SAVE:
    case BubbleType::LOCAL_CVC_SAVE:
      return l10n_util::GetStringUTF16(
          IDS_AUTOFILL_NO_THANKS_DESKTOP_LOCAL_SAVE);
    case BubbleType::UPLOAD_SAVE:
    case BubbleType::UPLOAD_CVC_SAVE:
      return l10n_util::GetStringUTF16(
          IDS_AUTOFILL_NO_THANKS_DESKTOP_UPLOAD_SAVE);
    case BubbleType::UPLOAD_IN_PROGRESS:
    case BubbleType::UPLOAD_COMPLETED:
    case BubbleType::MANAGE_CARDS:
    case BubbleType::INACTIVE:
      return std::u16string();
  }
}

AccountInfo SaveCardBubbleControllerImpl::GetAccountInfo() {
  // The results of this call should not be cached because the user can update
  // their account info at any time.
  Profile* profile = GetProfile();
  if (!profile) {
    return AccountInfo();
  }
  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(profile);
  if (!identity_manager) {
    return AccountInfo();
  }

  return identity_manager->FindExtendedAccountInfo(
      payments_data_manager_->GetAccountInfoForPaymentsServer());
}

Profile* SaveCardBubbleControllerImpl::GetProfile() const {
  if (!web_contents()) {
    return nullptr;
  }
  return Profile::FromBrowserContext(web_contents()->GetBrowserContext());
}

const CreditCard& SaveCardBubbleControllerImpl::GetCard() const {
  return card_;
}

base::OnceCallback<void(PaymentsUiClosedReason)>
SaveCardBubbleControllerImpl::GetOnBubbleClosedCallback() {
  return base::BindOnce(&SaveCardBubbleControllerImpl::OnBubbleClosed,
                        weak_ptr_factory_.GetWeakPtr());
}

const SavePaymentMethodAndVirtualCardEnrollConfirmationUiParams&
SaveCardBubbleControllerImpl::GetConfirmationUiParams() const {
  CHECK(confirmation_ui_params_.has_value());
  return confirmation_ui_params_.value();
}

bool SaveCardBubbleControllerImpl::ShouldRequestNameFromUser() const {
  return options_.should_request_name_from_user;
}

bool SaveCardBubbleControllerImpl::ShouldRequestExpirationDateFromUser() const {
  return options_.should_request_expiration_date_from_user;
}

ui::ImageModel SaveCardBubbleControllerImpl::GetCreditCardImage() const {
  const gfx::Image* const card_art_image =
      payments_data_manager_->GetCachedCardArtImageForUrl(card_.card_art_url());
  return ui::ImageModel::FromImage(
      card_art_image ? *card_art_image
                     : ui::ResourceBundle::GetSharedInstance().GetImageNamed(
                           CreditCard::IconResourceId(card_.network())));
}

void SaveCardBubbleControllerImpl::OnSaveButton(
    const payments::PaymentsAutofillClient::UserProvidedCardDetails&
        user_provided_card_details) {
  switch (current_bubble_type_) {
    case BubbleType::UPLOAD_SAVE: {
      CHECK(!upload_save_card_prompt_callback_.is_null());
      if (auto* sentiment_service =
              TrustSafetySentimentServiceFactory::GetForProfile(GetProfile())) {
        sentiment_service->SavedCard();
      }
      std::u16string name_provided_by_user;
      if (!user_provided_card_details.cardholder_name.empty()) {
        // Log whether the name was changed by the user or simply accepted
        // without edits.
        autofill_metrics::LogSaveCardCardholderNameWasEdited(
            user_provided_card_details.cardholder_name !=
            base::UTF8ToUTF16(GetAccountInfo().full_name));
        // Trim the cardholder name provided by the user and send it in the
        // callback so it can be included in the final request.
        CHECK(ShouldRequestNameFromUser());
        base::TrimWhitespace(user_provided_card_details.cardholder_name,
                             base::TRIM_ALL, &name_provided_by_user);
      }

      // Log metrics now for the upload save card. The upload case is special
      // because we don't immediately close the bubble (at which time the other
      // metrics are logged) after OnSaveButton() and logging now aligns the
      // timing of the log with the other cases.
      autofill_metrics::LogSaveCardPromptResultMetric(
          autofill_metrics::SaveCardPromptResult::kAccepted, is_upload_save_,
          is_reshow_, options_,
          payments_data_manager_->GetPaymentsSigninStateForMetrics(),
          /*has_saved_cards=*/
          !payments_data_manager_->GetCreditCards().empty());
      autofill_metrics::LogCreditCardUploadLoadingViewShownMetric(
          /*is_shown=*/true);
      current_bubble_type_ = BubbleType::UPLOAD_IN_PROGRESS;

      std::move(upload_save_card_prompt_callback_)
          .Run(payments::PaymentsAutofillClient::SaveCardOfferUserDecision::
                   kAccepted,
               user_provided_card_details);
      break;
    }
    case BubbleType::UPLOAD_CVC_SAVE: {
      CHECK(!upload_save_card_prompt_callback_.is_null());
      if (auto* sentiment_service =
              TrustSafetySentimentServiceFactory::GetForProfile(GetProfile())) {
        sentiment_service->SavedCard();
      }
      std::move(upload_save_card_prompt_callback_)
          .Run(payments::PaymentsAutofillClient::SaveCardOfferUserDecision::
                   kAccepted,
               /*user_provided_card_details=*/{});
      break;
    }
    case BubbleType::LOCAL_SAVE:
    case BubbleType::LOCAL_CVC_SAVE:
      CHECK(!local_save_card_prompt_callback_.is_null());
      if (auto* sentiment_service =
              TrustSafetySentimentServiceFactory::GetForProfile(GetProfile())) {
        sentiment_service->SavedCard();
      }
      // Show an animated card saved confirmation message next time
      // UpdatePageActionIcon() is called.
      should_show_card_saved_label_animation_ = true;
      std::move(local_save_card_prompt_callback_)
          .Run(payments::PaymentsAutofillClient::SaveCardOfferUserDecision::
                   kAccepted);
      break;
    case BubbleType::MANAGE_CARDS:
      CHECK(!is_upload_save_);
      LogManageCardsPromptMetric(ManageCardsPromptMetric::kManageCardsDone);
      return;
    case BubbleType::UPLOAD_IN_PROGRESS:
    case BubbleType::UPLOAD_COMPLETED:
    case BubbleType::INACTIVE:
      NOTREACHED();
  }
}

void SaveCardBubbleControllerImpl::OnLegalMessageLinkClicked(const GURL& url) {
  OpenUrl(url);
  autofill_metrics::LogCreditCardUploadLegalMessageLinkClicked();
}

void SaveCardBubbleControllerImpl::OnManageCardsClicked() {
  CHECK(current_bubble_type_ == BubbleType::MANAGE_CARDS);
  CHECK(!is_upload_save_);

  LogManageCardsPromptMetric(ManageCardsPromptMetric::kManageCardsManageCards);

  ShowPaymentsSettingsPage();
}

void SaveCardBubbleControllerImpl::ShowPaymentsSettingsPage() {
  chrome::ShowSettingsSubPage(chrome::FindBrowserWithTab(web_contents()),
                              chrome::kPaymentsSubPage);
}

void SaveCardBubbleControllerImpl::OnBubbleClosed(
    PaymentsUiClosedReason closed_reason) {
  set_bubble_view(nullptr);

  // If the dialog should be re-shown, do not change the bubble type or log
  // metrics.
  // TODO(crbug.com/316391673): Determine if we should track metrics on the
  // usage of this member.
  if (was_url_opened_) {
    return;
  }

  auto get_metric = [](PaymentsUiClosedReason reason) {
    switch (reason) {
      case PaymentsUiClosedReason::kAccepted:
        return autofill_metrics::SaveCardPromptResult::kAccepted;
      case PaymentsUiClosedReason::kCancelled:
        return autofill_metrics::SaveCardPromptResult::kCancelled;
      case PaymentsUiClosedReason::kClosed:
        return autofill_metrics::SaveCardPromptResult::kClosed;
      case PaymentsUiClosedReason::kNotInteracted:
        return autofill_metrics::SaveCardPromptResult::kNotInteracted;
      case PaymentsUiClosedReason::kLostFocus:
        return autofill_metrics::SaveCardPromptResult::kLostFocus;
      case PaymentsUiClosedReason::kUnknown:
        return autofill_metrics::SaveCardPromptResult::kUnknown;
    }
  };

  // Log save card prompt result according to the closed reason.
  switch (current_bubble_type_) {
    case BubbleType::LOCAL_CVC_SAVE:
    case BubbleType::UPLOAD_CVC_SAVE:
      autofill_metrics::LogSaveCvcPromptResultMetric(
          get_metric(closed_reason), is_upload_save_, is_reshow_);
      break;
    case BubbleType::LOCAL_SAVE:
    case BubbleType::UPLOAD_SAVE:
      autofill_metrics::LogSaveCardPromptResultMetric(
          get_metric(closed_reason), is_upload_save_, is_reshow_, options_,
          payments_data_manager_->GetPaymentsSigninStateForMetrics(),
          /*has_saved_cards=*/
          !payments_data_manager_->GetCreditCards().empty());
      break;
    case BubbleType::UPLOAD_IN_PROGRESS:
      autofill_metrics::LogCreditCardUploadLoadingViewResultMetric(
          get_metric(closed_reason));
      break;
    case BubbleType::UPLOAD_COMPLETED:
      autofill_metrics::LogCreditCardUploadConfirmationViewResultMetric(
          get_metric(closed_reason), confirmation_ui_params_->is_success);
      break;
    case BubbleType::INACTIVE:
    case BubbleType::MANAGE_CARDS:
      break;
  }

  // If the bubble is closed with the current_bubble_type_ as
  // UPLOAD_COMPLETED, transition the current_bubble_type_ to INACTIVE, reset
  // the confirmation_ui_model and run `on_confirmation_closed_callback_`.
  if (current_bubble_type_ == BubbleType::UPLOAD_COMPLETED) {
    current_bubble_type_ = BubbleType::INACTIVE;
    confirmation_ui_params_.reset();

    UpdatePageActionIcon();

    if (on_confirmation_closed_callback_) {
      (*std::exchange(on_confirmation_closed_callback_, std::nullopt)).Run();
    }
    auto_close_confirmation_timer_.Stop();
    return;
  }

  // Handles |current_bubble_type_| change according to its current type and the
  // |closed_reason|.
  using SaveCardOfferUserDecision =
      payments::PaymentsAutofillClient::SaveCardOfferUserDecision;
  std::optional<SaveCardOfferUserDecision> user_decision;
  switch (closed_reason) {
    case PaymentsUiClosedReason::kAccepted:
      user_decision = SaveCardOfferUserDecision::kAccepted;
      switch (current_bubble_type_) {
        case BubbleType::LOCAL_SAVE:
        case BubbleType::LOCAL_CVC_SAVE:
          current_bubble_type_ = BubbleType::MANAGE_CARDS;
          break;
        case BubbleType::UPLOAD_SAVE:
        case BubbleType::UPLOAD_CVC_SAVE:
        case BubbleType::MANAGE_CARDS:
          current_bubble_type_ = BubbleType::INACTIVE;
          break;
        case BubbleType::INACTIVE:
        case BubbleType::UPLOAD_IN_PROGRESS:
        case BubbleType::UPLOAD_COMPLETED:
          NOTREACHED();
      }
      break;
    case PaymentsUiClosedReason::kCancelled:
      user_decision = SaveCardOfferUserDecision::kDeclined;
      break;
    case PaymentsUiClosedReason::kClosed:
      user_decision = SaveCardOfferUserDecision::kIgnored;
      break;
    case PaymentsUiClosedReason::kUnknown:
    case PaymentsUiClosedReason::kNotInteracted:
    case PaymentsUiClosedReason::kLostFocus:
      break;
  }

  if (user_decision && *user_decision != SaveCardOfferUserDecision::kAccepted) {
    switch (current_bubble_type_) {
      case BubbleType::LOCAL_SAVE:
      case BubbleType::LOCAL_CVC_SAVE:
        std::move(local_save_card_prompt_callback_).Run(*user_decision);
        break;
      case BubbleType::UPLOAD_SAVE:
      case BubbleType::UPLOAD_CVC_SAVE:
        std::move(upload_save_card_prompt_callback_)
            .Run(*user_decision, /*user_provided_card_details=*/{});
        break;
      default:
        break;
    }
    current_bubble_type_ = BubbleType::INACTIVE;
  }

  UpdatePageActionIcon();
}

const LegalMessageLines& SaveCardBubbleControllerImpl::GetLegalMessageLines()
    const {
  return legal_message_lines_;
}

bool SaveCardBubbleControllerImpl::IsUploadSave() const {
  return is_upload_save_;
}

BubbleType SaveCardBubbleControllerImpl::GetBubbleType() const {
  return current_bubble_type_;
}

bool SaveCardBubbleControllerImpl::
    IsPaymentsSyncTransportEnabledWithoutSyncFeature() const {
  // TODO(crbug.com/40067296): Migrate away from IsSyncFeatureEnabled() when the
  // API returns false on desktop.
  return payments_data_manager_->IsPaymentsDownloadActive() &&
         !sync_service_->IsSyncFeatureEnabled();
}

void SaveCardBubbleControllerImpl::HideSaveCardBubble() {
  HideBubble();
}

std::u16string SaveCardBubbleControllerImpl::GetSavePaymentIconTooltipText()
    const {
  switch (current_bubble_type_) {
    case BubbleType::LOCAL_SAVE:
    case BubbleType::UPLOAD_SAVE:
      return l10n_util::GetStringUTF16(IDS_TOOLTIP_SAVE_CREDIT_CARD);
    case BubbleType::LOCAL_CVC_SAVE:
    case BubbleType::UPLOAD_CVC_SAVE:
      return l10n_util::GetStringUTF16(IDS_TOOLTIP_SAVE_CVC);
    case BubbleType::MANAGE_CARDS:
      return l10n_util::GetStringUTF16(
          options_.card_save_type ==
                  payments::PaymentsAutofillClient::CardSaveType::kCvcSaveOnly
              ? IDS_TOOLTIP_SAVE_CVC
              : IDS_TOOLTIP_SAVE_CREDIT_CARD);
    case BubbleType::UPLOAD_IN_PROGRESS:
      return l10n_util::GetStringUTF16(IDS_TOOLTIP_SAVE_CREDIT_CARD_PENDING);
    case BubbleType::UPLOAD_COMPLETED:
    case BubbleType::INACTIVE:
      return std::u16string();
  }
}

// TODO(crbug.com/374815809): Remove this method.
bool SaveCardBubbleControllerImpl::ShouldShowSavingPaymentAnimation() const {
  return false;
}

bool SaveCardBubbleControllerImpl::ShouldShowPaymentSavedLabelAnimation()
    const {
  return should_show_card_saved_label_animation_;
}

void SaveCardBubbleControllerImpl::OnAnimationEnded() {
  // Do not repeat the animation next time UpdatePageActionIcon() is called,
  // unless explicitly set somewhere else.
  should_show_card_saved_label_animation_ = false;
}

bool SaveCardBubbleControllerImpl::IsIconVisible() const {
  if (current_bubble_type_ == BubbleType::INACTIVE) {
    CHECK(!bubble_view());
    // If there is no bubble to show, then there should be no icon.
    return false;
  }
  return true;
}

AutofillBubbleBase* SaveCardBubbleControllerImpl::GetPaymentBubbleView() const {
  return bubble_view();
}

int SaveCardBubbleControllerImpl::GetSaveSuccessAnimationStringId() const {
  return options_.card_save_type ==
                 payments::PaymentsAutofillClient::CardSaveType::kCvcSaveOnly
             ? IDS_AUTOFILL_CVC_SAVED
             : IDS_AUTOFILL_CARD_SAVED;
}

// static
base::AutoReset<bool>
SaveCardBubbleControllerImpl::IgnoreWindowActivationForTesting() {
  return base::AutoReset<bool>(&g_ignore_window_activation_for_testing, true);
}

void SaveCardBubbleControllerImpl::OnVisibilityChanged(
    content::Visibility visibility) {
  if (visibility == content::Visibility::VISIBLE &&
      (was_url_opened_ ||
       current_bubble_type_ == BubbleType::UPLOAD_COMPLETED)) {
    ReshowBubble(/*is_user_gesture=*/false);
  } else if (visibility == content::Visibility::HIDDEN) {
    HideBubble();
  }
}

PageActionIconType SaveCardBubbleControllerImpl::GetPageActionIconType() {
  return PageActionIconType::kSaveCard;
}

void SaveCardBubbleControllerImpl::DoShowBubble() {
  if (!IsWebContentsActive()) {
    return;
  }

  Browser* browser = chrome::FindBrowserWithTab(web_contents());
  if (current_bubble_type_ == BubbleType::UPLOAD_COMPLETED) {
    set_bubble_view(browser->window()
                        ->GetAutofillBubbleHandler()
                        ->ShowSaveCardConfirmationBubble(web_contents(), this));
  } else {
    set_bubble_view(
        browser->window()->GetAutofillBubbleHandler()->ShowSaveCreditCardBubble(
            web_contents(), this, is_triggered_by_user_gesture_));
  }
  CHECK(bubble_view());

  // Do not log metrics for re-shows triggered by link clicks.
  // TODO(issuetracker.google.com/316391673): Determine whether we should log
  // metrics when using `was_url_opened_`.
  if (was_url_opened_) {
    was_url_opened_ = false;
    return;
  }

  switch (current_bubble_type_) {
    case BubbleType::UPLOAD_SAVE:
    case BubbleType::LOCAL_SAVE:
      autofill_metrics::LogSaveCardPromptOfferMetric(
          autofill_metrics::SaveCardPromptOffer::kShown, is_upload_save_,
          is_reshow_, options_,
          payments_data_manager_->GetPaymentsSigninStateForMetrics());
      break;
    case BubbleType::UPLOAD_CVC_SAVE:
    case BubbleType::LOCAL_CVC_SAVE:
      autofill_metrics::LogSaveCvcPromptOfferMetric(
          autofill_metrics::SaveCardPromptOffer::kShown, is_upload_save_,
          is_reshow_);
      break;
    case BubbleType::MANAGE_CARDS:
      CHECK(!is_upload_save_);
      LogManageCardsPromptMetric(ManageCardsPromptMetric::kManageCardsShown);
      break;
    case BubbleType::UPLOAD_COMPLETED:
      autofill_metrics::LogCreditCardUploadConfirmationViewShownMetric(
          /*is_shown=*/true, confirmation_ui_params_->is_success);
      break;
    case BubbleType::UPLOAD_IN_PROGRESS:
      break;
    case BubbleType::INACTIVE:
      NOTREACHED();
  }
}

void SaveCardBubbleControllerImpl::ShowBubble() {
  CHECK(current_bubble_type_ != BubbleType::INACTIVE);
  // Upload save callback should not be null for UPLOAD_SAVE or
  // UPLOAD_CVC_SAVE state.
  CHECK(!upload_save_card_prompt_callback_.is_null() ||
        (current_bubble_type_ != BubbleType::UPLOAD_SAVE &&
         current_bubble_type_ != BubbleType::UPLOAD_CVC_SAVE));
  // Local save callback should not be null for LOCAL_SAVE or LOCAL_CVC_SAVE
  // state.
  CHECK(!local_save_card_prompt_callback_.is_null() ||
        (current_bubble_type_ != BubbleType::LOCAL_SAVE &&
         current_bubble_type_ != BubbleType::LOCAL_CVC_SAVE));
  CHECK(!bubble_view());
  Show();
}

void SaveCardBubbleControllerImpl::ShowIconOnly() {
  CHECK(current_bubble_type_ != BubbleType::INACTIVE);
  // Upload save callback should not be null for UPLOAD_SAVE or
  // UPLOAD_CVC_SAVE state.
  CHECK(!upload_save_card_prompt_callback_.is_null() ||
        (current_bubble_type_ != BubbleType::UPLOAD_SAVE &&
         current_bubble_type_ != BubbleType::UPLOAD_CVC_SAVE));
  // Local save callback should not be null for LOCAL_SAVE or LOCAL_CVC_SAVE
  // state.
  CHECK(!local_save_card_prompt_callback_.is_null() ||
        current_bubble_type_ != BubbleType::LOCAL_SAVE &&
            current_bubble_type_ != BubbleType::LOCAL_CVC_SAVE);
  CHECK(!bubble_view());

  // Show the icon only. The bubble can still be displayed if the user
  // explicitly clicks the icon.
  UpdatePageActionIcon();

  switch (current_bubble_type_) {
    case BubbleType::UPLOAD_SAVE:
    case BubbleType::LOCAL_SAVE:
      autofill_metrics::LogSaveCardPromptOfferMetric(
          autofill_metrics::SaveCardPromptOffer::kNotShownMaxStrikesReached,
          is_upload_save_, is_reshow_, options_,
          payments_data_manager_->GetPaymentsSigninStateForMetrics());
      break;
    case BubbleType::UPLOAD_CVC_SAVE:
    case BubbleType::LOCAL_CVC_SAVE:
      autofill_metrics::LogSaveCvcPromptOfferMetric(
          autofill_metrics::SaveCardPromptOffer::kNotShownMaxStrikesReached,
          is_upload_save_, is_reshow_);
      break;
    case BubbleType::UPLOAD_IN_PROGRESS:
    case BubbleType::UPLOAD_COMPLETED:
    case BubbleType::MANAGE_CARDS:
    case BubbleType::INACTIVE:
      NOTREACHED();
  }
}

void SaveCardBubbleControllerImpl::OpenUrl(const GURL& url) {
  was_url_opened_ = true;

  web_contents()->OpenURL(
      content::OpenURLParams(url, content::Referrer(),
                             WindowOpenDisposition::NEW_FOREGROUND_TAB,
                             ui::PAGE_TRANSITION_LINK, false),
      /*navigation_handle_callback=*/{});
}

bool SaveCardBubbleControllerImpl::IsWebContentsActive() {
  if (g_ignore_window_activation_for_testing) {
    return true;
  }

  Browser* active_browser = chrome::FindBrowserWithActiveWindow();
  return active_browser &&
         active_browser->tab_strip_model()->GetActiveWebContents() ==
             web_contents();
}

void SaveCardBubbleControllerImpl::EndSaveCardPromptFlow() {
  HideBubble();
  current_bubble_type_ = BubbleType::INACTIVE;
  confirmation_ui_params_.reset();
  UpdatePageActionIcon();
}

WEB_CONTENTS_USER_DATA_KEY_IMPL(SaveCardBubbleControllerImpl);

}  // namespace autofill