File: app_banner_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 (1016 lines) | stat: -rw-r--r-- 33,685 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
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
// 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 "components/webapps/browser/banners/app_banner_manager.h"

#include <algorithm>
#include <string>
#include <utility>

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/containers/contains.h"
#include "base/containers/cxx20_erase.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/observer_list.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "components/back_forward_cache/back_forward_cache_disable.h"
#include "components/password_manager/content/common/web_ui_constants.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "components/webapps/browser/banners/app_banner_metrics.h"
#include "components/webapps/browser/banners/app_banner_settings_helper.h"
#include "components/webapps/browser/features.h"
#include "components/webapps/browser/installable/installable_data.h"
#include "components/webapps/browser/installable/installable_manager.h"
#include "components/webapps/browser/installable/installable_metrics.h"
#include "components/webapps/browser/webapps_client.h"
#include "components/webapps/common/switches.h"
#include "content/public/browser/back_forward_cache.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_utils.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/manifest/manifest_util.h"
#include "third_party/blink/public/common/permissions_policy/permissions_policy.h"
#include "third_party/blink/public/mojom/installation/installation.mojom.h"
#include "third_party/blink/public/mojom/manifest/manifest.mojom.h"
#include "third_party/skia/include/core/SkBitmap.h"

namespace webapps {
namespace {

bool IsManifestUrlChange(const InstallableData& result) {
  if (result.errors.empty()) {
    return false;
  }
  if (result.errors[0] != MANIFEST_URL_CHANGED) {
    return false;
  }
  return true;
}

}  // namespace

class AppBannerManager::StatusReporter {
 public:
  virtual ~StatusReporter() = default;

  // Reports |code| (via a mechanism which depends on the implementation).
  virtual void ReportStatus(InstallableStatusCode code) = 0;

  // Returns the WebappInstallSource to be used for this installation.
  virtual WebappInstallSource GetInstallSource(
      content::WebContents* web_contents,
      InstallTrigger trigger) = 0;
};

namespace {

int gTimeDeltaInDaysForTesting = 0;

InstallableParams ParamsToGetManifest() {
  InstallableParams params;
  params.check_eligibility = true;
  params.fetch_metadata =
      base::FeatureList::IsEnabled(features::kUniversalInstallManifest);
  return params;
}

// Logs installable status codes to the console.
class ConsoleStatusReporter : public AppBannerManager::StatusReporter {
 public:
  // Constructs a ConsoleStatusReporter which logs to the devtools console
  // attached to |web_contents|.
  explicit ConsoleStatusReporter(content::WebContents* web_contents)
      : web_contents_(web_contents) {}

  // Logs an error message corresponding to |code| to the devtools console.
  void ReportStatus(InstallableStatusCode code) override {
    LogToConsole(web_contents_, code,
                 blink::mojom::ConsoleMessageLevel::kError);
  }

  WebappInstallSource GetInstallSource(content::WebContents* web_contents,
                                       InstallTrigger trigger) override {
    return WebappInstallSource::DEVTOOLS;
  }

 private:
  raw_ptr<content::WebContents> web_contents_;
};

// Tracks installable status codes via an UMA histogram.
class TrackingStatusReporter : public AppBannerManager::StatusReporter {
 public:
  TrackingStatusReporter() = default;
  ~TrackingStatusReporter() override = default;

  // Records code via an UMA histogram.
  void ReportStatus(InstallableStatusCode code) override {
    // We only increment the histogram once per page load (and only if the
    // banner pipeline is triggered).
    if (!done_ && code != NO_ERROR_DETECTED)
      TrackInstallableStatusCode(code);

    done_ = true;
  }

  WebappInstallSource GetInstallSource(content::WebContents* web_contents,
                                       InstallTrigger trigger) override {
    return InstallableMetrics::GetInstallSource(web_contents, trigger);
  }

 private:
  bool done_ = false;
};

class NullStatusReporter : public AppBannerManager::StatusReporter {
 public:
  void ReportStatus(InstallableStatusCode code) override {
    // In general, NullStatusReporter::ReportStatus should not be called.
    // However, it may be called in cases where Stop is called without a
    // preceding call to RequestAppBanner e.g. because the WebContents is being
    // destroyed or web app uninstalled. In that case, code should always be
    // NO_ERROR_DETECTED or PIPELINE_RESTARTED.
    DCHECK(code == NO_ERROR_DETECTED || code == PIPELINE_RESTARTED);
  }

