File: desktop_media_picker_views_unittest.cc

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; 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 (1249 lines) | stat: -rw-r--r-- 50,439 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
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
// Copyright 2014 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/desktop_capture/desktop_media_picker_views.h"

#include <map>
#include <string>
#include <utility>
#include <vector>

#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/types/expected.h"
#include "build/build_config.h"
#include "chrome/browser/media/webrtc/desktop_media_picker_controller.h"
#include "chrome/browser/media/webrtc/desktop_media_picker_manager.h"
#include "chrome/browser/media/webrtc/desktop_media_picker_utils.h"
#include "chrome/browser/media/webrtc/fake_desktop_media_list.h"
#include "chrome/browser/ui/views/desktop_capture/desktop_media_delegated_source_list_view.h"
#include "chrome/browser/ui/views/desktop_capture/desktop_media_list_controller.h"
#include "chrome/browser/ui/views/desktop_capture/desktop_media_list_view.h"
#include "chrome/browser/ui/views/desktop_capture/desktop_media_picker_views_test_api.h"
#include "chrome/browser/ui/views/desktop_capture/desktop_media_source_view.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/test/views/chrome_test_views_delegate.h"
#include "components/web_modal/test_web_contents_modal_dialog_host.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/mojom/dialog_button.mojom.h"
#include "ui/base/ui_base_switches.h"
#include "ui/events/event_utils.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/test/button_test_api.h"
#include "ui/views/test/scoped_views_test_helper.h"
#include "ui/views/test/test_views_delegate.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/any_widget_observer.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"

#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#endif

using ::blink::mojom::MediaStreamRequestResult;
using ::content::DesktopMediaID;

using PickedIdOrErrorCode =
    base::expected<content::DesktopMediaID,
                   blink::mojom::MediaStreamRequestResult>;

namespace views {

class TestDialogObserver : public DesktopMediaPickerManager::DialogObserver {
 public:
  ~TestDialogObserver() override {
    EXPECT_TRUE(opened_);
    EXPECT_TRUE(closed_);
  }

 private:
  void OnDialogOpened(const DesktopMediaPicker::Params&) override {
    opened_ = true;
  }
  void OnDialogClosed() override { closed_ = true; }

  bool opened_ = false;
  bool closed_ = false;
};

std::vector<DesktopMediaList::Type> GetSourceTypes(bool new_order) {
  if (new_order) {
    return {DesktopMediaList::Type::kWebContents,
            DesktopMediaList::Type::kWindow, DesktopMediaList::Type::kScreen};
  } else {
    return {DesktopMediaList::Type::kScreen, DesktopMediaList::Type::kWindow,
            DesktopMediaList::Type::kWebContents};
  }
}

std::string GetTypeAsTestNameString(const DesktopMediaList::Type type) {
  switch (type) {
    case DesktopMediaList::Type::kScreen:
      return "Screen";
    case DesktopMediaList::Type::kWindow:
      return "Window";
    case DesktopMediaList::Type::kWebContents:
      return "Tab";
    case DesktopMediaList::Type::kCurrentTab:
      NOTREACHED();
    case DesktopMediaList::Type::kNone:
      return "None";
  }
  NOTREACHED();
}

class DesktopMediaPickerViewsTestBase : public testing::Test {
 public:
  explicit DesktopMediaPickerViewsTestBase(
      const std::vector<DesktopMediaList::Type>& source_types)
      : source_types_(source_types) {}

  ~DesktopMediaPickerViewsTestBase() override = default;

  void SetUp() override {
#if BUILDFLAG(IS_MAC)
    // These tests create actual child Widgets, which normally have a closure
    // animation on Mac; inhibit it here to avoid the tests flakily hanging.
    base::CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kDisableModalAnimations);
#endif
    DesktopMediaPickerManager::Get()->AddObserver(&observer_);
    MaybeCreatePickerViews();
  }

  virtual void MaybeCreatePickerViews() {
    CreatePickerViews(/*request_audio=*/true, /*exclude_system_audio=*/false);
  }

  void TearDown() override {
    if (GetPickerDialogView()) {
      GetPickerDialogView()->GetWidget()->CloseNow();
    }
    widget_destroyed_waiter_->Wait();
    DesktopMediaPickerManager::Get()->RemoveObserver(&observer_);
  }

  void CreatePickerViews(
      bool request_audio,
      bool exclude_system_audio,
      blink::mojom::PreferredDisplaySurface preferred_display_surface =
          blink::mojom::PreferredDisplaySurface::NO_PREFERENCE) {
    widget_destroyed_waiter_.reset();
    picker_views_.reset();

    picker_views_ = std::make_unique<DesktopMediaPickerImpl>();
    test_api_.set_picker(picker_views_.get());

    views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
                                         "DesktopMediaPickerDialogView");

    const std::u16string kAppName = u"foo";
    DesktopMediaPicker::Params picker_params{
        DesktopMediaPicker::Params::RequestSource::kUnknown};
    picker_params.context = test_helper_.GetContext();
    picker_params.app_name = kAppName;
    picker_params.target_name = kAppName;
    picker_params.request_audio = request_audio;
    picker_params.exclude_system_audio = exclude_system_audio;
    picker_params.preferred_display_surface = preferred_display_surface;

    std::vector<std::unique_ptr<DesktopMediaList>> source_lists;
    for (const DesktopMediaList::Type type : source_types_) {
      source_lists.push_back(std::make_unique<FakeDesktopMediaList>(type));
      media_lists_[type] =
          static_cast<FakeDesktopMediaList*>(source_lists.back().get());
    }

    for (const DesktopMediaList::Type type : delegated_source_types_) {
      source_lists.push_back(std::make_unique<FakeDesktopMediaList>(
          type, /*is_source_list_delegated=*/true));
      media_lists_[type] =
          static_cast<FakeDesktopMediaList*>(source_lists.back().get());
    }

