File: extensions_menu_view_controller.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 (1044 lines) | stat: -rw-r--r-- 41,537 bytes parent folder | download | duplicates (5)
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
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
// Copyright 2023 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/views/extensions/extensions_menu_view_controller.h"

#include <algorithm>

#include "base/functional/bind.h"
#include "base/i18n/case_conversion.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/notreached.h"
#include "chrome/browser/extensions/extension_action_runner.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/permissions/active_tab_permission_granter.h"
#include "chrome/browser/extensions/permissions/site_permissions_helper.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/extensions/extension_action_view_controller.h"
#include "chrome/browser/ui/extensions/extensions_container.h"
#include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
#include "chrome/browser/ui/toolbar/toolbar_action_view_controller.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_model.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/views/extensions/extensions_dialogs_utils.h"
#include "chrome/browser/ui/views/extensions/extensions_menu_item_view.h"
#include "chrome/browser/ui/views/extensions/extensions_menu_main_page_view.h"
#include "chrome/browser/ui/views/extensions/extensions_menu_site_permissions_page_view.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/permissions_manager.h"
#include "extensions/common/extension_id.h"
#include "ui/base/metadata/metadata_types.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/view_utils.h"
#include "ui/views/widget/widget.h"

namespace {

using PermissionsManager = extensions::PermissionsManager;
using SitePermissionsHelper = extensions::SitePermissionsHelper;

// Returns the state for the main page in the menu.
enum class MainPageState {
  // Site is restricted to all extensions.
  kRestrictedSite,
  // Site is restricted all non-enterprise extensions by policy.
  kPolicyBlockedSite,
  // User blocked all extensions access to the site.
  kUserBlockedSite,
  // User can customize each extension's access to the site.
  kUserCustomizedSite,
};

MainPageState GetMainPageState(Profile& profile,
                               const ToolbarActionsModel& toolbar_model,
                               content::WebContents& web_contents) {
  const GURL& url = web_contents.GetLastCommittedURL();
  if (toolbar_model.IsRestrictedUrl(url)) {
    return MainPageState::kRestrictedSite;
  }

  if (toolbar_model.IsPolicyBlockedHost(url)) {
    return MainPageState::kPolicyBlockedSite;
  }

  PermissionsManager::UserSiteSetting site_setting =
      PermissionsManager::Get(&profile)->GetUserSiteSetting(
          web_contents.GetPrimaryMainFrame()->GetLastCommittedOrigin());
  if (site_setting ==
      PermissionsManager::UserSiteSetting::kBlockAllExtensions) {
    return MainPageState::kUserBlockedSite;
  }

  return MainPageState::kUserCustomizedSite;
}

// Returns the extension for `extension_id`.
const extensions::Extension* GetExtension(
    Browser* browser,
    extensions::ExtensionId extension_id) {
  return extensions::ExtensionRegistry::Get(browser->profile())
      ->enabled_extensions()
      .GetByID(extension_id);
}

// Returns sorted extension ids based on their extensions name.
std::vector<std::string> SortExtensionsByName(
    ToolbarActionsModel& toolbar_model) {
  auto sort_by_name = [&toolbar_model](const ToolbarActionsModel::ActionId a,
                                       const ToolbarActionsModel::ActionId b) {
    return base::i18n::ToLower(toolbar_model.GetExtensionName(a)) <
           base::i18n::ToLower(toolbar_model.GetExtensionName(b));
  };
  std::vector<std::string> sorted_ids(toolbar_model.action_ids().begin(),
                                      toolbar_model.action_ids().end());
  std::sort(sorted_ids.begin(), sorted_ids.end(), sort_by_name);
  return sorted_ids;
}

// Returns the index of `action_id` in the toolbar model actions based on the
// extensions name alphabetical order.
size_t FindIndex(ToolbarActionsModel& toolbar_model,
                 const ToolbarActionsModel::ActionId& action_id) {
  std::u16string extension_name =
      base::i18n::ToLower(toolbar_model.GetExtensionName(action_id));
  auto sorted_action_ids = SortExtensionsByName(toolbar_model);
  return static_cast<size_t>(
      std::ranges::lower_bound(sorted_action_ids, extension_name, {},
                               [&toolbar_model](std::string id) {
                                 return base::i18n::ToLower(
                                     toolbar_model.GetExtensionName(id));
                               }) -
      sorted_action_ids.begin());
}

// Returns the main page, if it is the correct type.
ExtensionsMenuMainPageView* GetMainPage(views::View* page) {
  return views::AsViewClass<ExtensionsMenuMainPageView>(page);
}

// Returns the site permissions page, if it is the correct type.
ExtensionsMenuSitePermissionsPageView* GetSitePermissionsPage(
    views::View* page) {
  return views::AsViewClass<ExtensionsMenuSitePermissionsPageView>(page);
}

// Returns whether `extension` cannot have its site access modified by the user
// because of policy.
bool HasEnterpriseForcedAccess(const extensions::Extension& extension,
                               Profile& profile) {
  extensions::ManagementPolicy* policy =
      extensions::ExtensionSystem::Get(&profile)->management_policy();
  return !policy->UserMayModifySettings(&extension, nullptr) ||
         policy->MustRemainInstalled(&extension, nullptr);
}

// Returns whether the site permissions button should be visible.
bool IsSitePermissionsButtonVisible(const extensions::Extension& extension,
                                    Profile& profile,
                                    const ToolbarActionsModel& toolbar_model,
                                    content::WebContents& web_contents) {
  // Button is never visible when site is restricted.
  if (toolbar_model.IsRestrictedUrl(web_contents.GetLastCommittedURL())) {
    return false;
  }

  PermissionsManager::UserSiteSetting user_site_setting =
      PermissionsManager::Get(&profile)->GetUserSiteSetting(
          web_contents.GetPrimaryMainFrame()->GetLastCommittedOrigin());
  switch (user_site_setting) {
    case PermissionsManager::UserSiteSetting::kCustomizeByExtension: {
      // Extensions should always display the button.
      return true;
    }
    case PermissionsManager::UserSiteSetting::kBlockAllExtensions: {
      // Extension should only display the button when it's an enterprise
      // extension and has granted access.
      bool enterprise_forced_access =
          HasEnterpriseForcedAccess(extension, profile);
      SitePermissionsHelper::SiteInteraction site_interaction =
          SitePermissionsHelper(&profile).GetSiteInteraction(extension,
                                                             &web_contents);
      return enterprise_forced_access &&
             site_interaction ==
                 SitePermissionsHelper::SiteInteraction::kGranted;
    }
    case PermissionsManager::UserSiteSetting::kGrantAllExtensions: {
      NOTREACHED();
    }
  }
}

// Returns whether user can select the site access for `extension` on
// `web_contents`.
bool CanUserCustomizeExtensionSiteAccess(
    const extensions::Extension& extension,
    Profile& profile,
    const ToolbarActionsModel& toolbar_model,
    content::WebContents& web_contents) {
  const GURL& url = web_contents.GetLastCommittedURL();
  if (toolbar_model.IsRestrictedUrl(url)) {
    // We don't allow customization of restricted sites (e.g.
    // chrome://settings).
    return false;
  }

  if (extension.permissions_data()->IsPolicyBlockedHost(url)) {
    // Users can't customize the site access of policy-blocked sites.
    return false;
  }

  if (HasEnterpriseForcedAccess(extension, profile)) {
    // Users can't customize the site access of enterprise-installed extensions.
    return false;
  }

  // The extension wants site access if it at least wants "on click" access.
  auto* permissions_manager = PermissionsManager::Get(&profile);
  bool extension_wants_access = permissions_manager->CanUserSelectSiteAccess(
      extension, url, PermissionsManager::UserSiteAccess::kOnClick);
  if (!extension_wants_access) {
    // Users can't customize site access of extensions that don't want access to
    // begin with.
    return false;
  }

  // Users can only customize site access when they have allowed all extensions
  // to be customizable on the site.
  return permissions_manager->GetUserSiteSetting(
             web_contents.GetPrimaryMainFrame()->GetLastCommittedOrigin()) ==
         PermissionsManager::UserSiteSetting::kCustomizeByExtension;
}

// Returns the state for the `extension`'s site permissions button.
ExtensionMenuItemView::SitePermissionsButtonState GetSitePermissionsButtonState(
    const extensions::Extension& extension,
    Profile& profile,
    const ToolbarActionsModel& toolbar_model,
    content::WebContents& web_contents) {
  bool is_site_permissions_button_visible = IsSitePermissionsButtonVisible(
      extension, profile, toolbar_model, web_contents);
  if (!is_site_permissions_button_visible) {
    return ExtensionMenuItemView::SitePermissionsButtonState::kHidden;
  }

  bool is_site_permissions_button_enabled = CanUserCustomizeExtensionSiteAccess(
      extension, profile, toolbar_model, web_contents);
  return is_site_permissions_button_enabled
             ? ExtensionMenuItemView::SitePermissionsButtonState::kEnabled
             : ExtensionMenuItemView::SitePermissionsButtonState::kDisabled;
}

// Returns the sites access displayed by the `extension`'s site permissions
// button.
ExtensionMenuItemView::SitePermissionsButtonAccess
GetSitePermissionsButtonAccess(const extensions::Extension& extension,
                               Profile& profile,
                               const ToolbarActionsModel& toolbar_model,
                               content::WebContents& web_contents) {
  auto site_interaction = SitePermissionsHelper(&profile).GetSiteInteraction(
      extension, &web_contents);
  if (site_interaction == SitePermissionsHelper::SiteInteraction::kNone) {
    return ExtensionMenuItemView::SitePermissionsButtonAccess::kNone;
  }

  auto site_access = PermissionsManager::Get(&profile)->GetUserSiteAccess(
      extension, web_contents.GetLastCommittedURL());
  switch (site_access) {
    case PermissionsManager::UserSiteAccess::kOnClick:
      return ExtensionMenuItemView::SitePermissionsButtonAccess::kOnClick;
    case PermissionsManager::UserSiteAccess::kOnSite:
      return ExtensionMenuItemView::SitePermissionsButtonAccess::kOnSite;
    case PermissionsManager::UserSiteAccess::kOnAllSites:
      return ExtensionMenuItemView::SitePermissionsButtonAccess::kOnAllSites;
  }
}

// Returns the state for the `extension`'s site access toggle button.
ExtensionMenuItemView::SiteAccessToggleState GetSiteAccessToggleState(
    const extensions::Extension& extension,
    Profile& profile,
    const ToolbarActionsModel& toolbar_model,
    content::WebContents& web_contents) {
  if (!CanUserCustomizeExtensionSiteAccess(extension, profile, toolbar_model,
                                           web_contents)) {
    return ExtensionMenuItemView::SiteAccessToggleState::kHidden;
  }

  // Button is on iff the extension has access to the site.
  auto site_interaction = SitePermissionsHelper(&profile).GetSiteInteraction(
      extension, &web_contents);
  return site_interaction == SitePermissionsHelper::SiteInteraction::kGranted
             ? ExtensionMenuItemView::SiteAccessToggleState::kOn
             : ExtensionMenuItemView::SiteAccessToggleState::kOff;
}

void LogSiteAccessUpdate(PermissionsManager::UserSiteAccess site_access) {
  switch (site_access) {
    case PermissionsManager::UserSiteAccess::kOnClick:
      base::RecordAction(
          base::UserMetricsAction("Extensions.Menu.OnClickSelected"));
      break;
    case PermissionsManager::UserSiteAccess::kOnSite:
      base::RecordAction(
          base::UserMetricsAction("Extensions.Menu.OnSiteSelected"));
      break;
    case PermissionsManager::UserSiteAccess::kOnAllSites:
      base::RecordAction(
          base::UserMetricsAction("Extensions.Menu.OnAllSitesSelected"));
      break;
    default:
      NOTREACHED() << "Unknown site access";
  }
}

}  // namespace

