File: web_app_ui_manager_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 (899 lines) | stat: -rw-r--r-- 33,209 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
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
// Copyright 2019 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/web_applications/web_app_ui_manager_impl.h"

#include <map>
#include <memory>
#include <type_traits>
#include <utility>

#include "base/check.h"
#include "base/check_op.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/one_shot_event.h"
#include "base/task/sequenced_task_runner.h"
#include "base/types/pass_key.h"
#include "build/build_config.h"
#include "chrome/browser/apps/app_service/app_launch_params.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_element_identifiers.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_navigator_params.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/intent_picker_tab_helper.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "chrome/browser/ui/web_applications/web_app_dialog_utils.h"
#include "chrome/browser/ui/web_applications/web_app_dialogs.h"
#include "chrome/browser/ui/web_applications/web_app_launch_utils.h"
#include "chrome/browser/ui/web_applications/web_app_metrics.h"
#include "chrome/browser/ui/web_applications/web_app_run_on_os_login_notification.h"
#include "chrome/browser/web_applications/web_app_callback_app_identity.h"
#include "chrome/browser/web_applications/web_app_command_scheduler.h"
#include "chrome/browser/web_applications/web_app_icon_manager.h"
#include "chrome/browser/web_applications/web_app_pref_guardrails.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/web_app_tab_helper.h"
#include "chrome/browser/web_applications/web_app_ui_manager.h"
#include "chrome/browser/web_applications/web_app_uninstall_dialog_user_options.h"
#include "components/feature_engagement/public/feature_constants.h"
#include "components/user_education/common/feature_promo/feature_promo_controller.h"
#include "components/user_education/common/feature_promo/feature_promo_result.h"
#include "components/user_education/common/user_education_data.h"
#include "components/webapps/browser/installable/installable_metrics.h"
#include "components/webapps/browser/installable/ml_install_operation_tracker.h"
#include "components/webapps/browser/uninstall_result_code.h"
#include "components/webapps/common/web_app_id.h"
#include "content/public/browser/clear_site_data_utils.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/app_sorting.h"
#include "extensions/browser/extension_system.h"
#include "third_party/blink/public/mojom/manifest/manifest.mojom-shared.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/page_transition_types.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/native_window_tracker.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/url_constants.h"

#if !BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/apps/link_capturing/enable_link_capturing_infobar_delegate.h"
#include "chrome/browser/infobars/confirm_infobar_creator.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/infobar.h"
#else
#include "chrome/browser/ui/web_applications/web_app_relaunch_notification.h"
#endif  // !BUILDFLAG(IS_CHROMEOS)

#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#endif  // !BUILDFLAG(IS_MAC)

#if BUILDFLAG(IS_CHROMEOS)
#include "ash/public/cpp/shelf_model.h"
#include "chrome/browser/ash/app_list/app_list_syncable_service.h"
#include "chrome/browser/ash/app_list/app_list_syncable_service_factory.h"
#include "chrome/browser/ui/ash/shelf/chrome_shelf_controller.h"
#include "chrome/browser/ui/ash/shelf/chrome_shelf_controller_util.h"
#include "chromeos/ash/components/nonclosable_app_ui/nonclosable_app_ui_utils.h"
#include "components/sync/model/string_ordinal.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

#if BUILDFLAG(IS_WIN)
#include "base/process/process.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/web_applications/os_integration/os_integration_manager.h"
#include "chrome/browser/web_applications/os_integration/web_app_shortcut.h"
#include "chrome/browser/web_applications/web_app_install_finalizer.h"
#include "components/keep_alive_registry/keep_alive_types.h"
#include "components/keep_alive_registry/scoped_keep_alive.h"
#endif  // BUILDFLAG(IS_WIN)

namespace base {
class FilePath;
}