    picker_views_->Show(
        picker_params, std::move(source_lists),
        base::BindOnce(&DesktopMediaPickerViewsTestBase::OnPickerDone,
                       weak_factory_.GetWeakPtr()));
    widget_destroyed_waiter_ =
        std::make_unique<views::test::WidgetDestroyedWaiter>(
            waiter.WaitIfNeededAndGet());
  }

  DesktopMediaPickerDialogView* GetPickerDialogView() const {
    return picker_views_->GetDialogViewForTesting();
  }

  void OnPickerDone(PickedIdOrErrorCode result) {
    picker_result_ = result;
    run_loop_.Quit();
  }

  PickedIdOrErrorCode WaitForPickerResult() {
    run_loop_.Run();
    CHECK(picker_result_.has_value());
    return picker_result_.value();
  }

  // Checks whether `picker_result_` was ever set.
  bool has_picker_result() const { return picker_result_.has_value(); }

  const std::vector<DesktopMediaList::Type>& source_types() {
    return source_types_;
  }

 protected:
  content::BrowserTaskEnvironment task_environment_;
  views::ScopedViewsTestHelper test_helper_{
      std::make_unique<ChromeTestViewsDelegate<>>()};
  std::map<DesktopMediaList::Type,
           raw_ptr<FakeDesktopMediaList, CtnExperimental>>
      media_lists_;
  std::unique_ptr<DesktopMediaPickerImpl> picker_views_;
  DesktopMediaPickerViewsTestApi test_api_;
  TestDialogObserver observer_;
  std::vector<DesktopMediaList::Type> source_types_;
  std::vector<DesktopMediaList::Type> delegated_source_types_;

  base::RunLoop run_loop_;
  std::optional<PickedIdOrErrorCode> picker_result_;
  std::unique_ptr<views::test::WidgetDestroyedWaiter> widget_destroyed_waiter_;

  base::WeakPtrFactory<DesktopMediaPickerViewsTestBase> weak_factory_{this};
};

class DesktopMediaPickerViewsTest : public DesktopMediaPickerViewsTestBase,
                                    public testing::WithParamInterface<bool> {
 public:
  DesktopMediaPickerViewsTest()
      : DesktopMediaPickerViewsTestBase(GetSourceTypes(NewOrder())) {}
  ~DesktopMediaPickerViewsTest() override = default;

  bool NewOrder() const { return GetParam(); }
};

INSTANTIATE_TEST_SUITE_P(,
                         DesktopMediaPickerViewsTest,
                         /*NewOrder=*/testing::Bool());

TEST_P(DesktopMediaPickerViewsTest, DoneCallbackCalledWhenWindowClosed) {
  GetPickerDialogView()->GetWidget()->Close();
  EXPECT_EQ(
      WaitForPickerResult(),
      base::unexpected(MediaStreamRequestResult::PERMISSION_DENIED_BY_USER));
}

TEST_P(DesktopMediaPickerViewsTest, DoneCallbackCalledOnOkButtonPressed) {
  const DesktopMediaID kFakeId(DesktopMediaID::TYPE_WINDOW, 222);

  media_lists_[DesktopMediaList::Type::kWindow]->AddSourceByFullMediaID(
      kFakeId);

  EXPECT_FALSE(GetPickerDialogView()->IsDialogButtonEnabled(
      ui::mojom::DialogButton::kOk));

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWindow);
  test_api_.FocusSourceAtIndex(0);

  EXPECT_TRUE(GetPickerDialogView()->IsDialogButtonEnabled(
      ui::mojom::DialogButton::kOk));

  GetPickerDialogView()->AcceptDialog();
  EXPECT_EQ(kFakeId, WaitForPickerResult());
}

// Regression test for https://crbug.com/1102153
TEST_P(DesktopMediaPickerViewsTest, DoneCallbackNotCalledOnDoubleTap) {
  const DesktopMediaID kFakeId(DesktopMediaID::TYPE_SCREEN, 222);

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  if (test_api_.AudioSupported(DesktopMediaList::Type::kScreen)) {
    test_api_.SetAudioSharingApprovedByUser(false);
  }

  media_lists_[DesktopMediaList::Type::kScreen]->AddSourceByFullMediaID(
      kFakeId);
  test_api_.DoubleTapSourceAtIndex(0);
  EXPECT_FALSE(has_picker_result());
}

TEST_P(DesktopMediaPickerViewsTest, CancelButtonAlwaysEnabled) {
  EXPECT_TRUE(GetPickerDialogView()->IsDialogButtonEnabled(
      ui::mojom::DialogButton::kCancel));
}

TEST_P(DesktopMediaPickerViewsTest, AudioCheckboxDefaultStates) {
  if (test_api_.AudioSupported(DesktopMediaList::Type::kScreen)) {
    test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
    EXPECT_FALSE(test_api_.IsAudioSharingApprovedByUser());
  }

  if (test_api_.AudioSupported(DesktopMediaList::Type::kWindow)) {
    test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWindow);
    EXPECT_FALSE(test_api_.IsAudioSharingApprovedByUser());
  }

  if (test_api_.AudioSupported(DesktopMediaList::Type::kWebContents)) {
    test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
    EXPECT_TRUE(test_api_.IsAudioSharingApprovedByUser());
  }
}

TEST_P(DesktopMediaPickerViewsTest, DistinctAudioCheckboxesHaveDistinctState) {
  DesktopMediaList::Type source_1 = DesktopMediaList::Type::kWebContents;
  DesktopMediaList::Type source_2 = DesktopMediaList::Type::kScreen;

  DCHECK(test_api_.AudioSupported(source_1));
  if (!test_api_.AudioSupported(source_2)) {
    return;  // Cannot run this particular variant of the test on this platform.
  }

  // Record source_1's audio state.
  test_api_.SelectTabForSourceType(source_1);
  const bool init_source_1_state = test_api_.IsAudioSharingApprovedByUser();

  // Toggle the audio state of source_2.
  test_api_.SelectTabForSourceType(source_2);
  const bool init_source_2_state = test_api_.IsAudioSharingApprovedByUser();
  const bool source_2_state = !init_source_2_state;
  test_api_.SetAudioSharingApprovedByUser(source_2_state);
  ASSERT_EQ(test_api_.IsAudioSharingApprovedByUser(), source_2_state);

  // The audio state of source_1 should remain unaffected.
  test_api_.SelectTabForSourceType(source_1);
  ASSERT_EQ(test_api_.IsAudioSharingApprovedByUser(), init_source_1_state);
}

// Verifies the visible status of audio checkbox.
// This test takes it as an article of faith that no checkbox is visible
// when GetAudioShareCheckbox() returns false.
TEST_P(DesktopMediaPickerViewsTest, AudioCheckboxVisibility) {
  bool is_system_audio_capture_supported =
      DesktopMediaPickerController::IsSystemAudioCaptureSupported(
          DesktopMediaPicker::Params::RequestSource::kGetDisplayMedia);
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  EXPECT_EQ(is_system_audio_capture_supported,
            test_api_.HasAudioShareControl());
  if (!is_system_audio_capture_supported) {
    EXPECT_EQ(test_api_.GetAudioLabelText(),
              l10n_util::GetStringUTF16(
                  IDS_DESKTOP_MEDIA_PICKER_AUDIO_SHARE_HINT_TAB));
  }

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWindow);
  EXPECT_FALSE(test_api_.HasAudioShareControl());
  EXPECT_EQ(test_api_.GetAudioLabelText(),
            l10n_util::GetStringUTF16(
                is_system_audio_capture_supported
                    ? IDS_DESKTOP_MEDIA_PICKER_AUDIO_SHARE_HINT_TAB_OR_SCREEN
                    : IDS_DESKTOP_MEDIA_PICKER_AUDIO_SHARE_HINT_TAB));

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  EXPECT_TRUE(test_api_.HasAudioShareControl());
}

