File: fullscreen_controller_interactive_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1840 lines) | stat: -rw-r--r-- 78,030 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
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
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/functional/callback_forward.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "build/build_config.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/browser_window/public/browser_window_features.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_context.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_test.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/web_applications/test/isolated_web_app_test_utils.h"
#include "chrome/browser/web_applications/isolated_web_apps/isolated_web_app_url_info.h"
#include "chrome/browser/web_applications/isolated_web_apps/test/isolated_web_app_builder.h"
#include "chrome/browser/web_applications/test/os_integration_test_override_impl.h"
#include "chrome/common/chrome_features.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/blocked_content/popup_blocker_tab_helper.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/metrics/content/subprocess_metrics_provider.h"
#include "components/permissions/permission_request_manager.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/frame/user_activation_state.h"
#include "third_party/blink/public/common/switches.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom.h"
#include "ui/display/screen.h"
#include "ui/display/test/virtual_display_util.h"
#include "ui/display/types/display_constants.h"

#if BUILDFLAG(IS_LINUX) && BUILDFLAG(IS_OZONE)
#include "ui/ozone/public/ozone_platform.h"
#endif  // BUILDFLAG(IS_LINUX) && BUILDFLAG(IS_OZONE)

#if BUILDFLAG(IS_MAC)
#include "ui/base/cocoa/nswindow_test_util.h"
#endif  // BUILDFLAG(IS_MAC)

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

using content::WebContents;

namespace {

const base::FilePath::CharType* kSimpleFile = FILE_PATH_LITERAL("simple.html");

}  // namespace

class FullscreenControllerInteractiveTest : public ExclusiveAccessTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExclusiveAccessTest::SetUpCommandLine(command_line);
    // Slow bots are flaky due to slower loading interacting with
    // deferred commits.
    command_line->AppendSwitch(blink::switches::kAllowPreCommitInput);
  }

  // Tests that actually make the browser fullscreen have been flaky when
  // run sharded, and so are restricted here to interactive ui tests.
  void ToggleTabFullscreen(bool enter_fullscreen);
  void ToggleTabFullscreenNoRetries(bool enter_fullscreen);
  void ToggleBrowserFullscreen(bool enter_fullscreen);

  // IsPointerLocked verifies that the FullscreenController state believes
  // the pointer is locked. This is possible only for tests that initiate
  // pointer lock from a renderer process, and uses logic that tests that the
  // browser has focus. Thus, this can only be used in interactive ui tests
  // and not on sharded tests.
  bool IsPointerLocked() {
    // Verify that IsPointerLocked is consistent between the
    // Fullscreen Controller and the Render View Host View.
    EXPECT_TRUE(browser()->IsPointerLocked() == browser()
                                                    ->tab_strip_model()
                                                    ->GetActiveWebContents()
                                                    ->GetPrimaryMainFrame()
                                                    ->GetRenderViewHost()
                                                    ->GetWidget()
                                                    ->GetView()
                                                    ->IsPointerLocked());
    return browser()->IsPointerLocked();
  }

  void PressKeyAndWaitForPointerLockRequest(ui::KeyboardCode key_code) {
    base::RunLoop run_loop;
    browser()
        ->GetFeatures()
        .exclusive_access_manager()
        ->pointer_lock_controller()
        ->set_lock_state_callback_for_test(run_loop.QuitClosure());
    ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), key_code, false,
                                                false, false, false));
    run_loop.Run();
  }

  void WaitForPointerLockBubbleToHide() {
    if (!IsExclusiveAccessBubbleDisplayed()) {
      return;
    }

    PointerLockController* pointer_lock_controller =
        browser()
            ->GetFeatures()
            .exclusive_access_manager()
            ->pointer_lock_controller();
    base::RunLoop run_loop;
    pointer_lock_controller->set_bubble_hide_callback_for_test(
        base::BindRepeating(
            [](base::RunLoop* run_loop,
               ExclusiveAccessBubbleHideReason reason) {
              ASSERT_EQ(reason, ExclusiveAccessBubbleHideReason::kTimeout);
              run_loop->Quit();
            },
            &run_loop));
    run_loop.Run();
    pointer_lock_controller->set_bubble_hide_callback_for_test(
        base::NullCallback());
    FinishExclusiveAccessBubbleAnimation();
  }

 private:
  void ToggleTabFullscreen_Internal(bool enter_fullscreen,
                                    bool retry_until_success);
};

void FullscreenControllerInteractiveTest::ToggleTabFullscreen(
    bool enter_fullscreen) {
  ToggleTabFullscreen_Internal(enter_fullscreen, true);
}

// |ToggleTabFullscreen| should not need to tolerate the transition failing.
// Most fullscreen tests run sharded in fullscreen_controller_browsertest.cc
// and some flakiness has occurred when calling |ToggleTabFullscreen|, so that
// method has been made robust by retrying if the transition fails.
// The root cause of that flakiness should still be tracked down, see
// http://crbug.com/133831. In the mean time, this method
// allows a fullscreen_controller_interactive_browsertest.cc test to verify
// that when running serially there is no flakiness in the transition.
void FullscreenControllerInteractiveTest::ToggleTabFullscreenNoRetries(
    bool enter_fullscreen) {
  ToggleTabFullscreen_Internal(enter_fullscreen, false);
}

void FullscreenControllerInteractiveTest::ToggleBrowserFullscreen(
    bool enter_fullscreen) {
  ASSERT_EQ(browser()->window()->IsFullscreen(), !enter_fullscreen);

  ui_test_utils::ToggleFullscreenModeAndWait(browser());

  ASSERT_EQ(browser()->window()->IsFullscreen(), enter_fullscreen);
  ASSERT_EQ(IsFullscreenForBrowser(), enter_fullscreen);
}

void FullscreenControllerInteractiveTest::ToggleTabFullscreen_Internal(
    bool enter_fullscreen,
    bool retry_until_success) {
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  do {
    ui_test_utils::FullscreenWaiter waiter(
        browser(), {.tab_fullscreen = enter_fullscreen});
    if (enter_fullscreen) {
      browser()->EnterFullscreenModeForTab(tab->GetPrimaryMainFrame(), {});
    } else {
      browser()->ExitFullscreenModeForTab(tab);
    }
    waiter.Wait();
    // Repeat ToggleFullscreenModeForTab until the correct state is entered.
    // This addresses flakiness on test bots running many fullscreen
    // tests in parallel.
  } while (retry_until_success && !IsFullscreenForBrowser() &&
           browser()->window()->IsFullscreen() != enter_fullscreen);
  ASSERT_EQ(IsWindowFullscreenForTabOrPending(), enter_fullscreen);
  if (!IsFullscreenForBrowser()) {
    ASSERT_EQ(browser()->window()->IsFullscreen(), enter_fullscreen);
  }
}

// Tests ///////////////////////////////////////////////////////////////////////

// Tests that while in fullscreen creating a new tab will exit fullscreen.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       TestNewTabExitsFullscreen) {
#if BUILDFLAG(IS_LINUX) && BUILDFLAG(IS_OZONE)
  // Flaky in Linux interactive_ui_tests_wayland: crbug.com/1200036
  if (ui::OzonePlatform::GetPlatformNameForTest() == "wayland") {
    GTEST_SKIP();
  }
#endif

  ASSERT_TRUE(embedded_test_server()->Start());

  ASSERT_TRUE(
      AddTabAtIndex(0, GURL(url::kAboutBlankURL), ui::PAGE_TRANSITION_TYPED));

  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));

  {
    ui_test_utils::FullscreenWaiter waiter(browser(),
                                           {.tab_fullscreen = false});
    ASSERT_TRUE(
        AddTabAtIndex(1, GURL(url::kAboutBlankURL), ui::PAGE_TRANSITION_TYPED));
    waiter.Wait();
    ASSERT_FALSE(browser()->window()->IsFullscreen());
  }
}

// Tests a tab exiting fullscreen will bring the browser out of fullscreen.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       TestTabExitsItselfFromFullscreen) {
  ASSERT_TRUE(embedded_test_server()->Start());

  ASSERT_TRUE(
      AddTabAtIndex(0, GURL(url::kAboutBlankURL), ui::PAGE_TRANSITION_TYPED));

  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(false));
}

// Tests that the closure provided to RunOrDeferUntilTransitionIsComplete is
// run. Some platforms may be synchronous (lambda is executed immediately) and
// others (e.g. Mac) will run it asynchronously (after the transition).
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       RunOrDeferClosureDuringTransition) {
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  GetFullscreenController()->EnterFullscreenModeForTab(
      tab->GetPrimaryMainFrame(), {});
  ASSERT_TRUE(IsWindowFullscreenForTabOrPending());

  base::RunLoop run_loop;
  bool lambda_called = false;
  ASSERT_NO_FATAL_FAILURE(
      GetFullscreenController()->RunOrDeferUntilTransitionIsComplete(
          base::BindLambdaForTesting([&lambda_called, &run_loop]() {
            lambda_called = true;
            run_loop.Quit();
          })));
  // Lambda may run synchronously on some platforms. If it did not already run,
  // block until it has.
  if (!lambda_called) {
    run_loop.Run();
  }
  EXPECT_TRUE(lambda_called);
}