namespace web_app {

class AppLock;

namespace {

#if BUILDFLAG(IS_WIN)
void UninstallWebAppWithDialogFromStartupSwitch(
    std::unique_ptr<ScopedKeepAlive> scoped_keep_alive,
    const webapps::AppId& app_id,
    WebAppProvider* provider) {
  if (provider->registrar_unsafe().CanUserUninstallWebApp(app_id)) {
    provider->ui_manager().PresentUserUninstallDialog(
        app_id, webapps::WebappUninstallSource::kOsSettings,
        gfx::NativeWindow(),
        base::BindOnce(
            [](std::unique_ptr<ScopedKeepAlive> scoped_keep_alive,
               webapps::UninstallResultCode code) {
              // This ensures that the scoped_keep_alive will be deleted in the
              // next message loop, giving objects like DialogDelegate enough
              // time to shut itself down. See crbug.com/1506302 for more
              // information.
              base::SequencedTaskRunner::GetCurrentDefault()->DeleteSoon(
                  FROM_HERE, std::move(scoped_keep_alive));
            },
            std::move(scoped_keep_alive)));
  } else {
    // This is necessary to remove all OS integrations if the app has
    // been uninstalled.
    SynchronizeOsOptions synchronize_options;
    synchronize_options.force_unregister_os_integration = true;
    provider->scheduler().SynchronizeOsIntegration(
        app_id,
        base::BindOnce(
            [](std::unique_ptr<ScopedKeepAlive> scoped_keep_alive) {},
            std::move(scoped_keep_alive)),
        synchronize_options);
  }
}

#endif  // BUILDFLAG(IS_WIN)

#if BUILDFLAG(IS_CHROMEOS)
void ShowNonclosableAppToast(const web_app::WebAppRegistrar& registrar,
                             const webapps::AppId& app_id) {
  ash::ShowNonclosableAppToast(app_id, registrar.GetAppShortName(app_id));
}
#endif  // BUILDFLAG(IS_CHROMEOS)

}  // namespace

// static
std::unique_ptr<WebAppUiManager> WebAppUiManager::Create(Profile* profile) {
  return std::make_unique<WebAppUiManagerImpl>(profile);
}

WebAppUiManagerImpl::WebAppUiManagerImpl(Profile* profile)
    : profile_(profile) {}

WebAppUiManagerImpl::~WebAppUiManagerImpl() = default;

void WebAppUiManagerImpl::Start() {
  DCHECK(!started_);
  started_ = true;

  for (Browser* browser : *BrowserList::GetInstance()) {
    if (!IsBrowserForInstalledApp(browser)) {
      continue;
    }

    ++num_windows_for_apps_map_[GetAppIdForBrowser(browser)];
  }

  extensions::ExtensionSystem::Get(profile_)->ready().Post(
      FROM_HERE, base::BindOnce(&WebAppUiManagerImpl::OnExtensionSystemReady,
                                weak_ptr_factory_.GetWeakPtr()));

  BrowserList::AddObserver(this);
}

void WebAppUiManagerImpl::Shutdown() {
  BrowserList::RemoveObserver(this);
  started_ = false;
}

WebAppUiManagerImpl* WebAppUiManagerImpl::AsImpl() {
  return this;
}

size_t WebAppUiManagerImpl::GetNumWindowsForApp(const webapps::AppId& app_id) {
  DCHECK(started_);

  auto it = num_windows_for_apps_map_.find(app_id);
  if (it == num_windows_for_apps_map_.end()) {
    return 0;
  }

  return it->second;
}

void WebAppUiManagerImpl::CloseAppWindows(const webapps::AppId& app_id) {
  DCHECK(started_);

  for (Browser* browser : *BrowserList::GetInstance()) {
    const AppBrowserController* app_controller = browser->app_controller();
    if (app_controller && app_controller->app_id() == app_id) {
      browser->window()->Close();
    }
  }
}

void WebAppUiManagerImpl::NotifyOnAllAppWindowsClosed(
    const webapps::AppId& app_id,
    base::OnceClosure callback) {
  DCHECK(started_);

  const size_t num_windows_for_app = GetNumWindowsForApp(app_id);
  if (num_windows_for_app == 0) {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, std::move(callback));
    return;
  }

  windows_closed_requests_map_[app_id].push_back(std::move(callback));
}

void WebAppUiManagerImpl::OnExtensionSystemReady() {
  extensions::ExtensionSystem::Get(profile_)
      ->app_sorting()
      ->InitializePageOrdinalMapFromWebApps();
}

bool WebAppUiManagerImpl::CanAddAppToQuickLaunchBar() const {
#if BUILDFLAG(IS_CHROMEOS)
  return true;
#else
  return false;
#endif
}