  WebappInstallSource GetInstallSource(content::WebContents* web_contents,
                                       InstallTrigger trigger) override {
    NOTREACHED();
    return WebappInstallSource::COUNT;
  }
};

void TrackBeforeInstallEventPrompt(AppBannerManager::State state) {
  switch (state) {
    case AppBannerManager::State::SENDING_EVENT_GOT_EARLY_PROMPT:
      TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_EARLY_PROMPT);
      break;
    case AppBannerManager::State::PENDING_PROMPT_CANCELED:
      TrackBeforeInstallEvent(
          BEFORE_INSTALL_EVENT_PROMPT_CALLED_AFTER_PREVENT_DEFAULT);
      break;
    case AppBannerManager::State::PENDING_PROMPT_NOT_CANCELED:
      TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_PROMPT_CALLED_NOT_CANCELED);
      break;
    default:
      break;
  }
}
}  // anonymous namespace

namespace test {
bool g_disable_banner_triggering_for_testing = false;
}

// static
AppBannerManager* AppBannerManager::FromWebContents(
    content::WebContents* web_contents) {
  return WebappsClient::Get()
             ? WebappsClient::Get()->GetAppBannerManager(web_contents)
             : nullptr;
}

// static
base::Time AppBannerManager::GetCurrentTime() {
  return base::Time::Now() + base::Days(gTimeDeltaInDaysForTesting);
}

// static
void AppBannerManager::SetTimeDeltaForTesting(int days) {
  gTimeDeltaInDaysForTesting = days;
}

void AppBannerManager::RequestAppBanner(const GURL& validated_url) {
  DCHECK_EQ(State::INACTIVE, state_);

  UpdateState(State::ACTIVE);

  // If we already have enough engagement, or require no engagement to trigger
  // the banner, the rest of the banner pipeline should operate as if the
  // engagement threshold has been met.
  if (!has_sufficient_engagement_ &&
      (AppBannerSettingsHelper::HasSufficientEngagement(0) ||
       AppBannerSettingsHelper::HasSufficientEngagement(
           GetSiteEngagementService()->GetScore(validated_url)))) {
    has_sufficient_engagement_ = true;
  }

  if (ShouldBypassEngagementChecks())
    status_reporter_ = std::make_unique<ConsoleStatusReporter>(web_contents());
  else
    status_reporter_ = std::make_unique<TrackingStatusReporter>();

  if (validated_url_.is_empty())
    validated_url_ = validated_url;

  UpdateState(State::FETCHING_MANIFEST);
  manager_->GetData(ParamsToGetManifest(),
                    base::BindOnce(&AppBannerManager::OnDidGetManifest,
                                   GetWeakPtrForThisNavigation()));
}

void AppBannerManager::OnInstall(blink::mojom::DisplayMode display) {
  TrackInstallDisplayMode(display);
  mojo::Remote<blink::mojom::InstallationService> installation_service;
  web_contents()->GetPrimaryMainFrame()->GetRemoteInterfaces()->GetInterface(
      installation_service.BindNewPipeAndPassReceiver());
  DCHECK(installation_service);
  installation_service->OnInstall();

  // App has been installed (possibly by the user), page may no longer request
  // install prompt.
  receiver_.reset();
}

void AppBannerManager::SendBannerAccepted() {
  if (event_.is_bound()) {
    event_->BannerAccepted(GetBannerType());
    event_.reset();
  }
}

void AppBannerManager::SendBannerDismissed() {
  if (event_.is_bound())
    event_->BannerDismissed();

  SendBannerPromptRequest();
}

void AppBannerManager::AddObserver(Observer* observer) {
  observer_list_.AddObserver(observer);
}

void AppBannerManager::RemoveObserver(Observer* observer) {
  observer_list_.RemoveObserver(observer);
}

base::WeakPtr<AppBannerManager> AppBannerManager::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

bool AppBannerManager::TriggeringDisabledForTesting() const {
  return test::g_disable_banner_triggering_for_testing;
}

bool AppBannerManager::IsPromptAvailableForTesting() const {
  return receiver_.is_bound();
}

AppBannerManager::InstallableWebAppCheckResult
AppBannerManager::GetInstallableWebAppCheckResultForTesting() {
  return installable_web_app_check_result_;
}