// Tests Fullscreen entered in Browser, then Tab mode, then exited via Browser.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       BrowserFullscreenExit) {
  // Enter browser fullscreen.
  ASSERT_NO_FATAL_FAILURE(ToggleBrowserFullscreen(true));

  // Enter tab fullscreen.
  ASSERT_TRUE(
      AddTabAtIndex(0, GURL(url::kAboutBlankURL), ui::PAGE_TRANSITION_TYPED));
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));

  // Exit browser fullscreen.
  ASSERT_NO_FATAL_FAILURE(ToggleBrowserFullscreen(false));
  ASSERT_FALSE(browser()->window()->IsFullscreen());
}

// Tests Browser Fullscreen remains active after Tab mode entered and exited.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       BrowserFullscreenAfterTabFSExit) {
  // Enter browser fullscreen.
  ASSERT_NO_FATAL_FAILURE(ToggleBrowserFullscreen(true));

  // Enter and then exit tab fullscreen.
  ASSERT_TRUE(
      AddTabAtIndex(0, GURL(url::kAboutBlankURL), ui::PAGE_TRANSITION_TYPED));
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(false));

  // Verify browser fullscreen still active.
  ASSERT_TRUE(IsFullscreenForBrowser());
}

// Tests fullscreen entered without permision prompt for file:// urls.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, FullscreenFileURL) {
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), ui_test_utils::GetTestUrl(
                     base::FilePath(base::FilePath::kCurrentDirectory),
                     base::FilePath(kSimpleFile))));

  // Validate that going fullscreen for a file does not ask permision.
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(false));
}

// Tests fullscreen is exited on page navigation.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       TestTabExitsFullscreenOnNavigation) {
  ASSERT_TRUE(embedded_test_server()->Start());

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("chrome://newtab")));

  ASSERT_FALSE(browser()->window()->IsFullscreen());
}

// Test is flaky on all platforms: https://crbug.com/1234337
// Tests fullscreen is exited when navigating back.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       DISABLED_TestTabExitsFullscreenOnGoBack) {
  ASSERT_TRUE(embedded_test_server()->Start());

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("chrome://newtab")));

  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));

  GoBack();

  ASSERT_FALSE(browser()->window()->IsFullscreen());
}

// Tests fullscreen is not exited on sub frame navigation.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       TestTabDoesntExitFullscreenOnSubFrameNavigation) {
  ASSERT_TRUE(embedded_test_server()->Start());

  GURL url(ui_test_utils::GetTestUrl(
      base::FilePath(base::FilePath::kCurrentDirectory),
      base::FilePath(kSimpleFile)));
  GURL url_with_fragment(url.spec() + "#fragment");

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_with_fragment));
  ASSERT_TRUE(IsWindowFullscreenForTabOrPending());
}

// Test is flaky on all platforms: https://crbug.com/1234337
// Tests tab fullscreen exits, but browser fullscreen remains, on navigation.
IN_PROC_BROWSER_TEST_F(
    FullscreenControllerInteractiveTest,
    DISABLED_TestFullscreenFromTabWhenAlreadyInBrowserFullscreenWorks) {
  ASSERT_TRUE(embedded_test_server()->Start());

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("chrome://newtab")));

  ASSERT_NO_FATAL_FAILURE(ToggleBrowserFullscreen(true));
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));

  GoBack();

  ASSERT_TRUE(IsFullscreenForBrowser());
  ASSERT_FALSE(IsWindowFullscreenForTabOrPending());
}

// TODO(crbug.com/40779265) Flaky on Linux-ozone and MacOS.
#if (BUILDFLAG(IS_LINUX) && BUILDFLAG(IS_OZONE)) || BUILDFLAG(IS_MAC)
#define MAYBE_TabEntersPresentationModeFromWindowed \
  DISABLED_TabEntersPresentationModeFromWindowed
#else
#define MAYBE_TabEntersPresentationModeFromWindowed \
  TabEntersPresentationModeFromWindowed
#endif
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       MAYBE_TabEntersPresentationModeFromWindowed) {
  ASSERT_TRUE(embedded_test_server()->Start());

  ASSERT_TRUE(
      AddTabAtIndex(0, GURL(url::kAboutBlankURL), ui::PAGE_TRANSITION_TYPED));

  {
    EXPECT_FALSE(browser()->window()->IsFullscreen());
    ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreenNoRetries(true));
    EXPECT_TRUE(browser()->window()->IsFullscreen());
  }

  {
    ui_test_utils::FullscreenWaiter waiter(browser(),
                                           {.tab_fullscreen = false});
    chrome::ToggleFullscreenMode(browser());
    waiter.Wait();
    EXPECT_FALSE(browser()->window()->IsFullscreen());
  }

  {
    // Test that tab fullscreen mode doesn't make presentation mode the default
    // on Lion.
    ui_test_utils::ToggleFullscreenModeAndWait(browser());
    EXPECT_TRUE(browser()->window()->IsFullscreen());
  }
}

// Tests pointer lock can be escaped with ESC key.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       EscapingPointerLock) {
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kFullscreenPointerLockHTML)));

  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Request to lock the pointer.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);

  ASSERT_TRUE(IsPointerLocked());
  ASSERT_FALSE(IsWindowFullscreenForTabOrPending());

  // Escape, confirm we are out of pointer lock with no prompts.
  SendEscapeToExclusiveAccessManager();
  ASSERT_FALSE(IsPointerLocked());
  ASSERT_FALSE(IsWindowFullscreenForTabOrPending());
}

// Tests pointer lock and fullscreen modes can be escaped with ESC key.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       EscapingPointerLockAndFullscreen) {
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kFullscreenPointerLockHTML)));

  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Request to lock the pointer and enter fullscreen.
  {
    ui_test_utils::FullscreenWaiter waiter(browser(), {.tab_fullscreen = true});
    PressKeyAndWaitForPointerLockRequest(ui::VKEY_B);
    waiter.Wait();
  }

  // Escape, no prompts should remain.
  {
    ui_test_utils::FullscreenWaiter waiter(browser(),
                                           {.tab_fullscreen = false});
    SendEscapeToExclusiveAccessManager();
    waiter.Wait();
  }
  ASSERT_FALSE(IsPointerLocked());
  ASSERT_FALSE(IsWindowFullscreenForTabOrPending());
}

// Tests pointer lock then fullscreen.
// TODO(crbug.com/40835508): Re-enable this test
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_PointerLockThenFullscreen DISABLED_PointerLockThenFullscreen
#else
#define MAYBE_PointerLockThenFullscreen PointerLockThenFullscreen
#endif
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       MAYBE_PointerLockThenFullscreen) {
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kFullscreenPointerLockHTML)));

  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

#if !defined(MEMORY_SANITIZER)
  // Lock the pointer without a user gesture, expect no response.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_D);
  ASSERT_FALSE(IsPointerLocked());
  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());
#else
  // MSan builds change the timing of user gestures, which this part of the test
  // depends upon.  See `fullscreen_pointerlock.html` for more details, but the
  // main idea is that it waits ~5 seconds after the keypress and assumes that
  // the user gesture has expired.
#endif

  // Lock the pointer with a user gesture.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);
  ASSERT_TRUE(IsExclusiveAccessBubbleDisplayed());
  ASSERT_TRUE(IsPointerLocked());

  // Enter fullscreen mode, pointer should remain locked.
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));
  ASSERT_TRUE(IsPointerLocked());
  ASSERT_TRUE(IsWindowFullscreenForTabOrPending());
}

// Disabled on all due to issue with code under test: http://crbug.com/1255610.
//
// Was also disabled on platforms before:
// Times out sometimes on Linux. http://crbug.com/135115
// Mac: http://crbug.com/103912
// Tests pointer lock then fullscreen in same request.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       DISABLED_PointerLockAndFullscreen) {
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kFullscreenPointerLockHTML)));

  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Request to lock the pointer and enter fullscreen.
  {
    ui_test_utils::FullscreenWaiter waiter(browser(), {.tab_fullscreen = true});
    PressKeyAndWaitForPointerLockRequest(ui::VKEY_B);
    waiter.Wait();
  }
  ASSERT_TRUE(IsExclusiveAccessBubbleDisplayed());
  ASSERT_TRUE(IsPointerLocked());
  ASSERT_TRUE(IsWindowFullscreenForTabOrPending());
}

// Tests pointer lock can be exited and re-entered by an application silently
// with no UI distraction for users.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       PointerLockSilentAfterTargetUnlock) {
  SetWebContentsGrantedSilentPointerLockPermission();
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kFullscreenPointerLockHTML)));

  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Lock the pointer with a user gesture.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);
  ASSERT_TRUE(IsPointerLocked());
  ASSERT_TRUE(IsExclusiveAccessBubbleDisplayed());

  // Wait for the bubble to be shown for its full duration. This allows
  // the page to lock the pointer without showing the bubble later.
  WaitForPointerLockBubbleToHide();
  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Unlock the pointer from target, make sure it's unlocked.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_U);
  ASSERT_FALSE(IsPointerLocked());
  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Lock pointer again, make sure it works with no bubble.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);
  ASSERT_TRUE(IsPointerLocked());
  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Unlock the pointer again by target.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_U);
  ASSERT_FALSE(IsPointerLocked());
  FinishExclusiveAccessBubbleAnimation();
  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());
}