void WebAppUiManagerImpl::AddAppToQuickLaunchBar(const webapps::AppId& app_id) {
  DCHECK(CanAddAppToQuickLaunchBar());
#if BUILDFLAG(IS_CHROMEOS)
  // ChromeShelfController does not exist in unit tests.
  if (auto* controller = ChromeShelfController::instance()) {
    PinAppWithIDToShelf(app_id);
    controller->UpdateV1AppState(app_id);
  }
#endif  // BUILDFLAG(IS_CHROMEOS)
}

bool WebAppUiManagerImpl::IsAppInQuickLaunchBar(
    const webapps::AppId& app_id) const {
  DCHECK(CanAddAppToQuickLaunchBar());
#if BUILDFLAG(IS_CHROMEOS)
  // ChromeShelfController does not exist in unit tests.
  if (auto* controller = ChromeShelfController::instance()) {
    return controller->shelf_model()->IsAppPinned(app_id);
  }
#endif  // BUILDFLAG(IS_CHROMEOS)
  return false;
}

bool WebAppUiManagerImpl::CanReparentAppTabToWindow(
    const webapps::AppId& app_id,
    bool shortcut_created,
    content::WebContents* web_contents) const {
  CHECK(web_contents);
  const WebAppTabHelper* tab_helper =
      WebAppTabHelper::FromWebContents(web_contents);
  bool is_in_app_window = false;
  if (tab_helper) {
    // The tab helper doesn't exist in unit tests.
    is_in_app_window = tab_helper->is_in_app_window();
  }
  // App-to-app reparenting is not currently supported.
  if (is_in_app_window) {
    return false;
  }
#if BUILDFLAG(IS_MAC)
  // On macOS it is only possible to reparent the window when the shortcut (app
  // shim) was created. See https://crbug.com/915571.
  return shortcut_created;
#else
  return true;
#endif
}

Browser* WebAppUiManagerImpl::ReparentAppTabToWindow(
    content::WebContents* contents,
    const webapps::AppId& app_id,
    bool shortcut_created) {
  DCHECK(CanReparentAppTabToWindow(app_id, shortcut_created, contents));
  // Reparent the tab into an app window immediately.
  return ReparentWebContentsIntoAppBrowser(contents, app_id);
}

Browser* WebAppUiManagerImpl::ReparentAppTabToWindow(
    content::WebContents* contents,
    const webapps::AppId& app_id,
    base::OnceCallback<void(content::WebContents*)> completion_callback) {
  return ReparentWebContentsIntoAppBrowser(contents, app_id,
                                           std::move(completion_callback));
}

void WebAppUiManagerImpl::ShowWebAppFileLaunchDialog(
    const std::vector<base::FilePath>& file_paths,
    const webapps::AppId& app_id,
    WebAppLaunchAcceptanceCallback launch_callback) {
  ::web_app::ShowWebAppFileLaunchDialog(file_paths, profile_, app_id,
                                        std::move(launch_callback));
}

void WebAppUiManagerImpl::ShowWebAppProtocolLaunchDialog(
    const GURL& protocol_url,
    const webapps::AppId& app_id,
    WebAppLaunchAcceptanceCallback launch_callback) {
  ::web_app::ShowWebAppProtocolLaunchDialog(protocol_url, profile_, app_id,
                                            std::move(launch_callback));
}

void WebAppUiManagerImpl::ShowWebAppIdentityUpdateDialog(
    const std::string& app_id,
    bool title_change,
    bool icon_change,
    const std::u16string& old_title,
    const std::u16string& new_title,
    const SkBitmap& old_icon,
    const SkBitmap& new_icon,
    content::WebContents* web_contents,
    web_app::AppIdentityDialogCallback callback) {
  ::web_app::ShowWebAppIdentityUpdateDialog(
      app_id, title_change, icon_change, old_title, new_title, old_icon,
      new_icon, web_contents, std::move(callback));
}

void WebAppUiManagerImpl::ShowWebAppSettings(const webapps::AppId& app_id) {
  WebAppProvider* provider = WebAppProvider::GetForWebApps(profile_);
  if (!provider) {
    return;
  }

  GURL start_url = provider->registrar_unsafe().GetAppStartUrl(app_id);
  if (!start_url.is_valid()) {
    return;
  }

  chrome::ShowSiteSettings(profile_, start_url);
}

void WebAppUiManagerImpl::LaunchWebApp(apps::AppLaunchParams params,
                                       LaunchWebAppWindowSetting launch_setting,
                                       Profile& profile,
                                       LaunchWebAppDebugValueCallback callback,
                                       WithAppResources& lock) {
  ::web_app::LaunchWebApp(std::move(params), launch_setting, profile, lock,
                          std::move(callback));
}