AppBannerManager::AppBannerManager(content::WebContents* web_contents)
    : content::WebContentsObserver(web_contents),
      SiteEngagementObserver(site_engagement::SiteEngagementService::Get(
          web_contents->GetBrowserContext())),
      manager_(InstallableManager::FromWebContents(web_contents)),
      manifest_(blink::mojom::Manifest::New()),
      web_page_metadata_(mojom::WebPageMetadata::New()),
      status_reporter_(std::make_unique<NullStatusReporter>()) {
  DCHECK(manager_);

  AppBannerSettingsHelper::UpdateFromFieldTrial();
}

AppBannerManager::~AppBannerManager() = default;

AppBannerManager::UrlType AppBannerManager::GetUrlType(
    content::RenderFrameHost* render_frame_host,
    const GURL& url) {
  // Don't start the banner flow unless the primary main frame has finished
  // loading. |render_frame_host| can be null during retry attempts.
  if (render_frame_host && !render_frame_host->IsInPrimaryMainFrame())
    return UrlType::kNotPrimaryFrame;

  // There is never a need to trigger a banner for a WebUI page, except
  // for PasswordManager WebUI.
  if (content::HasWebUIScheme(url) &&
      (url.host() != password_manager::kChromeUIPasswordManagerHost)) {
    return UrlType::kInvalidPrimaryFrameUrl;
  }

  return UrlType::kValidForBanner;
}

bool AppBannerManager::CheckIfShouldShowBanner() {
  if (ShouldBypassEngagementChecks()) {
    return true;
  }
  if (GetAppIdentifier().empty()) {
    Stop(PACKAGE_NAME_OR_START_URL_EMPTY);
    return false;
  }
  return true;
}

bool AppBannerManager::ShouldDeferToRelatedNonWebApp() const {
  for (const auto& related_app : manifest().related_applications) {
    if (manifest().prefer_related_applications &&
        IsSupportedNonWebAppPlatform(
            related_app.platform.value_or(std::u16string()))) {
      return true;
    }
    if (IsRelatedNonWebAppInstalled(related_app))
      return true;
  }
  return false;
}

std::string AppBannerManager::GetAppIdentifier() {
  DCHECK(!blink::IsEmptyManifest(manifest()));
  return manifest().start_url.spec();
}

std::u16string AppBannerManager::GetAppName() const {
  return manifest().name.value_or(GetNameFromMetadata());
}

std::u16string AppBannerManager::GetNameFromMetadata() const {
  return web_page_metadata().application_name.empty()
             ? web_page_metadata().title
             : web_page_metadata().application_name;
}

const blink::mojom::Manifest& AppBannerManager::manifest() const {
  CHECK(manifest_);
  return *manifest_;
}

const mojom::WebPageMetadata& AppBannerManager::web_page_metadata() const {
  CHECK(web_page_metadata_);
  return *web_page_metadata_;
}

std::string AppBannerManager::GetBannerType() {
  return "web";
}

bool AppBannerManager::HasSufficientEngagement() const {
  return has_sufficient_engagement_ || ShouldBypassEngagementChecks();
}

bool AppBannerManager::ShouldBypassEngagementChecks() const {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kBypassAppBannerEngagementChecks);
}

bool AppBannerManager::ShouldAllowWebAppReplacementInstall() {
  return false;
}

void AppBannerManager::OnDidGetManifest(const InstallableData& data) {
  // The pipeline will be restarted from DidUpdateWebManifestURL.
  if (IsManifestUrlChange(data)) {
    return;
  }
  UpdateState(State::ACTIVE);
  if (!data.errors.empty()) {
    Stop(data.GetFirstError());
    return;
  }

  DCHECK(!data.manifest_url->is_empty());
  DCHECK(!blink::IsEmptyManifest(*data.manifest));

  manifest_url_ = *(data.manifest_url);
  manifest_ = data.manifest->Clone();
  web_page_metadata_ = data.web_page_metadata->Clone();

  // Skip checks for PasswordManager WebUI page.
  if (content::HasWebUIScheme(validated_url_) &&
      (validated_url_.host() ==
       password_manager::kChromeUIPasswordManagerHost)) {
    if (IsWebAppConsideredInstalled()) {
      TrackDisplayEvent(DISPLAY_EVENT_INSTALLED_PREVIOUSLY);
      SetInstallableWebAppCheckResult(
          InstallableWebAppCheckResult::kNo_AlreadyInstalled);
      Stop(ALREADY_INSTALLED);
    } else {
      SetInstallableWebAppCheckResult(
          InstallableWebAppCheckResult::kYes_Promotable);
      Stop(NO_ERROR_DETECTED);
    }
    return;
  }

  PerformInstallableChecks();
}