// TODO: crbug.com/371511161 - Flaky on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_SecondPointerLockShowsBubble DISABLED_SecondPointerLockShowsBubble
#else
#define MAYBE_SecondPointerLockShowsBubble SecondPointerLockShowsBubble
#endif
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       MAYBE_SecondPointerLockShowsBubble) {
  SetWebContentsGrantedSilentPointerLockPermission();
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kFullscreenPointerLockHTML)));

  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Lock the pointer with a user gesture.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);
  ASSERT_TRUE(IsPointerLocked());
  ASSERT_TRUE(IsExclusiveAccessBubbleDisplayed());

  // Unlock the pointer from target, make sure it's unlocked.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_U);
  ASSERT_FALSE(IsPointerLocked());
  FinishExclusiveAccessBubbleAnimation();
  ASSERT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Lock the pointer again. The bubble wasn't shown for its full duration last
  // time, so it gets shown again.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);
  ASSERT_TRUE(IsPointerLocked());
  ASSERT_TRUE(IsExclusiveAccessBubbleDisplayed());
}

// Tests pointer lock is exited on page navigation.
#if BUILDFLAG(IS_LINUX) && defined(USE_AURA)
// https://crbug.com/1191964
#define MAYBE_TestTabExitsPointerLockOnNavigation \
  DISABLED_TestTabExitsPointerLockOnNavigation
#else
#define MAYBE_TestTabExitsPointerLockOnNavigation \
  TestTabExitsPointerLockOnNavigation
#endif
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       MAYBE_TestTabExitsPointerLockOnNavigation) {
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kFullscreenPointerLockHTML)));

  // Lock the pointer with a user gesture.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);
  ASSERT_TRUE(IsExclusiveAccessBubbleDisplayed());

  ASSERT_TRUE(IsPointerLocked());

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("chrome://newtab")));

  ASSERT_FALSE(IsPointerLocked());
}

// Tests pointer lock is exited when navigating back.
#if BUILDFLAG(IS_LINUX) && defined(USE_AURA)
// https://crbug.com/1192097
#define MAYBE_TestTabExitsPointerLockOnGoBack \
  DISABLED_TestTabExitsPointerLockOnGoBack
#else
#define MAYBE_TestTabExitsPointerLockOnGoBack TestTabExitsPointerLockOnGoBack
#endif
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       MAYBE_TestTabExitsPointerLockOnGoBack) {
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);

  // Navigate twice to provide a place to go back to.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank")));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kFullscreenPointerLockHTML)));

  // Lock the pointer with a user gesture.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);
  ASSERT_TRUE(IsExclusiveAccessBubbleDisplayed());

  ASSERT_TRUE(IsPointerLocked());

  GoBack();

  ASSERT_FALSE(IsPointerLocked());
}

#if BUILDFLAG(IS_LINUX) && defined(USE_AURA) || \
    BUILDFLAG(IS_WIN) && defined(NDEBUG)
// TODO(erg): linux_aura bringup: http://crbug.com/163931
// Test is flaky on Windows: https://crbug.com/1124492
#define MAYBE_TestTabDoesntExitPointerLockOnSubFrameNavigation \
  DISABLED_TestTabDoesntExitPointerLockOnSubFrameNavigation
#else
#define MAYBE_TestTabDoesntExitPointerLockOnSubFrameNavigation \
  TestTabDoesntExitPointerLockOnSubFrameNavigation
#endif

// Tests pointer lock is not exited on sub frame navigation.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       MAYBE_TestTabDoesntExitPointerLockOnSubFrameNavigation) {
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);

  // Create URLs for test page and test page with #fragment.
  GURL url(embedded_test_server()->GetURL(kFullscreenPointerLockHTML));
  GURL url_with_fragment(url.spec() + "#fragment");

  // Navigate to test page.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  // Lock the pointer with a user gesture.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);
  ASSERT_TRUE(IsExclusiveAccessBubbleDisplayed());

  ASSERT_TRUE(IsPointerLocked());

  // Navigate to url with fragment. Pointer lock should persist.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_with_fragment));
  ASSERT_TRUE(IsPointerLocked());
}

IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       ReloadExitsPointerLockAndFullscreen) {
  auto test_server_handle = embedded_test_server()->StartAndReturnHandle();
  ASSERT_TRUE(test_server_handle);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL(kFullscreenPointerLockHTML)));

  // Request pointer lock.
  PressKeyAndWaitForPointerLockRequest(ui::VKEY_1);

  ASSERT_TRUE(IsPointerLocked());
  ASSERT_TRUE(IsExclusiveAccessBubbleDisplayed());

  // Reload. Pointer lock request should be cleared.
  {
    base::RunLoop run_loop;
    browser()
        ->GetFeatures()
        .exclusive_access_manager()
        ->pointer_lock_controller()
        ->set_lock_state_callback_for_test(run_loop.QuitClosure());
    Reload();
    run_loop.Run();
  }

  // Request to lock the pointer and enter fullscreen.
  {
    ui_test_utils::FullscreenWaiter waiter(browser(), {.tab_fullscreen = true});
    PressKeyAndWaitForPointerLockRequest(ui::VKEY_B);
    waiter.Wait();
  }

  // We are fullscreen.
  ASSERT_TRUE(IsWindowFullscreenForTabOrPending());

  // Reload. Pointer should be unlocked and fullscreen exited.
  {
    ui_test_utils::FullscreenWaiter waiter(browser(),
                                           {.tab_fullscreen = false});
    Reload();
    waiter.Wait();
    ASSERT_FALSE(IsPointerLocked());
    ASSERT_FALSE(IsWindowFullscreenForTabOrPending());
  }
}

// Tests ToggleFullscreenModeForTab always causes window to change.
IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       ToggleFullscreenModeForTab) {
  // Most fullscreen tests run sharded in fullscreen_controller_browsertest.cc
  // but flakiness required a while loop in
  // ExclusiveAccessTest::ToggleTabFullscreen. This test verifies that
  // when running serially there is no flakiness.

  EXPECT_TRUE(embedded_test_server()->Start());
  GURL url = embedded_test_server()->GetURL("/simple.html");
  ASSERT_TRUE(AddTabAtIndex(0, url, ui::PAGE_TRANSITION_TYPED));

  // Validate that going fullscreen for a URL defaults to asking permision.
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreenNoRetries(true));
  ASSERT_TRUE(IsWindowFullscreenForTabOrPending());
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreenNoRetries(false));
  ASSERT_FALSE(IsWindowFullscreenForTabOrPending());
}

IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       OpeningPopupExitsFullscreen) {
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));
  ASSERT_TRUE(IsWindowFullscreenForTabOrPending());

  // Open a popup, which is activated. The opener exits fullscreen to mitigate
  // usable security concerns. See WebContents::ForSecurityDropFullscreen().
  BrowserList* browser_list = BrowserList::GetInstance();
  EXPECT_EQ(1u, browser_list->size());
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  content::ExecuteScriptAsync(tab, "open('.', '', 'popup')");
  Browser* popup = ui_test_utils::WaitForBrowserToOpen();
  EXPECT_EQ(2u, browser_list->size());
  ui_test_utils::BrowserActivationWaiter(popup).WaitForActivation();
  EXPECT_TRUE(ui_test_utils::IsBrowserActive(popup));
  ASSERT_FALSE(IsWindowFullscreenForTabOrPending());
}

IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       BlockingContentsExitsFullscreen) {
  ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreen(true));
  ASSERT_TRUE(IsWindowFullscreenForTabOrPending());

  // Blocking the tab for a modal dialog exits fullscreen.
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  ui_test_utils::FullscreenWaiter waiter(browser(), {.tab_fullscreen = false});
  static_cast<web_modal::WebContentsModalDialogManagerDelegate*>(browser())
      ->SetWebContentsBlocked(tab, true);
  waiter.Wait();
  EXPECT_FALSE(IsWindowFullscreenForTabOrPending());
}

IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       CapturedContentEntersFullscreenWithinTab) {
  // Simulate tab capture, as used by getDisplayMedia() content sharing.
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  base::ScopedClosureRunner capture_closure =
      tab->IncrementCapturerCount(gfx::Size(), /*stay_hidden=*/false,
                                  /*stay_awake=*/false, /*is_activity=*/true);
  EXPECT_TRUE(tab->IsBeingVisiblyCaptured());

  // The browser enters fullscreen-within-tab mode synchronously, but the window
  // is not made fullscreen, and FullscreenWaiter is not notified.
  content::WebContentsDelegate* delegate = tab->GetDelegate();
  delegate->EnterFullscreenModeForTab(tab->GetPrimaryMainFrame(), {});
  EXPECT_TRUE(delegate->IsFullscreenForTabOrPending(tab));
  EXPECT_TRUE(tab->IsFullscreen());
  EXPECT_FALSE(IsWindowFullscreenForTabOrPending());
  EXPECT_EQ(tab->GetDelegate()->GetFullscreenState(tab).target_mode,
            content::FullscreenMode::kPseudoContent);

  delegate->ExitFullscreenModeForTab(tab);
  EXPECT_FALSE(delegate->IsFullscreenForTabOrPending(tab));
  EXPECT_FALSE(tab->IsFullscreen());
  EXPECT_FALSE(IsWindowFullscreenForTabOrPending());
  EXPECT_EQ(tab->GetDelegate()->GetFullscreenState(tab).target_mode,
            content::FullscreenMode::kWindowed);

  capture_closure.RunAndReset();
  EXPECT_FALSE(tab->IsBeingVisiblyCaptured());
}

IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       OpeningPopupDoesNotExitFullscreenWithinTab) {
  // Simulate visible tab capture and enter fullscreen-within-tab.
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  base::ScopedClosureRunner capture_closure =
      tab->IncrementCapturerCount(gfx::Size(), /*stay_hidden=*/false,
                                  /*stay_awake=*/false, /*is_activity=*/true);
  tab->GetDelegate()->EnterFullscreenModeForTab(tab->GetPrimaryMainFrame(), {});
  EXPECT_EQ(tab->GetDelegate()->GetFullscreenState(tab).target_mode,
            content::FullscreenMode::kPseudoContent);
  EXPECT_TRUE(tab->IsFullscreen());

  // Open a popup, which is activated. The opener remains fullscreen-within-tab.
  BrowserList* browser_list = BrowserList::GetInstance();
  EXPECT_EQ(1u, browser_list->size());
  content::ExecuteScriptAsync(tab, "open('.', '', 'popup')");
  Browser* popup = ui_test_utils::WaitForBrowserToOpen();
  ASSERT_TRUE(popup);
  ui_test_utils::WaitUntilBrowserBecomeActive(popup);
  EXPECT_EQ(2u, browser_list->size());
  EXPECT_EQ(tab->GetDelegate()->GetFullscreenState(tab).target_mode,
            content::FullscreenMode::kPseudoContent);
}

IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest,
                       BlockingContentsDoesNotExitFullscreenWithinTab) {
  // Simulate visible tab capture and enter fullscreen-within-tab.
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  base::ScopedClosureRunner capture_closure =
      tab->IncrementCapturerCount(gfx::Size(), /*stay_hidden=*/false,
                                  /*stay_awake=*/false, /*is_activity=*/true);
  tab->GetDelegate()->EnterFullscreenModeForTab(tab->GetPrimaryMainFrame(), {});
  EXPECT_EQ(tab->GetDelegate()->GetFullscreenState(tab).target_mode,
            content::FullscreenMode::kPseudoContent);
  EXPECT_TRUE(tab->IsFullscreen());

  // Blocking the tab for a modal dialog does not exit fullscreen-within-tab.
  static_cast<web_modal::WebContentsModalDialogManagerDelegate*>(browser())
      ->SetWebContentsBlocked(tab, true);
  EXPECT_EQ(tab->GetDelegate()->GetFullscreenState(tab).target_mode,
            content::FullscreenMode::kPseudoContent);
}

