File: omnibox_popup_view_views_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1099 lines) | stat: -rw-r--r-- 46,045 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
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
// Copyright 2018 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/omnibox/omnibox_popup_view_views.h"

#include <memory>

#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/themes/test/theme_service_changed_waiter.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/location_bar/location_bar_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_header_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_popup_view_views_test.h"
#include "chrome/browser/ui/views/omnibox/omnibox_result_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
#include "chrome/browser/ui/views/omnibox/rounded_omnibox_results_frame.h"
#include "chrome/browser/ui/views/toolbar/toolbar_view.h"
#include "chrome/common/chrome_features.h"
#include "chrome/test/base/search_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/omnibox/browser/actions/tab_switch_action.h"
#include "components/omnibox/browser/autocomplete_enums.h"
#include "components/omnibox/browser/autocomplete_result.h"
#include "components/omnibox/browser/fake_autocomplete_provider.h"
#include "components/omnibox/browser/omnibox_field_trial.h"
#include "components/omnibox/browser/omnibox_popup_selection.h"
#include "components/omnibox/browser/omnibox_prefs.h"
#include "components/omnibox/browser/omnibox_triggered_feature_service.h"
#include "components/omnibox/browser/suggestion_group_util.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/theme_provider.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_provider_utils.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/accessibility/ax_update_notifier.h"
#include "ui/views/accessibility/ax_update_observer.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"
#include "url/gurl.h"

#if defined(USE_AURA)
#include "ui/aura/window.h"
#endif

namespace {

std::string result_a11y_text(OmniboxResultView* result_view) {
  if (!result_view) {
    return "";
  }

  ui::AXNodeData result_node_data;
  result_view->GetViewAccessibility().GetAccessibleNodeData(&result_node_data);
  return result_node_data.GetStringAttribute(ax::mojom::StringAttribute::kName);
}

bool contains(std::string str, std::string substr) {
  return str.find(substr) != std::string::npos;
}

// A View that positions itself over another View to intercept clicks.
class ClickTrackingOverlayView : public views::View {
  METADATA_HEADER(ClickTrackingOverlayView, views::View)

 public:
  explicit ClickTrackingOverlayView(OmniboxResultView* result) {
    // |result|'s parent is the OmniboxPopupViewViews, which expects that all
    // its children are OmniboxResultViews.  So skip over it and add this to the
    // OmniboxPopupViewViews's parent.
    auto* contents = result->parent();
    SetBoundsRect(contents->ConvertRectToParent(result->bounds()));
    contents->parent()->AddChildViewRaw(this);
  }

  // views::View:
  void OnMouseEvent(ui::MouseEvent* event) override {
    last_click_ = event->location();
  }

  std::optional<gfx::Point> last_click() const { return last_click_; }

 private:
  std::optional<gfx::Point> last_click_;
};

BEGIN_METADATA(ClickTrackingOverlayView)
END_METADATA

class TestAXEventObserver : public views::AXUpdateObserver {
 public:
  TestAXEventObserver() { views::AXUpdateNotifier::Get()->AddObserver(this); }

  TestAXEventObserver(const TestAXEventObserver&) = delete;
  TestAXEventObserver& operator=(const TestAXEventObserver&) = delete;

  ~TestAXEventObserver() override {
    views::AXUpdateNotifier::Get()->RemoveObserver(this);
  }

  // views::AXUpdateObserver:
  void OnViewEvent(views::View* view, ax::mojom::Event event_type) override {
    if (!view->GetWidget()) {
      return;
    }
    ui::AXNodeData node_data;
    view->GetViewAccessibility().GetAccessibleNodeData(&node_data);
    ax::mojom::Role role = node_data.role;
    if (event_type == ax::mojom::Event::kTextChanged &&
        role == ax::mojom::Role::kListBoxOption) {
      text_changed_on_listboxoption_count_++;
    } else if (event_type == ax::mojom::Event::kSelectedChildrenChanged &&
               role == ax::mojom::Role::kListBox) {
      selected_children_changed_count_++;
    } else if (event_type == ax::mojom::Event::kSelection &&
               role == ax::mojom::Role::kListBoxOption) {
      selection_changed_count_++;
    } else if (event_type == ax::mojom::Event::kValueChanged &&
               role == ax::mojom::Role::kTextField) {
      value_changed_count_++;
      omnibox_value_ =
          node_data.GetStringAttribute(ax::mojom::StringAttribute::kValue);
    } else if (event_type == ax::mojom::Event::kActiveDescendantChanged &&
               role == ax::mojom::Role::kTextField) {
      active_descendant_changed_count_++;
    }
  }

  int text_changed_on_listboxoption_count() {
    return text_changed_on_listboxoption_count_;
  }
  int selected_children_changed_count() {
    return selected_children_changed_count_;
  }
  int selection_changed_count() { return selection_changed_count_; }
  int value_changed_count() { return value_changed_count_; }
  int active_descendant_changed_count() {
    return active_descendant_changed_count_;
  }

  std::string omnibox_value() { return omnibox_value_; }

 private:
  int text_changed_on_listboxoption_count_ = 0;
  int selected_children_changed_count_ = 0;
  int selection_changed_count_ = 0;
  int value_changed_count_ = 0;
  int active_descendant_changed_count_ = 0;
  std::string omnibox_value_;
};

}  // namespace

// Tests widget alignment of the different popup types.
IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest, PopupAlignment) {
  views::Widget* popup = CreatePopupForTestQuery();

#if defined(USE_AURA)
  popup_view()->UpdatePopupAppearance();
#endif  // defined(USE_AURA)

  gfx::Rect alignment_rect = location_bar()->GetBoundsInScreen();
  alignment_rect.Inset(
      -RoundedOmniboxResultsFrame::GetLocationBarAlignmentInsets());
  alignment_rect.Inset(-RoundedOmniboxResultsFrame::GetShadowInsets());
  // Top, left and right should align. Bottom depends on the results.
  gfx::Rect popup_rect = popup->GetRestoredBounds();
  EXPECT_EQ(popup_rect.y(), alignment_rect.y());
  EXPECT_EQ(popup_rect.x(), alignment_rect.x());
  EXPECT_EQ(popup_rect.right(), alignment_rect.right());
}