InstallableParams AppBannerManager::ParamsToPerformInstallableWebAppCheck() {
  InstallableParams params;
  params.valid_primary_icon = true;
  params.installable_criteria = InstallableCriteria::kValidManifestWithIcons;
  params.fetch_screenshots = true;

  return params;
}

void AppBannerManager::PerformInstallableChecks() {
  PerformInstallableWebAppCheck();
}

void AppBannerManager::PerformInstallableWebAppCheck() {
  if (!CheckIfShouldShowBanner())
    return;

  // Fetch and verify the other required information.
  UpdateState(State::PENDING_INSTALLABLE_CHECK);
  manager_->GetData(
      ParamsToPerformInstallableWebAppCheck(),
      base::BindOnce(&AppBannerManager::OnDidPerformInstallableWebAppCheck,
                     GetWeakPtrForThisNavigation()));
}

void AppBannerManager::OnDidPerformInstallableWebAppCheck(
    const InstallableData& data) {
  // The pipeline will be restarted from DidUpdateWebManifestURL.
  if (IsManifestUrlChange(data)) {
    return;
  }

  UpdateState(State::ACTIVE);
  if (data.installable_check_passed) {
    TrackDisplayEvent(DISPLAY_EVENT_WEB_APP_BANNER_REQUESTED);
  }

  bool is_installable = data.errors.empty();

  if (!is_installable) {
    SetInstallableWebAppCheckResult(InstallableWebAppCheckResult::kNo);
    Stop(data.GetFirstError());
    return;
  }

  if (IsWebAppConsideredInstalled() && !ShouldAllowWebAppReplacementInstall()) {
    TrackDisplayEvent(DISPLAY_EVENT_INSTALLED_PREVIOUSLY);
    SetInstallableWebAppCheckResult(
        InstallableWebAppCheckResult::kNo_AlreadyInstalled);
    Stop(ALREADY_INSTALLED);
    return;
  }

  if (ShouldDeferToRelatedNonWebApp()) {
    SetInstallableWebAppCheckResult(
        InstallableWebAppCheckResult::kYes_ByUserRequest);
    Stop(PREFER_RELATED_APPLICATIONS);
    return;
  }

  DCHECK(data.installable_check_passed);
  DCHECK(!data.primary_icon_url->is_empty());
  DCHECK(data.primary_icon);

  primary_icon_url_ = *data.primary_icon_url;
  primary_icon_ = *data.primary_icon;
  has_maskable_primary_icon_ = data.has_maskable_primary_icon;
  screenshots_ = *(data.screenshots);

  if (base::FeatureList::IsEnabled(features::kUniversalInstallManifest)) {
    SetInstallableWebAppCheckResult(
        InstallableWebAppCheckResult::kYes_ByUserRequest);

    InstallableParams check_promotable_params;
    check_promotable_params.installable_criteria =
        InstallableCriteria::kValidManifestWithIcons;
    manager_->GetData(
        check_promotable_params,
        base::BindOnce(&AppBannerManager::OnDidPerformPromotableWebAppCheck,
                       GetWeakPtrForThisNavigation()));
    return;
  }

  SetInstallableWebAppCheckResult(
      InstallableWebAppCheckResult::kYes_Promotable);
  CheckSufficientEngagement();
}

void AppBannerManager::OnDidPerformPromotableWebAppCheck(
    const InstallableData& data) {
  if (!data.errors.empty()) {
    Stop(data.GetFirstError());
    return;
  }

  SetInstallableWebAppCheckResult(
      InstallableWebAppCheckResult::kYes_Promotable);
  CheckSufficientEngagement();
}

void AppBannerManager::CheckSufficientEngagement() {
  // If we triggered the installability check on page load, then it's
  // possible we don't have enough engagement yet. If that's the case,
  // return here but don't call Terminate(). We wait for OnEngagementEvent
  // to tell us that we should trigger.
  if (!HasSufficientEngagement()) {
    UpdateState(State::PENDING_ENGAGEMENT);
    return;
  }

  SendBannerPromptRequest();
}

void AppBannerManager::RecordDidShowBanner() {
  content::WebContents* contents = web_contents();
  DCHECK(contents);

  AppBannerSettingsHelper::RecordBannerEvent(
      contents, validated_url_, GetAppIdentifier(),
      AppBannerSettingsHelper::APP_BANNER_EVENT_DID_SHOW, GetCurrentTime());
}

void AppBannerManager::ReportStatus(InstallableStatusCode code) {
  DCHECK(status_reporter_);
  status_reporter_->ReportStatus(code);
}