// Tests the automatic fullscreen content setting in IWA and non-IWA contexts.
class AutomaticFullscreenTest : public FullscreenControllerInteractiveTest,
                                public testing::WithParamInterface<bool> {
 public:
  AutomaticFullscreenTest() {
    feature_list_.InitWithFeatures(
        {features::kIsolatedWebApps, features::kIsolatedWebAppDevMode,
         features::kAutomaticFullscreenContentSetting},
        {});
  }

  void SetUpOnMainThread() override {
    auto allow_automatic_fullscreen = [&](const GURL& url) {
      HostContentSettingsMapFactory::GetForProfile(browser()->profile())
          ->SetContentSettingDefaultScope(
              url, url, ContentSettingsType::AUTOMATIC_FULLSCREEN,
              CONTENT_SETTING_ALLOW);
    };

    // Support multiple sites on the test server.
    host_resolver()->AddRule("*", "127.0.0.1");
    ASSERT_TRUE(embedded_https_test_server().Start());

    if (GetParam()) {
      std::unique_ptr<web_app::ScopedBundledIsolatedWebApp> app =
          web_app::IsolatedWebAppBuilder(
              web_app::ManifestBuilder().AddPermissionsPolicyWildcard(
                  network::mojom::PermissionsPolicyFeature::kFullscreen))
              .BuildBundle();
      app->TrustSigningKey();
      web_app::IsolatedWebAppUrlInfo url_info =
          app->InstallChecked(browser()->profile());
      allow_automatic_fullscreen(url_info.origin().GetURL());
      auto* frame =
          web_app::OpenIsolatedWebApp(browser()->profile(), url_info.app_id());
      web_contents_ = content::WebContents::FromRenderFrameHost(frame);
    } else {
      GURL url = embedded_https_test_server().GetURL("a.com", "/simple.html");
      allow_automatic_fullscreen(url);
      ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
      web_contents_ = browser()->tab_strip_model()->GetActiveWebContents();
    }
    ASSERT_TRUE(WaitForRenderFrameReady(web_contents_->GetPrimaryMainFrame()));
  }

  void TearDownOnMainThread() override { web_contents_ = nullptr; }

  bool RequestFullscreen(bool gesture = false,
                         content::RenderFrameHost* rfh = nullptr) {
    static constexpr char kScript[] = R"JS(
        (async () => {
          try { await document.body.requestFullscreen(); } catch {}
          return !!document.fullscreenElement;
        })();
    )JS";

    auto options = gesture ? content::EXECUTE_SCRIPT_DEFAULT_OPTIONS
                           : content::EXECUTE_SCRIPT_NO_USER_GESTURE;
    rfh = rfh ? rfh : web_contents_->GetPrimaryMainFrame();
    content::WebContents* tab = content::WebContents::FromRenderFrameHost(rfh);
    Browser* browser = chrome::FindBrowserWithTab(tab);
    if (!gesture) {
      // Ensure nothing inadvertently triggered user activation beforehand.
      EXPECT_EQ(false, EvalJs(rfh, "navigator.userActivation.isActive",
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));
    }
    ui_test_utils::FullscreenWaiter waiter(browser, {.tab_fullscreen = true});
    auto result = EvalJs(rfh, kScript, options);
    if (result.error.empty() && result.ExtractBool()) {
      waiter.Wait();
    }
    return browser->window()->IsFullscreen();
  }

  bool ExitFullscreen(WebContents* web_contents = nullptr) {
    web_contents = web_contents ? web_contents : web_contents_.get();
    Browser* browser = chrome::FindBrowserWithTab(web_contents);
    ui_test_utils::FullscreenWaiter waiter(browser, {.tab_fullscreen = false});
    const std::string script = R"((() => {
      window.lastExit = Date.now();
      return document.exitFullscreen();
    })())";
    // A user gesture is not needed and may break subsequent activation checks.
    auto result =
        EvalJs(web_contents, script, content::EXECUTE_SCRIPT_NO_USER_GESTURE);
    waiter.Wait();
    return result.error.empty() && !browser->window()->IsFullscreen();
  }

  std::pair<bool, Browser*> OpenPopupAndRequestFullscreenOnLoad() {
    ui_test_utils::BrowserChangeObserver popup_observer(
        nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kAdded);
    const std::string script = R"((() => {
      let w = open(location.href, '', 'popup');
      return new Promise(resolve => {
        w.onload = async () => {
          try { await w.document.body.requestFullscreen(); } catch {}
          resolve(!!w.document.fullscreenElement);
        };
      });
    })())";

    Browser* browser = chrome::FindBrowserWithTab(web_contents_);
    auto result = EvalJs(web_contents_, script);
    Browser* popup = popup_observer.Wait();
    if (!popup) {
      return std::make_pair(false, nullptr);
    }
    EXPECT_NE(popup, browser);
    ui_test_utils::WaitUntilBrowserBecomeActive(popup);
    ui_test_utils::FullscreenWaiter waiter(popup, {.tab_fullscreen = true});
    if (result.error.empty() && result.ExtractBool()) {
      waiter.Wait();
    }
    return std::make_pair(popup->window()->IsFullscreen(), popup);
  }

  std::string QueryPermission(
      const content::ToRenderFrameHost& target,
      std::optional<bool> allow_without_gesture = true) {
    const std::string options =
        allow_without_gesture.has_value()
            ? content::JsReplace(", allowWithoutGesture: $1",
                                 allow_without_gesture.value())
            : "";
    const std::string descriptor = "{name: 'fullscreen'" + options + "}";
    const std::string script =
        "navigator.permissions.query(" + descriptor +
        ").then(permission => permission.state).catch(e => e.name);";
    return EvalJs(target, script, content::EXECUTE_SCRIPT_NO_USER_GESTURE)
        .ExtractString();
  }

 protected:
  raw_ptr<content::WebContents> web_contents_ = nullptr;

 private:
  base::test::ScopedFeatureList feature_list_;
  web_app::OsIntegrationTestOverrideBlockingRegistration faked_os_integration_;
};

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, RequestFullscreenNoGesture) {
#if BUILDFLAG(IS_MAC)
  if (GetParam()) {
    GTEST_SKIP() << "Flaky. See https://crbug.com/404887514";
  }
#endif

  base::HistogramTester histograms;
  EXPECT_TRUE(RequestFullscreen());

  // Navigate away in order to flush use counters.
  Browser* browser = chrome::FindBrowserWithTab(web_contents_);
  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser, GURL(url::kAboutBlankURL)));
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
  if (!GetParam()) {  // TODO(crbug.com/41497058): Test use counter in IWA too.
    histograms.ExpectBucketCount(
        "Blink.UseCounter.Features",
        blink::mojom::WebFeature::kFullscreenAllowedByContentSetting, 1);
  }
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, ImmediatelyAfterExit) {
  EXPECT_TRUE(RequestFullscreen());
  const base::TimeTicks exit = base::TimeTicks::Now();
  EXPECT_TRUE(ExitFullscreen());
  EXPECT_LT(base::TimeTicks::Now() - exit, base::Seconds(5));
  EXPECT_FALSE(RequestFullscreen());
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, WithGestureAfterExit) {
#if BUILDFLAG(IS_MAC)
  if (GetParam()) {
    GTEST_SKIP() << "Flaky. See https://crbug.com/404887514";
  }
#endif

  EXPECT_TRUE(RequestFullscreen());
  EXPECT_TRUE(ExitFullscreen());
  EXPECT_TRUE(RequestFullscreen(/*gesture=*/true));
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, EventuallyAfterExit) {
#if BUILDFLAG(IS_MAC)
  if (GetParam()) {
    GTEST_SKIP() << "Flaky. See https://crbug.com/404887514";
  }
#endif

  EXPECT_TRUE(RequestFullscreen());
  EXPECT_TRUE(ExitFullscreen());
  base::RunLoop run_loop;
  // TODO(crbug.com/333133285): Avoid waiting this long in wall-clock time.
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE, run_loop.QuitClosure(), base::Milliseconds(5300));
  run_loop.Run();
  EXPECT_TRUE(RequestFullscreen());
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, Popup) {
  EXPECT_TRUE(OpenPopupAndRequestFullscreenOnLoad().first);
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, PopupImmediatelyAfterExit) {
  EXPECT_TRUE(RequestFullscreen());
  const base::TimeTicks exit = base::TimeTicks::Now();
  EXPECT_TRUE(ExitFullscreen());
  EXPECT_LT(base::TimeTicks::Now() - exit, base::Seconds(5));
  EXPECT_FALSE(OpenPopupAndRequestFullscreenOnLoad().first);
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, PopupEventuallyAfterExit) {
#if BUILDFLAG(IS_MAC)
  if (GetParam()) {
    GTEST_SKIP() << "Flaky. See https://crbug.com/404887514";
  }
#endif

  EXPECT_TRUE(RequestFullscreen());
  EXPECT_TRUE(ExitFullscreen());
  base::RunLoop run_loop;
  // TODO(crbug.com/333133285): Avoid waiting this long in wall-clock time.
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE, run_loop.QuitClosure(), base::Milliseconds(5300));
  run_loop.Run();
  EXPECT_TRUE(OpenPopupAndRequestFullscreenOnLoad().first);
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, ImmediatelyAfterPopupExit) {
#if BUILDFLAG(IS_MAC)
  if (GetParam()) {
    GTEST_SKIP() << "Flaky. See https://crbug.com/404887514";
  }
#endif

  auto [success, popup] = OpenPopupAndRequestFullscreenOnLoad();
  EXPECT_TRUE(success);
  ASSERT_TRUE(popup);
  const base::TimeTicks exit = base::TimeTicks::Now();
  ExitFullscreen(popup->tab_strip_model()->GetActiveWebContents());
  EXPECT_LT(base::TimeTicks::Now() - exit, base::Seconds(5));
  EXPECT_FALSE(RequestFullscreen());
  popup->window()->Close();
  ui_test_utils::WaitForBrowserToClose(popup);
  EXPECT_LT(base::TimeTicks::Now() - exit, base::Seconds(5));
  EXPECT_FALSE(RequestFullscreen());
  EXPECT_TRUE(RequestFullscreen(/*gesture=*/true));
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, EventuallyAfterPopupExit) {
#if BUILDFLAG(IS_MAC)
  if (GetParam()) {
    GTEST_SKIP() << "Flaky. See https://crbug.com/404887514";
  }
#endif

  auto [success, popup] = OpenPopupAndRequestFullscreenOnLoad();
  EXPECT_TRUE(success);
  ASSERT_TRUE(popup);
  ExitFullscreen(popup->tab_strip_model()->GetActiveWebContents());
  base::RunLoop run_loop;
  // TODO(crbug.com/333133285): Avoid waiting this long in wall-clock time.
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE, run_loop.QuitClosure(), base::Milliseconds(5300));
  run_loop.Run();
  EXPECT_TRUE(RequestFullscreen());
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, BlockingContentsDoesNotExit) {
#if BUILDFLAG(IS_MAC)
  if (GetParam()) {
    GTEST_SKIP() << "Flaky. See https://crbug.com/404887514";
  }
#endif

  EXPECT_TRUE(RequestFullscreen());
  EXPECT_TRUE(web_contents_->IsFullscreen());
  // Blocking the tab for a modal dialog does not exit fullscreen if the origin
  // has been granted the automatic fullscreen content setting.
  Browser* browser = chrome::FindBrowserWithTab(web_contents_);
  static_cast<web_modal::WebContentsModalDialogManagerDelegate*>(browser)
      ->SetWebContentsBlocked(web_contents_, true);
  EXPECT_TRUE(web_contents_->IsFullscreen());
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, QueryPermissionWithGesture) {
  // Expect an API TypeError when allowWithoutGesture is false or unspecified.
  EXPECT_EQ(
      "TypeError",
      QueryPermission(web_contents_, /*allow_without_gesture=*/std::nullopt));
  EXPECT_EQ("TypeError",
            QueryPermission(web_contents_, /*allow_without_gesture=*/false));
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, QueryPermissionWithoutGesture) {
  // Permission is pre-granted on the initial test origin and denied elsewhere.
  EXPECT_EQ("granted", QueryPermission(web_contents_));
  const GURL url = embedded_https_test_server().GetURL("b.com", "/simple.html");
  content::RenderFrameHost* rfh = ui_test_utils::NavigateToURL(browser(), url);
  EXPECT_EQ("denied", QueryPermission(rfh));
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, CrossOriginIFrameDenied) {
  // Append a cross-origin iframe without the permission policy.
  const GURL src = embedded_https_test_server().GetURL("b.com", "/simple.html");
  content::RenderFrameHost* rfh = web_contents_->GetPrimaryMainFrame();
  web_app::CreateIframe(rfh, "", src, /*permissions_policy=*/"");
  content::RenderFrameHost* child = ChildFrameAt(rfh, 0);
  EXPECT_EQ("denied", QueryPermission(child));
  EXPECT_FALSE(RequestFullscreen(/*gesture=*/false, child));
}

IN_PROC_BROWSER_TEST_P(AutomaticFullscreenTest, CrossOriginIFrameGranted) {
#if BUILDFLAG(IS_MAC)
  if (GetParam()) {
    GTEST_SKIP() << "Flaky. See https://crbug.com/404887514";
  }
#endif

  // Append a cross-origin iframe with the permission policy.
  const GURL src = embedded_https_test_server().GetURL("b.com", "/simple.html");
  content::RenderFrameHost* rfh = web_contents_->GetPrimaryMainFrame();
  web_app::CreateIframe(rfh, "", src, /*permissions_policy=*/"fullscreen *");
  content::RenderFrameHost* child = ChildFrameAt(rfh, 0);
  EXPECT_EQ("granted", QueryPermission(child));
  EXPECT_TRUE(RequestFullscreen(child));
  EXPECT_TRUE(ExitFullscreen());
}

INSTANTIATE_TEST_SUITE_P(, AutomaticFullscreenTest, ::testing::Bool());

// Tests fullscreen with multi-screen features from the Window Management API.
// Sites with the Window Management permission can request fullscreen on a
// specific screen, move fullscreen windows to different displays, and more.
// Tests must run in series to manage virtual displays on supported platforms.
// Use 2+ physical displays to run locally with --gtest_also_run_disabled_tests.
// See: //docs/ui/display/multiscreen_testing.md
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
#define MAYBE_MultiScreenFullscreenControllerInteractiveTest \
  MultiScreenFullscreenControllerInteractiveTest
#else
#define MAYBE_MultiScreenFullscreenControllerInteractiveTest \
  DISABLED_MultiScreenFullscreenControllerInteractiveTest
