File: page_action_view_unittest.cc

package info (click to toggle)
chromium 140.0.7339.127-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,201,772 kB
  • sloc: cpp: 35,093,800; ansic: 7,161,670; javascript: 4,199,694; python: 1,441,798; asm: 949,904; xml: 747,503; pascal: 187,748; perl: 88,691; sh: 88,248; objc: 79,953; sql: 52,714; cs: 44,599; fortran: 24,137; makefile: 22,119; tcl: 15,277; php: 13,980; yacc: 9,000; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (869 lines) | stat: -rw-r--r-- 33,234 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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/page_action/page_action_view.h"

#include <memory>
#include <string>

#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/run_loop.h"
#include "base/test/mock_callback.h"
#include "base/time/time.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/browser/ui/layout_constants.h"
#include "chrome/browser/ui/toolbar/pinned_toolbar/pinned_toolbar_actions_model.h"
#include "chrome/browser/ui/views/location_bar/icon_label_bubble_view.h"
#include "chrome/browser/ui/views/page_action/page_action_controller.h"
#include "chrome/browser/ui/views/page_action/page_action_model.h"
#include "chrome/browser/ui/views/page_action/page_action_model_observer.h"
#include "chrome/browser/ui/views/page_action/page_action_triggers.h"
#include "chrome/browser/ui/views/page_action/page_action_view_params.h"
#include "chrome/browser/ui/views/page_action/test_support/fake_tab_interface.h"
#include "chrome/browser/ui/views/page_action/test_support/mock_page_action_model.h"
#include "chrome/browser/ui/views/page_action/test_support/test_page_action_properties_provider.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/views/chrome_views_test_base.h"
#include "components/tabs/public/mock_tab_interface.h"
#include "components/vector_icons/vector_icons.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_web_contents_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/actions/actions.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/interaction/interaction_test_util.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/events/test/test_event.h"
#include "ui/gfx/animation/animation.h"
#include "ui/gfx/animation/animation_test_api.h"
#include "ui/views/actions/action_view_controller.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/background.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/interaction/interaction_test_util_views.h"
#include "ui/views/test/ax_event_counter.h"
#include "ui/views/view_class_properties.h"

namespace page_actions {
namespace {

using ::testing::Return;
using ::testing::ReturnRef;
using ::ui::EventType;

constexpr int kDefaultIconSize = 16;
const std::u16string kTestText = u"Test text";

static constexpr actions::ActionId kTestPageActionId = 0;
static const PageActionPropertiesMap kTestProperties = PageActionPropertiesMap{
    {
        kTestPageActionId,
        PageActionProperties{
            .histogram_name = "Test",
        },
    },
};

class MockIconLabelViewDelegate : public IconLabelBubbleView::Delegate {
 public:
  MOCK_METHOD(SkColor,
              GetIconLabelBubbleSurroundingForegroundColor,
              (),
              (const, override));
  MOCK_METHOD(SkColor,
              GetIconLabelBubbleBackgroundColor,
              (),
              (const, override));
};

class AlwaysActiveTabInterface : public FakeTabInterface {
 public:
  explicit AlwaysActiveTabInterface(TestingProfile* profile)
      : FakeTabInterface(profile) {}

  ~AlwaysActiveTabInterface() override = default;
  bool IsActivated() const override { return true; }
};

// Test class that includes a real controller and model. Prefer to use simpler
// PageActionViewTest where possible.
class PageActionViewWithControllerTest : public ChromeViewsTestBase {
 public:
  PageActionViewWithControllerTest() = default;

  void SetUp() override {
    ChromeViewsTestBase::SetUp();
    // Use any arbitrary vector icon.
    auto image = ui::ImageModel::FromVectorIcon(
        vector_icons::kBackArrowIcon, ui::kColorSysPrimary, kDefaultIconSize);
    action_item_ = actions::ActionManager::Get().AddAction(
        actions::ActionItem::Builder()
            .SetActionId(kTestPageActionId)
            .SetImage(image)
            .Build());
    test_page_action_view_ = std::make_unique<PageActionView>(
        action_item_,
        PageActionViewParams{
            .icon_size = kDefaultIconSize,
            .icon_label_bubble_delegate = &icon_label_view_delegate_,
        },
        ui::ElementIdentifier());

    pinned_actions_model_ =
        std::make_unique<PinnedToolbarActionsModel>(&profile_);
  }