void AppBannerManager::ResetBindings() {
  receiver_.reset();
  event_.reset();
}

void AppBannerManager::ResetCurrentPageData() {
  load_finished_ = false;
  has_sufficient_engagement_ = false;
  active_media_players_.clear();
  manifest_ = blink::mojom::Manifest::New();
  web_page_metadata_ = mojom::WebPageMetadata::New();
  manifest_url_ = GURL();
  validated_url_ = GURL();
  UpdateState(State::INACTIVE);
  SetInstallableWebAppCheckResult(InstallableWebAppCheckResult::kUnknown);
  install_path_tracker_.Reset();
  screenshots_.clear();
}

void AppBannerManager::Terminate() {
  switch (state_) {
    case State::PENDING_PROMPT_CANCELED:
      TrackBeforeInstallEvent(
          BEFORE_INSTALL_EVENT_PROMPT_NOT_CALLED_AFTER_PREVENT_DEFAULT);
      break;
    case State::PENDING_PROMPT_NOT_CANCELED:
      TrackBeforeInstallEvent(
          BEFORE_INSTALL_EVENT_PROMPT_NOT_CALLED_NOT_CANCELLED);
      break;
    case State::PENDING_ENGAGEMENT:
      if (!has_sufficient_engagement_)
        TrackDisplayEvent(DISPLAY_EVENT_NOT_VISITED_ENOUGH);
      break;
    default:
      break;
  }

  Stop(TerminationCode());
}

InstallableStatusCode AppBannerManager::TerminationCode() const {
  switch (state_) {
    case State::PENDING_PROMPT_CANCELED:
    case State::PENDING_PROMPT_NOT_CANCELED:
      return RENDERER_CANCELLED;
    case State::PENDING_ENGAGEMENT:
      return has_sufficient_engagement_ ? NO_ERROR_DETECTED
                                        : INSUFFICIENT_ENGAGEMENT;
    case State::FETCHING_MANIFEST:
      return WAITING_FOR_MANIFEST;
    case State::FETCHING_NATIVE_DATA:
      return WAITING_FOR_NATIVE_DATA;
    case State::PENDING_INSTALLABLE_CHECK:
      return WAITING_FOR_INSTALLABLE_CHECK;
    case State::ACTIVE:
    case State::SENDING_EVENT:
    case State::SENDING_EVENT_GOT_EARLY_PROMPT:
    case State::INACTIVE:
    case State::COMPLETE:
      break;
  }
  return NO_ERROR_DETECTED;
}

void AppBannerManager::SetInstallableWebAppCheckResult(
    InstallableWebAppCheckResult result) {
  if (installable_web_app_check_result_ == result)
    return;

  installable_web_app_check_result_ = result;

  switch (result) {
    case InstallableWebAppCheckResult::kUnknown:
      break;
    case InstallableWebAppCheckResult::kYes_Promotable:
      last_promotable_web_app_scope_ = manifest().scope;
      DCHECK(!last_promotable_web_app_scope_.is_empty());
      last_already_installed_web_app_scope_ = GURL();
      install_animation_pending_ =
          AppBannerSettingsHelper::CanShowInstallTextAnimation(
              web_contents(), last_promotable_web_app_scope_);
      break;
    case InstallableWebAppCheckResult::kNo_AlreadyInstalled:
      last_already_installed_web_app_scope_ = manifest().scope;
      DCHECK(!last_already_installed_web_app_scope_.is_empty());
      last_promotable_web_app_scope_ = GURL();
      install_animation_pending_ = false;
      break;
    case InstallableWebAppCheckResult::kYes_ByUserRequest:
    case InstallableWebAppCheckResult::kNo:
      last_promotable_web_app_scope_ = GURL();
      last_already_installed_web_app_scope_ = GURL();
      install_animation_pending_ = false;
      break;
  }

  for (Observer& observer : observer_list_)
    observer.OnInstallableWebAppStatusUpdated();
}

void AppBannerManager::RecheckInstallabilityForLoadedPage() {
  if (state_ == State::INACTIVE)
    return;

  if (state_ != State::COMPLETE) {
    Stop(InstallableStatusCode::PIPELINE_RESTARTED);
  }

  UpdateState(State::INACTIVE);
  RequestAppBanner(validated_url_);
}

void AppBannerManager::TrackInstallPath(bool bottom_sheet,
                                        WebappInstallSource install_source) {
  install_path_tracker_.TrackInstallPath(bottom_sheet, install_source);
}