ExtensionsMenuViewController::ExtensionsMenuViewController(
    Browser* browser,
    ExtensionsContainer* extensions_container,
    views::View* bubble_contents,
    views::BubbleDialogDelegate* bubble_delegate)
    : browser_(browser),
      extensions_container_(extensions_container),
      bubble_contents_(bubble_contents),
      bubble_delegate_(bubble_delegate),
      toolbar_model_(ToolbarActionsModel::Get(browser_->profile())) {
  browser_->tab_strip_model()->AddObserver(this);
  toolbar_model_observation_.Observe(toolbar_model_.get());
  permissions_manager_observation_.Observe(
      PermissionsManager::Get(browser_->profile()));
}

// Note: No need to call TabStripModel::RemoveObserver(), because it's handled
// directly within TabStripModelObserver::~TabStripModelObserver().
ExtensionsMenuViewController::~ExtensionsMenuViewController() = default;

void ExtensionsMenuViewController::OpenMainPage() {
  auto main_page = std::make_unique<ExtensionsMenuMainPageView>(browser_, this);
  UpdateMainPage(main_page.get(), GetActiveWebContents());
  PopulateMainPage(main_page.get());

  SwitchToPage(std::move(main_page));
}

void ExtensionsMenuViewController::OpenSitePermissionsPage(
    const extensions::ExtensionId& extension_id) {
  CHECK(CanUserCustomizeExtensionSiteAccess(
      *GetExtension(browser_, extension_id), *browser_->profile(),
      *toolbar_model_, *GetActiveWebContents()));

  auto site_permissions_page =
      std::make_unique<ExtensionsMenuSitePermissionsPageView>(
          browser_, extension_id, this);
  UpdateSitePermissionsPage(site_permissions_page.get(),
                            GetActiveWebContents());

  SwitchToPage(std::move(site_permissions_page));

  base::RecordAction(
      base::UserMetricsAction("Extensions.Menu.SitePermissionsPageOpened"));
}