#endif  // BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
class MAYBE_MultiScreenFullscreenControllerInteractiveTest
    : public FullscreenControllerInteractiveTest {
 public:
  void SetUpOnMainThread() override {
    if (!SetUpVirtualDisplays()) {
      GTEST_SKIP() << "Skipping test; unavailable multi-screen support.";
    }
    display::Screen* screen = display::Screen::GetScreen();
    for (const auto& d : screen->GetAllDisplays()) {
      if (d.id() != screen->GetPrimaryDisplay().id()) {
        secondary_display_id_ = d.id();
        break;
      }
    }
#if BUILDFLAG(IS_MAC)
    ns_window_faked_for_testing_ = ui::NSWindowFakedForTesting::IsEnabled();
    // Disable `NSWindowFakedForTesting` to wait for actual async fullscreen on
    // Mac via `FullscreenWaiter`.
    ui::NSWindowFakedForTesting::SetEnabled(false);
#endif
  }

  void TearDownOnMainThread() override {
    virtual_display_util_.reset();
#if BUILDFLAG(IS_MAC)
    ui::NSWindowFakedForTesting::SetEnabled(ns_window_faked_for_testing_);
#endif
  }

  // Create virtual displays as needed, ensuring 2 displays are available for
  // testing multi-screen functionality. Not all platforms and OS versions are
  // supported. Returns false if virtual displays could not be created.
  bool SetUpVirtualDisplays() {
    if (display::Screen::GetScreen()->GetNumDisplays() > 1) {
      return true;
    }
    if ((virtual_display_util_ = display::test::VirtualDisplayUtil::TryCreate(
             display::Screen::GetScreen()))) {
      virtual_display_util_->AddDisplay(
          display::test::VirtualDisplayUtil::k1024x768);
      return true;
    }
    return false;
  }

  // Get a new tab that observes the test screen environment and auto-accepts
  // Window Management permission prompts.
  content::WebContents* SetUpWindowManagementTab() {
    // Open a new tab that observes the test screen environment.
    EXPECT_TRUE(embedded_test_server()->Start());
    const GURL url(embedded_test_server()->GetURL("/simple.html"));
    EXPECT_TRUE(AddTabAtIndex(1, url, ui::PAGE_TRANSITION_TYPED));

    auto* tab = browser()->tab_strip_model()->GetActiveWebContents();

    // Auto-accept Window Management permission prompts.
    permissions::PermissionRequestManager* permission_request_manager =
        permissions::PermissionRequestManager::FromWebContents(tab);
    permission_request_manager->set_auto_response_for_test(
        permissions::PermissionRequestManager::ACCEPT_ALL);

    return tab;
  }

  // Get the display matching the `browser`'s current window bounds.
  display::Display GetCurrentDisplay(Browser* browser) const {
    return display::Screen::GetScreen()->GetDisplayMatching(
        browser->window()->GetBounds());
  }

  // Wait for a JS content fullscreen change with the given script and options.
  // Returns the script result.
  content::EvalJsResult RequestContentFullscreenFromScript(
      const std::string& eval_js_script,
      bool expect_fullscreen,
      int eval_js_options = content::EXECUTE_SCRIPT_DEFAULT_OPTIONS,
      bool expect_window_fullscreen = true,
      std::optional<int64_t> display_id = std::nullopt) {
    ui_test_utils::FullscreenWaiter waiter(
        browser(),
        {.tab_fullscreen = expect_fullscreen, .display_id = display_id});
    auto* tab = browser()->tab_strip_model()->GetActiveWebContents();
    content::EvalJsResult result = EvalJs(tab, eval_js_script, eval_js_options);
    waiter.Wait();
    EXPECT_EQ(expect_window_fullscreen, browser()->window()->IsFullscreen());
    return result;
  }

  // Execute JS to request content fullscreen on the current screen.
  void RequestContentFullscreen() {
    const std::string script = R"JS(
      (async () => {
        await document.body.requestFullscreen();
        return !!document.fullscreenElement;
      })();
    )JS";
    EXPECT_EQ(true, RequestContentFullscreenFromScript(script, true));
  }

  // Execute JS to request content fullscreen on a different screen from where
  // the window is currently located.
  void RequestContentFullscreenOnAnotherScreen() {
    const std::string script = R"JS(
      (async () => {
        if (!window.screenDetails)
          window.screenDetails = await window.getScreenDetails();
        const otherScreen = window.screenDetails.screens.find(
            s => s !== window.screenDetails.currentScreen);
        const options = { screen: otherScreen };
        await document.body.requestFullscreen(options);
        return !!document.fullscreenElement;
      })();
    )JS";
    EXPECT_EQ(true, RequestContentFullscreenFromScript(
                        script, true, content::EXECUTE_SCRIPT_DEFAULT_OPTIONS,
                        true, secondary_display_id_));
  }

  // Execute JS to exit content fullscreen.
  void ExitContentFullscreen(bool expect_window_fullscreen = false) {
    const std::string script = R"JS(
      (async () => {
        await document.exitFullscreen();
        return !!document.fullscreenElement;
      })();
    )JS";
    // Exiting fullscreen does not require a user gesture; do not supply one.
    EXPECT_EQ(false, RequestContentFullscreenFromScript(
                         script, false, content::EXECUTE_SCRIPT_NO_USER_GESTURE,
                         expect_window_fullscreen));
  }

  // Awaits expiry of the navigator.userActivation signal on the active tab.
  void WaitForUserActivationExpiry() {
    const std::string await_activation_expiry_script = R"(
      (async () => {
        while (navigator.userActivation.isActive)
          await new Promise(resolve => setTimeout(resolve, 1000));
        return navigator.userActivation.isActive;
      })();
    )";
    auto* tab = browser()->tab_strip_model()->GetActiveWebContents();
    EXPECT_EQ(false, EvalJs(tab, await_activation_expiry_script,
                            content::EXECUTE_SCRIPT_NO_USER_GESTURE));
    EXPECT_FALSE(tab->HasRecentInteraction());
  }

 private:
  std::unique_ptr<display::test::VirtualDisplayUtil> virtual_display_util_;
  uint64_t secondary_display_id_ = display::kInvalidDisplayId;
#if BUILDFLAG(IS_MAC)
  bool ns_window_faked_for_testing_ = false;
#endif
};

// TODO(crbug.com/40111905): Disabled on Windows, where views::FullscreenHandler
// implements fullscreen by directly obtaining MONITORINFO, ignoring the mocked
// display::Screen configuration used in this test. Disabled on Linux, where the
// window server's async handling of the fullscreen window state may transition
// the window into fullscreen on the actual (non-mocked) display bounds before
// or after the window bounds checks, yielding flaky results.
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
#define MAYBE_SeparateDisplay SeparateDisplay
#else
#define MAYBE_SeparateDisplay DISABLED_SeparateDisplay
#endif
// Test requesting fullscreen on a separate display.
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_SeparateDisplay) {
  SetUpWindowManagementTab();
#if !BUILDFLAG(IS_MAC)
  const gfx::Rect original_bounds = browser()->window()->GetBounds();
#endif
  const display::Display original_display = GetCurrentDisplay(browser());

  // Execute JS to request fullscreen on a different screen.
  RequestContentFullscreenOnAnotherScreen();
  EXPECT_NE(original_display.id(), GetCurrentDisplay(browser()).id());

  ExitContentFullscreen();
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());
  // TODO(crbug.com/40277425): Bounds are flaky on Mac.
#if !BUILDFLAG(IS_MAC)
  EXPECT_EQ(original_bounds, browser()->window()->GetBounds());
#endif
}

// TODO(crbug.com/40111905): Disabled on Windows, where views::FullscreenHandler
// implements fullscreen by directly obtaining MONITORINFO, ignoring the mocked
// display::Screen configuration used in this test. Disabled on Linux, where the
// window server's async handling of the fullscreen window state may transition
// the window into fullscreen on the actual (non-mocked) display bounds before
// or after the window bounds checks, yielding flaky results.
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
#define MAYBE_SeparateDisplayMaximized SeparateDisplayMaximized
#else
#define MAYBE_SeparateDisplayMaximized DISABLED_SeparateDisplayMaximized
#endif
// Test requesting fullscreen on a separate display from a maximized window.
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_SeparateDisplayMaximized) {
  SetUpWindowManagementTab();
#if !BUILDFLAG(IS_MAC)
  const gfx::Rect original_bounds = browser()->window()->GetBounds();
#endif
  const display::Display original_display = GetCurrentDisplay(browser());

  browser()->window()->Maximize();
  EXPECT_TRUE(browser()->window()->IsMaximized());
#if !BUILDFLAG(IS_MAC)
  const gfx::Rect maximized_bounds = browser()->window()->GetBounds();
#endif

  // Execute JS to request fullscreen on a different screen.
  RequestContentFullscreenOnAnotherScreen();
  EXPECT_NE(original_display.id(), GetCurrentDisplay(browser()).id());

  ExitContentFullscreen();
  EXPECT_TRUE(browser()->window()->IsMaximized());
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());
  // TODO(crbug.com/40277425): Bounds are flaky on Mac.
#if !BUILDFLAG(IS_MAC)
  EXPECT_EQ(maximized_bounds, browser()->window()->GetBounds());
#endif

  // Unmaximize the window and check that the original bounds are restored.
  browser()->window()->Restore();
  EXPECT_FALSE(browser()->window()->IsMaximized());
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());
  // TODO(crbug.com/40277425): Bounds are flaky on Mac.
#if !BUILDFLAG(IS_MAC)
  EXPECT_EQ(original_bounds, browser()->window()->GetBounds());
#endif
}