void AppBannerManager::TrackIphWasShown() {
  install_path_tracker_.TrackIphWasShown();
}

void AppBannerManager::Stop(InstallableStatusCode code) {
  ReportStatus(code);

  if (installable_web_app_check_result_ ==
      InstallableWebAppCheckResult::kUnknown) {
    SetInstallableWebAppCheckResult(InstallableWebAppCheckResult::kNo);
  }
  InvalidateWeakPtrsForThisNavigation();
  ResetBindings();
  UpdateState(State::COMPLETE);
  status_reporter_ = std::make_unique<NullStatusReporter>();
}

void AppBannerManager::SendBannerPromptRequest() {
  RecordCouldShowBanner();

  UpdateState(State::SENDING_EVENT);
  TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_CREATED);

  // Any existing binding is invalid when we send a new beforeinstallprompt.
  ResetBindings();

  mojo::Remote<blink::mojom::AppBannerController> controller;
  web_contents()->GetPrimaryMainFrame()->GetRemoteInterfaces()->GetInterface(
      controller.BindNewPipeAndPassReceiver());

  // Get a raw controller pointer before we move out of the smart pointer to
  // avoid crashing with MSVC's order of evaluation.
  blink::mojom::AppBannerController* controller_ptr = controller.get();
  controller_ptr->BannerPromptRequest(
      receiver_.BindNewPipeAndPassRemote(), event_.BindNewPipeAndPassReceiver(),
      {GetBannerType()},
      base::BindOnce(&AppBannerManager::OnBannerPromptReply,
                     GetWeakPtrForThisNavigation(), std::move(controller)));
}

void AppBannerManager::UpdateState(State state) {
  state_ = state;
}

void AppBannerManager::DidFinishNavigation(content::NavigationHandle* handle) {
  if (!handle->IsInPrimaryMainFrame() || !handle->HasCommitted() ||
      handle->IsSameDocument()) {
    return;
  }

  if (state_ != State::COMPLETE && state_ != State::INACTIVE)
    Terminate();
  ResetCurrentPageData();

  if (handle->IsServedFromBackForwardCache()) {
    RequestAppBanner(validated_url_);
  }
}

void AppBannerManager::DidFinishLoad(
    content::RenderFrameHost* render_frame_host,
    const GURL& validated_url) {
  if (TriggeringDisabledForTesting()) {
    return;
  }

  UrlType url_type = GetUrlType(render_frame_host, validated_url);
  if (url_type != UrlType::kValidForBanner) {
    return;
  }

  load_finished_ = true;
  validated_url_ = validated_url;

  // Start the pipeline immediately if we haven't already started it.
  if (state_ == State::INACTIVE)
    RequestAppBanner(validated_url);
}

void AppBannerManager::DidActivatePortal(
    content::WebContents* predecessor_contents,
    base::TimeTicks activation_time) {
  // If this page was loaded in a portal, AppBannerManager may have been
  // instantiated after DidFinishLoad. Trigger the banner pipeline now (on
  // portal activation) if we missed the load event.
  if (!load_finished_ && !web_contents()->ShouldShowLoadingUI()) {
    DidFinishLoad(web_contents()->GetPrimaryMainFrame(),
                  web_contents()->GetLastCommittedURL());
  }
}

void AppBannerManager::DidUpdateWebManifestURL(
    content::RenderFrameHost* target_frame,
    const GURL& manifest_url) {
  GURL url = validated_url_;
  switch (state_) {
    case State::INACTIVE:
      return;
    case State::FETCHING_MANIFEST:
    case State::PENDING_INSTALLABLE_CHECK:
      UpdateState(State::INACTIVE);
      RequestAppBanner(validated_url_);
      return;
    case State::ACTIVE:
    case State::FETCHING_NATIVE_DATA:
    case State::PENDING_ENGAGEMENT:
    case State::SENDING_EVENT:
    case State::SENDING_EVENT_GOT_EARLY_PROMPT:
    case State::PENDING_PROMPT_CANCELED:
    case State::PENDING_PROMPT_NOT_CANCELED:
      Terminate();
      [[fallthrough]];
    case State::COMPLETE:
      if (!manifest_url.is_empty()) {
        RecheckInstallabilityForLoadedPage();
      }
      return;
  }
}

void AppBannerManager::MediaStartedPlaying(const MediaPlayerInfo& media_info,
                                           const content::MediaPlayerId& id) {
  active_media_players_.push_back(id);
}