// Integration test for omnibox popup theming in regular.
IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest, ThemeIntegration) {
  ThemeService* theme_service =
      ThemeServiceFactory::GetForProfile(browser()->profile());
  UseDefaultTheme();
  SetUseDeviceTheme(false);

  SetUseDarkColor(true);
  const SkColor selection_color_dark = GetSelectedColor(browser());

  SetUseDarkColor(false);
  const SkColor selection_color_light = GetSelectedColor(browser());

  // Unthemed, non-incognito always has a white background. Exceptions: Inverted
  // color themes on Windows and GTK (not tested here).
  EXPECT_EQ(SK_ColorWHITE, GetNormalColor(browser()));

  // Tests below are mainly interested just whether things change, so ensure
  // that can be detected.
  EXPECT_NE(selection_color_dark, selection_color_light);

  EXPECT_EQ(selection_color_light, GetSelectedColor(browser()));

  // Install a theme (in both browsers, since it's the same profile).
  extensions::ChromeTestExtensionLoader loader(browser()->profile());
  {
    ThemeChangeWaiter wait(theme_service);
    base::FilePath path = ui_test_utils::GetTestFilePath(
        base::FilePath().AppendASCII("extensions"),
        base::FilePath().AppendASCII("theme"));
    loader.LoadExtension(path);
  }

  // Same in the non-incognito browser.
  // TODO(khalidpeer): Delete this clause once CR23 colors are supported on
  //   themed clients. Currently themed clients fall back to pre-CR23 colors.
  EXPECT_NE(selection_color_light, GetSelectedColor(browser()));

  // Switch to the default theme without installing a custom theme. E.g. this is
  // what gets used on KDE or when switching to the "classic" theme in settings.
  UseDefaultTheme();

  // Given that `UseDefaultTheme()` only changes the theme on Linux (i.e. the
  // call is a no-op on non-Linux platforms), the following test logic is
  // limited to executing only on the Linux platform.
#if BUILDFLAG(IS_LINUX)
  EXPECT_EQ(selection_color_light, GetSelectedColor(browser()));
#endif  // BUILDFLAG(IS_LINUX)
}

IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest, ThemeIntegrationInIncognito) {
  ThemeService* theme_service =
      ThemeServiceFactory::GetForProfile(browser()->profile());
  UseDefaultTheme();
  SetUseDeviceTheme(false);

  SetUseDarkColor(true);
  SetIsGrayscale(true);

  const SkColor selection_color_dark = GetSelectedColor(browser());

  SetUseDarkColor(false);
  SetIsGrayscale(false);

  // Install a theme (in both browsers, since it's the same profile).
  extensions::ChromeTestExtensionLoader loader(browser()->profile());
  {
    ThemeChangeWaiter wait(theme_service);
    base::FilePath path = ui_test_utils::GetTestFilePath(
        base::FilePath().AppendASCII("extensions"),
        base::FilePath().AppendASCII("theme"));
    loader.LoadExtension(path);
  }

  // Check unthemed incognito windows.
  Browser* incognito_browser = CreateIncognitoBrowser();

  EXPECT_EQ(selection_color_dark, GetSelectedColor(incognito_browser));
  // Switch to the default theme without installing a custom theme. E.g. this is
  // what gets used on KDE or when switching to the "classic" theme in settings.
  UseDefaultTheme();

  // Check incognito again. It should continue to use a dark theme, even on
  // Linux.
  EXPECT_EQ(selection_color_dark, GetSelectedColor(incognito_browser));
}

// TODO(tapted): https://crbug.com/905508 Fix and enable on Mac.
#if BUILDFLAG(IS_MAC)
#define MAYBE_ClickOmnibox DISABLED_ClickOmnibox
#else
#define MAYBE_ClickOmnibox ClickOmnibox
#endif
// Test that clicks over the omnibox do not hit the popup.
IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest, MAYBE_ClickOmnibox) {
  // TODO(https://crbug.com/329235190): Should be an interactive_ui_test if
  // omnibox popup is an accelerated widget.
  if (views::test::IsOzoneBubblesUsingPlatformWidgets()) {
    GTEST_SKIP();
  }

  CreatePopupForTestQuery();

  gfx::NativeWindow event_window = browser()->window()->GetNativeWindow();
#if defined(USE_AURA)
  event_window = event_window->GetRootWindow();
#endif
  ui::test::EventGenerator generator(event_window);

  OmniboxResultView* result = GetResultViewAt(0);
  ASSERT_TRUE(result);

  // Sanity check: ensure the EventGenerator clicks where we think it should
  // when clicking on a result (but don't dismiss the popup yet). This will fail
  // if the WindowTreeHost and EventGenerator coordinate systems do not align.
  {
    const gfx::Point expected_point = result->GetLocalBounds().CenterPoint();
    EXPECT_NE(gfx::Point(), expected_point);

    ClickTrackingOverlayView overlay(result);
    generator.MoveMouseTo(result->GetBoundsInScreen().CenterPoint());
    generator.ClickLeftButton();
    auto click = overlay.last_click();
    ASSERT_TRUE(click.has_value());
    ASSERT_EQ(expected_point, click.value());
  }

  // Select the text, so that we can test whether a click is received (which
  // should deselect the text);
  omnibox_view()->SelectAll(true);
  views::Textfield* textfield = omnibox_view();
  EXPECT_EQ(u"foo", textfield->GetSelectedText());

  // The omnibox likes to select all when it becomes focused which can happen
  // when we send a click. To avoid this, send a drag that won't trigger a
  // click.
  gfx::Point click_point = location_bar()->GetBoundsInScreen().CenterPoint();
  gfx::Point release_point(click_point.x() + 50, click_point.y());
  // Sanity check that our drag doesn't count as a click.
  ASSERT_TRUE(
      omnibox_view()->ExceededDragThreshold(release_point - click_point));

  generator.MoveMouseTo(click_point);
  generator.PressLeftButton();
  generator.MoveMouseTo(release_point);
  generator.ReleaseLeftButton();
  EXPECT_EQ(std::u16string(), textfield->GetSelectedText());

  // Clicking the result should dismiss the popup (asynchronously).
  generator.MoveMouseTo(result->GetBoundsInScreen().CenterPoint());

  ASSERT_TRUE(GetPopupWidget());
  EXPECT_FALSE(GetPopupWidget()->IsClosed());

  generator.ClickLeftButton();
  ASSERT_TRUE(GetPopupWidget());

  // Instantly finish all queued animations.
  GetPopupWidget()->GetLayer()->GetAnimator()->StopAnimating();
  EXPECT_TRUE(GetPopupWidget()->IsClosed());
}