// TODO(crbug.com/40111905): Disabled on Windows, where views::FullscreenHandler
// implements fullscreen by directly obtaining MONITORINFO, ignoring the mocked
// display::Screen configuration used in this test. Disabled on Linux, where the
// window server's async handling of the fullscreen window state may transition
// the window into fullscreen on the actual (non-mocked) display bounds before
// or after the window bounds checks, yielding flaky results.
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
#define MAYBE_SameDisplayAndSwap SameDisplayAndSwap
#else
#define MAYBE_SameDisplayAndSwap DISABLED_SameDisplayAndSwap
#endif
// Test requesting fullscreen on the current display and then swapping displays.
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_SameDisplayAndSwap) {
  SetUpWindowManagementTab();
#if !BUILDFLAG(IS_MAC)
  const gfx::Rect original_bounds = browser()->window()->GetBounds();
#endif
  const display::Display original_display = GetCurrentDisplay(browser());

  // Execute JS to request fullscreen on the current screen.
  RequestContentFullscreen();
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());

  // Execute JS to request fullscreen on a different screen.
  RequestContentFullscreenOnAnotherScreen();
  EXPECT_NE(original_display.id(), GetCurrentDisplay(browser()).id());

  ExitContentFullscreen();
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());
  // TODO(crbug.com/40277425): Bounds are flaky on Mac.
#if !BUILDFLAG(IS_MAC)
  EXPECT_EQ(original_bounds, browser()->window()->GetBounds());
#endif
}

// TODO(crbug.com/40111905): Disabled on Windows, where views::FullscreenHandler
// implements fullscreen by directly obtaining MONITORINFO, ignoring the mocked
// display::Screen configuration used in this test. Disabled on Linux, where the
// window server's async handling of the fullscreen window state may transition
// the window into fullscreen on the actual (non-mocked) display bounds before
// or after the window bounds checks, yielding flaky results.
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
#define MAYBE_SameDisplayAndSwapMaximized SameDisplayAndSwapMaximized
#else
#define MAYBE_SameDisplayAndSwapMaximized DISABLED_SameDisplayAndSwapMaximized
#endif
// Test requesting fullscreen on the current display and then swapping displays
// from a maximized window.
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_SameDisplayAndSwapMaximized) {
  SetUpWindowManagementTab();
#if !BUILDFLAG(IS_MAC)
  const gfx::Rect original_bounds = browser()->window()->GetBounds();
#endif
  const display::Display original_display = GetCurrentDisplay(browser());

  browser()->window()->Maximize();
  EXPECT_TRUE(browser()->window()->IsMaximized());
#if !BUILDFLAG(IS_MAC)
  const gfx::Rect maximized_bounds = browser()->window()->GetBounds();
#endif

  // Execute JS to request fullscreen on the current screen.
  RequestContentFullscreen();
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());

  // Execute JS to request fullscreen on a different screen.
  RequestContentFullscreenOnAnotherScreen();
  EXPECT_NE(original_display.id(), GetCurrentDisplay(browser()).id());

  ExitContentFullscreen();
  EXPECT_TRUE(browser()->window()->IsMaximized());
  // TODO(crbug.com/40277425): Bounds are flaky on Mac.
#if !BUILDFLAG(IS_MAC)
  EXPECT_EQ(maximized_bounds, browser()->window()->GetBounds());
#endif

  // Unmaximize the window and check that the original bounds are restored.
  browser()->window()->Restore();
  EXPECT_FALSE(browser()->window()->IsMaximized());
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());
  // TODO(crbug.com/40277425): Bounds are flaky on Mac.
#if !BUILDFLAG(IS_MAC)
  EXPECT_EQ(original_bounds, browser()->window()->GetBounds());
#endif
}

// TODO(crbug.com/40111905): Disabled on Windows, where views::FullscreenHandler
// implements fullscreen by directly obtaining MONITORINFO, ignoring the mocked
// display::Screen configuration used in this test. Disabled on Linux, where the
// window server's async handling of the fullscreen window state may transition
// the window into fullscreen on the actual (non-mocked) display bounds before
// or after the window bounds checks, yielding flaky results.
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
#define MAYBE_BrowserFullscreenContentFullscreenSwapDisplay \
  BrowserFullscreenContentFullscreenSwapDisplay
#else
#define MAYBE_BrowserFullscreenContentFullscreenSwapDisplay \
  DISABLED_BrowserFullscreenContentFullscreenSwapDisplay
#endif
// Test requesting browser fullscreen on current display, launching
// tab-fullscreen on a different display, and then closing tab-fullscreen to
// restore browser-fullscreen on the original display.
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_BrowserFullscreenContentFullscreenSwapDisplay) {
  SetUpWindowManagementTab();

  ToggleBrowserFullscreen(true);
  EXPECT_TRUE(IsFullscreenForBrowser());
  EXPECT_FALSE(IsWindowFullscreenForTabOrPending());

  const gfx::Rect fullscreen_bounds = browser()->window()->GetBounds();
  const display::Display original_display = GetCurrentDisplay(browser());

  // On the Mac, the available fullscreen space is not always the entire
  // screen. In non-immersive, on machines with a notch, the menu bar is not
  // visible, but there's a black bar at the top of the screen. In immersive
  // fullscreen, the top chrome appears to be part of the browser window but
  // is actually in a separate widget/window (the overlay widget) positioned
  // just above. The fullscreen bounds rect is therefore reduced in height
  // by the notch bar (maybe) and top chrome.
  //
  // What should always be true is the left, right, and bottom sides of the
  // fullscreen bounds match the those portions of the display bounds. The
  // top is trickier. By using the "work area," we should be able to take the
  // menu bar area out of the equation. Ideally, we would just check that
  // fullscreen_bounds.y - overlay_widget.height == display.work_area.bottom.
  // However, at this location in the source tree, we are not allowed to know
  // anything about Views or widgets, so we cannot access the overlay_widget
  // to query its frame. The most we can, therefore, say, is that the top
  // of the fullscreen bounds must be greater than or equal to the bottom of
  // the display bounds.
#if BUILDFLAG(IS_MAC)
  EXPECT_LE(original_display.work_area().y(), fullscreen_bounds.y());
  EXPECT_EQ(original_display.work_area().x(), fullscreen_bounds.x());
  EXPECT_EQ(original_display.work_area().right(), fullscreen_bounds.right());
  EXPECT_EQ(original_display.work_area().bottom(), fullscreen_bounds.bottom());
#else
  EXPECT_EQ(original_display.bounds(), fullscreen_bounds);
#endif  // BUILDFLAG(IS_MAC)

  // Execute JS to request fullscreen on a different screen.
  RequestContentFullscreenOnAnotherScreen();
  EXPECT_NE(original_display.id(), GetCurrentDisplay(browser()).id());
  // Fullscreen was originally initiated by browser, this should still be true.
  EXPECT_TRUE(IsFullscreenForBrowser());
  EXPECT_TRUE(IsWindowFullscreenForTabOrPending());

  ExitContentFullscreen(/*expect_window_fullscreen=*/true);
  EXPECT_EQ(fullscreen_bounds, browser()->window()->GetBounds());
  EXPECT_TRUE(IsFullscreenForBrowser());
  EXPECT_FALSE(IsWindowFullscreenForTabOrPending());
}

// TODO(crbug.com/40111905): Disabled on Windows, where views::FullscreenHandler
// implements fullscreen by directly obtaining MONITORINFO, ignoring the mocked
// display::Screen configuration used in this test. Disabled on Linux, where the
// window server's async handling of the fullscreen window state may transition
// the window into fullscreen on the actual (non-mocked) display bounds before
// or after the window bounds checks, yielding flaky results.
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
#define MAYBE_SeparateDisplayAndSwap SeparateDisplayAndSwap
#else
#define MAYBE_SeparateDisplayAndSwap DISABLED_SeparateDisplayAndSwap
#endif
// Test requesting fullscreen on a separate display and then swapping displays.
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_SeparateDisplayAndSwap) {
  SetUpWindowManagementTab();
#if !BUILDFLAG(IS_MAC)
  const gfx::Rect original_bounds = browser()->window()->GetBounds();
#endif
  const display::Display original_display = GetCurrentDisplay(browser());
  display::Display last_recorded_display = original_display;

  // Execute JS to request fullscreen on a different screen a few times.
  for (size_t i = 0; i < 4; ++i) {
    RequestContentFullscreenOnAnotherScreen();
    EXPECT_NE(last_recorded_display.id(), GetCurrentDisplay(browser()).id());
    last_recorded_display = GetCurrentDisplay(browser());
  }

  ExitContentFullscreen();
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());
  // TODO(crbug.com/40277425): Bounds are flaky on Mac.
#if !BUILDFLAG(IS_MAC)
  EXPECT_EQ(original_bounds, browser()->window()->GetBounds());
#endif
}

// TODO(crbug.com/40111905): Disabled on Windows, where views::FullscreenHandler
// implements fullscreen by directly obtaining MONITORINFO, ignoring the mocked
// display::Screen configuration used in this test. Disabled on Linux, where the
// window server's async handling of the fullscreen window state may transition
// the window into fullscreen on the actual (non-mocked) display bounds before
// or after the window bounds checks, yielding flaky results.
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC)
#define MAYBE_SwapShowsBubble SwapShowsBubble
#else
#define MAYBE_SwapShowsBubble DISABLED_SwapShowsBubble
#endif
// Test requesting fullscreen on the current display and then swapping displays.
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_SwapShowsBubble) {
  SetUpWindowManagementTab();

  // Execute JS to request fullscreen on the current screen.
  RequestContentFullscreen();
  const display::Display original_display = GetCurrentDisplay(browser());

  // Explicitly check for, and destroy, the exclusive access bubble.
  EXPECT_TRUE(IsExclusiveAccessBubbleDisplayed());
  Wait(ExclusiveAccessBubble::kShowTime);
  FinishExclusiveAccessBubbleAnimation();
  EXPECT_FALSE(IsExclusiveAccessBubbleDisplayed());

  // Execute JS to request fullscreen on a different screen.
  RequestContentFullscreenOnAnotherScreen();
  EXPECT_NE(original_display.id(), GetCurrentDisplay(browser()).id());

  // Ensure the exclusive access bubble is re-shown on fullscreen display swap.
  EXPECT_TRUE(IsExclusiveAccessBubbleDisplayed());
}