// Verifies that audio share information is recorded in the ID if the checkbox
// is checked.
TEST_P(DesktopMediaPickerViewsTest, DoneWithAudioShare) {
  constexpr DesktopMediaID kOriginId(DesktopMediaID::TYPE_WEB_CONTENTS, 222);

  DesktopMediaID result_id(DesktopMediaID::TYPE_WEB_CONTENTS, 222, true);

  // This matches the real workflow that when a source is generated in
  // media_list, its |audio_share| bit is not set. The bit is set by the picker
  // UI if the audio checkbox is checked.
  media_lists_[DesktopMediaList::Type::kWebContents]->AddSourceByFullMediaID(
      kOriginId);

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  test_api_.SetAudioSharingApprovedByUser(true);
  test_api_.FocusSourceAtIndex(0);

  GetPickerDialogView()->AcceptDialog();
  EXPECT_EQ(result_id, WaitForPickerResult());
}

TEST_P(DesktopMediaPickerViewsTest, OkButtonEnabledDuringAcceptSpecific) {
  // The first pane is |tabs| in the new order and |screens| otherwise.
  DesktopMediaID::Type type = NewOrder() ? DesktopMediaID::TYPE_WEB_CONTENTS
                                         : DesktopMediaID::TYPE_SCREEN;
  DesktopMediaID fake_id(type, 222);

  media_lists_[DesktopMediaList::Type::kWindow]->AddSourceByFullMediaID(
      fake_id);
  if (NewOrder()) {
    // Audio-sharing supported for tabs, but not for windows.
    fake_id.web_contents_id.disable_local_echo = true;
    fake_id.audio_share = true;
  }

  EXPECT_FALSE(GetPickerDialogView()->IsDialogButtonEnabled(
      ui::mojom::DialogButton::kOk));

  GetPickerDialogView()->AcceptSpecificSource(fake_id);
  EXPECT_EQ(fake_id, WaitForPickerResult());
}

#if BUILDFLAG(IS_MAC)
TEST_P(DesktopMediaPickerViewsTest, OnPermissionUpdateWithPermissions) {
  if (base::mac::MacOSMajorVersion() < 13) {
    GTEST_SKIP()
        << "ScreenCapturePermissionChecker only created for MacOS 13 and later";
  }

  test_api_.OnPermissionUpdate(true);

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  EXPECT_TRUE(test_api_.GetActivePane()->IsContentPaneVisible());
  EXPECT_FALSE(test_api_.GetActivePane()->IsPermissionPaneVisible());

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWindow);
  EXPECT_TRUE(test_api_.GetActivePane()->IsContentPaneVisible());
  EXPECT_FALSE(test_api_.GetActivePane()->IsPermissionPaneVisible());

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  EXPECT_TRUE(test_api_.GetActivePane()->IsContentPaneVisible());
  EXPECT_FALSE(test_api_.GetActivePane()->IsPermissionPaneVisible());
}

TEST_P(DesktopMediaPickerViewsTest, OnPermissionUpdateWithoutPermissions) {
  if (base::mac::MacOSMajorVersion() < 13) {
    GTEST_SKIP()
        << "ScreenCapturePermissionChecker only created for MacOS 13 and later";
  }

  test_api_.OnPermissionUpdate(false);

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  EXPECT_FALSE(test_api_.GetActivePane()->IsContentPaneVisible());
  EXPECT_TRUE(test_api_.GetActivePane()->IsPermissionPaneVisible());

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWindow);
  EXPECT_FALSE(test_api_.GetActivePane()->IsContentPaneVisible());
  EXPECT_TRUE(test_api_.GetActivePane()->IsPermissionPaneVisible());

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  EXPECT_TRUE(test_api_.GetActivePane()->IsContentPaneVisible());
  EXPECT_FALSE(test_api_.GetActivePane()->IsPermissionPaneVisible());
}
#endif

class DesktopMediaPickerViewsPerTypeTest
    : public DesktopMediaPickerViewsTestBase,
      public testing::WithParamInterface<
          std::tuple<bool, DesktopMediaList::Type>> {
 public:
  DesktopMediaPickerViewsPerTypeTest()
      : DesktopMediaPickerViewsTestBase(GetSourceTypes(NewOrder())),
        source_id_type_(AsDesktopMediaIdType(type())) {}
  ~DesktopMediaPickerViewsPerTypeTest() override = default;

  void SetUp() override {
    // We must first call the base class SetUp, as if we skip without doing so,
    // then teardown will fail.
    DesktopMediaPickerViewsTestBase::SetUp();

    if (!base::Contains(source_types(), type())) {
      GTEST_SKIP();
    }

    test_api_.SelectTabForSourceType(type());
  }

  bool NewOrder() const { return std::get<0>(GetParam()); }
  DesktopMediaList::Type type() const { return std::get<1>(GetParam()); }
  DesktopMediaID::Type source_id_type() const { return source_id_type_; }

  static std::string GetDescription(
      const testing::TestParamInfo<
          DesktopMediaPickerViewsPerTypeTest::ParamType>& info) {
    const bool new_order = std::get<0>(info.param);
    const DesktopMediaList::Type type = std::get<1>(info.param);

    return base::StrCat(
        {new_order ? "New" : "Old", "Order", GetTypeAsTestNameString(type)});
  }

 private:
  const DesktopMediaID::Type source_id_type_;
};

INSTANTIATE_TEST_SUITE_P(
    ,
    DesktopMediaPickerViewsPerTypeTest,
    testing::Combine(/*NewOrder=*/testing::Bool(),
                     testing::Values(DesktopMediaList::Type::kWebContents,
                                     DesktopMediaList::Type::kWindow,
                                     DesktopMediaList::Type::kScreen)),
    &DesktopMediaPickerViewsPerTypeTest::GetDescription);