// Flaky on Mac: https://crbug.com/1140153.
#if BUILDFLAG(IS_MAC)
#define MAYBE_EmitAccessibilityEvents DISABLED_EmitAccessibilityEvents
#else
#define MAYBE_EmitAccessibilityEvents EmitAccessibilityEvents
#endif
IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest,
                       MAYBE_EmitAccessibilityEvents) {
  // Creation and population of the popup should not result in a text/name
  // change accessibility event.
  base::HistogramTester histogram_tester;
  TestAXEventObserver observer;
  CreatePopupForTestQuery();
  ACMatches matches;
  AutocompleteMatch match(nullptr, 500, false,
                          AutocompleteMatchType::HISTORY_TITLE);
  match.destination_url = GURL("https://foobar.com");
  match.contents = u"https://foobar.com";
  match.description = u"FooBarCom";
  match.contents_class = {{0, 0}};
  match.description_class = {{0, 0}};
  matches.push_back(match);
  match.destination_url = GURL("https://foobarbaz.com");
  match.contents = u"https://foobarbaz.com";
  match.description = u"FooBarBazCom";
  match.contents_class = {{0, 0}};
  match.description_class = {{0, 0}};
  matches.push_back(match);
  controller()->autocomplete_controller()->internal_result_.AppendMatches(
      matches);
  popup_view()->UpdatePopupAppearance();
  EXPECT_EQ(observer.text_changed_on_listboxoption_count(), 0);

  edit_model()->SetUserText(u"bar");
  edit_model()->StartAutocomplete(false, false);
  popup_view()->UpdatePopupAppearance();
  EXPECT_EQ(observer.text_changed_on_listboxoption_count(), 1);
  EXPECT_EQ(observer.selected_children_changed_count(), 1);
  EXPECT_EQ(observer.selection_changed_count(), 1);
  EXPECT_EQ(observer.active_descendant_changed_count(), 1);
  EXPECT_EQ(observer.value_changed_count(), 2);

  edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
  EXPECT_EQ(observer.selected_children_changed_count(), 2);
  EXPECT_EQ(observer.selection_changed_count(), 2);
  EXPECT_EQ(observer.active_descendant_changed_count(), 2);
  EXPECT_EQ(observer.value_changed_count(), 3);
  EXPECT_TRUE(contains(observer.omnibox_value(), "2 of 3"));
  EXPECT_TRUE(contains(observer.omnibox_value(), "FooBarCom"));
  EXPECT_TRUE(contains(observer.omnibox_value(), "location from history"));

  OmniboxResultView* selected_result_view = GetResultViewAt(1);
  ui::AXNodeData result_node_data;
  selected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &result_node_data);
  std::string ax_name =
      result_node_data.GetStringAttribute(ax::mojom::StringAttribute::kName);
  EXPECT_FALSE(contains(ax_name, "2 of 3"));
  EXPECT_TRUE(contains(ax_name, "foobar.com"));
  EXPECT_TRUE(contains(ax_name, "FooBarCom"));
  EXPECT_TRUE(contains(ax_name, "location from history"));

  edit_model()->SetPopupSelection(OmniboxPopupSelection(2));
  EXPECT_EQ(observer.selected_children_changed_count(), 3);
  EXPECT_EQ(observer.selection_changed_count(), 3);
  EXPECT_EQ(observer.active_descendant_changed_count(), 3);
  EXPECT_EQ(observer.value_changed_count(), 4);
  EXPECT_TRUE(contains(observer.omnibox_value(), "3 of 3"));
  EXPECT_TRUE(contains(observer.omnibox_value(), "FooBarBazCom"));

  selected_result_view = GetResultViewAt(2);
  result_node_data = ui::AXNodeData();
  selected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &result_node_data);
  ax_name =
      result_node_data.GetStringAttribute(ax::mojom::StringAttribute::kName);
  EXPECT_FALSE(contains(ax_name, "3 of 3"));
  EXPECT_TRUE(contains(ax_name, "foobarbaz.com"));
  EXPECT_TRUE(contains(ax_name, "FooBarBazCom"));

  // Check that active descendant on textbox matches the selected result view.
  ui::AXNodeData ax_node_data_omnibox;
  omnibox_view()->GetViewAccessibility().GetAccessibleNodeData(
      &ax_node_data_omnibox);
  selected_result_view = GetResultViewAt(2);
  EXPECT_EQ(ax_node_data_omnibox.GetIntAttribute(
                ax::mojom::IntAttribute::kActivedescendantId),
            selected_result_view->GetViewAccessibility().GetUniqueId());

  result_node_data = ui::AXNodeData();
  selected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &result_node_data);
  int result_size = static_cast<int>(
      controller()->autocomplete_controller()->result().size());
  EXPECT_EQ(result_size, result_node_data.GetIntAttribute(
                             ax::mojom::IntAttribute::kSetSize));
  histogram_tester.ExpectUniqueSample("Omnibox.Views.PopupFirstPaint", 1, 0);
}

IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest,
                       AccessibleSelectionOnResultSelection) {
  CreatePopupForTestQuery();
  ACMatches matches;
  AutocompleteMatch match(nullptr, 500, false,
                          AutocompleteMatchType::HISTORY_TITLE);
  match.destination_url = GURL("https://foobar.com");
  match.contents = u"https://foobar.com";
  match.description = u"FooBarCom";
  match.contents_class = {{0, 0}};
  match.description_class = {{0, 0}};
  matches.push_back(match);
  match.destination_url = GURL("https://foobarbaz.com");
  match.contents = u"https://foobarbaz.com";
  match.description = u"FooBarBazCom";
  match.contents_class = {{0, 0}};
  match.description_class = {{0, 0}};
  matches.push_back(match);
  controller()->autocomplete_controller()->internal_result_.AppendMatches(
      matches);
  popup_view()->UpdatePopupAppearance();
  edit_model()->SetUserText(u"bar");
  edit_model()->StartAutocomplete(false, false);
  popup_view()->UpdatePopupAppearance();

  edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
  OmniboxResultView* selected_result_view = GetResultViewAt(1);
  ui::AXNodeData node_data_omnibox_result_view;
  selected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &node_data_omnibox_result_view);
  EXPECT_TRUE(node_data_omnibox_result_view.GetBoolAttribute(
      ax::mojom::BoolAttribute::kSelected));
  EXPECT_EQ(node_data_omnibox_result_view.GetString16Attribute(
                ax::mojom::StringAttribute::kName),
            u"FooBarCom https://foobar.com location from history");

  edit_model()->SetPopupSelection(OmniboxPopupSelection(2));
  OmniboxResultView* unselected_result_view = GetResultViewAt(1);
  node_data_omnibox_result_view = ui::AXNodeData();
  unselected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &node_data_omnibox_result_view);
  EXPECT_FALSE(node_data_omnibox_result_view.GetBoolAttribute(
      ax::mojom::BoolAttribute::kSelected));

  selected_result_view = GetResultViewAt(2);
  node_data_omnibox_result_view = ui::AXNodeData();
  selected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &node_data_omnibox_result_view);
  EXPECT_TRUE(node_data_omnibox_result_view.GetBoolAttribute(
      ax::mojom::BoolAttribute::kSelected));
  EXPECT_EQ(node_data_omnibox_result_view.GetString16Attribute(
                ax::mojom::StringAttribute::kName),
            u"FooBarBazCom https://foobarbaz.com location from history");
}

// Flaky on Mac: https://crbug.com/1146627.
#if BUILDFLAG(IS_MAC)
#define MAYBE_EmitAccessibilityEventsOnButtonFocusHint \
  DISABLED_EmitAccessibilityEventsOnButtonFocusHint
#else
#define MAYBE_EmitAccessibilityEventsOnButtonFocusHint \
  EmitAccessibilityEventsOnButtonFocusHint
#endif
IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest,
                       MAYBE_EmitAccessibilityEventsOnButtonFocusHint) {
  base::HistogramTester histogram_tester;
  TestAXEventObserver observer;
  CreatePopupForTestQuery();
  ACMatches matches;
  AutocompleteMatch match(nullptr, 500, false,
                          AutocompleteMatchType::HISTORY_TITLE);
  match.contents = u"https://foobar.com";
  match.description = u"The Foo Of All Bars";
  match.has_tab_match = true;
  match.actions.push_back(base::MakeRefCounted<TabSwitchAction>(GURL()));
  matches.push_back(match);
  controller()->autocomplete_controller()->internal_result_.AppendMatches(
      matches);
  controller()->autocomplete_controller()->NotifyChanged();
  popup_view()->UpdatePopupAppearance();

  edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
  EXPECT_EQ(observer.selected_children_changed_count(), 2);
  EXPECT_EQ(observer.selection_changed_count(), 2);
  EXPECT_EQ(observer.active_descendant_changed_count(), 2);
  EXPECT_EQ(observer.value_changed_count(), 2);
  EXPECT_TRUE(contains(observer.omnibox_value(), "The Foo Of All Bars"));
  EXPECT_TRUE(contains(observer.omnibox_value(), "press Tab then Enter"));
  EXPECT_TRUE(contains(observer.omnibox_value(), "2 of 2"));

  OmniboxResultView* selected_result_view = GetResultViewAt(1);
  ui::AXNodeData result_node_data;
  selected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &result_node_data);
  std::string ax_name =
      result_node_data.GetStringAttribute(ax::mojom::StringAttribute::kName);
  EXPECT_TRUE(contains(ax_name, "foobar.com"));
  EXPECT_TRUE(contains(ax_name, "press Tab then Enter"));
  EXPECT_FALSE(contains(ax_name, "2 of 2"));

  edit_model()->SetPopupSelection(
      OmniboxPopupSelection(1, OmniboxPopupSelection::FOCUSED_BUTTON_ACTION));
  EXPECT_TRUE(contains(observer.omnibox_value(), "Tab switch button"));
  EXPECT_EQ(observer.selected_children_changed_count(), 3);
  EXPECT_EQ(observer.selection_changed_count(), 3);
  EXPECT_EQ(observer.value_changed_count(), 3);
  EXPECT_TRUE(contains(observer.omnibox_value(), "press Enter to switch"));
  EXPECT_FALSE(contains(observer.omnibox_value(), "2 of 2"));

  result_node_data = ui::AXNodeData();
  selected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &result_node_data);
  ax_name =
      result_node_data.GetStringAttribute(ax::mojom::StringAttribute::kName);
  EXPECT_TRUE(contains(ax_name, "press Enter to switch"));
  EXPECT_FALSE(contains(ax_name, "2 of 2"));

  edit_model()->SetPopupSelection(
      OmniboxPopupSelection(1, OmniboxPopupSelection::NORMAL));
  EXPECT_TRUE(contains(observer.omnibox_value(), "The Foo Of All Bars"));
  EXPECT_EQ(observer.selected_children_changed_count(), 4);
  EXPECT_EQ(observer.selection_changed_count(), 4);
  EXPECT_EQ(observer.value_changed_count(), 4);
  EXPECT_TRUE(contains(observer.omnibox_value(), "press Tab then Enter"));
  EXPECT_TRUE(contains(observer.omnibox_value(), "2 of 2"));

  result_node_data = ui::AXNodeData();
  selected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &result_node_data);
  ax_name =
      result_node_data.GetStringAttribute(ax::mojom::StringAttribute::kName);
  EXPECT_TRUE(contains(ax_name, "foobar.com"));
  EXPECT_TRUE(contains(ax_name, "press Tab then Enter"));
  EXPECT_FALSE(contains(ax_name, "2 of 2"));

  histogram_tester.ExpectUniqueSample("Omnibox.Views.PopupFirstPaint", 1, 0);
}

IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest,
                       EmitSelectedChildrenChangedAccessibilityEvent) {
  // Create a popup for the matches.
  GetPopupWidget();
  edit_model()->SetUserText(u"foo");
  AutocompleteInput input(
      u"foo", metrics::OmniboxEventProto::BLANK,
      ChromeAutocompleteSchemeClassifier(browser()->profile()));
  input.set_omit_asynchronous_matches(true);
  controller()->autocomplete_controller()->Start(input);

  // Create a match to populate the autocomplete.
  std::u16string match_url = u"https://foobar.com";
  AutocompleteMatch match(nullptr, 500, false,
                          AutocompleteMatchType::HISTORY_TITLE);
  match.contents = match_url;
  match.contents_class.emplace_back(0, ACMatchClassification::URL);
  match.destination_url = GURL(match_url);
  match.description = u"Foobar";
  match.allowed_to_be_default_match = true;

  AutocompleteResult& results =
      controller()->autocomplete_controller()->internal_result_;
  ACMatches matches;
  matches.push_back(match);
  results.AppendMatches(matches);
  results.SortAndCull(input, /*template_url_service=*/nullptr,
                      triggered_feature_service(), /*is_lens_active=*/false,
                      /*can_show_contextual_suggestions=*/false,
                      /*mia_enabled*/ false);
  controller()->autocomplete_controller()->NotifyChanged();

  // Check that arrowing up and down emits the event.
  TestAXEventObserver observer;
  EXPECT_EQ(observer.selected_children_changed_count(), 0);
  EXPECT_EQ(observer.selection_changed_count(), 0);
  EXPECT_EQ(observer.value_changed_count(), 0);
  EXPECT_EQ(observer.active_descendant_changed_count(), 0);

  // This is equivalent of the user arrowing down in the omnibox.
  edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
  EXPECT_EQ(observer.selected_children_changed_count(), 1);
  EXPECT_EQ(observer.selection_changed_count(), 1);
  EXPECT_EQ(observer.value_changed_count(), 1);
  EXPECT_EQ(observer.active_descendant_changed_count(), 1);

  // This is equivalent of the user arrowing up in the omnibox.
  edit_model()->SetPopupSelection(OmniboxPopupSelection(0));
  EXPECT_EQ(observer.selected_children_changed_count(), 2);
  EXPECT_EQ(observer.selection_changed_count(), 2);
  EXPECT_EQ(observer.value_changed_count(), 2);
  EXPECT_EQ(observer.active_descendant_changed_count(), 2);

  // TODO(accessibility) Test that closing the popup fires an activedescendant
  //  changed event.

  // Check accessibility of list box while it's open.
  ui::AXNodeData popup_node_data_while_open;
  popup_view()->GetViewAccessibility().GetAccessibleNodeData(
      &popup_node_data_while_open);
  EXPECT_EQ(popup_node_data_while_open.role, ax::mojom::Role::kListBox);
  EXPECT_TRUE(popup_node_data_while_open.HasState(ax::mojom::State::kExpanded));
  EXPECT_FALSE(
      popup_node_data_while_open.HasState(ax::mojom::State::kCollapsed));
  EXPECT_FALSE(
      popup_node_data_while_open.HasState(ax::mojom::State::kInvisible));
  EXPECT_TRUE(popup_node_data_while_open.HasIntAttribute(
      ax::mojom::IntAttribute::kPopupForId));

  // Check accessibility of list box while it's closed.
  controller()->autocomplete_controller()->Stop(
      AutocompleteStopReason::kClobbered);
  popup_view()->UpdatePopupAppearance();
  popup_node_data_while_open = ui::AXNodeData();
  popup_view()->GetViewAccessibility().GetAccessibleNodeData(
      &popup_node_data_while_open);
  EXPECT_FALSE(
      popup_node_data_while_open.HasState(ax::mojom::State::kExpanded));
  EXPECT_TRUE(
      popup_node_data_while_open.HasState(ax::mojom::State::kCollapsed));
  EXPECT_TRUE(
      popup_node_data_while_open.HasState(ax::mojom::State::kInvisible));
}

IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest,
                       AccessibilityStatesOnWidgetDestroyed) {
  // Create a popup for the matches.
  views::Widget* widget = CreatePopupForTestQuery();
  views::test::WidgetDestroyedWaiter waiter(widget);

  // Check accessibility of list box while it's open.
  ui::AXNodeData popup_node_data;
  popup_view()->GetViewAccessibility().GetAccessibleNodeData(&popup_node_data);
  EXPECT_EQ(popup_node_data.role, ax::mojom::Role::kListBox);
  EXPECT_TRUE(popup_node_data.HasState(ax::mojom::State::kExpanded));
  EXPECT_FALSE(popup_node_data.HasState(ax::mojom::State::kCollapsed));
  EXPECT_FALSE(popup_node_data.HasState(ax::mojom::State::kInvisible));
  EXPECT_TRUE(
      popup_node_data.HasIntAttribute(ax::mojom::IntAttribute::kPopupForId));

  // Check accessibility of list box while it's closed.
  widget->Close();
  waiter.Wait();
  EXPECT_FALSE(popup_view()->IsOpen());
  popup_node_data = ui::AXNodeData();
  popup_view()->GetViewAccessibility().GetAccessibleNodeData(&popup_node_data);
  EXPECT_FALSE(popup_node_data.HasState(ax::mojom::State::kExpanded));
  EXPECT_TRUE(popup_node_data.HasState(ax::mojom::State::kCollapsed));
  EXPECT_TRUE(popup_node_data.HasState(ax::mojom::State::kInvisible));
}

IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest, AccessibleResultName) {
  CreatePopupForTestQuery();
  ACMatches matches;
  AutocompleteMatch match(nullptr, 500, false,
                          AutocompleteMatchType::HISTORY_TITLE);
  match.destination_url = GURL("https://foobar.com");
  match.contents = u"https://foobar.com";
  match.description = u"FooBarCom";
  match.contents_class = {{0, 0}};
  match.description_class = {{0, 0}};
  matches.push_back(match);
  controller()->autocomplete_controller()->internal_result_.AppendMatches(
      matches);
  popup_view()->UpdatePopupAppearance();
  edit_model()->SetUserText(u"bar");
  edit_model()->StartAutocomplete(false, false);
  popup_view()->UpdatePopupAppearance();

  edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
  OmniboxResultView* selected_result_view = GetResultViewAt(1);
  ui::AXNodeData result_node_data;
  selected_result_view->GetViewAccessibility().GetAccessibleNodeData(
      &result_node_data);
  EXPECT_EQ(
      result_node_data.GetString16Attribute(ax::mojom::StringAttribute::kName),
      u"FooBarCom https://foobar.com location from history");
}

IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest, DeleteSuggestion) {
  scoped_refptr<FakeAutocompleteProvider> provider =
      new FakeAutocompleteProvider(AutocompleteProvider::TYPE_SEARCH);
  controller()->autocomplete_controller()->providers_.push_back(provider);

  ACMatches matches;
  {
    std::u16string match_url = u"https://example.com/";
    AutocompleteMatch match(nullptr, 500, /*deletable=*/true,
                            AutocompleteMatchType::HISTORY_TITLE);
    match.contents = match_url;
    match.contents_class.emplace_back(0, ACMatchClassification::URL);
    match.destination_url = GURL(match_url);
    match.description = u"Deletable Match";
    match.description_class.emplace_back(0, ACMatchClassification::URL);
    match.allowed_to_be_default_match = true;
    match.provider = provider.get();
    matches.push_back(match);
  }
  {
    std::u16string match_url = u"https://google.com/";
    AutocompleteMatch match(nullptr, 500, false,
                            AutocompleteMatchType::HISTORY_TITLE);
    match.contents = match_url;
    match.contents_class.emplace_back(0, ACMatchClassification::URL);
    match.destination_url = GURL(match_url);
    match.description = u"Other Match";
    match.description_class.emplace_back(0, ACMatchClassification::URL);
    match.allowed_to_be_default_match = true;
    match.provider = provider.get();
    metrics::OmniboxScoringSignals scoring_signals;
    scoring_signals.set_first_bookmark_title_match_position(3);
    scoring_signals.set_allowed_to_be_default_match(true);
    scoring_signals.set_length_of_url(20);
    match.scoring_signals = scoring_signals;
    matches.push_back(match);
  }
  provider->matches_ = matches;

  edit_model()->SetUserText(u"foo");
  AutocompleteInput input(
      u"foo", metrics::OmniboxEventProto::BLANK,
      ChromeAutocompleteSchemeClassifier(browser()->profile()));
  input.set_omit_asynchronous_matches(true);
  controller()->autocomplete_controller()->Start(input);
  ASSERT_TRUE(popup_view()->IsOpen());

  // Select deletable match at index 1 (input is index 0).
  edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
  OmniboxResultView* result_view = popup_view()->result_view_at(1);
  EXPECT_EQ(u"Deletable Match", result_view->match_.contents);
  EXPECT_TRUE(result_view->remove_suggestion_button_->GetVisible());

  // Lay out `remove_suggestion_button_` so that it has non-zero size.
  views::test::RunScheduledLayout(result_view);

  // Click button.
  gfx::Rect button_local_bounds =
      result_view->remove_suggestion_button_->GetLocalBounds();
  ui::MouseEvent mouse_pressed_event(
      ui::EventType::kMousePressed, button_local_bounds.CenterPoint(),
      button_local_bounds.CenterPoint(), base::TimeTicks(),
      ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
  result_view->remove_suggestion_button_->OnMousePressed(mouse_pressed_event);
  ui::MouseEvent mouse_released_event(
      ui::EventType::kMouseReleased, button_local_bounds.CenterPoint(),
      button_local_bounds.CenterPoint(), base::TimeTicks(),
      ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
  result_view->remove_suggestion_button_->OnMouseReleased(mouse_released_event);

  EXPECT_EQ(1u, provider->deleted_matches_.size());
  // Make sure the deleted match's OmniboxResultView was hidden.
  // (OmniboxResultViews are never deleted.)
  int visible_children = 0;
  for (views::View* child : popup_view()->children()) {
    if (child->GetVisible()) {
      visible_children++;
    }
  }
  EXPECT_EQ(2, visible_children);
  EXPECT_EQ(u"foo", popup_view()->result_view_at(0)->match_.contents);
  EXPECT_EQ(u"Other Match", popup_view()->result_view_at(1)->match_.contents);
  EXPECT_EQ(OmniboxPopupSelection(1), edit_model()->GetPopupSelection());
}

// Flaky on Mac: https://crbug.com/1511356
// Flaky on Win and Linux: https://crbug.com/365250293
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
#define MAYBE_SpaceEntersKeywordMode DISABLED_SpaceEntersKeywordMode
#else
#define MAYBE_SpaceEntersKeywordMode SpaceEntersKeywordMode
#endif
IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest,
                       MAYBE_SpaceEntersKeywordMode) {
  CreatePopupForTestQuery();
  EXPECT_TRUE(popup_view()->IsOpen());

  omnibox_view()->controller()->client()->GetPrefs()->SetBoolean(
      omnibox::kKeywordSpaceTriggeringEnabled, true);
  omnibox_view()->SetUserText(u"@bookmarks");
  edit_model()->StartAutocomplete(false, false);
  popup_view()->UpdatePopupAppearance();

  EXPECT_FALSE(edit_model()->is_keyword_selected());
  ui::KeyEvent space(ui::EventType::kKeyPressed, ui::VKEY_SPACE, 0);
  omnibox_view()->OnKeyEvent(&space);
  EXPECT_TRUE(edit_model()->is_keyword_selected());
}

IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest,
                       AccesibilityAttributePopupForId) {
  CreatePopupForTestQuery();
  popup_view()->UpdatePopupAppearance();
  edit_model()->SetPopupSelection(OmniboxPopupSelection(0));

  ui::AXNodeData ax_node_data_omnibox;
  popup_view()->GetViewAccessibility().GetAccessibleNodeData(
      &ax_node_data_omnibox);
  EXPECT_TRUE(ax_node_data_omnibox.HasIntAttribute(
      ax::mojom::IntAttribute::kPopupForId));
  EXPECT_EQ(ax_node_data_omnibox.GetIntAttribute(
                ax::mojom::IntAttribute::kPopupForId),
            omnibox_view()->GetViewAccessibility().GetUniqueId());
}