  void TearDown() override {
    ChromeViewsTestBase::TearDown();
    action_item_ = nullptr;
    actions::ActionManager::Get().ResetActions();
    pinned_actions_model_.reset();
  }

  std::unique_ptr<PageActionController> NewPageActionController(
      tabs::TabInterface& tab) const {
    auto controller =
        std::make_unique<PageActionControllerImpl>(pinned_actions_model_.get());
    controller->Initialize(tab, {action_item_->GetActionId().value()},
                           TestPageActionPropertiesProvider(kTestProperties));
    return controller;
  }

  PageActionView* page_action_view() { return test_page_action_view_.get(); }
  actions::ActionItem* action_item() { return action_item_; }

 protected:
  TestingProfile profile_;

 private:
  std::unique_ptr<PageActionView> test_page_action_view_;
  raw_ptr<actions::ActionItem> action_item_;

  testing::NiceMock<MockIconLabelViewDelegate> icon_label_view_delegate_;

  std::unique_ptr<PinnedToolbarActionsModel> pinned_actions_model_;

  // Must exist in order to create PageActionView during the test.
  views::LayoutProvider layout_provider_;
};

// Base test class for PageActionView.  Uses a mock PageActionModel.
class PageActionViewTest : public ChromeViewsTestBase {
 public:
  PageActionViewTest() = default;

  void SetUp() override {
    ChromeViewsTestBase::SetUp();

    action_item_ =
        actions::ActionItem::Builder().SetActionId(kTestPageActionId).Build();

    // Host the view in a Widget so it can handle things like mouse input.
    widget_ = CreateTestWidget(views::Widget::InitParams::CLIENT_OWNS_WIDGET);
    widget_->Show();

    page_action_view_ =
        widget_->SetContentsView(std::make_unique<PageActionView>(
            action_item_.get(),
            PageActionViewParams{
                .icon_size = view_icon_size_,
                .icon_label_bubble_delegate = &icon_label_view_delegate_},
            ui::ElementIdentifier()));

    page_action_view_->GetSlideAnimationForTesting().SetSlideDuration(
        base::Seconds(0));

    ON_CALL(mock_model_, GetVisible()).WillByDefault(Return(false));
    ON_CALL(mock_model_, ShouldShowSuggestionChip())
        .WillByDefault(Return(false));
    ON_CALL(mock_model_, GetShouldAnimateChip()).WillByDefault(Return(false));
    ON_CALL(mock_model_, GetText()).WillByDefault(ReturnRef(mock_string_));
    ON_CALL(mock_model_, GetAccessibleName())
        .WillByDefault(ReturnRef(mock_string_));
    ON_CALL(mock_model_, GetTooltipText())
        .WillByDefault(ReturnRef(mock_string_));
    ON_CALL(mock_model_, GetImage()).WillByDefault(ReturnRef(mock_image_));

    page_action_view_->SetModel(model());
  }

  void TearDown() override {
    page_action_view_ = nullptr;
    widget_.reset();
    ChromeViewsTestBase::TearDown();
  }

  PageActionView* page_action_view() { return page_action_view_.get(); }
  MockPageActionModel* model() { return &mock_model_; }
  actions::ActionItem* action_item() { return action_item_.get(); }
  int view_icon_size() const { return view_icon_size_; }

 protected:
  testing::NiceMock<MockIconLabelViewDelegate> icon_label_view_delegate_;

 private:
  std::unique_ptr<actions::ActionItem> action_item_;

  std::unique_ptr<views::Widget> widget_;

  // Owned by widget_.
  raw_ptr<PageActionView> page_action_view_;

  // Must exist in order to create PageActionView during the test.
  views::LayoutProvider layout_provider_;

  // Mock model and associated placeholder data.
  testing::NiceMock<MockPageActionModel> mock_model_;
  const ui::ImageModel mock_image_ =
      ui::ImageModel::FromVectorIcon(vector_icons::kBackArrowIcon,
                                     ui::kColorSysPrimary,
                                     kDefaultIconSize);
  std::u16string mock_string_ = kTestText;