// Verifies that a MediaSourceView is selected with mouse left click and
// original selected MediaSourceView gets unselected.
TEST_P(DesktopMediaPickerViewsPerTypeTest, SelectMediaSourceViewOnSingleClick) {
  media_lists_[type()]->AddSourceByFullMediaID(
      DesktopMediaID(source_id_type(), 10));
  media_lists_[type()]->AddSourceByFullMediaID(
      DesktopMediaID(source_id_type(), 20));

  // By default, nothing should be selected.
  EXPECT_FALSE(test_api_.GetSelectedSourceId().has_value());

  test_api_.PressMouseOnSourceAtIndex(0);
  ASSERT_TRUE(test_api_.GetSelectedSourceId().has_value());
  EXPECT_EQ(10, test_api_.GetSelectedSourceId().value());

  test_api_.PressMouseOnSourceAtIndex(1);
  ASSERT_TRUE(test_api_.GetSelectedSourceId().has_value());
  EXPECT_EQ(20, test_api_.GetSelectedSourceId().value());
}

// Verifies that the MediaSourceView is added or removed when |media_list_| is
// updated.
TEST_P(DesktopMediaPickerViewsPerTypeTest, AddAndRemoveMediaSource) {
  // No media source at first.
  EXPECT_FALSE(test_api_.HasSourceAtIndex(0));

  for (int i = 0; i < 3; ++i) {
    media_lists_[type()]->AddSourceByFullMediaID(
        DesktopMediaID(source_id_type(), i));
    EXPECT_TRUE(test_api_.HasSourceAtIndex(i));
  }

  for (int i = 2; i >= 0; --i) {
    media_lists_[type()]->RemoveSource(i);
    EXPECT_FALSE(test_api_.HasSourceAtIndex(i));
  }
}

// Verifies that focusing the MediaSourceView marks it selected and the
// original selected MediaSourceView gets unselected.
TEST_P(DesktopMediaPickerViewsPerTypeTest, FocusMediaSourceViewToSelect) {
  media_lists_[type()]->AddSourceByFullMediaID(
      DesktopMediaID(source_id_type(), 10));
  media_lists_[type()]->AddSourceByFullMediaID(
      DesktopMediaID(source_id_type(), 20));

  test_api_.FocusSourceAtIndex(0);
  ASSERT_TRUE(test_api_.GetSelectedSourceId().has_value());
  EXPECT_EQ(10, test_api_.GetSelectedSourceId().value());

  if (test_api_.AudioSupported(type())) {
    test_api_.FocusAudioShareControl();
    ASSERT_TRUE(test_api_.GetSelectedSourceId().has_value());
    EXPECT_EQ(10, test_api_.GetSelectedSourceId().value());
  }

  test_api_.FocusSourceAtIndex(1);
  ASSERT_TRUE(test_api_.GetSelectedSourceId().has_value());
  EXPECT_EQ(20, test_api_.GetSelectedSourceId().value());
}

TEST_P(DesktopMediaPickerViewsPerTypeTest, OkButtonDisabledWhenNoSelection) {
  media_lists_[type()]->AddSourceByFullMediaID(
      DesktopMediaID(source_id_type(), 111));
  EXPECT_FALSE(GetPickerDialogView()->IsDialogButtonEnabled(
      ui::mojom::DialogButton::kOk));

  test_api_.FocusSourceAtIndex(0);
  EXPECT_TRUE(GetPickerDialogView()->IsDialogButtonEnabled(
      ui::mojom::DialogButton::kOk));

  media_lists_[type()]->RemoveSource(0);
  EXPECT_FALSE(GetPickerDialogView()->IsDialogButtonEnabled(
      ui::mojom::DialogButton::kOk));
}

// Verifies that the controller can successfully clear the selection when asked
// to do so.
TEST_P(DesktopMediaPickerViewsPerTypeTest, ClearSelection) {
  media_lists_[type()]->AddSourceByFullMediaID(
      DesktopMediaID(source_id_type(), 10));
  media_lists_[type()]->AddSourceByFullMediaID(
      DesktopMediaID(source_id_type(), 20));

  // By default, nothing should be selected.
  EXPECT_FALSE(test_api_.GetSelectedSourceId().has_value());

  // Select a Source ID.
  test_api_.PressMouseOnSourceAtIndex(0);
  ASSERT_TRUE(test_api_.GetSelectedSourceId().has_value());
  EXPECT_EQ(10, test_api_.GetSelectedSourceId().value());

  // Clear the selection and assert that nothing is selected.
  test_api_.GetSelectedController()->ClearSelection();
  EXPECT_FALSE(test_api_.GetSelectedSourceId().has_value());
}

class DesktopMediaPickerViewsPerTypeAndAudioTest
    : public DesktopMediaPickerViewsTestBase,
      public testing::WithParamInterface<
          std::tuple<DesktopMediaList::Type, bool, bool>> {
 public:
  DesktopMediaPickerViewsPerTypeAndAudioTest()
      : DesktopMediaPickerViewsTestBase(GetSourceTypes(/*new_order=*/true)) {}
  ~DesktopMediaPickerViewsPerTypeAndAudioTest() override = default;

  void MaybeCreatePickerViews() override {
    CreatePickerViews(RequireAudio(), SystemAudio());
  }

  DesktopMediaList::Type Type() const { return std::get<0>(GetParam()); }
  bool RequireAudio() const { return std::get<1>(GetParam()); }
  bool SystemAudio() const { return std::get<2>(GetParam()); }
};

INSTANTIATE_TEST_SUITE_P(
    ,
    DesktopMediaPickerViewsPerTypeAndAudioTest,
    testing::Combine(testing::Values(DesktopMediaList::Type::kWebContents,
                                     DesktopMediaList::Type::kWindow,
                                     DesktopMediaList::Type::kScreen),
                     testing::Bool(),
                     testing::Bool()));

TEST_P(DesktopMediaPickerViewsPerTypeAndAudioTest, AcceptSpecific) {
  DesktopMediaID fake_id(AsDesktopMediaIdType(Type()), 333);

  // Audio is enabled by default for tabs
  if (RequireAudio() &&
      AsDesktopMediaIdType(Type()) == DesktopMediaID::TYPE_WEB_CONTENTS) {
    fake_id.audio_share = true;
  }
  media_lists_[Type()]->AddSourceByFullMediaID(fake_id);

  GetPickerDialogView()->AcceptSpecificSource(fake_id);
  EXPECT_EQ(fake_id, WaitForPickerResult());
}

class DesktopMediaPickerViewsSystemAudioTest
    : public DesktopMediaPickerViewsTestBase {
 public:
  DesktopMediaPickerViewsSystemAudioTest()
      : DesktopMediaPickerViewsTestBase(GetSourceTypes(/*new_order=*/false)) {}
  ~DesktopMediaPickerViewsSystemAudioTest() override = default;

  void MaybeCreatePickerViews() override {
    // CreatePickerViews() called  directly from tests.
  }
};