void ExtensionsMenuViewController::CloseBubble() {
  bubble_contents_->GetWidget()->CloseWithReason(
      views::Widget::ClosedReason::kCloseButtonClicked);
}

void ExtensionsMenuViewController::OnSiteAccessSelected(
    const extensions::ExtensionId& extension_id,
    PermissionsManager::UserSiteAccess site_access) {
  LogSiteAccessUpdate(site_access);

  SitePermissionsHelper permissions(browser_->profile());
  permissions.UpdateSiteAccess(*GetExtension(browser_, extension_id),
                               GetActiveWebContents(), site_access);
}

void ExtensionsMenuViewController::OnSiteSettingsToggleButtonPressed(
    bool is_on) {
  content::WebContents* web_contents = GetActiveWebContents();
  const url::Origin& origin =
      web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin();
  PermissionsManager::UserSiteSetting site_setting =
      is_on ? PermissionsManager::UserSiteSetting::kCustomizeByExtension
            : PermissionsManager::UserSiteSetting::kBlockAllExtensions;

  extensions::TabHelper::FromWebContents(web_contents)
      ->SetReloadRequired(site_setting);
  PermissionsManager::Get(browser_->profile())
      ->UpdateUserSiteSetting(origin, site_setting);

  if (is_on) {
    base::RecordAction(
        base::UserMetricsAction("Extensions.Menu.AllowByExtensionSelected"));
  } else {
    base::RecordAction(
        base::UserMetricsAction("Extensions.Menu.ExtensionsBlockedSelected"));
  }
}