// TODO(crbug.com/40723237): Disabled on Windows, where RenderWidgetHostViewAura
// blindly casts display::Screen::GetScreen() to display::win::ScreenWin*.
#if BUILDFLAG(IS_WIN)
#define MAYBE_FullscreenOnPermissionGrant DISABLED_FullscreenOnPermissionGrant
#else
#define MAYBE_FullscreenOnPermissionGrant FullscreenOnPermissionGrant
#endif
// Test requesting fullscreen using the permission grant's transient activation.
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_FullscreenOnPermissionGrant) {
  EXPECT_TRUE(embedded_test_server()->Start());
  const GURL url(embedded_test_server()->GetURL("/simple.html"));
  ASSERT_TRUE(AddTabAtIndex(1, url, ui::PAGE_TRANSITION_TYPED));
  auto* tab = browser()->tab_strip_model()->GetActiveWebContents();

  permissions::PermissionRequestManager* permission_request_manager =
      permissions::PermissionRequestManager::FromWebContents(tab);

  // Request the Window Management permission and accept the prompt after user
  // activation expires; accepting should grant a new transient activation
  // signal that can be used to request fullscreen, without another gesture.
  ExecuteScriptAsync(tab, "getScreenDetails()");
  WaitForUserActivationExpiry();
  ASSERT_TRUE(permission_request_manager->IsRequestInProgress());
  permission_request_manager->Accept();
  const std::string script = R"(
    (async () => {
      await document.body.requestFullscreen();
      return !!document.fullscreenElement;
    })();
  )";
  EXPECT_EQ(true, RequestContentFullscreenFromScript(
                      script, true, content::EXECUTE_SCRIPT_NO_USER_GESTURE));
}

// TODO(crbug.com/40111905): Disabled on Windows, where views::FullscreenHandler
// implements fullscreen by directly obtaining MONITORINFO, ignoring the mocked
// display::Screen configuration used in this test. Disabled on Mac and Linux,
// where the window server's async handling of the fullscreen window state may
// transition the window into fullscreen on the actual (non-mocked) display
// bounds before or after the window bounds checks, yielding flaky results.
#if !BUILDFLAG(IS_CHROMEOS)
#define MAYBE_OpenPopupWhileFullscreen DISABLED_OpenPopupWhileFullscreen
#else
#define MAYBE_OpenPopupWhileFullscreen OpenPopupWhileFullscreen
#endif
// Test opening a popup on a separate display while fullscreen.
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_OpenPopupWhileFullscreen) {
  content::WebContents* tab = SetUpWindowManagementTab();
  const display::Display original_display = GetCurrentDisplay(browser());

  BrowserList* browser_list = BrowserList::GetInstance();
  EXPECT_EQ(1u, browser_list->size());
  blocked_content::PopupBlockerTabHelper* popup_blocker =
      blocked_content::PopupBlockerTabHelper::FromWebContents(tab);
  EXPECT_EQ(0u, popup_blocker->GetBlockedPopupsCount());

  // Execute JS to request fullscreen on the current screen.
  RequestContentFullscreen();
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());

  // Execute JS to open a popup on a different screen.
  const std::string script = R"(
    (async () => {
      // Note: WindowManagementPermissionContext will send an activation signal.
      window.screenDetails = await window.getScreenDetails();
      const otherScreen = window.screenDetails.screens.find(
          s => s !== window.screenDetails.currentScreen);
      const l = otherScreen.availLeft + 100;
      const t = otherScreen.availTop + 100;
      const w = window.open('', '', `left=${l},top=${t},width=300,height=300`);
      // Return true iff the opener is fullscreen and the popup is open.
      return !!document.fullscreenElement && !!w && !w.closed;
    })();
  )";
  content::ExecuteScriptAsync(tab, script);
  Browser* popup = ui_test_utils::WaitForBrowserToOpen();
  EXPECT_NE(popup, browser());
  auto* popup_contents = popup->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(WaitForRenderFrameReady(popup_contents->GetPrimaryMainFrame()));
  EXPECT_EQ(0u, popup_blocker->GetBlockedPopupsCount());
  EXPECT_EQ(2u, browser_list->size());
  EXPECT_EQ(original_display.id(), GetCurrentDisplay(browser()).id());
  EXPECT_NE(original_display.id(), GetCurrentDisplay(popup).id());

  // The opener should still be fullscreen.
  EXPECT_TRUE(IsWindowFullscreenForTabOrPending());
  // Popup window activation is delayed until its opener exits fullscreen.
  EXPECT_FALSE(ui_test_utils::IsBrowserActive(popup));
  ToggleTabFullscreen(/*enter_fullscreen=*/false);
  ui_test_utils::BrowserActivationWaiter(popup).WaitForActivation();
  EXPECT_TRUE(ui_test_utils::IsBrowserActive(popup));
}

// TODO(crbug.com/40111905): Disabled on Windows, where views::FullscreenHandler
// implements fullscreen by directly obtaining MONITORINFO, ignoring the mocked
// display::Screen configuration used in this test. Disabled on Mac and Linux,
// where the window server's async handling of the fullscreen window state may
// transition the window into fullscreen on the actual (non-mocked) display
// bounds before or after the window bounds checks, yielding flaky results.
#if !BUILDFLAG(IS_CHROMEOS)
#define MAYBE_FullscreenCompanionWindow DISABLED_FullscreenCompanionWindow
#else
#define MAYBE_FullscreenCompanionWindow FullscreenCompanionWindow
#endif
// Test requesting fullscreen on a specific screen and opening a cross-screen
// popup window from one gesture. Check the expected window activation pattern.
// https://w3c.github.io/window-management/#usage-overview-initiate-multi-screen-experiences
IN_PROC_BROWSER_TEST_F(MAYBE_MultiScreenFullscreenControllerInteractiveTest,
                       MAYBE_FullscreenCompanionWindow) {
  content::WebContents* tab = SetUpWindowManagementTab();

  BrowserList* browser_list = BrowserList::GetInstance();
  EXPECT_EQ(1u, browser_list->size());
  blocked_content::PopupBlockerTabHelper* popup_blocker =
      blocked_content::PopupBlockerTabHelper::FromWebContents(tab);
  EXPECT_EQ(0u, popup_blocker->GetBlockedPopupsCount());

  // Execute JS to request fullscreen and open a popup on separate screens.
  const std::string script = R"(
    (async () => {
      // Note: WindowManagementPermissionContext will send an activation signal.
      window.screenDetails = await window.getScreenDetails();

      const fullscreen_change_promise = new Promise(resolve => {
          function waitAndRemove(e) {
              document.removeEventListener("fullscreenchange", waitAndRemove);
              document.removeEventListener("fullscreenerror", waitAndRemove);
              resolve(document.fullscreenElement);
          }
          document.addEventListener("fullscreenchange", waitAndRemove);
          document.addEventListener("fullscreenerror", waitAndRemove);
      });

      // Request fullscreen and ensure that transient activation is consumed.
      const options = { screen: window.screenDetails.screens[0] };
      const fullscreen_promise = document.body.requestFullscreen(options);
      if (navigator.userActivation.isActive) {
        console.error("Transient activation unexpectedly not consumed");
        return false;
      }

      // Attempt to open a fullscreen companion window.
      const s = window.screenDetails.screens[1];
      const f = `left=${s.availLeft},top=${s.availTop},width=300,height=200`;
      const w = window.open('.', '', f);

      // Now await the fullscreen promise and change (or error) event.
      await fullscreen_promise;
      if (!await fullscreen_change_promise) {
        console.error("Unexpected fullscreen change or error");
        return false;
      }

      // Return true iff the opener is fullscreen and the popup is open.
      return !!document.fullscreenElement && !!w && !w.closed;
    })();
  )";
  EXPECT_TRUE(RequestContentFullscreenFromScript(script, true).ExtractBool());
  EXPECT_TRUE(IsWindowFullscreenForTabOrPending());
  EXPECT_EQ(0u, popup_blocker->GetBlockedPopupsCount());
  EXPECT_EQ(2u, browser_list->size());
  Browser* popup = browser_list->get(1);
  EXPECT_NE(browser(), popup);
  EXPECT_NE(GetCurrentDisplay(browser()).id(), GetCurrentDisplay(popup).id());

  // Popup window activation is delayed until its opener exits fullscreen.
  EXPECT_FALSE(ui_test_utils::IsBrowserActive(popup));
  ToggleTabFullscreen(/*enter_fullscreen=*/false);
  ui_test_utils::BrowserActivationWaiter(popup).WaitForActivation();
  EXPECT_TRUE(ui_test_utils::IsBrowserActive(popup));
}