void WebAppUiManagerImpl::WaitForFirstRunService(
    Profile& profile,
    FirstRunServiceCompletedCallback callback) {
  std::move(callback).Run(/*success=*/true);
}

#if BUILDFLAG(IS_CHROMEOS)
void WebAppUiManagerImpl::MigrateLauncherState(
    const webapps::AppId& from_app_id,
    const webapps::AppId& to_app_id,
    base::OnceClosure callback) {
  auto* app_list_syncable_service =
      app_list::AppListSyncableServiceFactory::GetForProfile(profile_);
  bool to_app_in_shelf =
      app_list_syncable_service->GetPinPosition(to_app_id).IsValid();
  // If the new app is already pinned to the shelf don't transfer UI prefs
  // across as that could cause it to become unpinned.
  if (!to_app_in_shelf) {
    app_list_syncable_service->TransferItemAttributes(from_app_id, to_app_id);
  }
  std::move(callback).Run();
}

void WebAppUiManagerImpl::DisplayRunOnOsLoginNotification(
    const base::flat_map<webapps::AppId, RoolNotificationBehavior>& apps,
    base::WeakPtr<Profile> profile) {
  web_app::DisplayRunOnOsLoginNotification(apps, profile);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

void WebAppUiManagerImpl::NotifyAppRelaunchState(
    const webapps::AppId& placeholder_app_id,
    const webapps::AppId& final_app_id,
    const std::u16string& final_app_name,
    base::WeakPtr<Profile> profile,
    AppRelaunchState relaunch_state) {
#if BUILDFLAG(IS_CHROMEOS)
  web_app::NotifyAppRelaunchState(placeholder_app_id, final_app_id,
                                  final_app_name, std::move(profile),
                                  relaunch_state);
#endif  // BUILDFLAG(IS_CHROMEOS)
}

content::WebContents* WebAppUiManagerImpl::CreateNewTab() {
  NavigateParams params(profile_, GURL(url::kAboutBlankURL),
                        ui::PAGE_TRANSITION_FROM_API);
  base::WeakPtr<content::NavigationHandle> handle = Navigate(&params);
  if (handle) {
    return handle->GetWebContents();
  }
  return nullptr;
}

bool WebAppUiManagerImpl::IsWebContentsActiveTabInBrowser(
    content::WebContents* web_contents) {
  Browser* browser = chrome::FindBrowserWithTab(web_contents);
  return browser && browser->tab_strip_model() &&
         browser->tab_strip_model()->GetActiveWebContents() == web_contents;
}

void WebAppUiManagerImpl::TriggerInstallDialog(
    content::WebContents* web_contents,
    webapps::WebappInstallSource source,
    InstallCallback callback) {
  web_app::CreateWebAppFromManifest(web_contents, source, std::move(callback));
}

void WebAppUiManagerImpl::TriggerInstallDialogForBackgroundInstall(
    content::WebContents* initiating_web_contents,
    std::unique_ptr<webapps::MlInstallOperationTracker> tracker,
    const GURL& install_url,
    const std::optional<GURL>& manifest_id,
    InstallCallback callback) {
  web_app::CreateWebAppForBackgroundInstall(initiating_web_contents,
                                            std::move(tracker), install_url,
                                            manifest_id, std::move(callback));
}

void WebAppUiManagerImpl::TriggerLaunchDialogForBackgroundInstall(
    content::WebContents* initiating_web_contents,
    const webapps::AppId& app_id,
    Profile* profile,
    const std::string& app_name,
    WebInstallAppLaunchAcceptanceCallback callback) {
  ShowWebInstallAppLaunchDialog(initiating_web_contents, app_id, profile,
                                app_name, std::move(callback));
}

void WebAppUiManagerImpl::PresentUserUninstallDialog(
    const webapps::AppId& app_id,
    webapps::WebappUninstallSource uninstall_source,
    BrowserWindow* parent_window,
    UninstallCompleteCallback callback) {
  PresentUserUninstallDialog(
      app_id, uninstall_source,
      parent_window ? parent_window->GetNativeWindow() : gfx::NativeWindow(),
      std::move(callback), base::DoNothing());
}

void WebAppUiManagerImpl::PresentUserUninstallDialog(
    const webapps::AppId& app_id,
    webapps::WebappUninstallSource uninstall_source,
    gfx::NativeWindow native_window,
    UninstallCompleteCallback callback) {
  PresentUserUninstallDialog(app_id, uninstall_source, native_window,
                             std::move(callback), base::DoNothing());
}

void WebAppUiManagerImpl::PresentUserUninstallDialog(
    const webapps::AppId& app_id,
    webapps::WebappUninstallSource uninstall_source,
    gfx::NativeWindow parent_window,
    UninstallCompleteCallback uninstall_complete_callback,
    UninstallScheduledCallback uninstall_scheduled_callback) {
  std::unique_ptr<views::NativeWindowTracker> parent_window_tracker;
  if (parent_window) {
    parent_window_tracker = views::NativeWindowTracker::Create(parent_window);
  }

  if (parent_window && parent_window_tracker->WasNativeWindowDestroyed()) {
    OnUninstallCancelled(std::move(uninstall_complete_callback),
                         std::move(uninstall_scheduled_callback));
    return;
  }

  WebAppProvider* provider = WebAppProvider::GetForWebApps(profile_);
  CHECK(provider);

  provider->icon_manager().ReadIcons(
      app_id, IconPurpose::ANY,
      provider->registrar_unsafe().GetAppDownloadedIconSizesAny(app_id),
      base::BindOnce(&WebAppUiManagerImpl::OnIconsReadForUninstall,
                     weak_ptr_factory_.GetWeakPtr(), app_id, uninstall_source,
                     parent_window, std::move(parent_window_tracker),
                     std::move(uninstall_complete_callback),
                     std::move(uninstall_scheduled_callback)));
}

void WebAppUiManagerImpl::ShowIntentPicker(
    const GURL& url,
    content::WebContents* web_contents,
    ShowIntentPickerBubbleCallback callback) {
  IntentPickerTabHelper* intent_picker_tab_helper =
      IntentPickerTabHelper::FromWebContents(web_contents);

  if (!intent_picker_tab_helper) {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), /*launched=*/false));
    return;
  }
  intent_picker_tab_helper->ShowIntentPickerBubbleOrLaunchApp(
      url, /*always_show =*/true, std::move(callback));
}