// Changing selection in omnibox popup view should update activedescendant id in
// omnibox view.
IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest,
                       AccessibleActivedescendantId) {
  ui::AXNodeData ax_node_data_omnibox;
  omnibox_view()->GetViewAccessibility().GetAccessibleNodeData(
      &ax_node_data_omnibox);
  EXPECT_FALSE(popup_view()->IsOpen());
  EXPECT_FALSE(ax_node_data_omnibox.HasIntAttribute(
      ax::mojom::IntAttribute::kActivedescendantId));

  CreatePopupForTestQuery();
  ACMatches matches;
  AutocompleteMatch match(nullptr, 500, false,
                          AutocompleteMatchType::HISTORY_TITLE);
  match.destination_url = GURL("https://foobar.com");
  match.contents = u"https://foobar.com";
  match.description = u"FooBarCom";
  match.contents_class = {{0, 0}};
  match.description_class = {{0, 0}};
  matches.push_back(match);
  match.destination_url = GURL("https://foobarbaz.com");
  match.contents = u"https://foobarbaz.com";
  match.description = u"FooBarBazCom";
  match.contents_class = {{0, 0}};
  match.description_class = {{0, 0}};
  matches.push_back(match);
  controller()->autocomplete_controller()->internal_result_.AppendMatches(
      matches);

  // Check accessibility when popup is open.
  ax_node_data_omnibox = ui::AXNodeData();
  edit_model()->StartAutocomplete(false, false);
  omnibox_view()->GetViewAccessibility().GetAccessibleNodeData(
      &ax_node_data_omnibox);
  EXPECT_TRUE(popup_view()->IsOpen());
  EXPECT_TRUE(ax_node_data_omnibox.HasIntAttribute(
      ax::mojom::IntAttribute::kActivedescendantId));
  // First result is selected by default.
  EXPECT_EQ(ax_node_data_omnibox.GetIntAttribute(
                ax::mojom::IntAttribute::kActivedescendantId),
            GetResultViewAt(0)->GetViewAccessibility().GetUniqueId());

  ax_node_data_omnibox = ui::AXNodeData();
  edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
  omnibox_view()->GetViewAccessibility().GetAccessibleNodeData(
      &ax_node_data_omnibox);
  EXPECT_EQ(ax_node_data_omnibox.GetIntAttribute(
                ax::mojom::IntAttribute::kActivedescendantId),
            GetResultViewAt(1)->GetViewAccessibility().GetUniqueId());

  // Check accessibility when popup is closed.
  ax_node_data_omnibox = ui::AXNodeData();
  controller()->autocomplete_controller()->Stop(
      AutocompleteStopReason::kClobbered);
  omnibox_view()->GetViewAccessibility().GetAccessibleNodeData(
      &ax_node_data_omnibox);
  EXPECT_FALSE(popup_view()->IsOpen());
  EXPECT_FALSE(ax_node_data_omnibox.HasIntAttribute(
      ax::mojom::IntAttribute::kActivedescendantId));
}

IN_PROC_BROWSER_TEST_F(OmniboxPopupViewViewsTest, AccessibleControlIds) {
  ui::AXNodeData ax_node_data_omnibox, data;
  omnibox_view()->GetViewAccessibility().GetAccessibleNodeData(
      &ax_node_data_omnibox);
  EXPECT_FALSE(popup_view()->IsOpen());
  EXPECT_FALSE(ax_node_data_omnibox.HasIntListAttribute(
      ax::mojom::IntListAttribute::kControlsIds));

  CreatePopupForTestQuery();

  // Check accessibility when popup is open.
  ax_node_data_omnibox = ui::AXNodeData();
  edit_model()->StartAutocomplete(false, false);
  omnibox_view()->GetViewAccessibility().GetAccessibleNodeData(
      &ax_node_data_omnibox);
  EXPECT_TRUE(popup_view()->IsOpen());
  EXPECT_TRUE(ax_node_data_omnibox.HasIntListAttribute(
      ax::mojom::IntListAttribute::kControlsIds));
  EXPECT_THAT(ax_node_data_omnibox.GetIntListAttribute(
                  ax::mojom::IntListAttribute::kControlsIds)[0],
              popup_view()->GetViewAccessibility().GetUniqueId());

  // Check accessibility when popup is closed.
  ax_node_data_omnibox = ui::AXNodeData();
  controller()->autocomplete_controller()->Stop(
      AutocompleteStopReason::kClobbered);
  omnibox_view()->GetViewAccessibility().GetAccessibleNodeData(
      &ax_node_data_omnibox);
  EXPECT_FALSE(popup_view()->IsOpen());
  EXPECT_FALSE(ax_node_data_omnibox.HasIntListAttribute(
      ax::mojom::IntListAttribute::kControlsIds));
}