void ExtensionsMenuViewController::OnExtensionToggleSelected(
    const extensions::ExtensionId& extension_id,
    bool is_on) {
  const extensions::Extension* extension = GetExtension(browser_, extension_id);
  content::WebContents* web_contents = GetActiveWebContents();
  CHECK(CanUserCustomizeExtensionSiteAccess(*extension, *browser_->profile(),
                                            *toolbar_model_, *web_contents));

  SitePermissionsHelper permissions_helper(browser_->profile());
  auto* permissions_manager = PermissionsManager::Get(browser_->profile());
  auto current_site_access = permissions_manager->GetUserSiteAccess(
      *extension, web_contents->GetLastCommittedURL());
  PermissionsManager::ExtensionSiteAccess extension_site_access =
      permissions_manager->GetSiteAccess(*extension,
                                         web_contents->GetLastCommittedURL());

  // Grant extension site access when extension is toggled on.
  if (is_on) {
    DCHECK_EQ(current_site_access,
              PermissionsManager::UserSiteAccess::kOnClick);

    // Update site access when extension requested host permissions for the
    // current site (that is, site access was withheld).
    if (extension_site_access.withheld_site_access ||
        extension_site_access.withheld_all_sites_access) {
      // Restore to previous access by looking whether broad site access was
      // previously granted.
      PermissionsManager::UserSiteAccess new_site_access =
          permissions_manager->HasPreviousBroadSiteAccess(extension_id)
              ? PermissionsManager::UserSiteAccess::kOnAllSites
              : PermissionsManager::UserSiteAccess::kOnSite;
      permissions_helper.UpdateSiteAccess(*extension, web_contents,
                                          new_site_access);
      return;
    }

    // Otherwise, grant one-time access (e.g. extension with activeTab is
    // granted access).
    extensions::ExtensionActionRunner* action_runner =
        extensions::ExtensionActionRunner::GetForWebContents(web_contents);
    if (action_runner) {
      action_runner->GrantTabPermissions({extension});
    }
    return;
  }

  // Revoke extension's site access when extension is toggled off.

  // Update site access to "on click" when extension requested, and was granted,
  // host permissions for the current site (that is, extension has site access).
  if (extension_site_access.has_site_access ||
      extension_site_access.has_all_sites_access) {
    DCHECK_NE(current_site_access,
              PermissionsManager::UserSiteAccess::kOnClick);
    permissions_helper.UpdateSiteAccess(
        *extension, web_contents, PermissionsManager::UserSiteAccess::kOnClick);
    return;
  }

  // Otherwise, extension has one-time access and we need to clear tab
  // permissions (e.g extension with activeTab was granted one-time access).
  DCHECK_EQ(current_site_access, PermissionsManager::UserSiteAccess::kOnClick);
  extensions::ActiveTabPermissionGranter::FromWebContents(web_contents)
      ->ClearActiveExtensionAndNotify(extension_id);

  auto* action_runner =
      extensions::ExtensionActionRunner::GetForWebContents(web_contents);
  if (action_runner) {
    action_runner->ShowReloadPageBubble({extension_id});
  }
}

void ExtensionsMenuViewController::OnReloadPageButtonClicked() {
  GetActiveWebContents()->GetController().Reload(content::ReloadType::NORMAL,
                                                 false);
}

void ExtensionsMenuViewController::OnAllowExtensionClicked(
    const extensions::ExtensionId& extension_id) {
  content::WebContents* web_contents = GetActiveWebContents();
  extensions::ExtensionActionRunner* action_runner =
      extensions::ExtensionActionRunner::GetForWebContents(web_contents);
  if (!action_runner) {
    return;
  }

  // Accepting a site access request grants always access to the site.
  extensions::SitePermissionsHelper(browser_->profile())
      .UpdateSiteAccess(
          *GetExtension(browser_, extension_id), web_contents,
          extensions::PermissionsManager::UserSiteAccess::kOnSite);

  base::RecordAction(base::UserMetricsAction(
      "Extensions.Toolbar.ExtensionActivatedFromAllowingRequestAccessInMenu"));
}

void ExtensionsMenuViewController::OnDismissExtensionClicked(
    const extensions::ExtensionId& extension_id) {
  auto* permissions_manager = PermissionsManager::Get(browser_->profile());
  CHECK(permissions_manager);
  content::WebContents* web_contents = GetActiveWebContents();
  int tab_id = extensions::ExtensionTabUtil::GetTabId(web_contents);
  permissions_manager->UserDismissedHostAccessRequest(web_contents, tab_id,
                                                      extension_id);

  base::RecordAction(base::UserMetricsAction(
      "Extensions.Toolbar.ExtensionRequestDismissedFromMenu"));
}

void ExtensionsMenuViewController::OnShowRequestsTogglePressed(
    const extensions::ExtensionId& extension_id,
    bool is_on) {
  extensions::SitePermissionsHelper(browser_->profile())
      .SetShowAccessRequestsInToolbar(extension_id, is_on);

  if (is_on) {
    base::RecordAction(base::UserMetricsAction(
        "Extensions.Menu.ShowRequestsInToolbarPressed"));
  } else {
    base::RecordAction(base::UserMetricsAction(
        "Extensions.Menu.HideRequestsInToolbarPressed"));
  }
}