  const int view_icon_size_ = kDefaultIconSize;
};

TEST_F(PageActionViewTest, ViewHasCorrectElementIdentifier) {
  const ui::ElementIdentifier kCustomIdentifier =
      ui::ElementIdentifier::FromName("PageActionViewTestIdentifier");

  auto view_with_id = std::make_unique<PageActionView>(
      action_item(),
      PageActionViewParams{
          .icon_size = view_icon_size(),
          .icon_label_bubble_delegate = &icon_label_view_delegate_},
      kCustomIdentifier);

  EXPECT_EQ(view_with_id->GetProperty(views::kElementIdentifierKey),
            kCustomIdentifier);
}

// Tests that calling Show/Hide on an inactive controller will not affect the
// view.
TEST_F(PageActionViewWithControllerTest, ViewIgnoresInactiveController) {
  // Use an always-active tab to ensure consistent visibility updates.
  AlwaysActiveTabInterface tab(&profile_);
  auto controller_a = NewPageActionController(tab);
  auto controller_b = NewPageActionController(tab);
  actions::ActionItem* item = action_item();
  item->SetEnabled(true);
  item->SetVisible(true);
  PageActionView* view = page_action_view();
  view->OnNewActiveController(controller_a.get());

  controller_a->Show(0);
  EXPECT_TRUE(view->GetVisible());

  controller_b->Hide(0);
  EXPECT_TRUE(view->GetVisible());

  controller_a->Hide(0);
  EXPECT_FALSE(view->GetVisible());

  controller_b->Show(0);
  EXPECT_FALSE(view->GetVisible());

  // Updating the active controller should apply the new model's state.
  view->OnNewActiveController(controller_b.get());
  EXPECT_TRUE(view->GetVisible());
}

// Tests that the PageActionView should never display when it doesn't have an
// active PageActionController.
TEST_F(PageActionViewWithControllerTest, NoActiveController) {
  actions::ActionItem* item = action_item();
  item->SetEnabled(true);
  item->SetVisible(true);
  PageActionView* view = page_action_view();
  EXPECT_FALSE(view->GetVisible());

  // Use an always-active tab to ensure consistent visibility updates.
  AlwaysActiveTabInterface tab(&profile_);
  auto controller = NewPageActionController(tab);
  view->OnNewActiveController(controller.get());
  controller->Show(0);
  EXPECT_TRUE(view->GetVisible());

  view->OnNewActiveController(nullptr);
  EXPECT_FALSE(view->GetVisible());
}

TEST_F(PageActionViewTest, Visibility) {
  // Ensure view defaults to invisible.
  EXPECT_FALSE(page_action_view()->GetVisible());

  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_TRUE(page_action_view()->GetVisible());

  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(false));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_FALSE(page_action_view()->GetVisible());
}

TEST_F(PageActionViewTest, LabelVisibility) {
  // Ensure view defaults to invisible.
  EXPECT_FALSE(page_action_view()->GetVisible());

  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetText()).WillRepeatedly(ReturnRef(kTestText));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_TRUE(page_action_view()->GetVisible());
  EXPECT_TRUE(page_action_view()->IsChipVisible());

  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(false));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_TRUE(page_action_view()->GetVisible());
  EXPECT_FALSE(page_action_view()->IsChipVisible());
}

TEST_F(PageActionViewTest, ChipStateUpdatesBackgroundColor) {
  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetText()).WillRepeatedly(ReturnRef(kTestText));
  page_action_view()->OnPageActionModelChanged(*model());

  ASSERT_NE(page_action_view()->GetBackground(), nullptr);
  EXPECT_EQ(page_action_view()->GetBackground()->color(),
            page_action_view()->GetColorProvider()->GetColor(
                kColorOmniboxIconBackgroundTonal));

  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(false));
  page_action_view()->OnPageActionModelChanged(*model());

  EXPECT_EQ(page_action_view()->GetBackground(), nullptr);
}

TEST_F(PageActionViewTest, ChipStateUpdatesForegroundColor) {
  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetText()).WillRepeatedly(ReturnRef(kTestText));
  page_action_view()->OnPageActionModelChanged(*model());

  ASSERT_TRUE(page_action_view()->GetVisible());
  ASSERT_TRUE(page_action_view()->IsChipVisible());

  const SkColor expected_color =
      page_action_view()->GetColorProvider()->GetColor(
          kColorOmniboxIconForegroundTonal);
  EXPECT_EQ(page_action_view()->GetCurrentTextColor(), expected_color);
}