void AppBannerManager::MediaStoppedPlaying(
    const MediaPlayerInfo& media_info,
    const content::MediaPlayerId& id,
    WebContentsObserver::MediaStoppedReason reason) {
  base::Erase(active_media_players_, id);
}

void AppBannerManager::WebContentsDestroyed() {
  Terminate();
}

void AppBannerManager::OnEngagementEvent(
    content::WebContents* contents,
    const GURL& url,
    double score,
    site_engagement::EngagementType /*type*/) {
  if (TriggeringDisabledForTesting()) {
    return;
  }

  // Only trigger a banner using site engagement if:
  //  1. engagement increased for the web contents which we are attached to; and
  //  2. there are no currently active media players; and
  //  3. we have accumulated sufficient engagement.
  if (web_contents() == contents && active_media_players_.empty() &&
      AppBannerSettingsHelper::HasSufficientEngagement(score)) {
    has_sufficient_engagement_ = true;

    if (state_ == State::PENDING_ENGAGEMENT) {
      // We have already finished the installability eligibility checks. Proceed
      // directly to sending the banner prompt request.
      UpdateState(State::ACTIVE);
      SendBannerPromptRequest();
    } else if (load_finished_ && state_ == State::INACTIVE) {
      // This performs some simple tests and starts async checks to test
      // installability. It should be safe to start in response to user input.
      // Don't call if we're already working on processing a banner request.
      RequestAppBanner(url);
    }
  }
}

bool AppBannerManager::IsRunning() const {
  switch (state_) {
    case State::INACTIVE:
    case State::PENDING_PROMPT_CANCELED:
    case State::PENDING_PROMPT_NOT_CANCELED:
    case State::PENDING_ENGAGEMENT:
    case State::COMPLETE:
      return false;
    case State::ACTIVE:
    case State::FETCHING_MANIFEST:
    case State::FETCHING_NATIVE_DATA:
    case State::PENDING_INSTALLABLE_CHECK:
    case State::SENDING_EVENT:
    case State::SENDING_EVENT_GOT_EARLY_PROMPT:
      return true;
  }
  return false;
}

// static
std::u16string AppBannerManager::GetInstallableWebAppName(
    content::WebContents* web_contents) {
  AppBannerManager* manager = FromWebContents(web_contents);
  if (!manager)
    return std::u16string();
  switch (manager->installable_web_app_check_result_) {
    case InstallableWebAppCheckResult::kUnknown:
    case InstallableWebAppCheckResult::kNo:
    case InstallableWebAppCheckResult::kNo_AlreadyInstalled:
      return std::u16string();
    case InstallableWebAppCheckResult::kYes_ByUserRequest:
    case InstallableWebAppCheckResult::kYes_Promotable:
      return manager->GetAppName();
  }
}
// static
std::string AppBannerManager::GetInstallableWebAppManifestId(
    content::WebContents* web_contents) {
  AppBannerManager* manager = FromWebContents(web_contents);
  if (!manager)
    return std::string();
  switch (manager->installable_web_app_check_result_) {
    case InstallableWebAppCheckResult::kUnknown:
    case InstallableWebAppCheckResult::kNo:
    case InstallableWebAppCheckResult::kNo_AlreadyInstalled:
      return std::string();
    case InstallableWebAppCheckResult::kYes_ByUserRequest:
    case InstallableWebAppCheckResult::kYes_Promotable:
      return manager->manifest().id.spec();
  }
}
bool AppBannerManager::IsProbablyPromotableWebApp(
    bool ignore_existing_installations) const {
  bool in_promotable_scope =
      last_promotable_web_app_scope_.is_valid() &&
      base::StartsWith(web_contents()->GetLastCommittedURL().spec(),
                       last_promotable_web_app_scope_.spec(),
                       base::CompareCase::SENSITIVE);
  bool in_already_installed_scope =
      last_already_installed_web_app_scope_.is_valid() &&
      base::StartsWith(web_contents()->GetLastCommittedURL().spec(),
                       last_already_installed_web_app_scope_.spec(),
                       base::CompareCase::SENSITIVE);
  switch (installable_web_app_check_result_) {
    case InstallableWebAppCheckResult::kUnknown:
      return in_promotable_scope ||
             (ignore_existing_installations && in_already_installed_scope);
    case InstallableWebAppCheckResult::kNo:
    case InstallableWebAppCheckResult::kNo_AlreadyInstalled:
      return ignore_existing_installations;
    case InstallableWebAppCheckResult::kYes_ByUserRequest:
      return false;
    case InstallableWebAppCheckResult::kYes_Promotable:
      return true;
  }
}