void ExtensionsMenuViewController::TabChangedAt(content::WebContents* contents,
                                                int index,
                                                TabChangeType change_type) {
  bool should_update_page = false;
  switch (change_type) {
    case TabChangeType::kAll:
      should_update_page = true;
      break;
    case TabChangeType::kLoadingOnly:
      should_update_page = false;
      break;
  }

  if (!should_update_page || GetActiveWebContents() != contents) {
    return;
  }

  UpdatePage(contents);
}

void ExtensionsMenuViewController::OnTabStripModelChanged(
    TabStripModel* tab_strip_model,
    const TabStripModelChange& change,
    const TabStripSelectionChange& selection) {
  CHECK_EQ(tab_strip_model, browser_->tab_strip_model());
  content::WebContents* web_contents = GetActiveWebContents();

  if (!selection.active_tab_changed() || !web_contents) {
    return;
  }

  UpdatePage(web_contents);
}

void ExtensionsMenuViewController::UpdatePage(
    content::WebContents* web_contents) {
  DCHECK(current_page_);

  if (!web_contents) {
    return;
  }

  auto* site_permissions_page = GetSitePermissionsPage(current_page_.view());
  if (site_permissions_page) {
    // Update site permissions page if the extension can have one.
    if (CanUserCustomizeExtensionSiteAccess(
            *GetExtension(browser_, site_permissions_page->extension_id()),
            *browser_->profile(), *toolbar_model_, *web_contents)) {
      UpdateSitePermissionsPage(site_permissions_page, web_contents);
      return;
    }

    // Otherwise navigate back to the main page.
    OpenMainPage();
    return;
  }

  ExtensionsMenuMainPageView* main_page = GetMainPage(current_page_.view());
  DCHECK(main_page);
  UpdateMainPage(main_page, web_contents);
}

void ExtensionsMenuViewController::UpdateMainPage(
    ExtensionsMenuMainPageView* main_page,
    content::WebContents* web_contents) {
  CHECK(web_contents);
  auto has_enterprise_extensions = [&]() {
    return std::any_of(
        toolbar_model_->action_ids().begin(),
        toolbar_model_->action_ids().end(),
        [this](const ToolbarActionsModel::ActionId extension_id) {
          auto* extension = GetExtension(browser_, extension_id);
          return HasEnterpriseForcedAccess(*extension, *browser_->profile());
        });
  };
  auto reload_required = [web_contents]() {
    return extensions::TabHelper::FromWebContents(web_contents)
        ->IsReloadRequired();
  };

  std::u16string current_site = GetCurrentHost(web_contents);
  int site_settings_label_id;
  bool is_site_settings_toggle_visible = false;
  bool is_site_settings_toggle_on = false;
  bool is_site_settings_tooltip_visible = false;
  bool is_reload_required = false;
  bool can_have_requests = false;

  MainPageState state =
      GetMainPageState(*browser_->profile(), *toolbar_model_, *web_contents);
  switch (state) {
    case MainPageState::kRestrictedSite:
      site_settings_label_id =
          IDS_EXTENSIONS_MENU_SITE_SETTINGS_NOT_ALLOWED_LABEL;
      is_site_settings_toggle_visible = false;
      is_site_settings_toggle_on = false;
      break;
    case MainPageState::kPolicyBlockedSite:
      site_settings_label_id =
          IDS_EXTENSIONS_MENU_SITE_SETTINGS_NOT_ALLOWED_LABEL;
      is_site_settings_toggle_visible = false;
      is_site_settings_toggle_on = false;
      is_site_settings_tooltip_visible = has_enterprise_extensions();
      break;
    case MainPageState::kUserBlockedSite:
      site_settings_label_id = IDS_EXTENSIONS_MENU_SITE_SETTINGS_LABEL;
      is_site_settings_toggle_visible = true;
      is_site_settings_toggle_on = false;
      is_site_settings_tooltip_visible = has_enterprise_extensions();
      is_reload_required = reload_required();
      break;
    case MainPageState::kUserCustomizedSite:
      site_settings_label_id = IDS_EXTENSIONS_MENU_SITE_SETTINGS_LABEL;
      is_site_settings_toggle_visible = true;
      is_site_settings_toggle_on = true;
      is_reload_required = reload_required();
      can_have_requests = true;
      break;
  }

  main_page->UpdateSiteSettings(
      current_site, site_settings_label_id, is_site_settings_tooltip_visible,
      is_site_settings_toggle_visible, is_site_settings_toggle_on);

  if (is_reload_required) {
    main_page->ShowReloadSection();
  } else if (can_have_requests) {
    int tab_id = extensions::ExtensionTabUtil::GetTabId(web_contents);
    auto* permissions_manager = PermissionsManager::Get(browser_->profile());
    int index = 0;
    std::vector<std::string> extension_ids =
        SortExtensionsByName(*toolbar_model_);

    for (const auto& extension_id : extension_ids) {
      if (permissions_manager->HasActiveHostAccessRequest(tab_id,
                                                          extension_id)) {
        AddOrUpdateExtensionRequestingAccess(main_page, extension_id, index,
                                             web_contents);
        ++index;
      } else {
        // Otherwise remove its entry, if existent.
        main_page->RemoveExtensionRequestingAccess(extension_id);
      }
    }
    main_page->MaybeShowRequestsSection();
  }

  // Update menu items.
  // TODO(crbug.com/40879945): Reorder the extensions after updating them, since
  // their names can change.
  std::vector<ExtensionMenuItemView*> menu_items = main_page->GetMenuItems();
  for (auto* menu_item : menu_items) {
    const extensions::Extension* extension =
        GetExtension(browser_, menu_item->view_controller()->GetId());
    CHECK(extension);

    ExtensionMenuItemView::SiteAccessToggleState site_access_toggle_state =
        GetSiteAccessToggleState(*extension, *browser_->profile(),
                                 *toolbar_model_, *web_contents);
    ExtensionMenuItemView::SitePermissionsButtonState
        site_permissions_button_state = GetSitePermissionsButtonState(
            *extension, *browser_->profile(), *toolbar_model_, *web_contents);
    ExtensionMenuItemView::SitePermissionsButtonAccess
        site_permissions_button_access = GetSitePermissionsButtonAccess(
            *extension, *browser_->profile(), *toolbar_model_, *web_contents);
    bool is_enterprise =
        HasEnterpriseForcedAccess(*extension, *browser_->profile());
    menu_item->Update(site_access_toggle_state, site_permissions_button_state,
                      site_permissions_button_access, is_enterprise);
  }
}