TEST_F(PageActionViewTest, SuggestionText) {
  EXPECT_CALL(*model(), GetText()).WillRepeatedly(ReturnRef(kTestText));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_EQ(page_action_view()->GetText(), kTestText);
}

TEST_F(PageActionViewTest, TooltipText) {
  EXPECT_CALL(*model(), GetTooltipText()).WillRepeatedly(ReturnRef(kTestText));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_EQ(page_action_view()->GetTooltipText(), kTestText);
}

TEST_F(PageActionViewTest, Highlight) {
  auto scoped_mode = gfx::AnimationTestApi::SetRichAnimationRenderMode(
      gfx::Animation::RichAnimationRenderMode::FORCE_DISABLED);

  views::InkDropHost* const ink_drop =
      views::InkDrop::Get(page_action_view()->ink_drop_view());

  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetActionActive()).WillRepeatedly(Return(true));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_TRUE(ink_drop->GetHighlighted());

  EXPECT_CALL(*model(), GetActionActive()).WillRepeatedly(Return(false));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_FALSE(ink_drop->GetHighlighted());
}

// Regression test to ensure proper clean up when the view is destroyed while
// highlighted.
TEST_F(PageActionViewTest, HandleDestructionWhileHighlighted) {
  auto scoped_mode = gfx::AnimationTestApi::SetRichAnimationRenderMode(
      gfx::Animation::RichAnimationRenderMode::FORCE_DISABLED);

  views::InkDropHost* const ink_drop =
      views::InkDrop::Get(page_action_view()->ink_drop_view());

  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetActionActive()).WillRepeatedly(Return(true));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_TRUE(ink_drop->GetHighlighted());
}

// Test that OnThemeChanged updates the icon image correctly.
TEST_F(PageActionViewTest, OnThemeChangedUpdatesIconImage) {
  // If the default size is the intended icon size, this test is useless.
  const int kOriginalIconSize = view_icon_size() + 1;
  auto icon_image = ui::ImageModel::FromVectorIcon(
      vector_icons::kBackArrowIcon, ui::kColorSysPrimary, kOriginalIconSize);
  EXPECT_CALL(*model(), GetImage()).WillRepeatedly(ReturnRef(icon_image));

  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_EQ(page_action_view()
                ->GetImageModel(views::Button::STATE_NORMAL)
                ->Size()
                .width(),
            view_icon_size());

  // Icon maintains required size on theme change.
  page_action_view()->OnThemeChanged();
  EXPECT_EQ(page_action_view()
                ->GetImageModel(views::Button::STATE_NORMAL)
                ->Size()
                .width(),
            view_icon_size());
}

// Test that UpdateIconImage() correctly handles ImageModels created without a
// vector icon
TEST_F(PageActionViewTest, UpdateIconImageHandlesDifferentImageTypes) {
  // Set up for a non vector icon.
  SkBitmap bitmap;
  bitmap.allocN32Pixels(kDefaultIconSize, kDefaultIconSize);
  const ui::ImageModel bitmap_image =
      ui::ImageModel::FromImage(gfx::Image::CreateFrom1xBitmap(bitmap));
  EXPECT_CALL(*model(), GetImage()).WillRepeatedly(ReturnRef(bitmap_image));

  // Trigger the icon update.
  page_action_view()->OnPageActionModelChanged(*model());

  // Check that the image model in the PageActionView is correctly set and is
  // not a vector icon.
  EXPECT_FALSE(page_action_view()
                   ->GetImageModel(views::Button::STATE_NORMAL)
                   ->IsEmpty());
  EXPECT_FALSE(page_action_view()
                   ->GetImageModel(views::Button::STATE_NORMAL)
                   ->IsVectorIcon());
}