TEST_F(DesktopMediaPickerViewsSystemAudioTest,
       SystemAudioCheckboxVisibleIfExcludeSystemAudioNotSpecified) {
  CreatePickerViews(/*request_audio=*/true, /*exclude_system_audio=*/false);

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);

  // System audio checkbox shown to the user iff the platform supports it.
  EXPECT_EQ(DesktopMediaPickerController::IsSystemAudioCaptureSupported(
                DesktopMediaPicker::Params::RequestSource::kGetDisplayMedia),
            test_api_.HasAudioShareControl());
}

TEST_F(DesktopMediaPickerViewsSystemAudioTest,
       SystemAudioCheckboxInvisibleIfExcludeSystemAudioSpecified) {
  CreatePickerViews(/*request_audio=*/true, /*exclude_system_audio=*/true);

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);

  // Main expectation: System audio control not shown to the user, only a hint
  // to select a tab instead.
  EXPECT_FALSE(test_api_.HasAudioShareControl());
  EXPECT_EQ(
      test_api_.GetAudioLabelText(),
      l10n_util::GetStringUTF16(IDS_DESKTOP_MEDIA_PICKER_AUDIO_SHARE_HINT_TAB));

  // Secondary expectation: No effect on the tab-audio checkbox.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  EXPECT_TRUE(test_api_.HasAudioShareControl());
}

TEST_F(DesktopMediaPickerViewsSystemAudioTest,
       IfAudioNotRequestedThenExcludeSystemAudioHasNoEffect) {
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);

  // Main expectation: System audio checkbox not shown to the user.
  EXPECT_FALSE(test_api_.HasAudioShareControl());

  // Secondary expectation: No effect on the tab-audio checkbox.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  EXPECT_FALSE(test_api_.HasAudioShareControl());  // Not requested.
}

// Creates a single pane DesktopMediaPickerImpl that only has a tab list.
class DesktopMediaPickerViewsSingleTabPaneTest
    : public DesktopMediaPickerViewsTestBase {
 public:
  DesktopMediaPickerViewsSingleTabPaneTest()
      : DesktopMediaPickerViewsTestBase(
            {DesktopMediaList::Type::kWebContents}) {}
  ~DesktopMediaPickerViewsSingleTabPaneTest() override = default;

 protected:
  void AddTabSource() {
    media_lists_[DesktopMediaList::Type::kWebContents]->AddSourceByFullMediaID(
        DesktopMediaID(DesktopMediaID::TYPE_WEB_CONTENTS, 0));
  }
};

// Validates that the tab list's preferred size is not zero.
// (https://crbug.com/965408).
TEST_F(DesktopMediaPickerViewsSingleTabPaneTest, TabListPreferredSizeNotZero) {
  EXPECT_GT(test_api_.GetSelectedListView()->height(), 0);
}

// Validates that the tab list has a fixed height (https://crbug.com/998485).
TEST_F(DesktopMediaPickerViewsSingleTabPaneTest, TabListHasFixedHeight) {
  auto GetDialogHeight = [&]() {
    return GetPickerDialogView()->GetPreferredSize().height();
  };

  int initial_size = GetDialogHeight();

  // The dialog's height should not change when going from zero sources to nine
  // sources.
  for (int i = 0; i < 9; i++) {
    AddTabSource();
  }
  EXPECT_EQ(GetDialogHeight(), initial_size);

  // The dialog's height should be fixed and equal to the equivalent of ten
  // rows, thus it should not change when going from nine to eleven either.
  AddTabSource();
  EXPECT_EQ(GetDialogHeight(), initial_size);
  AddTabSource();
  EXPECT_EQ(GetDialogHeight(), initial_size);

  // And then it shouldn't change when going to a larger number of sources.
  for (int i = 0; i < 50; i++) {
    AddTabSource();
  }
  EXPECT_EQ(GetDialogHeight(), initial_size);

  // And then it shouldn't change when going from a large number of sources (in
  // this case 61) to a larger number, because the ScrollView should scroll
  // large numbers of sources.
  for (int i = 0; i < 50; i++) {
    AddTabSource();
  }
  EXPECT_EQ(GetDialogHeight(), initial_size);
}

// Regression test for https://crbug.com/1042976.
TEST_F(DesktopMediaPickerViewsSingleTabPaneTest,
       CannotAcceptTabWithoutSelection) {
  AddTabSource();
  AddTabSource();
  AddTabSource();

  test_api_.FocusSourceAtIndex(0, false);
  EXPECT_EQ(std::nullopt, test_api_.GetSelectedSourceId());
  EXPECT_FALSE(GetPickerDialogView()->IsDialogButtonEnabled(
      ui::mojom::DialogButton::kOk));

  // Send the tab list a Return key press, to make sure it doesn't try to accept
  // with no selected source. If the fix to https://crbug.com/1042976 regresses,
  // this test will crash here.
  test_api_.PressKeyOnSourceAtIndex(
      0, ui::KeyEvent(ui::EventType::kKeyPressed, ui::VKEY_RETURN, 0));
}