void ExtensionsMenuViewController::UpdateSitePermissionsPage(
    ExtensionsMenuSitePermissionsPageView* site_permissions_page,
    content::WebContents* web_contents) {
  CHECK(web_contents);

  auto* permissions_manager = PermissionsManager::Get(browser_->profile());
  SitePermissionsHelper permissions_helper(browser_->profile());

  extensions::ExtensionId extension_id = site_permissions_page->extension_id();
  const extensions::Extension* extension = GetExtension(browser_, extension_id);
  const GURL& url = web_contents->GetLastCommittedURL();
  const int icon_size = ChromeLayoutProvider::Get()->GetDistanceMetric(
      DISTANCE_EXTENSIONS_MENU_EXTENSION_ICON_SIZE);
  ToolbarActionViewController* action_controller =
      extensions_container_->GetActionForId(extension_id);

  std::u16string extension_name = action_controller->GetActionName();
  ui::ImageModel extension_icon =
      action_controller->GetIcon(web_contents, gfx::Size(icon_size, icon_size));
  std::u16string current_site = GetCurrentHost(web_contents);
  PermissionsManager::UserSiteAccess user_site_access =
      permissions_manager->GetUserSiteAccess(*extension, url);
  bool is_show_requests_toggle_on =
      permissions_helper.ShowAccessRequestsInToolbar(extension_id);
  bool is_on_site_enabled = permissions_manager->CanUserSelectSiteAccess(
      *extension, url, PermissionsManager::UserSiteAccess::kOnSite);
  bool is_on_all_sites_enabled = permissions_manager->CanUserSelectSiteAccess(
      *extension, url, PermissionsManager::UserSiteAccess::kOnAllSites);

  site_permissions_page->Update(extension_name, extension_icon, current_site,
                                user_site_access, is_show_requests_toggle_on,
                                is_on_site_enabled, is_on_all_sites_enabled);
}

void ExtensionsMenuViewController::OnToolbarActionAdded(
    const ToolbarActionsModel::ActionId& action_id) {
  DCHECK(current_page_);

  // Do nothing when site permission page is opened as a new extension doesn't
  // affect the site permissions page of another extension.
  if (GetSitePermissionsPage(current_page_.view())) {
    return;
  }

  // Insert a menu item for the extension when main page is opened.
  auto* main_page = GetMainPage(current_page_.view());
  DCHECK(main_page);
  int index = FindIndex(*toolbar_model_, action_id);
  InsertMenuItemMainPage(main_page, action_id, index);
}

void ExtensionsMenuViewController::OnToolbarActionRemoved(
    const ToolbarActionsModel::ActionId& action_id) {
  DCHECK(current_page_);

  auto* site_permissions_page = GetSitePermissionsPage(current_page_.view());
  if (site_permissions_page) {
    // Return to the main page if site permissions page belongs to the extension
    // removed.
    if (site_permissions_page->extension_id() == action_id) {
      OpenMainPage();
    }
    return;
  }

  // Remove the menu item for the extension when main page is opened.
  auto* main_page = GetMainPage(current_page_.view());
  DCHECK(main_page);
  main_page->RemoveMenuItem(action_id);
}

void ExtensionsMenuViewController::OnToolbarActionUpdated(
    const ToolbarActionsModel::ActionId& action_id) {
  UpdatePage(GetActiveWebContents());
}

void ExtensionsMenuViewController::OnToolbarModelInitialized() {
  DCHECK(current_page_);

  // Toolbar model should have been initialized if site permissions page is
  // open, since this page can only be reached after main page was populated
  // after toolbar model was initialized.
  CHECK(!GetSitePermissionsPage(current_page_.view()));

  auto* main_page = GetMainPage(current_page_.view());
  DCHECK(main_page);
  PopulateMainPage(main_page);
}