// Test that UpdateBorder() applies correct padding to image that is not a
// vector icon.
TEST_F(PageActionViewTest, UpdateBorderUsesChipPaddingForBitmapIcon) {
  SkBitmap bitmap;
  bitmap.allocN32Pixels(kDefaultIconSize, kDefaultIconSize);
  const ui::ImageModel bitmap_image =
      ui::ImageModel::FromImage(gfx::Image::CreateFrom1xBitmap(bitmap));
  EXPECT_CALL(*model(), GetImage()).WillRepeatedly(ReturnRef(bitmap_image));
  ASSERT_FALSE(bitmap_image.IsVectorIcon());

  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));

  page_action_view()->OnPageActionModelChanged(*model());
  page_action_view()->UpdateBorder();

  const gfx::Insets expected_insets =
      gfx::Insets::VH(GetLayoutConstant(LOCATION_BAR_CHILD_INTERIOR_PADDING),
                      GetLayoutConstant(LOCATION_BAR_CHIP_PADDING));
  EXPECT_EQ(page_action_view()->GetInsets(), expected_insets);
  EXPECT_EQ(page_action_view()->GetMinimumSize(),
            page_action_view()->GetImageContainerView()->GetPreferredSize() +
                expected_insets.size());
}

// Test that the corner radii are consistent for chips, regardless of whether
// the icon is a vector or bitmap.
TEST_F(PageActionViewTest, ChipCornerRadiiConsistentForVectorAndBitmapIcons) {
  SkBitmap bitmap;
  bitmap.allocN32Pixels(kDefaultIconSize, kDefaultIconSize);
  const ui::ImageModel bitmap_image =
      ui::ImageModel::FromImage(gfx::Image::CreateFrom1xBitmap(bitmap));

  const ui::ImageModel vector_image = ui::ImageModel::FromVectorIcon(
      vector_icons::kBackArrowIcon, ui::kColorSysPrimary, kDefaultIconSize);

  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));

  EXPECT_CALL(*model(), GetImage()).WillRepeatedly(ReturnRef(bitmap_image));
  page_action_view()->OnPageActionModelChanged(*model());
  gfx::RoundedCornersF bitmap_radii = page_action_view()->GetCornerRadii();
  EXPECT_FALSE(bitmap_radii.IsEmpty());

  EXPECT_CALL(*model(), GetImage()).WillRepeatedly(ReturnRef(vector_image));
  page_action_view()->OnPageActionModelChanged(*model());
  gfx::RoundedCornersF vector_radii = page_action_view()->GetCornerRadii();
  EXPECT_FALSE(vector_radii.IsEmpty());

  EXPECT_EQ(bitmap_radii, vector_radii);
}

// TODO(crbug.com/411078148): Re-enable on Mac.
#if BUILDFLAG(IS_MAC)
#define MAYBE_ChipAnnouncements DISABLED_ChipAnnouncements
#else
#define MAYBE_ChipAnnouncements ChipAnnouncements
#endif
TEST_F(PageActionViewTest, MAYBE_ChipAnnouncements) {
  views::test::AXEventCounter counter(views::AXUpdateNotifier::Get());
  ASSERT_EQ(0, counter.GetCount(ax::mojom::Event::kAlert));

  // Initialize the page action so that the chip is showing, but announcements
  // are disabled.
  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetShouldAnnounceChip()).WillRepeatedly(Return(false));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kAlert));

  // Enabling the announcements now shouldn't trigger anything, since the chip
  // is already showing.
  EXPECT_CALL(*model(), GetShouldAnnounceChip()).WillRepeatedly(Return(true));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kAlert));

  // Hide the suggestion chip, then re-show it. This should trigger an
  // announcement.
  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(false));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_EQ(0, counter.GetCount(ax::mojom::Event::kAlert));

  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  page_action_view()->OnPageActionModelChanged(*model());
  EXPECT_EQ(1, counter.GetCount(ax::mojom::Event::kAlert));
}