void WebAppUiManagerImpl::LaunchOrFocusIsolatedWebAppInstaller(
    const base::FilePath& bundle_path) {
  auto it = active_installers_.find(bundle_path);

  if (it == active_installers_.end()) {
    // If no installer exists for the path, we create a new coordinator
    active_installers_[bundle_path] = ::web_app::LaunchIsolatedWebAppInstaller(
        profile_, bundle_path,
        base::BindOnce(&WebAppUiManagerImpl::OnIsolatedWebAppInstallerClosed,
                       weak_ptr_factory_.GetWeakPtr(), bundle_path));
  } else {
    // If an installer already exists for |path|, we focus the existing
    // installer.
    FocusIsolatedWebAppInstaller(it->second);
  }
}

void WebAppUiManagerImpl::OnIsolatedWebAppInstallerClosed(
    base::FilePath bundle_path) {
  auto it = active_installers_.find(bundle_path);
  CHECK(it != active_installers_.end())
      << "Installer with path " << bundle_path
      << " is being closed, but it is not found in the list of active "
         "installers.";
  active_installers_.erase(it);
}

void WebAppUiManagerImpl::MaybeCreateEnableSupportedLinksInfobar(
    content::WebContents* web_contents,
    const std::string& launch_name) {
#if !BUILDFLAG(IS_CHROMEOS)
  std::unique_ptr<apps::EnableLinkCapturingInfoBarDelegate> delegate =
      apps::EnableLinkCapturingInfoBarDelegate::MaybeCreate(web_contents,
                                                            launch_name);
  if (delegate) {
    infobars::ContentInfoBarManager::FromWebContents(web_contents)
        ->AddInfoBar(CreateConfirmInfoBar(std::move(delegate)));
  }
#endif  // !BUILDFLAG(IS_CHROMEOS)
}