// Tests accessible properties of DesktopMediaListView and
// DesktopMediaSourceView.
TEST_F(DesktopMediaPickerViewsSingleTabPaneTest, AccessibleProperties) {
  ui::AXNodeData data;
  DesktopMediaSourceViewStyle style = DesktopMediaSourceViewStyle(
      /*columns=*/2,
      /*item_size=*/gfx::Size(266, 224),
      /*icon_rect=*/gfx::Rect(),
      /*label_rect=*/gfx::Rect(8, 196, 250, 36),
      /*text_alignment=*/gfx::HorizontalAlignment::ALIGN_CENTER,
      /*image_rect=*/gfx::Rect(8, 8, 250, 180));

  // DesktopMediaListView accessible properties test.

  std::u16string sample_accessible_name = u"Sample accessible name";
  auto list_view = std::make_unique<DesktopMediaListView>(
      test_api_.GetSelectedController(), style, style, sample_accessible_name);

  list_view->GetViewAccessibility().GetAccessibleNodeData(&data);
  EXPECT_EQ(data.role, ax::mojom::Role::kGroup);
  EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
            sample_accessible_name);
  EXPECT_EQ(list_view->GetViewAccessibility().GetCachedName(),
            sample_accessible_name);

  // DesktopMediaSourceView accessible properties test.
  const content::DesktopMediaID media_id(content::DesktopMediaID::TYPE_SCREEN,
                                         content::DesktopMediaID::kFakeId);
  auto source_view = std::make_unique<DesktopMediaSourceView>(list_view.get(),
                                                              media_id, style);
  data = ui::AXNodeData();

  ASSERT_TRUE(source_view);
  source_view->GetViewAccessibility().GetAccessibleNodeData(&data);
  EXPECT_EQ(data.role, ax::mojom::Role::kButton);
  EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
            l10n_util::GetStringUTF16(
                IDS_DESKTOP_MEDIA_SOURCE_EMPTY_ACCESSIBLE_NAME));
  EXPECT_EQ(source_view->GetViewAccessibility().GetCachedName(),
            l10n_util::GetStringUTF16(
                IDS_DESKTOP_MEDIA_SOURCE_EMPTY_ACCESSIBLE_NAME));

  source_view->SetName(sample_accessible_name);

  data = ui::AXNodeData();
  source_view->GetViewAccessibility().GetAccessibleNodeData(&data);
  EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
            sample_accessible_name);
  EXPECT_EQ(source_view->GetViewAccessibility().GetCachedName(),
            sample_accessible_name);

  // DesktopMediaDelegatedSourceListView accessible properties test.
  auto view = std::make_unique<DesktopMediaDelegatedSourceListView>(
      test_api_.GetSelectedController()->GetWeakPtr(), sample_accessible_name,
      DesktopMediaList::Type::kScreen);

  data = ui::AXNodeData();
  view->GetViewAccessibility().GetAccessibleNodeData(&data);
  EXPECT_EQ(data.role, ax::mojom::Role::kGroup);
  EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
            sample_accessible_name);
}

class DesktopMediaPickerPreferredDisplaySurfaceTest
    : public DesktopMediaPickerViewsTestBase,
      public testing::WithParamInterface<
          std::tuple<bool, blink::mojom::PreferredDisplaySurface>> {
 public:
  DesktopMediaPickerPreferredDisplaySurfaceTest()
      : DesktopMediaPickerViewsTestBase(GetSourceTypes(NewOrder())) {}

  void MaybeCreatePickerViews() override {
    CreatePickerViews(/*request_audio=*/true, /*exclude_system_audio=*/false,
                      PreferredDisplaySurface());
  }

  bool NewOrder() const { return std::get<0>(GetParam()); }

  blink::mojom::PreferredDisplaySurface PreferredDisplaySurface() const {
    return std::get<1>(GetParam());
  }
};

INSTANTIATE_TEST_SUITE_P(
    ,
    DesktopMediaPickerPreferredDisplaySurfaceTest,
    testing::Combine(
        /*NewOrder=*/testing::Bool(),
        testing::Values(blink::mojom::PreferredDisplaySurface::NO_PREFERENCE,
                        blink::mojom::PreferredDisplaySurface::MONITOR,
                        blink::mojom::PreferredDisplaySurface::WINDOW,
                        blink::mojom::PreferredDisplaySurface::BROWSER)));

TEST_P(DesktopMediaPickerPreferredDisplaySurfaceTest,
       SelectedTabMatchesPreferredDisplaySurface) {
  switch (PreferredDisplaySurface()) {
    case blink::mojom::PreferredDisplaySurface::NO_PREFERENCE:
      EXPECT_EQ(test_api_.GetSelectedSourceListType(),
                NewOrder() ? DesktopMediaList::Type::kWebContents
                           : DesktopMediaList::Type::kScreen);
      break;
    case blink::mojom::PreferredDisplaySurface::MONITOR:
      EXPECT_EQ(test_api_.GetSelectedSourceListType(),
                DesktopMediaList::Type::kScreen);
      break;
    case blink::mojom::PreferredDisplaySurface::WINDOW:
      EXPECT_EQ(test_api_.GetSelectedSourceListType(),
                DesktopMediaList::Type::kWindow);
      break;
    case blink::mojom::PreferredDisplaySurface::BROWSER:
      EXPECT_EQ(test_api_.GetSelectedSourceListType(),
                DesktopMediaList::Type::kWebContents);
      break;
  }
}

class DesktopMediaPickerDoubleClickTest
    : public DesktopMediaPickerViewsTestBase,
      public testing::WithParamInterface<
          std::pair<DesktopMediaList::Type, DesktopMediaID::Type>> {
 public:
  DesktopMediaPickerDoubleClickTest()
      : DesktopMediaPickerViewsTestBase(GetSourceTypes(/*new_order=*/true)) {}
};

INSTANTIATE_TEST_SUITE_P(
    ,
    DesktopMediaPickerDoubleClickTest,
    testing::Values(std::make_pair(DesktopMediaList::Type::kWindow,
                                   DesktopMediaID::TYPE_WINDOW),
                    std::make_pair(DesktopMediaList::Type::kScreen,
                                   DesktopMediaID::TYPE_SCREEN),
                    std::make_pair(DesktopMediaList::Type::kWebContents,
                                   DesktopMediaID::TYPE_WEB_CONTENTS)));

// Regression test for https://crbug.com/1102153 and https://crbug.com/1127496
TEST_P(DesktopMediaPickerDoubleClickTest, DoneCallbackNotCalledOnDoubleClick) {
  const DesktopMediaList::Type media_list_type = std::get<0>(GetParam());
  const DesktopMediaID::Type media_type = std::get<1>(GetParam());

  const DesktopMediaID kFakeId(media_type, 222);

  media_lists_[media_list_type]->AddSourceByFullMediaID(kFakeId);
  test_api_.SelectTabForSourceType(media_list_type);
  test_api_.PressMouseOnSourceAtIndex(0, true);

  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, run_loop_.QuitClosure());
  run_loop_.Run();

  EXPECT_FALSE(has_picker_result());
}

// This class expects tests to directly call first SetSourceTypes() and then
// CreatePickerViews().
class DelegatedSourceListTest : public DesktopMediaPickerViewsTestBase {
 public:
  DelegatedSourceListTest() : DesktopMediaPickerViewsTestBase({}) {}
  ~DelegatedSourceListTest() override = default;

  void MaybeCreatePickerViews() override {}

  void SetSourceTypes(
      const std::vector<DesktopMediaList::Type>& source_types,
      const std::vector<DesktopMediaList::Type>& delegated_source_types) {
    source_types_ = source_types;
    delegated_source_types_ = delegated_source_types;
    ASSERT_FALSE(
        std::ranges::any_of(source_types_, [this](DesktopMediaList::Type type) {
          return base::Contains(delegated_source_types_, type);
        }));
  }
};