TEST_F(PageActionViewTest, ChipExpandedCallbackNoAnimation) {
  base::MockCallback<PageActionView::IsChipShowingChangedCallback>
      mock_callback;
  page_action_view()->SetIsChipShowingChangedCallback(mock_callback.Get());

  base::RunLoop first_loop;
  EXPECT_CALL(mock_callback, Run(/*is_chip_showing=*/true))
      .WillOnce([&first_loop](bool) { first_loop.Quit(); });

  EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetShouldAnimateChip()).WillRepeatedly(Return(false));
  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*model(), GetText()).WillRepeatedly(ReturnRef(kTestText));
  EXPECT_CALL(*model(), GetAccessibleName())
      .WillRepeatedly(ReturnRef(kTestText));

  page_action_view()->OnPageActionModelChanged(*model());
  first_loop.Run();
  testing::Mock::VerifyAndClearExpectations(&mock_callback);

  base::RunLoop second_loop;
  EXPECT_CALL(mock_callback, Run(/*is_chip_showing=*/false))
      .WillOnce([&second_loop](bool) { second_loop.Quit(); });

  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(false));

  page_action_view()->OnPageActionModelChanged(*model());
  second_loop.Run();
}

class PageActionViewTriggerTest : public PageActionViewTest {
 public:
  PageActionViewTriggerTest() = default;
  ~PageActionViewTriggerTest() override = default;

  void SetUp() override {
    PageActionViewTest::SetUp();
    action_item()->SetInvokeActionCallback(base::BindRepeating(
        &PageActionViewTriggerTest::ActionInvocationCallback,
        base::Unretained(this)));
  }

  void ActionInvocationCallback(actions::ActionItem* item,
                                actions::ActionInvocationContext context) {
    const PageActionTrigger trigger = static_cast<PageActionTrigger>(
        context.GetProperty(kPageActionTriggerKey));
    switch (trigger) {
      case PageActionTrigger::kMouse:
        ++mouse_trigger_count_;
        break;
      case PageActionTrigger::kKeyboard:
        ++key_trigger_count_;
        break;
      case PageActionTrigger::kGesture:
        ++gesture_trigger_count_;
        break;
    }
  }

  int TotalTriggerCount() const {
    return mouse_trigger_count_ + key_trigger_count_ + gesture_trigger_count_;
  }
  int mouse_trigger_count() const { return mouse_trigger_count_; }
  int key_trigger_count() const { return key_trigger_count_; }
  int gesture_trigger_count() const { return gesture_trigger_count_; }

 private:
  int mouse_trigger_count_ = 0;
  int key_trigger_count_ = 0;
  int gesture_trigger_count_ = 0;
};

TEST_F(PageActionViewTriggerTest, PageActionKeyTriggerPropagation) {
  page_action_view()->NotifyClick(ui::test::TestEvent(EventType::kKeyPressed));
  EXPECT_EQ(1, key_trigger_count());
  EXPECT_EQ(1, TotalTriggerCount());
}

TEST_F(PageActionViewTriggerTest, PageActionMouseTriggerPropagation) {
  page_action_view()->NotifyClick(
      ui::test::TestEvent(EventType::kMousePressed));
  EXPECT_EQ(1, mouse_trigger_count());
  EXPECT_EQ(1, TotalTriggerCount());
}

TEST_F(PageActionViewTriggerTest, PageActionGestureTriggerPropagation) {
  page_action_view()->NotifyClick(ui::test::TestEvent(EventType::kGestureTap));
  EXPECT_EQ(1, gesture_trigger_count());
  EXPECT_EQ(1, TotalTriggerCount());
}

TEST_F(PageActionViewTriggerTest, PageActionTriggersOnKeyboardClick) {
  EXPECT_CALL(*model(), GetActionItemIsShowingBubble())
      .WillRepeatedly(Return(false));
  views::test::InteractionTestUtilSimulatorViews::PressButton(
      page_action_view(), ui::test::InteractionTestUtil::InputType::kKeyboard);
  EXPECT_EQ(1, TotalTriggerCount());
}

TEST_F(PageActionViewTriggerTest, PageActionTriggersOnMouseClick) {
  EXPECT_CALL(*model(), GetActionItemIsShowingBubble())
      .WillRepeatedly(Return(false));
  views::test::InteractionTestUtilSimulatorViews::PressButton(
      page_action_view(), ui::test::InteractionTestUtil::InputType::kMouse);
  EXPECT_EQ(1, TotalTriggerCount());
}