void WebAppUiManagerImpl::MaybeShowIPHPromoForAppsLaunchedViaLinkCapturing(
    Browser* browser,
    Profile* profile,
    const std::string& app_id) {
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
  WebAppProvider* provider = WebAppProvider::GetForWebApps(profile);
  CHECK(provider);

  if (!provider->registrar_unsafe().CapturesLinksInScope(app_id)) {
    return;
  }

  const Browser* app_browser =
      browser ? browser : AppBrowserController::FindForWebApp(*profile, app_id);
  if (!app_browser) {
    return;
  }

  if (WebAppPrefGuardrails::GetForNavigationCapturingIph(
          app_browser->profile()->GetPrefs())
          .IsBlockedByGuardrails(app_id)) {
    return;
  }

  web_app::PostCallbackOnBrowserActivation(
      app_browser, kToolbarAppMenuButtonElementId,
      base::BindOnce(
          &WebAppUiManagerImpl::ShowIPHPromoForAppsLaunchedViaLinkCapturing,
          weak_ptr_factory_.GetWeakPtr(), app_browser, app_id));
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
}

void WebAppUiManagerImpl::OnBrowserAdded(Browser* browser) {
  DCHECK(started_);
  if (!IsBrowserForInstalledApp(browser)) {
    return;
  }

  ++num_windows_for_apps_map_[GetAppIdForBrowser(browser)];

#if BUILDFLAG(IS_CHROMEOS)
  browser->tab_strip_model()->AddObserver(this);
#endif  // BUILDFLAG(IS_CHROMEOS)
}

#if BUILDFLAG(IS_CHROMEOS)
void WebAppUiManagerImpl::OnBrowserCloseCancelled(Browser* browser,
                                                  BrowserClosingStatus reason) {
  DCHECK(started_);
  if (!IsBrowserForInstalledApp(browser) ||
      reason != BrowserClosingStatus::kDeniedByPolicy) {
    return;
  }

  ShowNonclosableAppToast(
      WebAppProvider::GetForWebApps(profile_)->registrar_unsafe(),
      GetAppIdForBrowser(browser));
}
#endif  // BUILDFLAG(IS_CHROMEOS)

void WebAppUiManagerImpl::OnBrowserRemoved(Browser* browser) {
  DCHECK(started_);
  if (!IsBrowserForInstalledApp(browser)) {
    return;
  }

  const auto& app_id = GetAppIdForBrowser(browser);

  size_t& num_windows_for_app = num_windows_for_apps_map_[app_id];
  DCHECK_GT(num_windows_for_app, 0u);
  --num_windows_for_app;

#if BUILDFLAG(IS_CHROMEOS)
  browser->tab_strip_model()->RemoveObserver(this);
#endif  // BUILDFLAG(IS_CHROMEOS)

  if (num_windows_for_app > 0) {
    return;
  }

  auto it = windows_closed_requests_map_.find(app_id);
  if (it == windows_closed_requests_map_.end()) {
    return;
  }

  for (auto& callback : it->second) {
    std::move(callback).Run();
  }

  windows_closed_requests_map_.erase(app_id);
}

#if BUILDFLAG(IS_CHROMEOS)
void WebAppUiManagerImpl::TabCloseCancelled(
    const content::WebContents* contents) {
  CHECK(contents);
  const WebAppTabHelper* tab_helper =
      WebAppTabHelper::FromWebContents(contents);
  if (!tab_helper || !tab_helper->window_app_id()) {
    return;
  }

  ShowNonclosableAppToast(
      WebAppProvider::GetForWebApps(profile_)->registrar_unsafe(),
      *tab_helper->window_app_id());
}
#endif  // BUILDFLAG(IS_CHROMEOS)

#if BUILDFLAG(IS_WIN)
void WebAppUiManagerImpl::UninstallWebAppFromStartupSwitch(
    const webapps::AppId& app_id) {
  WebAppProvider* provider = WebAppProvider::GetForWebApps(profile_);
  // ScopedKeepAlive not only keeps the process from terminating early
  // during uninstall, it also ensures the process will terminate in the next
  // message loop if there are no active browser windows.
  provider->on_registry_ready().Post(
      FROM_HERE, base::BindOnce(&UninstallWebAppWithDialogFromStartupSwitch,
                                std::make_unique<ScopedKeepAlive>(
                                    KeepAliveOrigin::WEB_APP_UNINSTALL,
                                    KeepAliveRestartOption::DISABLED),
                                app_id, provider));
}
#endif  //  BUILDFLAG(IS_WIN)