// Ensures that Focus/Hide View events get plumbed correctly to the source lists
// upon the view being selected or not.
TEST_F(DelegatedSourceListTest, EnsureFocus) {
  SetSourceTypes(
      {DesktopMediaList::Type::kWebContents},
      {DesktopMediaList::Type::kScreen, DesktopMediaList::Type::kWindow});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  EXPECT_FALSE(media_lists_[DesktopMediaList::Type::kScreen]->is_focused());
  EXPECT_FALSE(media_lists_[DesktopMediaList::Type::kWindow]->is_focused());

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  EXPECT_TRUE(media_lists_[DesktopMediaList::Type::kScreen]->is_focused());
  EXPECT_FALSE(media_lists_[DesktopMediaList::Type::kWindow]->is_focused());

  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWindow);
  EXPECT_FALSE(media_lists_[DesktopMediaList::Type::kScreen]->is_focused());
  EXPECT_TRUE(media_lists_[DesktopMediaList::Type::kWindow]->is_focused());
}

#if BUILDFLAG(IS_MAC)

// Ensures that the first (only) source from a delegated source list is
// selected.
TEST_F(DelegatedSourceListTest, TestSelection) {
  SetSourceTypes(
      {DesktopMediaList::Type::kWebContents},
      {DesktopMediaList::Type::kScreen, DesktopMediaList::Type::kWindow});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  // Add the one entry that is expected for a delegated source list and switch
  // to it. Note that since this is a delegated source, we must select its pane
  // before the observer will be set for adding items to the list.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  media_lists_[DesktopMediaList::Type::kScreen]->AddSourceByFullMediaID(
      DesktopMediaID(AsDesktopMediaIdType(DesktopMediaList::Type::kScreen),
                     10));

  // On MacOS, the added source is automatically selected.
  ASSERT_TRUE(test_api_.GetSelectedSourceId().has_value());
  EXPECT_EQ(10, test_api_.GetSelectedSourceId().value());
}

#else

// Ensures that the first (only) source from a delegated source list is selected
// after being notified that it has made a selection.
TEST_F(DelegatedSourceListTest, TestSelection) {
  SetSourceTypes(
      {DesktopMediaList::Type::kWebContents},
      {DesktopMediaList::Type::kScreen, DesktopMediaList::Type::kWindow});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  // Add the one entry that is expected for a delegated source list and switch
  // to it. Note that since this is a delegated source, we must select its pane
  // before the observer will be set for adding items to the list.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  media_lists_[DesktopMediaList::Type::kScreen]->AddSourceByFullMediaID(
      DesktopMediaID(AsDesktopMediaIdType(DesktopMediaList::Type::kScreen),
                     10));
  ASSERT_FALSE(test_api_.GetSelectedSourceId().has_value());

  // Indicate that a selection has been made and ensure that our one source is
  // now selected.
  media_lists_[DesktopMediaList::Type::kScreen]
      ->OnDelegatedSourceListSelection();

  ASSERT_TRUE(test_api_.GetSelectedSourceId().has_value());
  EXPECT_EQ(10, test_api_.GetSelectedSourceId().value());
}

#endif  // BUILDFLAG(IS_MACOS)

// Creates a single pane picker and verifies that when it gets notified that the
// delegated source list is dismissed that it finishes without a selection.
TEST_F(DelegatedSourceListTest, SinglePaneReject) {
  SetSourceTypes({}, {DesktopMediaList::Type::kScreen});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  media_lists_[DesktopMediaList::Type::kScreen]
      ->OnDelegatedSourceListDismissed();

  EXPECT_EQ(
      WaitForPickerResult(),
      base::unexpected(MediaStreamRequestResult::PERMISSION_DENIED_BY_USER));
}

// Creates a picker without the default fallback pane and verifies that when it
// gets notified that the delegated source list is dismissed that it finishes
// without a selection.
TEST_F(DelegatedSourceListTest, NoFallbackPaneReject) {
  // kWebContents is the fallback type, so give two types but ensure that it
  // isn't one of them.
  SetSourceTypes(
      {}, {DesktopMediaList::Type::kScreen, DesktopMediaList::Type::kWindow});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  media_lists_[DesktopMediaList::Type::kScreen]
      ->OnDelegatedSourceListDismissed();
  EXPECT_EQ(
      WaitForPickerResult(),
      base::unexpected(MediaStreamRequestResult::PERMISSION_DENIED_BY_USER));
}

#if BUILDFLAG(IS_MAC)
// Creates a picker with the default fallback pane and verifies that when it
// gets notified that the delegated source list is dismissed that it closes the
// picker.
TEST_F(DelegatedSourceListTest, ClosePickerOnSourceListDismissed) {
  // WebContents is the fallback type, so need to have a picker with it and
  // one other type.
  SetSourceTypes({DesktopMediaList::Type::kWebContents},
                 {DesktopMediaList::Type::kScreen});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  // Switch to the screen pane and simulate the user dismissing the native
  // picker.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  media_lists_[DesktopMediaList::Type::kScreen]
      ->OnDelegatedSourceListDismissed();

  // Dismissing the delegated source list should close the picker
  // without a selection.
  EXPECT_EQ(
      WaitForPickerResult(),
      base::unexpected(MediaStreamRequestResult::PERMISSION_DENIED_BY_USER));
}

// The delegated picker experience on MacOS (using SCContentSharingPicker)
// starts the capture immediately after the user has made their choice, so
// the reselect button is not enabled for any capture type
TEST_F(DelegatedSourceListTest, ReselectButtonAbsent) {
  SetSourceTypes(
      {DesktopMediaList::Type::kWebContents},
      {DesktopMediaList::Type::kScreen, DesktopMediaList::Type::kWindow});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  // Ensure that we don't have a reselect button for the non-delegated type.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  EXPECT_EQ(nullptr, test_api_.GetReselectButton());

  // Ensure that we don't have a reselect button for the screen delegated type.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  ASSERT_EQ(nullptr, test_api_.GetReselectButton());

  // Ensure that we don't have a reselect button for window delegated type.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWindow);
  ASSERT_EQ(nullptr, test_api_.GetReselectButton());
}

#else
// Creates a picker with the default fallback pane and verifies that when it
// gets notified that the delegated source list is dismissed that it switches
// to that pane.
TEST_F(DelegatedSourceListTest, SwitchToWebContents) {
  // WebContents is the fallback type, so need to have a picker with it and
  // one other type.
  SetSourceTypes({DesktopMediaList::Type::kWebContents},
                 {DesktopMediaList::Type::kScreen});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  // Switch to the screen pane, dismiss it, then validate that we're back on
  // the WebContents pane.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  media_lists_[DesktopMediaList::Type::kScreen]
      ->OnDelegatedSourceListDismissed();

  EXPECT_EQ(DesktopMediaList::Type::kWebContents,
            test_api_.GetSelectedSourceListType());
}