TEST_F(PageActionViewTriggerTest, PageActionMouseRightClickIgnored) {
  ui::MouseEvent mouse_press(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(),
                             ui::EF_RIGHT_MOUSE_BUTTON,
                             ui::EF_RIGHT_MOUSE_BUTTON);
  ui::MouseEvent mouse_release(ui::EventType::kMouseReleased, gfx::Point(),
                               gfx::Point(), ui::EventTimeForNow(),
                               ui::EF_RIGHT_MOUSE_BUTTON,
                               ui::EF_RIGHT_MOUSE_BUTTON);
  page_action_view()->OnMouseEvent(&mouse_press);
  page_action_view()->OnMouseEvent(&mouse_release);
  EXPECT_EQ(0, TotalTriggerCount());
}

// Action invocations are suppressed when the ActionItem is displaying UI.
TEST_F(PageActionViewTriggerTest, PageActionDoesNotTriggerIfBubbleShowing) {
  EXPECT_CALL(*model(), GetActionItemIsShowingBubble())
      .WillRepeatedly(Return(true));
  views::test::InteractionTestUtilSimulatorViews::PressButton(
      page_action_view(), ui::test::InteractionTestUtil::InputType::kMouse);
  EXPECT_EQ(0, TotalTriggerCount());
}

class PageActionViewAnimationTest : public PageActionViewTest {
 public:
  using PageActionViewTest::PageActionViewTest;

  void SetUp() override {
    PageActionViewTest::SetUp();
    animation_ = std::make_unique<gfx::AnimationTestApi>(
        &page_action_view()->GetSlideAnimationForTesting());
  }

  void TearDown() override {
    animation_.reset();
    PageActionViewTest::TearDown();
  }

  void SetInitialChipVisibility(bool showing) {
    // Make the visibility change instant.
    page_action_view()->GetSlideAnimationForTesting().SetSlideDuration(
        base::Seconds(0));
    EXPECT_CALL(*model(), ShouldShowSuggestionChip())
        .WillRepeatedly(Return(showing));
    EXPECT_CALL(*model(), GetVisible()).WillRepeatedly(Return(true));
    EXPECT_CALL(*model(), GetText()).WillRepeatedly(ReturnRef(kTestText));
    EXPECT_CALL(*model(), GetAccessibleName())
        .WillRepeatedly(ReturnRef(kTestText));
    page_action_view()->OnPageActionModelChanged(*model());

    ASSERT_FALSE(page_action_view()->is_animating_label());
    ASSERT_EQ(page_action_view()->IsChipVisible(), showing);
  }

  // Force the animation to extend beyond the duration of this test, allowing
  // us to inspect the view's state mid-animation.
  void ExtendAnimations() {
    page_action_view()->GetSlideAnimationForTesting().SetSlideDuration(
        extended_animation_duration_);
  }

  // Force the current animation to given percentage.
  void FastForwardAnimation(double progress = 1.0) {
    auto now = base::TimeTicks::Now();
    animation_->SetStartTime(now);
    animation_->Step(now + (progress * extended_animation_duration_));
  }

  gfx::AnimationTestApi& animation() { return *animation_.get(); }

 private:
  std::unique_ptr<gfx::AnimationTestApi> animation_;

  const base::TimeDelta extended_animation_duration_ = base::Hours(1);
};

TEST_F(PageActionViewAnimationTest, ChipStateDuringAnimateOut) {
  EXPECT_CALL(*model(), GetShouldAnimateChip()).WillRepeatedly(Return(true));
  SetInitialChipVisibility(true);
  ExtendAnimations();

  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(false));
  page_action_view()->OnPageActionModelChanged(*model());

  // The page action should be in the middle of animating and its chip should
  // be visible.
  EXPECT_TRUE(page_action_view()->is_animating_label());
  EXPECT_TRUE(page_action_view()->IsChipVisible());
  EXPECT_NE(page_action_view()->GetBackground(), nullptr);

  // Skip the animation to its ending.
  FastForwardAnimation();

  // The page action should no longer be animating and its chip should be
  // hidden.
  EXPECT_FALSE(page_action_view()->is_animating_label());
  EXPECT_FALSE(page_action_view()->IsChipVisible());
  EXPECT_EQ(page_action_view()->GetBackground(), nullptr);
}