bool AppBannerManager::IsPromotableWebApp() const {
  switch (installable_web_app_check_result_) {
    case InstallableWebAppCheckResult::kUnknown:
    case InstallableWebAppCheckResult::kNo:
    case InstallableWebAppCheckResult::kNo_AlreadyInstalled:
    case InstallableWebAppCheckResult::kYes_ByUserRequest:
      return false;
    case InstallableWebAppCheckResult::kYes_Promotable:
      return true;
  }
}

const GURL& AppBannerManager::GetManifestStartUrl() const {
  return manifest().start_url;
}

blink::mojom::DisplayMode AppBannerManager::GetManifestDisplayMode() const {
  return manifest().display;
}

bool AppBannerManager::MaybeConsumeInstallAnimation() {
  DCHECK(IsProbablyPromotableWebApp());
  if (!install_animation_pending_)
    return false;
  AppBannerSettingsHelper::RecordInstallTextAnimationShown(
      web_contents(), last_promotable_web_app_scope_);
  install_animation_pending_ = false;
  return true;
}

void AppBannerManager::RecordCouldShowBanner() {
  content::WebContents* contents = web_contents();
  DCHECK(contents);

  AppBannerSettingsHelper::RecordBannerEvent(
      contents, validated_url_, GetAppIdentifier(),
      AppBannerSettingsHelper::APP_BANNER_EVENT_COULD_SHOW, GetCurrentTime());
}

void AppBannerManager::OnBannerPromptReply(
    mojo::Remote<blink::mojom::AppBannerController> controller,
    blink::mojom::AppBannerPromptReply reply) {
  // The renderer might have requested the prompt to be canceled. They may
  // request that it is redisplayed later, so don't Terminate() here. However,
  // log that the cancelation was requested, so Terminate() can be called if a
  // redisplay isn't asked for.
  //
  // If the redisplay request has not been received already, we stop here and
  // wait for the prompt function to be called. If the redisplay request has
  // already been received before cancel was sent (e.g. if redisplay was
  // requested in the beforeinstallprompt event handler), we keep going and show
  // the banner immediately.
  bool event_canceled = reply == blink::mojom::AppBannerPromptReply::CANCEL;
  if (event_canceled) {
    TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_PREVENT_DEFAULT_CALLED);
    if (ShouldBypassEngagementChecks()) {
      web_contents()->GetPrimaryMainFrame()->AddMessageToConsole(
          blink::mojom::ConsoleMessageLevel::kInfo,
          "Banner not shown: beforeinstallpromptevent.preventDefault() called. "
          "The page must call beforeinstallpromptevent.prompt() to show the "
          "banner.");
    }
  }

  if (state_ == State::SENDING_EVENT) {
    if (!event_canceled) {
      MaybeShowAmbientBadge();
      UpdateState(State::PENDING_PROMPT_NOT_CANCELED);
    } else {
      UpdateState(State::PENDING_PROMPT_CANCELED);
    }
    return;
  }

  DCHECK_EQ(State::SENDING_EVENT_GOT_EARLY_PROMPT, state_);

  ShowBanner();
}

void AppBannerManager::MaybeShowAmbientBadge() {}

void AppBannerManager::ShowBanner() {
  // The banner is only shown if the site explicitly requests it to be shown.
  DCHECK_NE(State::SENDING_EVENT, state_);

  content::WebContents* contents = web_contents();
  WebappInstallSource install_source;

  TrackBeforeInstallEventPrompt(state_);

  install_source =
      status_reporter_->GetInstallSource(contents, InstallTrigger::API);

  DCHECK(!manifest_url_.is_empty());
  DCHECK(!blink::IsEmptyManifest(manifest()));
  DCHECK(!primary_icon_url_.is_empty());
  DCHECK(!primary_icon_.drawsNothing());

  TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_COMPLETE);
  ShowBannerUi(install_source);
  UpdateState(State::COMPLETE);
}

void AppBannerManager::DisplayAppBanner() {
  // Prevent this from being called multiple times on the same connection.
  receiver_.reset();

  if (state_ == State::PENDING_PROMPT_CANCELED ||
      state_ == State::PENDING_PROMPT_NOT_CANCELED) {
    ShowBanner();
  } else if (state_ == State::SENDING_EVENT) {
    // Log that the prompt request was made for when we get the prompt reply.
    UpdateState(State::SENDING_EVENT_GOT_EARLY_PROMPT);
  }
}

}  // namespace webapps