void ExtensionsMenuViewController::OnToolbarPinnedActionsChanged() {
  DCHECK(current_page_);

  // Do nothing when site permissions page is opened as it doesn't have pin
  // buttons.
  if (GetSitePermissionsPage(current_page_.view())) {
    return;
  }

  auto* main_page = GetMainPage(current_page_.view());
  DCHECK(main_page);

  std::vector<ExtensionMenuItemView*> menu_items = main_page->GetMenuItems();
  for (auto* menu_item : menu_items) {
    bool is_action_pinned =
        toolbar_model_->IsActionPinned(menu_item->view_controller()->GetId());
    menu_item->UpdateContextMenuButton(is_action_pinned);
  }
}

void ExtensionsMenuViewController::OnUserPermissionsSettingsChanged(
    const PermissionsManager::UserPermissionsSettings& settings) {
  DCHECK(current_page_);

  if (GetSitePermissionsPage(current_page_.view())) {
    // Site permissions page can only be opened when site setting is set to
    // "customize by extension". Thus, when site settings changed, we have to
    // return to main page.
    DCHECK_NE(PermissionsManager::Get(browser_->profile())
                  ->GetUserSiteSetting(GetActiveWebContents()
                                           ->GetPrimaryMainFrame()
                                           ->GetLastCommittedOrigin()),
              PermissionsManager::UserSiteSetting::kCustomizeByExtension);
    OpenMainPage();
    return;
  }

  ExtensionsMenuMainPageView* main_page = GetMainPage(current_page_.view());
  DCHECK(main_page);
  UpdateMainPage(main_page, GetActiveWebContents());

  // TODO(crbug.com/40879945): Update the "highlighted section" based on the
  // `site_setting` and whether a page refresh is needed.

  // TODO(crbug.com/40879945): Run blocked actions for extensions that only have
  // blocked actions that don't require a page refresh to run.
}

void ExtensionsMenuViewController::OnShowAccessRequestsInToolbarChanged(
    const extensions::ExtensionId& extension_id,
    bool can_show_requests) {
  DCHECK(current_page_);

  // Changing whether an extension can show requests access in the toolbar only
  // affects the site permissions page for such extension.
  auto* site_permissions_page = GetSitePermissionsPage(current_page_.view());
  if (site_permissions_page &&
      site_permissions_page->extension_id() == extension_id) {
    site_permissions_page->UpdateShowRequestsToggle(can_show_requests);
  }
}

void ExtensionsMenuViewController::OnHostAccessRequestDismissedByUser(
    const extensions::ExtensionId& extension_id,
    const url::Origin& origin) {
  DCHECK(current_page_);

  // Extension can only dismiss requests from the menu's main page. if it has
  // navigated to another site in between, do nothing (navigation listeners will
  // handle menu updates).
  auto* main_page = GetMainPage(current_page_.view());
  if (!main_page ||
      GetActiveWebContents()->GetPrimaryMainFrame()->GetLastCommittedOrigin() !=
          origin) {
    return;
  }

  main_page->RemoveExtensionRequestingAccess(extension_id);
  main_page->MaybeShowRequestsSection();
}

void ExtensionsMenuViewController::OnHostAccessRequestAdded(
    const extensions::ExtensionId& extension_id,
    int tab_id) {
  DCHECK(current_page_);

  // Ignore requests for other tabs.
  int current_tab_id =
      extensions::ExtensionTabUtil::GetTabId(GetActiveWebContents());
  if (tab_id != current_tab_id) {
    return;
  }

  // Site access requests only affect the main page.
  ExtensionsMenuMainPageView* main_page = GetMainPage(current_page_.view());
  if (!main_page) {
    return;
  }

  // Add the request iff it's an active one.
  auto* permissions_manager =
      extensions::PermissionsManager::Get(browser_->profile());
  if (permissions_manager->HasActiveHostAccessRequest(tab_id, extension_id)) {
    // TODO(crbug.com/330588494): Add to correct index based on alphabetic
    // order.
    int index = 0;
    AddOrUpdateExtensionRequestingAccess(main_page, extension_id, index,
                                         GetActiveWebContents());
    main_page->MaybeShowRequestsSection();
  }
}

void ExtensionsMenuViewController::OnHostAccessRequestUpdated(
    const extensions::ExtensionId& extension_id,
    int tab_id) {
  DCHECK(current_page_);

  // Ignore requests for other tabs.
  int current_tab_id =
      extensions::ExtensionTabUtil::GetTabId(GetActiveWebContents());
  if (tab_id != current_tab_id) {
    return;
  }

  // Site access requests only affect the main page.
  ExtensionsMenuMainPageView* main_page = GetMainPage(current_page_.view());
  if (!main_page) {
    return;
  }

  // Update the request iff it's an active one.
  auto* permissions_manager =
      extensions::PermissionsManager::Get(browser_->profile());
  if (permissions_manager->HasActiveHostAccessRequest(tab_id, extension_id)) {
    // TODO(crbug.com/330588494): Add to correct index based on alphabetic
    // order.
    int index = 0;
    AddOrUpdateExtensionRequestingAccess(main_page, extension_id, index,
                                         GetActiveWebContents());
    main_page->MaybeShowRequestsSection();
    return;
  }

  // Otherwise, remove the request if existent.
  main_page->RemoveExtensionRequestingAccess(extension_id);
  main_page->MaybeShowRequestsSection();
}