IN_PROC_BROWSER_TEST_F(OmniboxPopupSuggestionGroupHeadersTest,
                       ShowSuggestionGroupHeadersByPageContext) {
  scoped_refptr<FakeAutocompleteProvider> provider =
      new FakeAutocompleteProvider(AutocompleteProvider::TYPE_SEARCH);
  controller()->autocomplete_controller()->providers_.push_back(provider);

  const auto group1 = omnibox::GroupId::GROUP_VISITED_DOC_RELATED;
  const auto group2 = omnibox::GroupId::GROUP_CONTEXTUAL_SEARCH;

  ACMatches matches;
  // Non-contextual search suggestion.
  {
    std::u16string match_url = u"https://google.com/search?q=foo1";
    AutocompleteMatch match(nullptr, 500, false,
                            AutocompleteMatchType::SEARCH_SUGGEST);
    match.contents = u"foo1";
    match.contents_class.emplace_back(0, ACMatchClassification::URL);
    match.destination_url = GURL(match_url);
    match.description = u"first match";
    match.description_class.emplace_back(0, ACMatchClassification::URL);
    match.allowed_to_be_default_match = true;
    match.provider = provider.get();
    match.suggestion_group_id = group1;
    match.keyword = u"foo1";
    matches.push_back(match);
  }
  // Contextual search suggestion.
  {
    std::u16string match_url = u"https://google.com/search?q=foo2";
    AutocompleteMatch match(nullptr, 450, false,
                            AutocompleteMatchType::SEARCH_SUGGEST);
    match.contents = u"foo2";
    match.contents_class.emplace_back(0, ACMatchClassification::URL);
    match.destination_url = GURL(match_url);
    match.description = u"second match";
    match.description_class.emplace_back(0, ACMatchClassification::URL);
    match.allowed_to_be_default_match = true;
    match.provider = provider.get();
    match.suggestion_group_id = group2;
    match.keyword = u"foo2";
    matches.push_back(match);
  }
  provider->matches_ = matches;

  omnibox::GroupConfigMap suggestion_groups_map;
  // Non-contextual suggestion group header.
  const std::string kNonContextualSuggestionGroupHeaderText =
      "Related to this page";
  suggestion_groups_map[group1];
  suggestion_groups_map[group1].set_header_text(
      kNonContextualSuggestionGroupHeaderText);
  // Contextual suggestion group header.
  const std::string kContextualSuggestionGroupHeaderText =
      "Suggested questions about this page";
  suggestion_groups_map[group2];
  suggestion_groups_map[group2].set_header_text(
      kContextualSuggestionGroupHeaderText);
  provider->suggestion_groups_map_ = suggestion_groups_map;

  // NTP page context.
  {
    edit_model()->SetUserText(u"foo");
    AutocompleteInput input(
        u"foo",
        metrics::OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS,
        ChromeAutocompleteSchemeClassifier(browser()->profile()));
    input.set_omit_asynchronous_matches(true);
    controller()->autocomplete_controller()->Start(input);
    ASSERT_TRUE(popup_view()->IsOpen());

    // Skip over implicit SEARCH_WHAT_YOU_TYPED suggestion at index 0.

    // Non-contextual suggestion group header should be SHOWN.
    EXPECT_TRUE(GetHeaderViewAt(1)->GetVisible());
    EXPECT_TRUE(GetResultViewAt(1)->GetVisible());

    // Header text should be INCLUDED in the suggestion a11y text.
    edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
    EXPECT_TRUE(contains(result_a11y_text(GetResultViewAt(1)),
                         kNonContextualSuggestionGroupHeaderText));

    // Contextual suggestion group header should be SHOWN.
    EXPECT_TRUE(GetHeaderViewAt(2)->GetVisible());
    EXPECT_TRUE(GetResultViewAt(2)->GetVisible());

    // Header text should be INCLUDED in the suggestion a11y text.
    edit_model()->SetPopupSelection(OmniboxPopupSelection(2));
    EXPECT_TRUE(contains(result_a11y_text(GetResultViewAt(2)),
                         kContextualSuggestionGroupHeaderText));
  }

  // SRP page context.
  {
    edit_model()->SetUserText(u"foo");
    AutocompleteInput input(
        u"foo",
        metrics::OmniboxEventProto::
            SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT,
        ChromeAutocompleteSchemeClassifier(browser()->profile()));
    input.set_omit_asynchronous_matches(true);
    controller()->autocomplete_controller()->Start(input);
    ASSERT_TRUE(popup_view()->IsOpen());

    // Skip over implicit SEARCH_WHAT_YOU_TYPED suggestion at index 0.

    // Non-contextual suggestion group header should be HIDDEN for SRP page
    // context.
    EXPECT_FALSE(popup_view()->header_view_at(1)->GetVisible());
    EXPECT_TRUE(popup_view()->result_view_at(1)->GetVisible());

    // Header text should be EXCLUDED from the suggestion a11y text.
    edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
    EXPECT_FALSE(contains(result_a11y_text(GetResultViewAt(1)),
                          kNonContextualSuggestionGroupHeaderText));

    // Contextual suggestion group header should be HIDDEN for SRP page
    // context.
    EXPECT_FALSE(popup_view()->header_view_at(2)->GetVisible());
    EXPECT_TRUE(popup_view()->result_view_at(2)->GetVisible());
  }

  // Web page context.
  {
    edit_model()->SetUserText(u"foo");
    AutocompleteInput input(
        u"foo", metrics::OmniboxEventProto::OTHER,
        ChromeAutocompleteSchemeClassifier(browser()->profile()));
    input.set_omit_asynchronous_matches(true);
    controller()->autocomplete_controller()->Start(input);
    ASSERT_TRUE(popup_view()->IsOpen());

    // Skip over implicit SEARCH_WHAT_YOU_TYPED suggestion at index 0.

    // Non-contextual suggestion group header should be HIDDEN for Web page
    // context.
    EXPECT_FALSE(popup_view()->header_view_at(1)->GetVisible());
    EXPECT_TRUE(popup_view()->result_view_at(1)->GetVisible());

    // Header text should be EXCLUDED from the suggestion a11y text.
    edit_model()->SetPopupSelection(OmniboxPopupSelection(1));
    EXPECT_FALSE(contains(result_a11y_text(GetResultViewAt(1)),
                          kNonContextualSuggestionGroupHeaderText));

    // Contextual suggestion group header should be SHOWN for Web page
    // context.
    EXPECT_FALSE(popup_view()->header_view_at(2)->GetVisible());
    EXPECT_TRUE(popup_view()->result_view_at(2)->GetVisible());
  }
}