TEST_F(PageActionViewAnimationTest, ChipStateDuringAnimateIn) {
  EXPECT_CALL(*model(), GetShouldAnimateChip()).WillRepeatedly(Return(true));
  SetInitialChipVisibility(false);
  ExtendAnimations();

  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  page_action_view()->OnPageActionModelChanged(*model());

  // The page action should be in the middle of animating and its chip should
  // be visible.
  EXPECT_TRUE(page_action_view()->is_animating_label());
  EXPECT_TRUE(page_action_view()->IsChipVisible());
  EXPECT_NE(page_action_view()->GetBackground(), nullptr);

  // Skip the animation to its ending.
  FastForwardAnimation();

  // The page action should no longer be animating and its chip should be
  // visible.
  EXPECT_FALSE(page_action_view()->is_animating_label());
  EXPECT_TRUE(page_action_view()->IsChipVisible());
  EXPECT_NE(page_action_view()->GetBackground(), nullptr);
}

TEST_F(PageActionViewAnimationTest, AnimationsDisabled) {
  gfx::Animation::SetPrefersReducedMotionForTesting(false);
  ASSERT_FALSE(gfx::Animation::PrefersReducedMotion());
  SetInitialChipVisibility(false);

  ExtendAnimations();
  EXPECT_CALL(*model(), GetShouldAnimateChip()).WillRepeatedly(Return(false));
  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  page_action_view()->OnPageActionModelChanged(*model());

  EXPECT_FALSE(page_action_view()->is_animating_label());
  EXPECT_TRUE(page_action_view()->IsChipVisible());

  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(false));
  page_action_view()->OnPageActionModelChanged(*model());

  EXPECT_FALSE(page_action_view()->is_animating_label());
  EXPECT_FALSE(page_action_view()->IsChipVisible());
}

TEST_F(PageActionViewAnimationTest, ChipExpandedCallbackAnimateIn) {
  base::RunLoop run_loop;
  base::MockCallback<PageActionView::IsChipShowingChangedCallback>
      mock_callback;

  // 1)  Start with the chip completely hidden (no animation).
  SetInitialChipVisibility(false);

  // 2)  Register the observer *after* the initial setup so we only count
  //     the animate-in completion.
  page_action_view()->SetIsChipShowingChangedCallback(mock_callback.Get());

  // One call when the chip is fully expanded – quit the loop so the test waits
  // for the async PostTask fired by the view.
  EXPECT_CALL(mock_callback, Run(/*is_chip_showing=*/true))
      .WillOnce([&run_loop](bool) { run_loop.Quit(); });

  // 3)  Animate-in path.
  EXPECT_CALL(*model(), GetShouldAnimateChip()).WillRepeatedly(Return(true));
  ExtendAnimations();
  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(true));
  page_action_view()->OnPageActionModelChanged(*model());

  // 4)  Fast-forward to the end → AnimationEnded() → callback fires.
  FastForwardAnimation();
  run_loop.Run();
}

TEST_F(PageActionViewAnimationTest, ChipExpandedCallbackAnimateOut) {
  base::RunLoop run_loop;
  base::MockCallback<PageActionView::IsChipShowingChangedCallback>
      mock_callback;

  // Register *before* the initial setup; we expect one "expanded" callback.
  page_action_view()->SetIsChipShowingChangedCallback(mock_callback.Get());

  // 1)  Start with the chip fully visible.
  SetInitialChipVisibility(/*showing=*/true);
  testing::Mock::VerifyAndClearExpectations(&mock_callback);

  // 2)  Expect a second call after collapse.
  {
    testing::InSequence seq;

    // (a) Still showing when the animation starts.
    EXPECT_CALL(mock_callback, Run(/*is_chip_showing=*/true));

    // (b) Hidden once the animation ends → quit the loop.
    EXPECT_CALL(mock_callback, Run(/*is_chip_showing=*/false))
        .WillOnce([&run_loop](bool) { run_loop.Quit(); });
  }

  // 3)  Animate-out path.
  EXPECT_CALL(*model(), GetShouldAnimateChip()).WillRepeatedly(Return(true));
  ExtendAnimations();
  EXPECT_CALL(*model(), ShouldShowSuggestionChip())
      .WillRepeatedly(Return(false));
  page_action_view()->OnPageActionModelChanged(*model());

  // 4)  Fast-forward to the end → AnimationEnded() → callback fires again.
  FastForwardAnimation();
  run_loop.Run();
}

}  // namespace
}  // namespace page_actions