void ExtensionsMenuViewController::OnHostAccessRequestRemoved(
    const extensions::ExtensionId& extension_id,
    int tab_id) {
  DCHECK(current_page_);

  // Ignore requests for other tabs.
  int current_tab_id =
      extensions::ExtensionTabUtil::GetTabId(GetActiveWebContents());
  if (tab_id != current_tab_id) {
    return;
  }

  // Site access requests only affect the main page.
  ExtensionsMenuMainPageView* main_page = GetMainPage(current_page_.view());
  if (!main_page) {
    return;
  }

  main_page->RemoveExtensionRequestingAccess(extension_id);
  main_page->MaybeShowRequestsSection();
}

void ExtensionsMenuViewController::OnHostAccessRequestsCleared(int tab_id) {
  DCHECK(current_page_);

  // Ignore requests for other tabs.
  int current_tab_id =
      extensions::ExtensionTabUtil::GetTabId(GetActiveWebContents());
  if (tab_id != current_tab_id) {
    return;
  }

  // Site access requests only affect the 'user customized access' section in
  // the main page.
  ExtensionsMenuMainPageView* main_page = GetMainPage(current_page_.view());
  if (!main_page) {
    return;
  }

  main_page->ClearExtensionsRequestingAccess();
  main_page->MaybeShowRequestsSection();
}

ExtensionsMenuMainPageView*
ExtensionsMenuViewController::GetMainPageViewForTesting() {
  DCHECK(current_page_);
  return GetMainPage(current_page_.view());
}

ExtensionsMenuSitePermissionsPageView*
ExtensionsMenuViewController::GetSitePermissionsPageForTesting() {
  DCHECK(current_page_);
  return GetSitePermissionsPage(current_page_.view());
}

void ExtensionsMenuViewController::SwitchToPage(
    std::unique_ptr<views::View> page) {
  if (current_page_) {
    bubble_contents_->RemoveChildViewT(current_page_.view());
  }
  DCHECK(!current_page_);
  current_page_.SetView(bubble_contents_->AddChildView(std::move(page)));
}

void ExtensionsMenuViewController::PopulateMainPage(
    ExtensionsMenuMainPageView* main_page) {
  // TODO(crbug.com/40879945): We should update the subheader here since it
  // depends on `toolbar_model_`.
  std::vector<std::string> sorted_ids = SortExtensionsByName(*toolbar_model_);
  for (size_t i = 0; i < sorted_ids.size(); ++i) {
    InsertMenuItemMainPage(main_page, sorted_ids[i], i);
  }
}

void ExtensionsMenuViewController::InsertMenuItemMainPage(
    ExtensionsMenuMainPageView* main_page,
    const extensions::ExtensionId& extension_id,
    int index) {
  // TODO(emiliapaz): Under MVC architecture, view should not own the view
  // controller. However, the current extensions structure depends on this
  // thus a major restructure is needed.
  std::unique_ptr<ExtensionActionViewController> action_controller =
      ExtensionActionViewController::Create(extension_id, browser_,
                                            extensions_container_);
  const extensions::Extension* extension = action_controller->extension();
  Profile* profile = browser_->profile();
  content::WebContents* web_contents = GetActiveWebContents();

  bool is_enterprise = HasEnterpriseForcedAccess(*extension, *profile);
  ExtensionMenuItemView::SiteAccessToggleState site_access_toggle_state =
      GetSiteAccessToggleState(*extension, *profile, *toolbar_model_,
                               *web_contents);
  ExtensionMenuItemView::SitePermissionsButtonState
      site_permissions_button_state = GetSitePermissionsButtonState(
          *extension, *profile, *toolbar_model_, *web_contents);
  ExtensionMenuItemView::SitePermissionsButtonAccess
      site_permissions_button_access = GetSitePermissionsButtonAccess(
          *extension, *profile, *toolbar_model_, *web_contents);

  main_page->CreateAndInsertMenuItem(std::move(action_controller), extension_id,
                                     is_enterprise, site_access_toggle_state,
                                     site_permissions_button_state,
                                     site_permissions_button_access, index);
}

void ExtensionsMenuViewController::AddOrUpdateExtensionRequestingAccess(
    ExtensionsMenuMainPageView* main_page,
    const extensions::ExtensionId& extension_id,
    int index,
    content::WebContents* web_contents) {
  ToolbarActionViewController* action_controller =
      extensions_container_->GetActionForId(extension_id);
  std::u16string name = action_controller->GetActionName();
  const int icon_size = ChromeLayoutProvider::Get()->GetDistanceMetric(
      DISTANCE_EXTENSIONS_MENU_EXTENSION_ICON_SIZE);
  ui::ImageModel icon =
      action_controller->GetIcon(web_contents, gfx::Size(icon_size, icon_size));

  main_page->AddOrUpdateExtensionRequestingAccess(extension_id, name, icon,
                                                  index);
}

content::WebContents* ExtensionsMenuViewController::GetActiveWebContents()
    const {
  return browser_->tab_strip_model()->GetActiveWebContents();
}