bool WebAppUiManagerImpl::IsBrowserForInstalledApp(Browser* browser) {
  if (browser->profile() != profile_) {
    return false;
  }

  if (!browser->app_controller()) {
    return false;
  }

  return true;
}

webapps::AppId WebAppUiManagerImpl::GetAppIdForBrowser(Browser* browser) {
  return browser->app_controller()->app_id();
}

void WebAppUiManagerImpl::OnIconsReadForUninstall(
    const webapps::AppId& app_id,
    webapps::WebappUninstallSource uninstall_source,
    gfx::NativeWindow parent_window,
    std::unique_ptr<views::NativeWindowTracker> parent_window_tracker,
    UninstallCompleteCallback complete_callback,
    UninstallScheduledCallback uninstall_scheduled_callback,
    std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
  if (parent_window && parent_window_tracker->WasNativeWindowDestroyed()) {
    OnUninstallCancelled(std::move(complete_callback),
                         std::move(uninstall_scheduled_callback));
    return;
  }

  ShowWebAppUninstallDialog(
      profile_, app_id, uninstall_source, parent_window,
      std::move(icon_bitmaps),
      base::BindOnce(&WebAppUiManagerImpl::ScheduleUninstallIfUserRequested,
                     weak_ptr_factory_.GetWeakPtr(), app_id, uninstall_source,
                     std::move(complete_callback),
                     std::move(uninstall_scheduled_callback)));
}

void WebAppUiManagerImpl::ScheduleUninstallIfUserRequested(
    const webapps::AppId& app_id,
    webapps::WebappUninstallSource uninstall_source,
    UninstallCompleteCallback complete_callback,
    UninstallScheduledCallback uninstall_scheduled_callback,
    web_app::UninstallUserOptions uninstall_options) {
  WebAppProvider* provider = WebAppProvider::GetForWebApps(profile_);
  CHECK(provider);

  const bool uninstall_scheduled =
      uninstall_options.user_wants_uninstall &&
      provider->registrar_unsafe().CanUserUninstallWebApp(app_id);
  std::move(uninstall_scheduled_callback).Run(uninstall_scheduled);
  if (!uninstall_scheduled) {
    std::move(complete_callback).Run(webapps::UninstallResultCode::kCancelled);
    return;
  }

  UninstallCompleteCallback final_callback;
  if (uninstall_options.clear_site_data) {
    CHECK(uninstall_options.user_wants_uninstall);
    const GURL app_start_url =
        provider->registrar_unsafe().GetAppStartUrl(app_id);
    final_callback =
        base::BindOnce(&WebAppUiManagerImpl::ClearWebAppSiteDataIfNeeded,
                       weak_ptr_factory_.GetWeakPtr(), app_start_url,
                       std::move(complete_callback));
  } else {
    final_callback = std::move(complete_callback);
  }

  provider->scheduler().RemoveUserUninstallableManagements(
      app_id, uninstall_source, std::move(final_callback));
}

void WebAppUiManagerImpl::OnUninstallCancelled(
    UninstallCompleteCallback complete_callback,
    UninstallScheduledCallback uninstall_scheduled_callback) {
  std::move(uninstall_scheduled_callback).Run(false);
  std::move(complete_callback).Run(webapps::UninstallResultCode::kCancelled);
}

void WebAppUiManagerImpl::ClearWebAppSiteDataIfNeeded(
    const GURL app_start_url,
    UninstallCompleteCallback uninstall_complete_callback,
    webapps::UninstallResultCode uninstall_code) {
  // This callback should be run at the very end of the uninstallation + site
  // data removal process (if any).
  base::OnceClosure final_uninstall_callback =
      base::BindOnce(std::move(uninstall_complete_callback), uninstall_code);

  // Only clear site data if the uninstallation has succeeded, i.e. either the
  // app has been uninstalled completely, or it was previously uninstalled but
  // some data had been left over.
  if (webapps::UninstallSucceeded(uninstall_code)) {
    content::ClearSiteData(profile_->GetWeakPtr(),
                           /*storage_partition_config=*/std::nullopt,
                           url::Origin::Create(app_start_url),
                           content::ClearSiteDataTypeSet::All(),
                           /*storage_buckets_to_remove=*/{},
                           /*avoid_closing_connections=*/false,
                           /*cookie_partition_key=*/std::nullopt,
                           /*storage_key=*/std::nullopt,
                           /*partitioned_state_allowed_only=*/false,
                           std::move(final_uninstall_callback));
  } else {
    std::move(final_uninstall_callback).Run();
  }
}

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)