// Creates a picker with the default fallback pane and verifies that when it
// gets notified that the delegated source list is dismissed that it switches
// to that pane and clears any previous selection.
TEST_F(DelegatedSourceListTest, EnsureNoWebContentsSelected) {
  // Ensure that we have the (Fallback) WebContents type and a different type
  SetSourceTypes({DesktopMediaList::Type::kWebContents},
                 {DesktopMediaList::Type::kScreen});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);
  const auto web_contents_source_type =
      AsDesktopMediaIdType(DesktopMediaList::Type::kWebContents);

  // Add a couple of tabs
  media_lists_[DesktopMediaList::Type::kWebContents]->AddSourceByFullMediaID(
      DesktopMediaID(web_contents_source_type, 10));
  media_lists_[DesktopMediaList::Type::kWebContents]->AddSourceByFullMediaID(
      DesktopMediaID(web_contents_source_type, 20));

  // Select a tab
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  test_api_.PressMouseOnSourceAtIndex(0);
  ASSERT_TRUE(test_api_.GetSelectedSourceId().has_value());
  EXPECT_EQ(10, test_api_.GetSelectedSourceId().value());

  // Switch to screen and then indicate that we need to switch back because it
  // has been dismissed.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  media_lists_[DesktopMediaList::Type::kScreen]
      ->OnDelegatedSourceListDismissed();

  // We should be back on the tab pane with no item selected.
  EXPECT_EQ(DesktopMediaList::Type::kWebContents,
            test_api_.GetSelectedSourceListType());
  ASSERT_FALSE(test_api_.GetSelectedSourceId().has_value());
}

// Verify that the reselect button is only present on the delegated source list
// type panes.
TEST_F(DelegatedSourceListTest, ReselectButtonEnabled) {
  SetSourceTypes(
      {DesktopMediaList::Type::kWebContents},
      {DesktopMediaList::Type::kScreen, DesktopMediaList::Type::kWindow});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  // Ensure that we don't have a reselect button for the non-delegated type.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  EXPECT_EQ(nullptr, test_api_.GetReselectButton());

  // Ensure that we do have a reselect button for the screen delegated type, and
  // that it is not enabled by default.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  ASSERT_NE(nullptr, test_api_.GetReselectButton());
  EXPECT_FALSE(test_api_.GetReselectButton()->GetEnabled());

  // Ensure that the reselect button is cleared by switching back to the non
  // delegated type.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWebContents);
  EXPECT_EQ(nullptr, test_api_.GetReselectButton());

  // Ensure that we do have a reselect button for the window delegated type, and
  // that it is not enabled by default.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWindow);
  ASSERT_NE(nullptr, test_api_.GetReselectButton());
  EXPECT_FALSE(test_api_.GetReselectButton()->GetEnabled());
}

// Verifies that the reselect button is disabled until a selection has been
// made in the delegated source list, and then disables itself again after a
// click.
TEST_F(DelegatedSourceListTest, ReselectButtonEnabledState) {
  SetSourceTypes(
      {DesktopMediaList::Type::kWebContents},
      {DesktopMediaList::Type::kScreen, DesktopMediaList::Type::kWindow});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  // Ensure that we do have a reselect button for the screen delegated type, and
  // that it is not enabled by default.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  ASSERT_NE(nullptr, test_api_.GetReselectButton());
  EXPECT_FALSE(test_api_.GetReselectButton()->GetEnabled());

  // Simulate a selection and verify that the reselect button gets enabled.
  media_lists_[DesktopMediaList::Type::kScreen]
      ->OnDelegatedSourceListSelection();
  EXPECT_TRUE(test_api_.GetReselectButton()->GetEnabled());

  // Verify that the other Reselect button remains disabled.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kWindow);
  ASSERT_NE(nullptr, test_api_.GetReselectButton());
  EXPECT_FALSE(test_api_.GetReselectButton()->GetEnabled());

  // Verify that clicking the button causes the button to become disabled.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);
  views::test::ButtonTestApi(test_api_.GetReselectButton()).NotifyClick(event);
  EXPECT_FALSE(test_api_.GetReselectButton()->GetEnabled());

  // Simulate a selection and verify that the reselect button can get re-enabled
  // again.
  media_lists_[DesktopMediaList::Type::kScreen]
      ->OnDelegatedSourceListSelection();
  EXPECT_TRUE(test_api_.GetReselectButton()->GetEnabled());
}

// Verifies that clicking the Reselect button will cause the delegated source
// list to be triggered to show again.
TEST_F(DelegatedSourceListTest, ReselectTriggersShowDelegatedSourceList) {
  SetSourceTypes(
      {DesktopMediaList::Type::kWebContents},
      {DesktopMediaList::Type::kScreen, DesktopMediaList::Type::kWindow});
  CreatePickerViews(/*request_audio=*/false, /*exclude_system_audio=*/true);

  // ClearSourceListSelection should not have been called on either list yet.
  EXPECT_EQ(0, media_lists_[DesktopMediaList::Type::kScreen]
                   ->clear_delegated_source_list_selection_count());
  EXPECT_EQ(0, media_lists_[DesktopMediaList::Type::kWindow]
                   ->clear_delegated_source_list_selection_count());

  // Ensure that we have an enabled source list button.
  test_api_.SelectTabForSourceType(DesktopMediaList::Type::kScreen);
  media_lists_[DesktopMediaList::Type::kScreen]
      ->OnDelegatedSourceListSelection();
  ASSERT_NE(nullptr, test_api_.GetReselectButton());
  EXPECT_TRUE(test_api_.GetReselectButton()->GetEnabled());

  // Verify that clicking the button causes the selection to be cleared on the
  // current source list.
  const ui::MouseEvent event(ui::EventType::kMousePressed, gfx::Point(),
                             gfx::Point(), ui::EventTimeForNow(), 0, 0);
  views::test::ButtonTestApi(test_api_.GetReselectButton()).NotifyClick(event);
  EXPECT_EQ(1, media_lists_[DesktopMediaList::Type::kScreen]
                   ->clear_delegated_source_list_selection_count());
  EXPECT_EQ(0, media_lists_[DesktopMediaList::Type::kWindow]
                   ->clear_delegated_source_list_selection_count());
}

#endif  // BUILDFLAG(IS_MAC)
}  // namespace views