const base::Feature& GetPromoFeatureEngagementFromBrowser(
    const Browser* browser) {
  return browser->app_controller() != nullptr
             ? feature_engagement::kIPHDesktopPWAsLinkCapturingLaunch
             : feature_engagement::kIPHDesktopPWAsLinkCapturingLaunchAppInTab;
}

void WebAppUiManagerImpl::ShowIPHPromoForAppsLaunchedViaLinkCapturing(
    const Browser* browser,
    const webapps::AppId& app_id,
    bool is_activated) {
  if (!is_activated) {
    return;
  }

  const auto& feature = GetPromoFeatureEngagementFromBrowser(browser);
  user_education::FeaturePromoParams promo_params(feature, app_id);
  promo_params.close_callback =
      base::BindOnce(&WebAppUiManagerImpl::OnIPHPromoResponseForLinkCapturing,
                     weak_ptr_factory_.GetWeakPtr(), browser, app_id);
  promo_params.show_promo_result_callback =
      base::BindOnce([](user_education::FeaturePromoResult result) {
        if (result) {
          base::RecordAction(
              base::UserMetricsAction("LinkCapturingIPHAppBubbleShown"));
        }
      });

  browser->window()->MaybeShowFeaturePromo(std::move(promo_params));

  // This is only needed for IPH bubbles that are anchored to a tab in a
  // browser. App browsers don't require this logic since tab switching and
  // navigating to another page isn't something to worry about in an app
  // window.
  if (&feature ==
      &feature_engagement::kIPHDesktopPWAsLinkCapturingLaunchAppInTab) {
    WebAppTabHelper* const tab_helper = WebAppTabHelper::FromWebContents(
        browser->tab_strip_model()->GetActiveWebContents());
    CHECK(tab_helper);
    tab_helper->SetCallbackToRunOnTabChanges(base::BindOnce(
        &WebAppUiManagerImpl::OnTabChangedDuringIph,
        weak_ptr_factory_.GetWeakPtr(), base::Unretained(browser)));
  }
}

void WebAppUiManagerImpl::OnIPHPromoResponseForLinkCapturing(
    const Browser* browser,
    const webapps::AppId& app_id) {
  if (!browser) {
    return;
  }

  const auto* const feature_promo_controller =
      browser->window()->GetFeaturePromoController(
          base::PassKey<WebAppUiManagerImpl>());
  if (!feature_promo_controller) {
    return;
  }

  user_education::FeaturePromoClosedReason close_reason;
  feature_promo_controller->HasPromoBeenDismissed(
      {GetPromoFeatureEngagementFromBrowser(browser), app_id}, &close_reason);
  switch (close_reason) {
    case user_education::FeaturePromoClosedReason::kAction:
      base::RecordAction(
          base::UserMetricsAction("LinkCapturingIPHAppBubbleAccepted"));
      WebAppPrefGuardrails::GetForNavigationCapturingIph(
          browser->profile()->GetPrefs())
          .RecordAccept(app_id);
      break;
    case user_education::FeaturePromoClosedReason::kDismiss:
    case user_education::FeaturePromoClosedReason::kCancel:
    // This is needed if the promo is cancelled automatically by the
    // `WebAppTabHelper`.
    case user_education::FeaturePromoClosedReason::kFeatureEngaged:
      base::RecordAction(
          base::UserMetricsAction("LinkCapturingIPHAppBubbleNotAccepted"));
      WebAppPrefGuardrails::GetForNavigationCapturingIph(
          browser->profile()->GetPrefs())
          .RecordDismiss(app_id, base::Time::Now());
      break;
    default:
      break;
  }
}

void WebAppUiManagerImpl::OnTabChangedDuringIph(const Browser* browser) {
  const auto& feature =
      feature_engagement::kIPHDesktopPWAsLinkCapturingLaunchAppInTab;
  if (browser->window()->IsFeaturePromoQueued(feature)) {
    browser->window()->AbortFeaturePromo(feature);
  } else if (browser->window()->IsFeaturePromoActive(feature)) {
    browser->window()->NotifyFeaturePromoFeatureUsed(
        feature, FeaturePromoFeatureUsedAction::kClosePromoIfPresent);
  }
}

#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)

}  // namespace web_app