summaryrefslogtreecommitdiff
path: root/chromium/ui/views/widget/native_widget_mac_unittest.mm
blob: c2f6e1bffe90da29980b62b430d448cc7649dff1 (plain)
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
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/memory/raw_ptr.h"

#import "ui/views/widget/native_widget_mac.h"

#import <Cocoa/Cocoa.h>

#include "base/bind.h"
#include "base/callback.h"
#import "base/mac/foundation_util.h"
#include "base/mac/mac_util.h"
#import "base/mac/scoped_nsobject.h"
#import "base/mac/scoped_objc_class_swizzler.h"
#include "base/run_loop.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#import "components/remote_cocoa/app_shim/bridged_content_view.h"
#import "components/remote_cocoa/app_shim/native_widget_mac_nswindow.h"
#import "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#import "testing/gtest_mac.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#import "ui/base/cocoa/constrained_window/constrained_window_animation.h"
#import "ui/base/cocoa/window_size_constants.h"
#import "ui/base/test/scoped_fake_full_keyboard_access.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/recyclable_compositor_mac.h"
#import "ui/events/test/cocoa_test_event_utils.h"
#include "ui/events/test/event_generator.h"
#import "ui/gfx/mac/coordinate_conversion.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/test_widget_observer.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/native_widget_mac.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/window/dialog_delegate.h"

namespace {
// "{}" in base64encode, to create some dummy restoration data.
const std::string kDummyWindowRestorationData = "e30=";
}  // namespace

// Donates an implementation of -[NSAnimation stopAnimation] which calls the
// original implementation, then quits a nested run loop.
@interface TestStopAnimationWaiter : NSObject
@end

@interface ConstrainedWindowAnimationBase (TestingAPI)
- (void)setWindowStateForEnd;
@end

// Test NSWindow that provides hooks via method overrides to verify behavior.
@interface NativeWidgetMacTestWindow : NativeWidgetMacNSWindow
@property(readonly, nonatomic) int invalidateShadowCount;
@property(assign, nonatomic) BOOL fakeOnInactiveSpace;
@property(assign, nonatomic) bool* deallocFlag;
@end

// Used to mock BridgedContentView so that calls to drawRect: can be
// intercepted.
@interface MockBridgedView : NSView {
 @private
  // Number of times -[NSView drawRect:] has been called.
  NSUInteger _drawRectCount;

  // The dirtyRect parameter passed to last invocation of drawRect:.
  NSRect _lastDirtyRect;
}

@property(assign, nonatomic) NSUInteger drawRectCount;
@property(assign, nonatomic) NSRect lastDirtyRect;
@end

@interface FocusableTestNSView : NSView
@end

namespace views {
namespace test {

// NativeWidgetNSWindowBridge friend to access private members.
class BridgedNativeWidgetTestApi {
 public:
  explicit BridgedNativeWidgetTestApi(NSWindow* window) {
    bridge_ = NativeWidgetMacNSWindowHost::GetFromNativeWindow(window)
                  ->GetInProcessNSWindowBridge();
  }

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

  // Simulate a frame swap from the compositor.
  void SimulateFrameSwap(const gfx::Size& size) {
    const float kScaleFactor = 1.0f;
    gfx::CALayerParams ca_layer_params;
    ca_layer_params.is_empty = false;
    ca_layer_params.pixel_size = size;
    ca_layer_params.scale_factor = kScaleFactor;
    bridge_->SetCALayerParams(ca_layer_params);
  }

  NSAnimation* show_animation() {
    return base::mac::ObjCCastStrict<NSAnimation>(
        bridge_->show_animation_.get());
  }

  bool HasWindowRestorationData() {
    return bridge_->HasWindowRestorationData();
  }

 private:
  raw_ptr<remote_cocoa::NativeWidgetNSWindowBridge> bridge_;
};

// Custom native_widget to create a NativeWidgetMacTestWindow.
class TestWindowNativeWidgetMac : public NativeWidgetMac {
 public:
  explicit TestWindowNativeWidgetMac(Widget* delegate)
      : NativeWidgetMac(delegate) {}

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

 protected:
  // NativeWidgetMac:
  void PopulateCreateWindowParams(
      const views::Widget::InitParams& widget_params,
      remote_cocoa::mojom::CreateWindowParams* params) override {
    params->style_mask = NSWindowStyleMaskBorderless;
    if (widget_params.type == Widget::InitParams::TYPE_WINDOW) {
      params->style_mask = NSWindowStyleMaskTexturedBackground |
                           NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
                           NSWindowStyleMaskMiniaturizable |
                           NSWindowStyleMaskResizable;
    }
  }
  NativeWidgetMacNSWindow* CreateNSWindow(
      const remote_cocoa::mojom::CreateWindowParams* params) override {
    return [[[NativeWidgetMacTestWindow alloc]
        initWithContentRect:ui::kWindowSizeDeterminedLater
                  styleMask:params->style_mask
                    backing:NSBackingStoreBuffered
                      defer:NO] autorelease];
  }
};

// Tests for parts of NativeWidgetMac not covered by NativeWidgetNSWindowBridge,
// which need access to Cocoa APIs.
class NativeWidgetMacTest : public WidgetTest {
 public:
  NativeWidgetMacTest() = default;

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

  // Make an NSWindow with a close button and a title bar to use as a parent.
  // This NSWindow is backed by a widget that is not exposed to the caller.
  // To destroy the Widget, the native NSWindow must be closed.
  NativeWidgetMacTestWindow* MakeClosableTitledNativeParent() {
    NativeWidgetMacTestWindow* native_parent = nil;
    Widget::InitParams parent_init_params =
        CreateParams(Widget::InitParams::TYPE_WINDOW);
    parent_init_params.bounds = gfx::Rect(100, 100, 200, 200);
    CreateWidgetWithTestWindow(std::move(parent_init_params), &native_parent);
    return native_parent;
  }

  // Same as the above, but creates a borderless NSWindow.
  NativeWidgetMacTestWindow* MakeBorderlessNativeParent() {
    NativeWidgetMacTestWindow* native_parent = nil;
    Widget::InitParams parent_init_params =
        CreateParams(Widget::InitParams::TYPE_WINDOW);
    parent_init_params.remove_standard_frame = true;
    parent_init_params.bounds = gfx::Rect(100, 100, 200, 200);
    CreateWidgetWithTestWindow(std::move(parent_init_params), &native_parent);
    return native_parent;
  }

  // Create a Widget backed by the NativeWidgetMacTestWindow NSWindow subclass.
  Widget* CreateWidgetWithTestWindow(Widget::InitParams params,
                                     NativeWidgetMacTestWindow** window) {
    Widget* widget = new Widget;
    params.native_widget = new TestWindowNativeWidgetMac(widget);
    widget->Init(std::move(params));
    widget->Show();
    *window = base::mac::ObjCCastStrict<NativeWidgetMacTestWindow>(
        widget->GetNativeWindow().GetNativeNSWindow());
    EXPECT_TRUE(*window);
    return widget;
  }

  FocusManager* GetFocusManager(NativeWidgetMac* native_widget) const {
    return native_widget->focus_manager_;
  }
};

class WidgetChangeObserver : public TestWidgetObserver {
 public:
  explicit WidgetChangeObserver(Widget* widget) : TestWidgetObserver(widget) {}

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

  void WaitForVisibleCounts(int gained, int lost) {
    if (gained_visible_count_ >= gained && lost_visible_count_ >= lost)
      return;

    target_gained_visible_count_ = gained;
    target_lost_visible_count_ = lost;

    base::RunLoop run_loop;
    run_loop_ = &run_loop;
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout());
    run_loop.Run();
    run_loop_ = nullptr;
  }

  int gained_visible_count() const { return gained_visible_count_; }
  int lost_visible_count() const { return lost_visible_count_; }

 private:
  // WidgetObserver:
  void OnWidgetVisibilityChanged(Widget* widget,
                                 bool visible) override {
    ++(visible ? gained_visible_count_ : lost_visible_count_);
    if (run_loop_ && gained_visible_count_ >= target_gained_visible_count_ &&
        lost_visible_count_ >= target_lost_visible_count_)
      run_loop_->Quit();
  }

  int gained_visible_count_ = 0;
  int lost_visible_count_ = 0;
  int target_gained_visible_count_ = 0;
  int target_lost_visible_count_ = 0;
  raw_ptr<base::RunLoop> run_loop_ = nullptr;
};

// This class gives public access to the protected ctor of
// BubbleDialogDelegateView.
class SimpleBubbleView : public BubbleDialogDelegateView {
 public:
  SimpleBubbleView() = default;

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

  ~SimpleBubbleView() override = default;
};

class CustomTooltipView : public View {
 public:
  CustomTooltipView(const std::u16string& tooltip, View* tooltip_handler)
      : tooltip_(tooltip), tooltip_handler_(tooltip_handler) {}

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

  // View:
  std::u16string GetTooltipText(const gfx::Point& p) const override {
    return tooltip_;
  }

  View* GetTooltipHandlerForPoint(const gfx::Point& point) override {
    return tooltip_handler_ ? tooltip_handler_.get() : this;
  }

 private:
  std::u16string tooltip_;
  raw_ptr<View> tooltip_handler_;  // Weak
};

// A Widget subclass that exposes counts to calls made to OnMouseEvent().
class MouseTrackingWidget : public Widget {
 public:
  int GetMouseEventCount(ui::EventType type) { return counts_[type]; }
  void OnMouseEvent(ui::MouseEvent* event) override {
    ++counts_[event->type()];
    Widget::OnMouseEvent(event);
  }

 private:
  std::map<int, int> counts_;
};

// Test visibility states triggered externally.
TEST_F(NativeWidgetMacTest, HideAndShowExternally) {
  Widget* widget = CreateTopLevelPlatformWidget();
  NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow();
  WidgetChangeObserver observer(widget);

  // Should initially be hidden.
  EXPECT_FALSE(widget->IsVisible());
  EXPECT_FALSE([ns_window isVisible]);
  EXPECT_EQ(0, observer.gained_visible_count());
  EXPECT_EQ(0, observer.lost_visible_count());

  widget->Show();
  EXPECT_TRUE(widget->IsVisible());
  EXPECT_TRUE([ns_window isVisible]);
  EXPECT_EQ(1, observer.gained_visible_count());
  EXPECT_EQ(0, observer.lost_visible_count());

  widget->Hide();
  EXPECT_FALSE(widget->IsVisible());
  EXPECT_FALSE([ns_window isVisible]);
  EXPECT_EQ(1, observer.gained_visible_count());
  EXPECT_EQ(1, observer.lost_visible_count());

  widget->Show();
  EXPECT_TRUE(widget->IsVisible());
  EXPECT_TRUE([ns_window isVisible]);
  EXPECT_EQ(2, observer.gained_visible_count());
  EXPECT_EQ(1, observer.lost_visible_count());

  // Test when hiding individual windows.
  [ns_window orderOut:nil];
  EXPECT_FALSE(widget->IsVisible());
  EXPECT_FALSE([ns_window isVisible]);
  EXPECT_EQ(2, observer.gained_visible_count());
  EXPECT_EQ(2, observer.lost_visible_count());

  [ns_window orderFront:nil];
  EXPECT_TRUE(widget->IsVisible());
  EXPECT_TRUE([ns_window isVisible]);
  EXPECT_EQ(3, observer.gained_visible_count());
  EXPECT_EQ(2, observer.lost_visible_count());

  // Test when hiding the entire application. This doesn't send an orderOut:
  // to the NSWindow.
  [NSApp hide:nil];
  // When the activation policy is NSApplicationActivationPolicyRegular, the
  // calls via NSApp are asynchronous, and the run loop needs to be flushed.
  // With NSApplicationActivationPolicyProhibited, the following
  // WaitForVisibleCounts calls are superfluous, but don't hurt.
  observer.WaitForVisibleCounts(3, 3);
  EXPECT_FALSE(widget->IsVisible());
  EXPECT_FALSE([ns_window isVisible]);
  EXPECT_EQ(3, observer.gained_visible_count());
  EXPECT_EQ(3, observer.lost_visible_count());

  [NSApp unhideWithoutActivation];
  observer.WaitForVisibleCounts(4, 3);
  EXPECT_TRUE(widget->IsVisible());
  EXPECT_TRUE([ns_window isVisible]);
  EXPECT_EQ(4, observer.gained_visible_count());
  EXPECT_EQ(3, observer.lost_visible_count());

  // Hide again to test unhiding with an activation.
  [NSApp hide:nil];
  observer.WaitForVisibleCounts(4, 4);
  EXPECT_EQ(4, observer.lost_visible_count());
  [NSApp unhide:nil];
  observer.WaitForVisibleCounts(5, 4);
  EXPECT_EQ(5, observer.gained_visible_count());

  // Hide again to test makeKeyAndOrderFront:.
  [ns_window orderOut:nil];
  EXPECT_FALSE(widget->IsVisible());
  EXPECT_FALSE([ns_window isVisible]);
  EXPECT_EQ(5, observer.gained_visible_count());
  EXPECT_EQ(5, observer.lost_visible_count());

  [ns_window makeKeyAndOrderFront:nil];
  EXPECT_TRUE(widget->IsVisible());
  EXPECT_TRUE([ns_window isVisible]);
  EXPECT_EQ(6, observer.gained_visible_count());
  EXPECT_EQ(5, observer.lost_visible_count());

  // No change when closing.
  widget->CloseNow();
  EXPECT_EQ(5, observer.lost_visible_count());
  EXPECT_EQ(6, observer.gained_visible_count());
}

// A view that counts calls to OnPaint().
class PaintCountView : public View {
 public:
  PaintCountView() { SetBounds(0, 0, 100, 100); }

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

  // View:
  void OnPaint(gfx::Canvas* canvas) override {
    EXPECT_TRUE(GetWidget()->IsVisible());
    ++paint_count_;
    if (run_loop_ && paint_count_ == target_paint_count_)
      run_loop_->Quit();
  }

  void WaitForPaintCount(int target) {
    if (paint_count_ == target)
      return;

    target_paint_count_ = target;
    base::RunLoop run_loop;
    run_loop_ = &run_loop;
    run_loop.Run();
    run_loop_ = nullptr;
  }

  int paint_count() { return paint_count_; }

 private:
  int paint_count_ = 0;
  int target_paint_count_ = 0;
  raw_ptr<base::RunLoop> run_loop_ = nullptr;
};


// Test that a child widget is only added to its parent NSWindow when the
// parent is on the active space. Otherwise, it may cause a space transition.
// See https://crbug.com/866760.
TEST_F(NativeWidgetMacTest, ChildWidgetOnInactiveSpace) {
  NativeWidgetMacTestWindow* parent_window;
  NativeWidgetMacTestWindow* child_window;

  Widget::InitParams init_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW);
  init_params.bounds = gfx::Rect(100, 100, 200, 200);
  Widget* parent =
      CreateWidgetWithTestWindow(std::move(init_params), &parent_window);

  parent_window.fakeOnInactiveSpace = YES;

  init_params.parent = parent->GetNativeView();
  CreateWidgetWithTestWindow(std::move(init_params), &child_window);

  EXPECT_EQ(nil, child_window.parentWindow);

  parent_window.fakeOnInactiveSpace = NO;
  parent->Show();
  EXPECT_EQ(parent_window, child_window.parentWindow);

  parent->CloseNow();
}

// Test minimized states triggered externally, implied visibility and restored
// bounds whilst minimized.
TEST_F(NativeWidgetMacTest, MiniaturizeExternally) {
  Widget* widget = new Widget;
  Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW);
  widget->Init(std::move(init_params));

  PaintCountView* view = new PaintCountView();
  widget->GetContentsView()->AddChildView(view);
  NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow();
  WidgetChangeObserver observer(widget);

  widget->SetBounds(gfx::Rect(100, 100, 300, 300));

  EXPECT_TRUE(view->IsDrawn());
  EXPECT_EQ(0, view->paint_count());
  widget->Show();
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(1, observer.gained_visible_count());
  EXPECT_EQ(0, observer.lost_visible_count());
  const gfx::Rect restored_bounds = widget->GetRestoredBounds();
  EXPECT_FALSE(restored_bounds.IsEmpty());
  EXPECT_FALSE(widget->IsMinimized());
  EXPECT_TRUE(widget->IsVisible());

  // Showing should paint.
  view->WaitForPaintCount(1);

  // First try performMiniaturize:, which requires a minimize button. Note that
  // Cocoa just blocks the UI thread during the animation, so no need to do
  // anything fancy to wait for it finish.
  [ns_window performMiniaturize:nil];
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(widget->IsMinimized());
  EXPECT_FALSE(widget->IsVisible());  // Minimizing also makes things invisible.
  EXPECT_EQ(1, observer.gained_visible_count());
  EXPECT_EQ(1, observer.lost_visible_count());
  EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());

  // No repaint when minimizing. But note that this is partly due to not calling
  // [NSView setNeedsDisplay:YES] on the content view. The superview, which is
  // an NSThemeFrame, would repaint |view| if we had, because the miniaturize
  // button is highlighted for performMiniaturize.
  EXPECT_EQ(1, view->paint_count());

  [ns_window deminiaturize:nil];
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(widget->IsMinimized());
  EXPECT_TRUE(widget->IsVisible());
  EXPECT_EQ(2, observer.gained_visible_count());
  EXPECT_EQ(1, observer.lost_visible_count());
  EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());

  view->WaitForPaintCount(2);  // A single paint when deminiaturizing.
  EXPECT_FALSE([ns_window isMiniaturized]);

  widget->Minimize();
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(widget->IsMinimized());
  EXPECT_TRUE([ns_window isMiniaturized]);
  EXPECT_EQ(2, observer.gained_visible_count());
  EXPECT_EQ(2, observer.lost_visible_count());
  EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());
  EXPECT_EQ(2, view->paint_count());  // No paint when miniaturizing.

  widget->Restore();  // If miniaturized, should deminiaturize.
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(widget->IsMinimized());
  EXPECT_FALSE([ns_window isMiniaturized]);
  EXPECT_EQ(3, observer.gained_visible_count());
  EXPECT_EQ(2, observer.lost_visible_count());
  EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());
  view->WaitForPaintCount(3);

  widget->Restore();  // If not miniaturized, does nothing.
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(widget->IsMinimized());
  EXPECT_FALSE([ns_window isMiniaturized]);
  EXPECT_EQ(3, observer.gained_visible_count());
  EXPECT_EQ(2, observer.lost_visible_count());
  EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());
  EXPECT_EQ(3, view->paint_count());

  widget->CloseNow();
}

TEST_F(NativeWidgetMacTest, MiniaturizeFramelessWindow) {
  // Create a widget without a minimize button.
  Widget* widget = CreateTopLevelFramelessPlatformWidget();
  NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow();
  widget->SetBounds(gfx::Rect(100, 100, 300, 300));
  widget->Show();
  EXPECT_FALSE(widget->IsMinimized());

  // This should fail, since performMiniaturize: requires a minimize button.
  [ns_window performMiniaturize:nil];
  EXPECT_FALSE(widget->IsMinimized());

  // But this should work.
  widget->Minimize();
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(widget->IsMinimized());

  // Test closing while minimized.
  widget->CloseNow();
}

// Simple view for the SetCursor test that overrides View::GetCursor().
class CursorView : public View {
 public:
  CursorView(int x, const ui::Cursor& cursor) : cursor_(cursor) {
    SetBounds(x, 0, 100, 300);
  }

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

  // View:
  ui::Cursor GetCursor(const ui::MouseEvent& event) override { return cursor_; }

 private:
  ui::Cursor cursor_;
};

// Test for Widget::SetCursor(). There is no Widget::GetCursor(), so this uses
// -[NSCursor currentCursor] to validate expectations. Note that currentCursor
// is just "the top cursor on the application's cursor stack.", which is why it
// is safe to use this in a non-interactive UI test with the EventGenerator.
TEST_F(NativeWidgetMacTest, SetCursor) {
  NSCursor* arrow = [NSCursor arrowCursor];
  NSCursor* hand = [NSCursor pointingHandCursor];
  NSCursor* ibeam = [NSCursor IBeamCursor];

  Widget* widget = CreateTopLevelPlatformWidget();
  widget->SetBounds(gfx::Rect(0, 0, 300, 300));
  auto* view_hand = widget->non_client_view()->frame_view()->AddChildView(
      std::make_unique<CursorView>(0, ui::mojom::CursorType::kHand));
  auto* view_ibeam = widget->non_client_view()->frame_view()->AddChildView(
      std::make_unique<CursorView>(100, ui::mojom::CursorType::kIBeam));
  widget->Show();
  NSWindow* widget_window = widget->GetNativeWindow().GetNativeNSWindow();

  // Events used to simulate tracking rectangle updates. These are not passed to
  // toolkit-views, so it only matters whether they are inside or outside the
  // content area.
  const gfx::Rect bounds = widget->GetWindowBoundsInScreen();
  NSEvent* event_in_content = cocoa_test_event_utils::MouseEventAtPoint(
      NSMakePoint(bounds.x(), bounds.y()), NSEventTypeMouseMoved, 0);
  NSEvent* event_out_of_content = cocoa_test_event_utils::MouseEventAtPoint(
      NSMakePoint(-50, -50), NSEventTypeMouseMoved, 0);

  EXPECT_NE(arrow, hand);
  EXPECT_NE(arrow, ibeam);

  // Make arrow the current cursor.
  [arrow set];
  EXPECT_EQ(arrow, [NSCursor currentCursor]);

  // Use an event generator to ask views code to set the cursor. However, note
  // that this does not cause Cocoa to generate tracking rectangle updates.
  ui::test::EventGenerator event_generator(GetContext(), widget_window);

  // Move the mouse over the first view, then simulate a tracking rectangle
  // update. Verify that the cursor changed from arrow to hand type.
  event_generator.MoveMouseTo(view_hand->GetBoundsInScreen().CenterPoint());
  [widget_window cursorUpdate:event_in_content];
  EXPECT_EQ(hand, [NSCursor currentCursor]);

  // A tracking rectangle update not in the content area should forward to
  // the native NSWindow implementation, which sets the arrow cursor.
  [widget_window cursorUpdate:event_out_of_content];
  EXPECT_EQ(arrow, [NSCursor currentCursor]);

  // Now move to the second view.
  event_generator.MoveMouseTo(view_ibeam->GetBoundsInScreen().CenterPoint());
  [widget_window cursorUpdate:event_in_content];
  EXPECT_EQ(ibeam, [NSCursor currentCursor]);

  // Moving to the third view (but remaining in the content area) should also
  // forward to the native NSWindow implementation.
  event_generator.MoveMouseTo(widget->non_client_view()
                                  ->frame_view()
                                  ->GetBoundsInScreen()
                                  .bottom_right());
  [widget_window cursorUpdate:event_in_content];
  EXPECT_EQ(arrow, [NSCursor currentCursor]);

  widget->CloseNow();
}

// Tests that an accessibility request from the system makes its way through to
// a views::Label filling the window.
TEST_F(NativeWidgetMacTest, AccessibilityIntegration) {
  Widget* widget = CreateTopLevelPlatformWidget();
  gfx::Rect screen_rect(50, 50, 100, 100);
  widget->SetBounds(screen_rect);

  const std::u16string test_string = u"Green";
  views::Label* label = new views::Label(test_string);
  label->SetBounds(0, 0, 100, 100);
  widget->GetContentsView()->AddChildView(label);
  widget->Show();

  // Accessibility hit tests come in Cocoa screen coordinates.
  NSRect nsrect = gfx::ScreenRectToNSRect(screen_rect);
  NSPoint midpoint = NSMakePoint(NSMidX(nsrect), NSMidY(nsrect));

  id hit = [widget->GetNativeWindow().GetNativeNSWindow()
      accessibilityHitTest:midpoint];
  ASSERT_TRUE([hit conformsToProtocol:@protocol(NSAccessibility)]);
  id<NSAccessibility> ax_hit = hit;
  id title = ax_hit.accessibilityValue;
  EXPECT_NSEQ(title, @"Green");

  widget->CloseNow();
}

namespace {

Widget* AttachPopupToNativeParent(NSWindow* native_parent) {
  base::scoped_nsobject<NSView> anchor_view(
      [[NSView alloc] initWithFrame:[[native_parent contentView] bounds]]);
  [[native_parent contentView] addSubview:anchor_view];

  // Note: Don't use WidgetTest::CreateChildPlatformWidget because that makes
  // windows of TYPE_CONTROL which need a parent Widget to obtain the focus
  // manager.
  Widget* child = new Widget;
  Widget::InitParams init_params;
  init_params.parent = anchor_view.get();
  init_params.child = true;
  init_params.type = Widget::InitParams::TYPE_POPUP;
  child->Init(std::move(init_params));
  return child;
}

}  // namespace

// Tests creating a views::Widget parented off a native NSWindow.
TEST_F(NativeWidgetMacTest, NonWidgetParent) {
  NSWindow* native_parent = MakeBorderlessNativeParent();

  Widget::Widgets children;
  Widget::GetAllChildWidgets([native_parent contentView], &children);
  EXPECT_EQ(1u, children.size());

  Widget* child = AttachPopupToNativeParent(native_parent);
  EXPECT_FALSE(child->is_top_level());
  TestWidgetObserver child_observer(child);

  // GetTopLevelNativeWidget() will go up through |native_parent|'s Widget.
  internal::NativeWidgetPrivate* top_level_widget =
      internal::NativeWidgetPrivate::GetTopLevelNativeWidget(
          child->GetNativeView());
  EXPECT_EQ(Widget::GetWidgetForNativeWindow(native_parent),
            top_level_widget->GetWidget());
  EXPECT_NE(child, top_level_widget->GetWidget());

  // To verify the parent, we need to use NativeWidgetMac APIs.
  NativeWidgetMacNSWindowHost* bridged_native_widget_host =
      NativeWidgetMacNSWindowHost::GetFromNativeWindow(
          child->GetNativeWindow());
  EXPECT_EQ(bridged_native_widget_host->parent()
                ->native_widget_mac()
                ->GetNativeWindow(),
            native_parent);

  const gfx::Rect child_bounds(50, 50, 200, 100);
  child->SetBounds(child_bounds);
  EXPECT_FALSE(child->IsVisible());
  EXPECT_EQ(0u, [[native_parent childWindows] count]);

  child->Show();
  EXPECT_TRUE(child->IsVisible());
  EXPECT_EQ(1u, [[native_parent childWindows] count]);
  EXPECT_EQ(child->GetNativeWindow(), [native_parent childWindows][0]);
  EXPECT_EQ(native_parent,
            [child->GetNativeWindow().GetNativeNSWindow() parentWindow]);

  Widget::GetAllChildWidgets([native_parent contentView], &children);
  ASSERT_EQ(2u, children.size());
  EXPECT_EQ(1u, children.count(child));

  // Only non-toplevel Widgets are positioned relative to the parent, so the
  // bounds set above should be in screen coordinates.
  EXPECT_EQ(child_bounds, child->GetWindowBoundsInScreen());

  // Removing the anchor view from its view hierarchy is permitted. This should
  // not break the relationship between the two windows.
  NSView* anchor_view = [[native_parent contentView] subviews][0];
  EXPECT_TRUE(anchor_view);
  [anchor_view removeFromSuperview];
  EXPECT_EQ(bridged_native_widget_host->parent()
                ->native_widget_mac()
                ->GetNativeWindow(),
            native_parent);

  // Closing the parent should close and destroy the child.
  EXPECT_FALSE(child_observer.widget_closed());
  [native_parent close];
  EXPECT_TRUE(child_observer.widget_closed());

  EXPECT_EQ(0u, [[native_parent childWindows] count]);
  [native_parent close];
}

// Tests that CloseAllSecondaryWidgets behaves in various configurations.
TEST_F(NativeWidgetMacTest, CloseAllSecondaryWidgetsValidState) {
  NativeWidgetMacTestWindow* last_window = nil;
  bool window_deallocated = false;
  @autoreleasepool {
    // First verify the behavior of CloseAllSecondaryWidgets in the normal case,
    // and how [NSApp windows] changes in response to Widget closure.
    Widget* widget = CreateWidgetWithTestWindow(
        Widget::InitParams(Widget::InitParams::TYPE_WINDOW), &last_window);
    last_window.deallocFlag = &window_deallocated;
    TestWidgetObserver observer(widget);
    EXPECT_TRUE([[NSApp windows] containsObject:last_window]);
    Widget::CloseAllSecondaryWidgets();
    EXPECT_TRUE(observer.widget_closed());
  }

  EXPECT_TRUE(window_deallocated);
  window_deallocated = false;

  @autoreleasepool {
    // Repeat, but now retain a reference and close the window before
    // CloseAllSecondaryWidgets().
    Widget* widget = CreateWidgetWithTestWindow(
        Widget::InitParams(Widget::InitParams::TYPE_WINDOW), &last_window);
    last_window.deallocFlag = &window_deallocated;
    TestWidgetObserver observer(widget);
    [last_window retain];
    widget->CloseNow();
    EXPECT_TRUE(observer.widget_closed());
  }

  EXPECT_FALSE(window_deallocated);
  @autoreleasepool {
    Widget::CloseAllSecondaryWidgets();
    [last_window release];
  }
  EXPECT_TRUE(window_deallocated);

  // Repeat, with two Widgets. We can't control the order of window closure.
  // If the parent is closed first, it should tear down the child while
  // iterating over the windows. -[NSWindow close] will be sent to the child
  // twice, but that should be fine.
  Widget* parent = CreateTopLevelPlatformWidget();
  Widget* child = CreateChildPlatformWidget(parent->GetNativeView());
  parent->Show();
  child->Show();
  TestWidgetObserver parent_observer(parent);
  TestWidgetObserver child_observer(child);

  EXPECT_TRUE([[NSApp windows]
      containsObject:parent->GetNativeWindow().GetNativeNSWindow()]);
  EXPECT_TRUE([[NSApp windows]
      containsObject:child->GetNativeWindow().GetNativeNSWindow()]);
  Widget::CloseAllSecondaryWidgets();
  EXPECT_TRUE(parent_observer.widget_closed());
  EXPECT_TRUE(child_observer.widget_closed());
}

// Tests closing the last remaining NSWindow reference via -windowWillClose:.
// This is a regression test for http://crbug.com/616701.
TEST_F(NativeWidgetMacTest, NonWidgetParentLastReference) {
  bool child_dealloced = false;
  bool native_parent_dealloced = false;
  NativeWidgetMacTestWindow* native_parent = nil;
  @autoreleasepool {
    native_parent = MakeBorderlessNativeParent();
    [native_parent setDeallocFlag:&native_parent_dealloced];

    NativeWidgetMacTestWindow* window;
    Widget::InitParams init_params =
        CreateParams(Widget::InitParams::TYPE_POPUP);
    init_params.parent = [native_parent contentView];
    init_params.bounds = gfx::Rect(0, 0, 100, 200);
    CreateWidgetWithTestWindow(std::move(init_params), &window);
    [window setDeallocFlag:&child_dealloced];
  }
  @autoreleasepool {
    // On 10.11, closing a weak reference on the parent window works, but older
    // versions of AppKit get upset if things are released inside -[NSWindow
    // close]. This test tries to establish a situation where the last reference
    // to the child window is released inside WidgetOwnerNSWindowAdapter::
    // OnWindowWillClose().
    [native_parent close];
  }

  // Check this only once the autorelease pool has been drained: AppKit likes to
  // autorelease NSWindows when tearing them down, presumably to make UAF bugs
  // with NSWindows less likely.
  EXPECT_TRUE(child_dealloced);
  EXPECT_TRUE(native_parent_dealloced);
}

// Tests visibility for a child of a native NSWindow, reshowing after a
// deminiaturize on the parent window (after attempting to show the child while
// the parent was miniaturized).
TEST_F(NativeWidgetMacTest, VisibleAfterNativeParentDeminiaturize) {
  NSWindow* native_parent = MakeBorderlessNativeParent();
  [native_parent makeKeyAndOrderFront:nil];
  [native_parent miniaturize:nil];
  Widget* child = AttachPopupToNativeParent(native_parent);

  child->Show();
  EXPECT_FALSE([native_parent isVisible]);
  EXPECT_FALSE(child->IsVisible());  // Parent is hidden so child is also.

  [native_parent deminiaturize:nil];
  EXPECT_TRUE([native_parent isVisible]);
  // Don't WaitForVisibleCounts() here: deminiaturize is synchronous, so any
  // spurious _occlusion_ state change would have already occurred. Further
  // occlusion changes are not guaranteed to be triggered by the deminiaturize.
  EXPECT_TRUE(child->IsVisible());
  [native_parent close];
}

// Use Native APIs to query the tooltip text that would be shown once the
// tooltip delay had elapsed.
std::u16string TooltipTextForWidget(Widget* widget) {
  // For Mac, the actual location doesn't matter, since there is only one native
  // view and it fills the window. This just assumes the window is at least big
  // big enough for a constant coordinate to be within it.
  NSPoint point = NSMakePoint(30, 30);
  NSView* view = [widget->GetNativeView().GetNativeNSView() hitTest:point];
  NSString* text =
      [view view:view stringForToolTip:0 point:point userData:nullptr];
  return base::SysNSStringToUTF16(text);
}

// Tests tooltips. The test doesn't wait for tooltips to appear. That is, the
// test assumes Cocoa calls stringForToolTip: at appropriate times and that,
// when a tooltip is already visible, changing it causes an update. These were
// tested manually by inserting a base::RunLoop.Run().
TEST_F(NativeWidgetMacTest, Tooltips) {
  Widget* widget = CreateTopLevelPlatformWidget();
  gfx::Rect screen_rect(50, 50, 100, 100);
  widget->SetBounds(screen_rect);

  const std::u16string tooltip_back = u"Back";
  const std::u16string tooltip_front = u"Front";
  const std::u16string long_tooltip(2000, 'W');

  // Create a nested layout to test corner cases.
  LabelButton* back = widget->non_client_view()->frame_view()->AddChildView(
      std::make_unique<LabelButton>());
  back->SetBounds(10, 10, 80, 80);
  widget->Show();

  ui::test::EventGenerator event_generator(GetContext(),
                                           widget->GetNativeWindow());

  // Initially, there should be no tooltip.
  const gfx::Rect widget_bounds = widget->GetClientAreaBoundsInScreen();
  event_generator.MoveMouseTo(widget_bounds.CenterPoint());
  EXPECT_TRUE(TooltipTextForWidget(widget).empty());

  // Create a new button for the "front", and set the tooltip, but don't add it
  // to the view hierarchy yet.
  auto front_managed = std::make_unique<LabelButton>();
  front_managed->SetBounds(20, 20, 40, 40);
  front_managed->SetTooltipText(tooltip_front);

  // Changing the tooltip text shouldn't require an additional mousemove to take
  // effect.
  EXPECT_TRUE(TooltipTextForWidget(widget).empty());
  back->SetTooltipText(tooltip_back);
  EXPECT_EQ(tooltip_back, TooltipTextForWidget(widget));

  // Adding a new view under the mouse should also take immediate effect.
  LabelButton* front = back->AddChildView(std::move(front_managed));
  EXPECT_EQ(tooltip_front, TooltipTextForWidget(widget));

  // A long tooltip will be wrapped by Cocoa, but the full string should appear.
  // Note that render widget hosts clip at 1024 to prevent DOS, but in toolkit-
  // views the UI is more trusted.
  front->SetTooltipText(long_tooltip);
  EXPECT_EQ(long_tooltip, TooltipTextForWidget(widget));

  // Move the mouse to a different view - tooltip should change.
  event_generator.MoveMouseTo(back->GetBoundsInScreen().origin());
  EXPECT_EQ(tooltip_back, TooltipTextForWidget(widget));

  // Move the mouse off of any view, tooltip should clear.
  event_generator.MoveMouseTo(widget_bounds.origin());
  EXPECT_TRUE(TooltipTextForWidget(widget).empty());

  widget->CloseNow();
}

// Tests case when mouse events are handled in one Widget,
// but tooltip belongs to another.
// It happens in menus when a submenu is shown and the parent gets the
// MouseExit event.
TEST_F(NativeWidgetMacTest, TwoWidgetTooltips) {
  // Init two widgets, one above another.
  Widget* widget_below = CreateTopLevelPlatformWidget();
  widget_below->SetBounds(gfx::Rect(50, 50, 200, 200));

  Widget* widget_above =
      CreateChildPlatformWidget(widget_below->GetNativeView());
  widget_above->SetBounds(gfx::Rect(100, 0, 100, 200));

  const std::u16string tooltip_above = u"Front";
  CustomTooltipView* view_above = widget_above->GetContentsView()->AddChildView(
      std::make_unique<CustomTooltipView>(tooltip_above, nullptr));
  view_above->SetBoundsRect(widget_above->GetContentsView()->bounds());

  CustomTooltipView* view_below =
      widget_below->non_client_view()->frame_view()->AddChildView(
          std::make_unique<CustomTooltipView>(u"Back", view_above));
  view_below->SetBoundsRect(widget_below->GetContentsView()->bounds());

  widget_below->Show();
  widget_above->Show();

  // Move mouse above second widget and check that it returns tooltip
  // for second. Despite that event was handled in the first one.
  ui::test::EventGenerator event_generator(GetContext(),
                                           widget_below->GetNativeWindow());
  event_generator.MoveMouseTo(
      widget_above->GetWindowBoundsInScreen().CenterPoint());
  EXPECT_EQ(tooltip_above, TooltipTextForWidget(widget_below));

  widget_above->CloseNow();
  widget_below->CloseNow();
}

// Ensure captured mouse events correctly update dragging state in BaseView.
// Regression test for https://crbug.com/942452.
TEST_F(NativeWidgetMacTest, CapturedMouseUpClearsDrag) {
  MouseTrackingWidget* widget = new MouseTrackingWidget;
  Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW);
  widget->Init(std::move(init_params));

  NSWindow* window = widget->GetNativeWindow().GetNativeNSWindow();
  BridgedContentView* native_view = [window contentView];

  // Note: using native coordinates for consistency.
  [window setFrame:NSMakeRect(50, 50, 100, 100) display:YES animate:NO];
  NSEvent* enter_event = cocoa_test_event_utils::EnterEvent({50, 50}, window);
  NSEvent* exit_event = cocoa_test_event_utils::ExitEvent({200, 200}, window);

  widget->Show();
  EXPECT_EQ(0, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
  EXPECT_EQ(0, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));

  [native_view mouseEntered:enter_event];
  EXPECT_EQ(1, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
  EXPECT_EQ(0, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));

  [native_view mouseExited:exit_event];
  EXPECT_EQ(1, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
  EXPECT_EQ(1, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));

  // Send a click. Note a click may initiate a drag, so the mouse-up is sent as
  // a captured event.
  std::pair<NSEvent*, NSEvent*> click =
      cocoa_test_event_utils::MouseClickInView(native_view, 1);
  [native_view mouseDown:click.first];
  [native_view processCapturedMouseEvent:click.second];

  // After a click, Enter/Exit should still work.
  [native_view mouseEntered:enter_event];
  EXPECT_EQ(2, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
  EXPECT_EQ(1, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));

  [native_view mouseExited:exit_event];
  EXPECT_EQ(2, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
  EXPECT_EQ(2, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));

  widget->CloseNow();
}

namespace {

// TODO(ellyjones): Once DialogDelegate::CreateDialogWidget can accept a
// unique_ptr, return unique_ptr here.
DialogDelegateView* MakeModalDialog(ui::ModalType modal_type) {
  auto dialog = std::make_unique<DialogDelegateView>();
  dialog->SetModalType(modal_type);
  return dialog.release();
}

// While in scope, waits for a call to a swizzled objective C method, then quits
// a nested run loop.
class ScopedSwizzleWaiter {
 public:
  explicit ScopedSwizzleWaiter(Class target)
      : swizzler_(target,
                  [TestStopAnimationWaiter class],
                  @selector(setWindowStateForEnd)) {
    DCHECK(!instance_);
    instance_ = this;
  }

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

  ~ScopedSwizzleWaiter() { instance_ = nullptr; }

  static void OriginalSetWindowStateForEnd(id receiver, SEL method) {
    return instance_->CallMethodInternal(receiver, method);
  }

  void WaitForMethod() {
    if (method_called_)
      return;

    base::RunLoop run_loop;
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout());
    run_loop_ = &run_loop;
    run_loop.Run();
    run_loop_ = nullptr;
  }

  bool method_called() const { return method_called_; }

 private:
  void CallMethodInternal(id receiver, SEL selector) {
    DCHECK(!method_called_);
    method_called_ = true;
    if (run_loop_)
      run_loop_->Quit();
    swizzler_.InvokeOriginal<void>(receiver, selector);
  }

  static ScopedSwizzleWaiter* instance_;

  base::mac::ScopedObjCClassSwizzler swizzler_;
  raw_ptr<base::RunLoop> run_loop_ = nullptr;
  bool method_called_ = false;
};

ScopedSwizzleWaiter* ScopedSwizzleWaiter::instance_ = nullptr;

// Shows a modal widget and waits for the show animation to complete. Waiting is
// not compulsory (calling Close() while animating the show will cancel the show
// animation). However, testing with overlapping swizzlers is tricky.
Widget* ShowChildModalWidgetAndWait(NSWindow* native_parent) {
  Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
      MakeModalDialog(ui::MODAL_TYPE_CHILD), nullptr,
      [native_parent contentView]);

  modal_dialog_widget->SetBounds(gfx::Rect(50, 50, 200, 150));
  EXPECT_FALSE(modal_dialog_widget->IsVisible());
  ScopedSwizzleWaiter show_waiter([ConstrainedWindowAnimationShow class]);

  BridgedNativeWidgetTestApi test_api(
      modal_dialog_widget->GetNativeWindow().GetNativeNSWindow());
  EXPECT_FALSE(test_api.show_animation());

  modal_dialog_widget->Show();
  // Visible immediately (although it animates from transparent).
  EXPECT_TRUE(modal_dialog_widget->IsVisible());
  base::scoped_nsobject<NSAnimation> retained_animation(
      test_api.show_animation(), base::scoped_policy::RETAIN);
  EXPECT_TRUE(retained_animation);
  EXPECT_TRUE([retained_animation isAnimating]);

  // Run the animation.
  show_waiter.WaitForMethod();
  EXPECT_TRUE(modal_dialog_widget->IsVisible());
  EXPECT_TRUE(show_waiter.method_called());
  EXPECT_FALSE([retained_animation isAnimating]);
  EXPECT_FALSE(test_api.show_animation());
  return modal_dialog_widget;
}

// Shows a window-modal Widget (as a sheet). No need to wait since the native
// sheet animation is blocking.
Widget* ShowWindowModalWidget(NSWindow* native_parent) {
  Widget* sheet_widget = views::DialogDelegate::CreateDialogWidget(
      MakeModalDialog(ui::MODAL_TYPE_WINDOW), nullptr,
      [native_parent contentView]);
  sheet_widget->Show();
  return sheet_widget;
}

}  // namespace

// Tests object lifetime for the show/hide animations used for child-modal
// windows.
TEST_F(NativeWidgetMacTest, NativeWindowChildModalShowHide) {
  NSWindow* native_parent = MakeBorderlessNativeParent();
  {
    Widget* modal_dialog_widget = ShowChildModalWidgetAndWait(native_parent);
    TestWidgetObserver widget_observer(modal_dialog_widget);

    ScopedSwizzleWaiter hide_waiter([ConstrainedWindowAnimationHide class]);
    EXPECT_TRUE(modal_dialog_widget->IsVisible());
    EXPECT_FALSE(widget_observer.widget_closed());

    // Widget::Close() is always asynchronous, so we can check that the widget
    // is initially visible, but then it's destroyed.
    modal_dialog_widget->Close();
    EXPECT_TRUE(modal_dialog_widget->IsVisible());
    EXPECT_FALSE(hide_waiter.method_called());
    EXPECT_FALSE(widget_observer.widget_closed());

    // Wait for a hide to finish.
    hide_waiter.WaitForMethod();
    EXPECT_TRUE(hide_waiter.method_called());

    // The animation finishing should also mean it has closed the window.
    EXPECT_TRUE(widget_observer.widget_closed());
  }

  {
    // Make a new dialog to test another lifetime flow.
    Widget* modal_dialog_widget = ShowChildModalWidgetAndWait(native_parent);
    TestWidgetObserver widget_observer(modal_dialog_widget);

    // Start an asynchronous close as above.
    ScopedSwizzleWaiter hide_waiter([ConstrainedWindowAnimationHide class]);
    modal_dialog_widget->Close();
    EXPECT_FALSE(widget_observer.widget_closed());
    EXPECT_FALSE(hide_waiter.method_called());

    // Now close the _parent_ window to force a synchronous close of the child.
    [native_parent close];

    // Widget is destroyed immediately. No longer paints, but the animation is
    // still running.
    EXPECT_TRUE(widget_observer.widget_closed());
    EXPECT_FALSE(hide_waiter.method_called());

    // Wait for the hide again. It will call close on its retained copy of the
    // child NSWindow, but that's fine since all the C++ objects are detached.
    hide_waiter.WaitForMethod();
    EXPECT_TRUE(hide_waiter.method_called());
  }
}

// Tests that the first call into SetVisibilityState() restores the window state
// for windows that start off miniaturized in the dock.
TEST_F(NativeWidgetMacTest, ConfirmMinimizedWindowRestoration) {
  Widget* widget = new Widget;
  Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
  params.native_widget =
      CreatePlatformNativeWidgetImpl(widget, kStubCapture, nullptr);
  // Start the window off in the dock.
  params.show_state = ui::SHOW_STATE_MINIMIZED;
  params.workspace = kDummyWindowRestorationData;
  widget->Init(std::move(params));

  BridgedNativeWidgetTestApi test_api(
      widget->GetNativeWindow().GetNativeNSWindow());

  EXPECT_TRUE(test_api.HasWindowRestorationData());

  // Show() ultimately invokes SetVisibilityState().
  widget->Show();

  EXPECT_FALSE(test_api.HasWindowRestorationData());

  widget->CloseNow();
}

// Tests that the first call into SetVisibilityState() restores the window state
// for windows that start off visible.
TEST_F(NativeWidgetMacTest, ConfirmVisibleWindowRestoration) {
  Widget* widget = new Widget;
  Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
  params.native_widget =
      CreatePlatformNativeWidgetImpl(widget, kStubCapture, nullptr);
  params.show_state = ui::SHOW_STATE_NORMAL;
  params.workspace = kDummyWindowRestorationData;
  widget->Init(std::move(params));

  BridgedNativeWidgetTestApi test_api(
      widget->GetNativeWindow().GetNativeNSWindow());

  EXPECT_TRUE(test_api.HasWindowRestorationData());

  // Show() ultimately invokes SetVisibilityState().
  widget->Show();

  EXPECT_FALSE(test_api.HasWindowRestorationData());

  widget->CloseNow();
}

// Tests that calls to Hide() a Widget cancel any in-progress show animation,
// and that clients can control the triggering of the animation.
TEST_F(NativeWidgetMacTest, ShowAnimationControl) {
  NSWindow* native_parent = MakeBorderlessNativeParent();
  Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
      MakeModalDialog(ui::MODAL_TYPE_CHILD), nullptr,
      [native_parent contentView]);

  modal_dialog_widget->SetBounds(gfx::Rect(50, 50, 200, 150));
  EXPECT_FALSE(modal_dialog_widget->IsVisible());

  BridgedNativeWidgetTestApi test_api(
      modal_dialog_widget->GetNativeWindow().GetNativeNSWindow());
  EXPECT_FALSE(test_api.show_animation());
  modal_dialog_widget->Show();

  EXPECT_TRUE(modal_dialog_widget->IsVisible());
  base::scoped_nsobject<NSAnimation> retained_animation(
      test_api.show_animation(), base::scoped_policy::RETAIN);
  EXPECT_TRUE(retained_animation);
  EXPECT_TRUE([retained_animation isAnimating]);

  // Hide without waiting for the animation to complete. Animation should cancel
  // and clear references from NativeWidgetNSWindowBridge.
  modal_dialog_widget->Hide();
  EXPECT_FALSE([retained_animation isAnimating]);
  EXPECT_FALSE(test_api.show_animation());
  retained_animation.reset();

  // Disable animations and show again.
  modal_dialog_widget->SetVisibilityAnimationTransition(Widget::ANIMATE_NONE);
  modal_dialog_widget->Show();
  EXPECT_FALSE(test_api.show_animation());  // No animation this time.
  modal_dialog_widget->Hide();

  // Test after re-enabling.
  modal_dialog_widget->SetVisibilityAnimationTransition(Widget::ANIMATE_BOTH);
  modal_dialog_widget->Show();
  EXPECT_TRUE(test_api.show_animation());
  retained_animation.reset(test_api.show_animation(),
                           base::scoped_policy::RETAIN);

  // Test whether disabling native animations also disables custom modal ones.
  modal_dialog_widget->SetVisibilityChangedAnimationsEnabled(false);
  modal_dialog_widget->Show();
  EXPECT_FALSE(test_api.show_animation());  // No animation this time.
  modal_dialog_widget->Hide();
  // Renable.
  modal_dialog_widget->SetVisibilityChangedAnimationsEnabled(true);
  modal_dialog_widget->Show();
  EXPECT_TRUE(test_api.show_animation());
  retained_animation.reset(test_api.show_animation(),
                           base::scoped_policy::RETAIN);

  // Closing should also cancel the animation.
  EXPECT_TRUE([retained_animation isAnimating]);
  [native_parent close];
  EXPECT_FALSE([retained_animation isAnimating]);
}

// Tests behavior of window-modal dialogs, displayed as sheets.
#if defined(ARCH_CPU_ARM64)
// Bulk-disabled as part of arm64 bot stabilization: https://crbug.com/1154345
#define MAYBE_WindowModalSheet DISABLED_WindowModalSheet
#else
#define MAYBE_WindowModalSheet WindowModalSheet
#endif
TEST_F(NativeWidgetMacTest, MAYBE_WindowModalSheet) {
  NSWindow* native_parent = MakeClosableTitledNativeParent();

  Widget* sheet_widget = views::DialogDelegate::CreateDialogWidget(
      MakeModalDialog(ui::MODAL_TYPE_WINDOW), nullptr,
      [native_parent contentView]);

  WidgetChangeObserver widget_observer(sheet_widget);

  // Retain, to run checks after the Widget is torn down.
  base::scoped_nsobject<NSWindow> sheet_window(
      [sheet_widget->GetNativeWindow().GetNativeNSWindow() retain]);

  // Although there is no titlebar displayed, sheets need
  // NSWindowStyleMaskTitled in order to properly engage window-modal behavior
  // in AppKit.
  EXPECT_TRUE(NSWindowStyleMaskTitled & [sheet_window styleMask]);

  // But to properly size, sheets also need
  // NSWindowStyleMaskFullSizeContentView.
  EXPECT_TRUE(NSWindowStyleMaskFullSizeContentView & [sheet_window styleMask]);

  sheet_widget->SetBounds(gfx::Rect(50, 50, 200, 150));
  EXPECT_FALSE(sheet_widget->IsVisible());
  EXPECT_FALSE(sheet_widget->GetLayer()->IsDrawn());

  NSButton* parent_close_button =
      [native_parent standardWindowButton:NSWindowCloseButton];
  EXPECT_TRUE(parent_close_button);
  EXPECT_TRUE([parent_close_button isEnabled]);

  bool did_observe = false;
  bool* did_observe_ptr = &did_observe;
  id observer = [[NSNotificationCenter defaultCenter]
      addObserverForName:NSWindowWillBeginSheetNotification
                  object:native_parent
                   queue:nil
              usingBlock:^(NSNotification* note) {
                // Ensure that before the sheet runs, the window contents would
                // be drawn.
                EXPECT_TRUE(sheet_widget->IsVisible());
                EXPECT_TRUE(sheet_widget->GetLayer()->IsDrawn());
                *did_observe_ptr = true;
              }];

  Widget::Widgets children;
  Widget::GetAllChildWidgets([native_parent contentView], &children);
  ASSERT_EQ(2u, children.size());

  sheet_widget->Show();  // Should run the above block, then animate the sheet.
  EXPECT_TRUE(did_observe);
  [[NSNotificationCenter defaultCenter] removeObserver:observer];

  // Ensure sheets are included as a child.
  Widget::GetAllChildWidgets([native_parent contentView], &children);
  ASSERT_EQ(2u, children.size());
  EXPECT_TRUE(children.count(sheet_widget));

  ASSERT_EQ(0U, native_parent.childWindows.count);

  // Modal, so the close button in the parent window should get disabled.
  EXPECT_FALSE([parent_close_button isEnabled]);

  // The sheet should be hidden and shown in step with the parent.
  widget_observer.WaitForVisibleCounts(1, 0);
  EXPECT_TRUE(sheet_widget->IsVisible());

  // TODO(tapted): Ideally [native_parent orderOut:nil] would also work here.
  // But it does not. AppKit's childWindow management breaks down after an
  // -orderOut: (see NativeWidgetNSWindowBridge::OnVisibilityChanged()). For
  // regular child windows, NativeWidgetNSWindowBridge fixes the behavior with
  // its own management. However, it can't do that for sheets without
  // encountering http://crbug.com/605098 and http://crbug.com/667602. -[NSApp
  // hide:] makes the NSWindow hidden in a different way, which does not break
  // like -orderOut: does. Which is good, because a user can always do -[NSApp
  // hide:], e.g., with Cmd+h, and that needs to work correctly.
  [NSApp hide:nil];

  widget_observer.WaitForVisibleCounts(1, 1);
  EXPECT_FALSE(sheet_widget->IsVisible());
  [native_parent makeKeyAndOrderFront:nil];
  ASSERT_EQ(0u, native_parent.childWindows.count);
  widget_observer.WaitForVisibleCounts(2, 1);
  EXPECT_TRUE(sheet_widget->IsVisible());

  // Trigger the close. Don't use CloseNow, since that tears down the UI before
  // the close sheet animation gets a chance to run (so it's banned).
  sheet_widget->Close();
  EXPECT_TRUE(sheet_widget->IsVisible());

  // Pump in order to trigger -[NSWindow endSheet:..], which will block while
  // the animation runs, then delete |sheet_widget|.
  EXPECT_TRUE([sheet_window delegate]);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE([sheet_window delegate]);
  [[NSNotificationCenter defaultCenter] removeObserver:observer];

  EXPECT_TRUE(widget_observer.widget_closed());
  EXPECT_TRUE([parent_close_button isEnabled]);

  [native_parent close];
}

// Tests behavior when closing a window that is a sheet, or that hosts a sheet,
// and reshowing a sheet on a window after the sheet was closed with -[NSWindow
// close].
TEST_F(NativeWidgetMacTest, CloseWithWindowModalSheet) {
  NSWindow* native_parent = MakeClosableTitledNativeParent();

  {
    Widget* sheet_widget = ShowWindowModalWidget(native_parent);
    EXPECT_TRUE(
        [sheet_widget->GetNativeWindow().GetNativeNSWindow() isVisible]);

    WidgetChangeObserver widget_observer(sheet_widget);

    // Test synchronous close (asynchronous close is tested above).
    sheet_widget->CloseNow();
    EXPECT_TRUE(widget_observer.widget_closed());

    // Spin the RunLoop to ensure the task that ends the modal session on
    // |native_parent| is executed. Otherwise |native_parent| will refuse to
    // show another sheet.
    base::RunLoop().RunUntilIdle();
  }

  {
    Widget* sheet_widget = ShowWindowModalWidget(native_parent);

    // Ensure the sheet wasn't blocked by a previous modal session.
    EXPECT_TRUE(
        [sheet_widget->GetNativeWindow().GetNativeNSWindow() isVisible]);

    WidgetChangeObserver widget_observer(sheet_widget);

    // Test native -[NSWindow close] on the sheet. Does not animate.
    [sheet_widget->GetNativeWindow().GetNativeNSWindow() close];
    EXPECT_TRUE(widget_observer.widget_closed());
    base::RunLoop().RunUntilIdle();
  }

  // Similar, but invoke -[NSWindow close] immediately after an asynchronous
  // Close(). This exercises a scenario where two tasks to end the sheet may be
  // posted. Experimentally (on 10.13) both tasks run, but the second will never
  // attempt to invoke -didEndSheet: on the |modalDelegate| arg of -beginSheet:.
  // (If it did, it would be fine.)
  {
    Widget* sheet_widget = ShowWindowModalWidget(native_parent);
    base::scoped_nsobject<NSWindow> sheet_window(
        sheet_widget->GetNativeWindow().GetNativeNSWindow(),
        base::scoped_policy::RETAIN);
    EXPECT_TRUE([sheet_window isVisible]);

    WidgetChangeObserver widget_observer(sheet_widget);
    sheet_widget->Close();  // Asynchronous. Can't be called after -close.
    EXPECT_FALSE(widget_observer.widget_closed());
    [sheet_window close];
    EXPECT_TRUE(widget_observer.widget_closed());
    base::RunLoop().RunUntilIdle();

    // Pretend both tasks ran fully. Note that |sheet_window| serves as its own
    // |modalDelegate|.
    [base::mac::ObjCCastStrict<NativeWidgetMacNSWindow>(sheet_window)
        sheetDidEnd:sheet_window
         returnCode:NSModalResponseStop
        contextInfo:nullptr];
  }

  // Test another hypothetical: What if -sheetDidEnd: was invoked somehow
  // without going through [NSApp endSheet:] or -[NSWindow endSheet:].
  @autoreleasepool {
    Widget* sheet_widget = ShowWindowModalWidget(native_parent);
    NSWindow* sheet_window =
        sheet_widget->GetNativeWindow().GetNativeNSWindow();
    EXPECT_TRUE([sheet_window isVisible]);

    WidgetChangeObserver widget_observer(sheet_widget);
    sheet_widget->Close();

    [base::mac::ObjCCastStrict<NativeWidgetMacNSWindow>(sheet_window)
        sheetDidEnd:sheet_window
         returnCode:NSModalResponseStop
        contextInfo:nullptr];

    EXPECT_TRUE(widget_observer.widget_closed());
    // Here, the ViewsNSWindowDelegate should be dealloc'd.
  }
  base::RunLoop().RunUntilIdle();  // Run the task posted in Close().

  // Test -[NSWindow close] on the parent window.
  {
    Widget* sheet_widget = ShowWindowModalWidget(native_parent);
    EXPECT_TRUE(
        [sheet_widget->GetNativeWindow().GetNativeNSWindow() isVisible]);
    WidgetChangeObserver widget_observer(sheet_widget);

    [native_parent close];
    EXPECT_TRUE(widget_observer.widget_closed());
  }
}

// Exercise a scenario where the task posted in the asynchronous Close() could
// eventually complete on a destroyed NSWindowDelegate. Regression test for
// https://crbug.com/851376.
TEST_F(NativeWidgetMacTest, CloseWindowModalSheetWithoutSheetParent) {
  NSWindow* native_parent = MakeClosableTitledNativeParent();
  @autoreleasepool {
    Widget* sheet_widget = ShowWindowModalWidget(native_parent);
    NSWindow* sheet_window =
        sheet_widget->GetNativeWindow().GetNativeNSWindow();
    EXPECT_TRUE([sheet_window isVisible]);

    sheet_widget->Close();  // Asynchronous. Can't be called after -close.

    // Now there's a task to end the sheet in the message queue. But destroying
    // the NSWindowDelegate without _also_ posting a task that will _retain_ it
    // is hard. It _is_ possible for a -performSelector:afterDelay: already in
    // the queue to happen _after_ a PostTask posted now, but it's a very rare
    // occurrence. So to simulate it, we pretend the sheet isn't actually a
    // sheet by hiding its sheetParent. This avoids a task being posted that
    // would retain the delegate, but also puts |native_parent| into a weird
    // state.
    //
    // In fact, the "real" suspected trigger for this bug requires the PostTask
    // to still be posted, then run to completion, and to dealloc the delegate
    // it retains all before the -performSelector:afterDelay runs. That's the
    // theory anyway.
    //
    // In reality, it didn't seem possible for -sheetDidEnd: to be invoked twice
    // (AppKit would suppress it on subsequent calls to -[NSApp endSheet:] or
    // -[NSWindow endSheet:]), so if the PostTask were to run to completion, the
    // waiting -performSelector would always no- op. So this is actually testing
    // a hypothetical where the sheetParent may be somehow nil during teardown
    // (perhaps due to the parent window being further along in its teardown).
    EXPECT_TRUE([sheet_window sheetParent]);
    [sheet_window setValue:nil forKey:@"sheetParent"];
    EXPECT_FALSE([sheet_window sheetParent]);
    [sheet_window close];

    // To repro the crash, we need a dealloc to occur here on |sheet_widget|'s
    // NSWindowDelegate.
  }
  // Now there is still a task to end the sheet in the message queue, which
  // should not crash.
  base::RunLoop().RunUntilIdle();
  [native_parent close];
}

// Test calls to Widget::ReparentNativeView() that result in a no-op on Mac.
TEST_F(NativeWidgetMacTest, NoopReparentNativeView) {
  NSWindow* parent = MakeBorderlessNativeParent();
  Widget* dialog = views::DialogDelegate::CreateDialogWidget(
      new DialogDelegateView, nullptr, [parent contentView]);
  NativeWidgetMacNSWindowHost* window_host =
      NativeWidgetMacNSWindowHost::GetFromNativeWindow(
          dialog->GetNativeWindow());

  EXPECT_EQ(window_host->parent()->native_widget_mac()->GetNativeWindow(),
            parent);
  Widget::ReparentNativeView(dialog->GetNativeView(), [parent contentView]);
  EXPECT_EQ(window_host->parent()->native_widget_mac()->GetNativeWindow(),
            parent);

  [parent close];

  Widget* parent_widget = CreateTopLevelNativeWidget();
  parent = parent_widget->GetNativeWindow().GetNativeNSWindow();
  dialog = views::DialogDelegate::CreateDialogWidget(
      new DialogDelegateView, nullptr, [parent contentView]);
  window_host = NativeWidgetMacNSWindowHost::GetFromNativeWindow(
      dialog->GetNativeWindow());

  EXPECT_EQ(window_host->parent()->native_widget_mac()->GetNativeWindow(),
            parent);
  Widget::ReparentNativeView(dialog->GetNativeView(), [parent contentView]);
  EXPECT_EQ(window_host->parent()->native_widget_mac()->GetNativeWindow(),
            parent);

  parent_widget->CloseNow();
}

// Attaches a child window to |parent| that checks its parent's delegate is
// cleared when the child is destroyed. This assumes the child is destroyed via
// destruction of its parent.
class ParentCloseMonitor : public WidgetObserver {
 public:
  explicit ParentCloseMonitor(Widget* parent) {
    Widget* child = new Widget();
    child->AddObserver(this);
    Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
    init_params.parent = parent->GetNativeView();
    init_params.bounds = gfx::Rect(100, 100, 100, 100);
    init_params.native_widget =
        CreatePlatformNativeWidgetImpl(child, kStubCapture, nullptr);
    child->Init(std::move(init_params));
    child->Show();

    // NSWindow parent/child relationship should be established on Show() and
    // the parent should have a delegate. Retain the parent since it can't be
    // retrieved from the child while it is being destroyed.
    parent_nswindow_.reset(
        [[child->GetNativeWindow().GetNativeNSWindow() parentWindow] retain]);
    EXPECT_TRUE(parent_nswindow_);
    EXPECT_TRUE([parent_nswindow_ delegate]);
  }

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

  ~ParentCloseMonitor() override {
    EXPECT_TRUE(child_closed_);  // Otherwise the observer wasn't removed.
  }

  void OnWidgetDestroying(Widget* child) override {
    // Upon a parent-triggered close, the NSWindow relationship will still exist
    // (it's removed just after OnWidgetDestroying() returns). The parent should
    // still be open (children are always closed first), but not have a delegate
    // (since it is being torn down).
    EXPECT_TRUE([child->GetNativeWindow().GetNativeNSWindow() parentWindow]);
    EXPECT_TRUE([parent_nswindow_ isVisible]);
    EXPECT_FALSE([parent_nswindow_ delegate]);

    EXPECT_FALSE(child_closed_);
  }

  void OnWidgetDestroyed(Widget* child) override {
    EXPECT_FALSE([child->GetNativeWindow().GetNativeNSWindow() parentWindow]);
    EXPECT_TRUE([parent_nswindow_ isVisible]);
    EXPECT_FALSE([parent_nswindow_ delegate]);

    EXPECT_FALSE(child_closed_);
    child->RemoveObserver(this);
    child_closed_ = true;
  }

  bool child_closed() const { return child_closed_; }

 private:
  base::scoped_nsobject<NSWindow> parent_nswindow_;
  bool child_closed_ = false;
};

// Ensures when a parent window is destroyed, and triggers its child windows to
// be closed, that the child windows (via AppKit) do not attempt to call back
// into the parent, whilst it's in the process of being destroyed.
TEST_F(NativeWidgetMacTest, NoParentDelegateDuringTeardown) {
  // First test "normal" windows and AppKit close.
  {
    Widget* parent = CreateTopLevelPlatformWidget();
    parent->SetBounds(gfx::Rect(100, 100, 300, 200));
    parent->Show();
    ParentCloseMonitor monitor(parent);
    [parent->GetNativeWindow().GetNativeNSWindow() close];
    EXPECT_TRUE(monitor.child_closed());
  }

  // Test the Widget::CloseNow() flow.
  {
    Widget* parent = CreateTopLevelPlatformWidget();
    parent->SetBounds(gfx::Rect(100, 100, 300, 200));
    parent->Show();
    ParentCloseMonitor monitor(parent);
    parent->CloseNow();
    EXPECT_TRUE(monitor.child_closed());
  }

  // Test the WIDGET_OWNS_NATIVE_WIDGET flow.
  {
    std::unique_ptr<Widget> parent(new Widget);
    Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
    params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    params.bounds = gfx::Rect(100, 100, 300, 200);
    parent->Init(std::move(params));
    parent->Show();

    ParentCloseMonitor monitor(parent.get());
    parent.reset();
    EXPECT_TRUE(monitor.child_closed());
  }
}

// Tests Cocoa properties that should be given to particular widget types.
TEST_F(NativeWidgetMacTest, NativeProperties) {
  // Create a regular widget (TYPE_WINDOW).
  Widget* regular_widget = CreateTopLevelNativeWidget();
  EXPECT_TRUE([regular_widget->GetNativeWindow().GetNativeNSWindow()
                   canBecomeKeyWindow]);
  EXPECT_TRUE([regular_widget->GetNativeWindow().GetNativeNSWindow()
                   canBecomeMainWindow]);

  // Disabling activation should prevent key and main status.
  regular_widget->widget_delegate()->SetCanActivate(false);
  EXPECT_FALSE([regular_widget->GetNativeWindow().GetNativeNSWindow()
                    canBecomeKeyWindow]);
  EXPECT_FALSE([regular_widget->GetNativeWindow().GetNativeNSWindow()
                    canBecomeMainWindow]);

  // Create a dialog widget (also TYPE_WINDOW), but with a DialogDelegate.
  Widget* dialog_widget = views::DialogDelegate::CreateDialogWidget(
      MakeModalDialog(ui::MODAL_TYPE_CHILD), nullptr,
      regular_widget->GetNativeView());
  EXPECT_TRUE([dialog_widget->GetNativeWindow().GetNativeNSWindow()
                   canBecomeKeyWindow]);
  // Dialogs shouldn't take main status away from their parent.
  EXPECT_FALSE([dialog_widget->GetNativeWindow().GetNativeNSWindow()
                    canBecomeMainWindow]);

  // Create a bubble widget (with a parent): also shouldn't get main.
  BubbleDialogDelegateView* bubble_view = new SimpleBubbleView();
  bubble_view->set_parent_window(regular_widget->GetNativeView());
  Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_view);
  EXPECT_TRUE([bubble_widget->GetNativeWindow().GetNativeNSWindow()
                   canBecomeKeyWindow]);
  EXPECT_FALSE([bubble_widget->GetNativeWindow().GetNativeNSWindow()
                    canBecomeMainWindow]);
  EXPECT_EQ(NSWindowCollectionBehaviorTransient,
            [bubble_widget->GetNativeWindow().GetNativeNSWindow()
                    collectionBehavior] &
                NSWindowCollectionBehaviorTransient);

  regular_widget->CloseNow();
}

class CustomTitleWidgetDelegate : public WidgetDelegate {
 public:
  explicit CustomTitleWidgetDelegate(Widget* widget) : widget_(widget) {}

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

  void set_title(const std::u16string& title) { title_ = title; }
  void set_should_show_title(bool show) { should_show_title_ = show; }

  // WidgetDelegate:
  std::u16string GetWindowTitle() const override { return title_; }
  bool ShouldShowWindowTitle() const override { return should_show_title_; }
  Widget* GetWidget() override { return widget_; }
  const Widget* GetWidget() const override { return widget_; }

 private:
  raw_ptr<Widget> widget_;
  std::u16string title_;
  bool should_show_title_ = true;
};

// Test calls to invalidate the shadow when composited frames arrive.
TEST_F(NativeWidgetMacTest, InvalidateShadow) {
  NativeWidgetMacTestWindow* window;
  const gfx::Rect rect(0, 0, 100, 200);
  Widget::InitParams init_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  init_params.bounds = rect;
  Widget* widget = CreateWidgetWithTestWindow(std::move(init_params), &window);

  // Simulate the initial paint.
  BridgedNativeWidgetTestApi(window).SimulateFrameSwap(rect.size());

  // Default is an opaque window, so shadow doesn't need to be invalidated.
  EXPECT_EQ(0, [window invalidateShadowCount]);
  widget->CloseNow();

  init_params.opacity = Widget::InitParams::WindowOpacity::kTranslucent;
  widget = CreateWidgetWithTestWindow(std::move(init_params), &window);
  BridgedNativeWidgetTestApi test_api(window);

  // First paint on a translucent window needs to invalidate the shadow. Once.
  EXPECT_EQ(0, [window invalidateShadowCount]);
  test_api.SimulateFrameSwap(rect.size());
  EXPECT_EQ(1, [window invalidateShadowCount]);
  test_api.SimulateFrameSwap(rect.size());
  EXPECT_EQ(1, [window invalidateShadowCount]);

  // Resizing the window also needs to trigger a shadow invalidation.
  [window setContentSize:NSMakeSize(123, 456)];
  // A "late" frame swap at the old size should do nothing.
  test_api.SimulateFrameSwap(rect.size());
  EXPECT_EQ(1, [window invalidateShadowCount]);

  test_api.SimulateFrameSwap(gfx::Size(123, 456));
  EXPECT_EQ(2, [window invalidateShadowCount]);
  test_api.SimulateFrameSwap(gfx::Size(123, 456));
  EXPECT_EQ(2, [window invalidateShadowCount]);

  // Hiding the window does not require shadow invalidation.
  widget->Hide();
  test_api.SimulateFrameSwap(gfx::Size(123, 456));
  EXPECT_EQ(2, [window invalidateShadowCount]);

  // Showing a translucent window after hiding it, should trigger shadow
  // invalidation.
  widget->Show();
  test_api.SimulateFrameSwap(gfx::Size(123, 456));
  EXPECT_EQ(3, [window invalidateShadowCount]);

  widget->CloseNow();
}

// Test that the contentView opacity corresponds to the window type.
TEST_F(NativeWidgetMacTest, ContentOpacity) {
  NativeWidgetMacTestWindow* window;
  Widget::InitParams init_params =
      CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);

  EXPECT_EQ(init_params.opacity, Widget::InitParams::WindowOpacity::kInferred);
  Widget* widget = CreateWidgetWithTestWindow(std::move(init_params), &window);

  // Infer should default to opaque on Mac.
  EXPECT_TRUE([[window contentView] isOpaque]);
  widget->CloseNow();

  init_params.opacity = Widget::InitParams::WindowOpacity::kTranslucent;
  widget = CreateWidgetWithTestWindow(std::move(init_params), &window);
  EXPECT_FALSE([[window contentView] isOpaque]);
  widget->CloseNow();

  // Test opaque explicitly.
  init_params.opacity = Widget::InitParams::WindowOpacity::kOpaque;
  widget = CreateWidgetWithTestWindow(std::move(init_params), &window);
  EXPECT_TRUE([[window contentView] isOpaque]);
  widget->CloseNow();
}

// Test the expected result of GetWorkAreaBoundsInScreen().
TEST_F(NativeWidgetMacTest, GetWorkAreaBoundsInScreen) {
  Widget widget;
  Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
  params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;

  // This is relative to the top-left of the primary screen, so unless the bot's
  // display is smaller than 400x300, the window will be wholly contained there.
  params.bounds = gfx::Rect(100, 100, 300, 200);
  widget.Init(std::move(params));
  widget.Show();
  NSRect expected = [[[NSScreen screens] firstObject] visibleFrame];
  NSRect actual = gfx::ScreenRectToNSRect(widget.GetWorkAreaBoundsInScreen());
  EXPECT_FALSE(NSIsEmptyRect(actual));
  EXPECT_NSEQ(expected, actual);

  [widget.GetNativeWindow().GetNativeNSWindow() close];
  actual = gfx::ScreenRectToNSRect(widget.GetWorkAreaBoundsInScreen());
  EXPECT_TRUE(NSIsEmptyRect(actual));
}

// Test that Widget opacity can be changed.
TEST_F(NativeWidgetMacTest, ChangeOpacity) {
  Widget* widget = CreateTopLevelPlatformWidget();
  NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow();

  CGFloat old_opacity = [ns_window alphaValue];
  widget->SetOpacity(.7f);
  EXPECT_NE(old_opacity, [ns_window alphaValue]);
  EXPECT_DOUBLE_EQ(.7f, [ns_window alphaValue]);

  widget->CloseNow();
}

// Ensure traversing NSView focus correctly updates the views::FocusManager.
TEST_F(NativeWidgetMacTest, ChangeFocusOnChangeFirstResponder) {
  Widget* widget = CreateTopLevelPlatformWidget();
  widget->GetRootView()->SetFocusBehavior(View::FocusBehavior::ALWAYS);
  widget->Show();

  base::scoped_nsobject<NSView> child_view([[FocusableTestNSView alloc]
      initWithFrame:[widget->GetNativeView().GetNativeNSView() bounds]]);
  [widget->GetNativeView().GetNativeNSView() addSubview:child_view];
  EXPECT_TRUE([child_view acceptsFirstResponder]);
  EXPECT_TRUE(widget->GetRootView()->IsFocusable());

  FocusManager* manager = widget->GetFocusManager();
  manager->SetFocusedView(widget->GetRootView());
  EXPECT_EQ(manager->GetFocusedView(), widget->GetRootView());

  [widget->GetNativeWindow().GetNativeNSWindow() makeFirstResponder:child_view];
  EXPECT_FALSE(manager->GetFocusedView());

  [widget->GetNativeWindow().GetNativeNSWindow()
      makeFirstResponder:widget->GetNativeView().GetNativeNSView()];
  EXPECT_EQ(manager->GetFocusedView(), widget->GetRootView());

  widget->CloseNow();
}

// Test two kinds of widgets to re-parent.
TEST_F(NativeWidgetMacTest, ReparentNativeViewTypes) {
  std::unique_ptr<Widget> toplevel1(new Widget);
  Widget::InitParams toplevel_params =
      CreateParams(Widget::InitParams::TYPE_POPUP);
  toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  toplevel1->Init(std::move(toplevel_params));
  toplevel1->Show();

  std::unique_ptr<Widget> toplevel2(new Widget);
  toplevel2->Init(std::move(toplevel_params));
  toplevel2->Show();

  Widget* child = new Widget;
  Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL);
  child->Init(std::move(child_params));
  child->Show();

  Widget::ReparentNativeView(child->GetNativeView(),
                             toplevel1->GetNativeView());
  EXPECT_EQ([child->GetNativeWindow().GetNativeNSWindow() parentWindow],
            [toplevel1->GetNativeView().GetNativeNSView() window]);

  Widget::ReparentNativeView(child->GetNativeView(),
                             toplevel2->GetNativeView());
  EXPECT_EQ([child->GetNativeWindow().GetNativeNSWindow() parentWindow],
            [toplevel2->GetNativeView().GetNativeNSView() window]);

  Widget::ReparentNativeView(toplevel2->GetNativeView(),
                             toplevel1->GetNativeView());
  EXPECT_EQ([toplevel2->GetNativeWindow().GetNativeNSWindow() parentWindow],
            [toplevel1->GetNativeView().GetNativeNSView() window]);
}

// Test class for Full Keyboard Access related tests.
class NativeWidgetMacFullKeyboardAccessTest : public NativeWidgetMacTest {
 public:
  NativeWidgetMacFullKeyboardAccessTest() {}

 protected:
  // testing::Test:
  void SetUp() override {
    NativeWidgetMacTest::SetUp();

    widget_ = CreateTopLevelPlatformWidget();
    bridge_ = NativeWidgetMacNSWindowHost::GetFromNativeWindow(
                  widget_->GetNativeWindow())
                  ->GetInProcessNSWindowBridge();
    fake_full_keyboard_access_ =
        ui::test::ScopedFakeFullKeyboardAccess::GetInstance();
    DCHECK(fake_full_keyboard_access_);
    widget_->Show();
  }

  void TearDown() override {
    widget_->CloseNow();
    NativeWidgetMacTest::TearDown();
  }

  raw_ptr<Widget> widget_ = nullptr;
  raw_ptr<remote_cocoa::NativeWidgetNSWindowBridge> bridge_ = nullptr;
  raw_ptr<ui::test::ScopedFakeFullKeyboardAccess> fake_full_keyboard_access_ =
      nullptr;
};

// Ensure that calling SetSize doesn't change the origin.
TEST_F(NativeWidgetMacTest, SetSizeDoesntChangeOrigin) {
  Widget* parent = CreateTopLevelFramelessPlatformWidget();
  gfx::Rect parent_rect(100, 100, 400, 200);
  parent->SetBounds(parent_rect);

  // Popup children specify their bounds relative to their parent window.
  Widget* child_control = new Widget;
  gfx::Rect child_control_rect(50, 70, 300, 100);
  {
    Widget::InitParams params(Widget::InitParams::TYPE_CONTROL);
    params.parent = parent->GetNativeView();
    params.bounds = child_control_rect;
    child_control->Init(std::move(params));
    child_control->SetContentsView(new View);
  }

  // Window children specify their bounds in screen coords.
  Widget* child_window = new Widget;
  gfx::Rect child_window_rect(110, 90, 200, 50);
  {
    Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
    params.parent = parent->GetNativeView();
    params.bounds = child_window_rect;
    child_window->Init(std::move(params));
  }

  // Sanity-check the initial bounds. Note that the CONTROL should be offset by
  // the parent's origin.
  EXPECT_EQ(parent->GetWindowBoundsInScreen(), parent_rect);
  EXPECT_EQ(
      child_control->GetWindowBoundsInScreen(),
      gfx::Rect(child_control_rect.origin() + parent_rect.OffsetFromOrigin(),
                child_control_rect.size()));
  EXPECT_EQ(child_window->GetWindowBoundsInScreen(), child_window_rect);

  // Update the size, but not the origin.
  parent_rect.set_size(gfx::Size(505, 310));
  parent->SetSize(parent_rect.size());
  child_control_rect.set_size(gfx::Size(256, 102));
  child_control->SetSize(child_control_rect.size());
  child_window_rect.set_size(gfx::Size(172, 96));
  child_window->SetSize(child_window_rect.size());

  // Ensure that the origin didn't change.
  EXPECT_EQ(parent->GetWindowBoundsInScreen(), parent_rect);
  EXPECT_EQ(
      child_control->GetWindowBoundsInScreen(),
      gfx::Rect(child_control_rect.origin() + parent_rect.OffsetFromOrigin(),
                child_control_rect.size()));
  EXPECT_EQ(child_window->GetWindowBoundsInScreen(), child_window_rect);

  parent->CloseNow();
}

// Tests that tooltip widgets get the correct accessibilty role so that they're
// not announced as windows by VoiceOver.
TEST_F(NativeWidgetMacTest, AccessibilityRole) {
  {
    NativeWidgetMacTestWindow* window;

    Widget::InitParams init_params =
        CreateParams(Widget::InitParams::TYPE_WINDOW);
    Widget* widget =
        CreateWidgetWithTestWindow(std::move(init_params), &window);
    ASSERT_EQ([window accessibilityRole], NSAccessibilityWindowRole);
    widget->CloseNow();
  }
  {
    NativeWidgetMacTestWindow* window;

    Widget::InitParams init_params =
        CreateParams(Widget::InitParams::TYPE_TOOLTIP);
    Widget* widget =
        CreateWidgetWithTestWindow(std::move(init_params), &window);
    ASSERT_EQ([window accessibilityRole], NSAccessibilityHelpTagRole);
    widget->CloseNow();
  }
}

// Test that updateFullKeyboardAccess method on BridgedContentView correctly
// sets the keyboard accessibility mode on the associated focus manager.
TEST_F(NativeWidgetMacFullKeyboardAccessTest, FullKeyboardToggle) {
  EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());
  fake_full_keyboard_access_->set_full_keyboard_access_state(false);
  [bridge_->ns_view() updateFullKeyboardAccess];
  EXPECT_FALSE(widget_->GetFocusManager()->keyboard_accessible());
  fake_full_keyboard_access_->set_full_keyboard_access_state(true);
  [bridge_->ns_view() updateFullKeyboardAccess];
  EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());
}

// Test that a Widget's associated FocusManager is initialized with the correct
// keyboard accessibility value.
TEST_F(NativeWidgetMacFullKeyboardAccessTest, Initialization) {
  EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());

  fake_full_keyboard_access_->set_full_keyboard_access_state(false);
  Widget* widget2 = CreateTopLevelPlatformWidget();
  EXPECT_FALSE(widget2->GetFocusManager()->keyboard_accessible());
  widget2->CloseNow();
}

// Test that the correct keyboard accessibility mode is set when the window
// becomes active.
TEST_F(NativeWidgetMacFullKeyboardAccessTest, Activation) {
  EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());

  widget_->Hide();
  fake_full_keyboard_access_->set_full_keyboard_access_state(false);
  // [bridge_->ns_view() updateFullKeyboardAccess] is not explicitly called
  // since we may not receive full keyboard access toggle notifications when our
  // application is inactive.

  widget_->Show();
  EXPECT_FALSE(widget_->GetFocusManager()->keyboard_accessible());

  widget_->Hide();
  fake_full_keyboard_access_->set_full_keyboard_access_state(true);

  widget_->Show();
  EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());
}

class NativeWidgetMacViewsOrderTest : public WidgetTest {
 public:
  NativeWidgetMacViewsOrderTest() {}

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

 protected:
  class NativeHostHolder {
   public:
    static std::unique_ptr<NativeHostHolder> CreateAndAddToParent(
        View* parent) {
      std::unique_ptr<NativeHostHolder> holder(new NativeHostHolder(
          parent->AddChildView(std::make_unique<NativeViewHost>())));
      holder->host()->Attach(holder->view());
      return holder;
    }

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

    NSView* view() const { return view_.get(); }
    NativeViewHost* host() const { return host_; }

   private:
    NativeHostHolder(NativeViewHost* host)
        : host_(host), view_([[NSView alloc] init]) {}

    const raw_ptr<NativeViewHost> host_;
    base::scoped_nsobject<NSView> view_;
  };

  // testing::Test:
  void SetUp() override {
    WidgetTest::SetUp();

    widget_ = CreateTopLevelPlatformWidget();

    starting_subviews_.reset(
        [[widget_->GetNativeView().GetNativeNSView() subviews] copy]);

    native_host_parent_ = new View();
    widget_->GetContentsView()->AddChildView(native_host_parent_.get());

    const size_t kNativeViewCount = 3;
    for (size_t i = 0; i < kNativeViewCount; ++i) {
      hosts_.push_back(
          NativeHostHolder::CreateAndAddToParent(native_host_parent_));
    }
    EXPECT_EQ(kNativeViewCount, native_host_parent_->children().size());
    EXPECT_NSEQ([widget_->GetNativeView().GetNativeNSView() subviews],
                ([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
                  hosts_[0]->view(), hosts_[1]->view(), hosts_[2]->view()
                ]]));
  }

  void TearDown() override {
    widget_->CloseNow();
    hosts_.clear();
    WidgetTest::TearDown();
  }

  NSView* GetContentNativeView() {
    return widget_->GetNativeView().GetNativeNSView();
  }

  NSArray<NSView*>* GetStartingSubviews() { return starting_subviews_; }

  raw_ptr<Widget> widget_ = nullptr;
  raw_ptr<View> native_host_parent_ = nullptr;
  std::vector<std::unique_ptr<NativeHostHolder>> hosts_;
  base::scoped_nsobject<NSArray<NSView*>> starting_subviews_;
};

// Test that NativeViewHost::Attach()/Detach() method saves the NativeView
// z-order.
TEST_F(NativeWidgetMacViewsOrderTest, NativeViewAttached) {
  NativeHostHolder* second_host = hosts_[1].get();
  second_host->host()->Detach();
  EXPECT_NSEQ([GetContentNativeView() subviews],
              ([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
                hosts_[0]->view(), hosts_[2]->view()
              ]]));

  second_host->host()->Attach(second_host->view());
  EXPECT_NSEQ([GetContentNativeView() subviews],
              ([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
                hosts_[0]->view(), hosts_[1]->view(), hosts_[2]->view()
              ]]));
}

// Tests that NativeViews order changes according to views::View hierarchy.
TEST_F(NativeWidgetMacViewsOrderTest, ReorderViews) {
  native_host_parent_->ReorderChildView(hosts_[2]->host(), 1);
  EXPECT_NSEQ([GetContentNativeView() subviews],
              ([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
                hosts_[0]->view(), hosts_[2]->view(), hosts_[1]->view()
              ]]));

  native_host_parent_->RemoveChildView(hosts_[2]->host());
  EXPECT_NSEQ([GetContentNativeView() subviews],
              ([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
                hosts_[0]->view(), hosts_[1]->view()
              ]]));

  View* new_parent = new View();
  native_host_parent_->RemoveChildView(hosts_[1]->host());
  native_host_parent_->AddChildView(new_parent);
  new_parent->AddChildView(hosts_[1]->host());
  new_parent->AddChildView(hosts_[2]->host());
  EXPECT_NSEQ([GetContentNativeView() subviews],
              ([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
                hosts_[0]->view(), hosts_[1]->view(), hosts_[2]->view()
              ]]));

  native_host_parent_->ReorderChildView(new_parent, 0);
  EXPECT_NSEQ([GetContentNativeView() subviews],
              ([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
                hosts_[1]->view(), hosts_[2]->view(), hosts_[0]->view()
              ]]));
}

// Test that unassociated native views stay on top after reordering.
TEST_F(NativeWidgetMacViewsOrderTest, UnassociatedViewsIsAbove) {
  base::scoped_nsobject<NSView> child_view([[NSView alloc] init]);
  [GetContentNativeView() addSubview:child_view];
  EXPECT_NSEQ(
      [GetContentNativeView() subviews],
      ([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
        hosts_[0]->view(), hosts_[1]->view(), hosts_[2]->view(), child_view
      ]]));

  native_host_parent_->ReorderChildView(hosts_[2]->host(), 1);
  EXPECT_NSEQ(
      [GetContentNativeView() subviews],
      ([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
        hosts_[0]->view(), hosts_[2]->view(), hosts_[1]->view(), child_view
      ]]));
}

namespace {

// Returns an array of NSTouchBarItemIdentifier (i.e. NSString), extracted from
// the principal of |view|'s touch bar, which must be a NSGroupTouchBarItem.
// Also verifies that the touch bar's delegate returns non-nil for all items.
NSArray* ExtractTouchBarGroupIdentifiers(NSView* view) {
  NSArray* result = nil;
  NSTouchBar* touch_bar = [view touchBar];
  NSTouchBarItemIdentifier principal = [touch_bar principalItemIdentifier];
  EXPECT_TRUE(principal);
  NSGroupTouchBarItem* group = base::mac::ObjCCastStrict<NSGroupTouchBarItem>(
      [[touch_bar delegate] touchBar:touch_bar
               makeItemForIdentifier:principal]);
  EXPECT_TRUE(group);
  NSTouchBar* nested_touch_bar = [group groupTouchBar];
  result = [nested_touch_bar itemIdentifiers];

  for (NSTouchBarItemIdentifier item in result) {
    EXPECT_TRUE([[touch_bar delegate] touchBar:nested_touch_bar
                         makeItemForIdentifier:item]);
  }

  return result;
}

}  // namespace

// Test TouchBar integration.
TEST_F(NativeWidgetMacTest, TouchBar) {
  DialogDelegate* delegate = MakeModalDialog(ui::MODAL_TYPE_NONE);
  views::DialogDelegate::CreateDialogWidget(delegate, nullptr, nullptr);
  NSView* content =
      [delegate->GetWidget()->GetNativeWindow().GetNativeNSWindow()
              contentView];

  // Constants from bridged_content_view_touch_bar.mm.
  NSString* const kTouchBarOKId = @"com.google.chrome-OK";
  NSString* const kTouchBarCancelId = @"com.google.chrome-CANCEL";

  EXPECT_TRUE(content);
  EXPECT_TRUE(delegate->GetOkButton());
  EXPECT_TRUE(delegate->GetCancelButton());

  NSTouchBar* touch_bar = [content touchBar];
  EXPECT_TRUE([touch_bar delegate]);
  EXPECT_TRUE([[touch_bar delegate] touchBar:touch_bar
                       makeItemForIdentifier:kTouchBarOKId]);
  EXPECT_TRUE([[touch_bar delegate] touchBar:touch_bar
                       makeItemForIdentifier:kTouchBarCancelId]);

  NSString* principal = [touch_bar principalItemIdentifier];
  EXPECT_NSEQ(@"com.google.chrome-DIALOG-BUTTONS-GROUP", principal);
  EXPECT_NSEQ((@[ kTouchBarCancelId, kTouchBarOKId ]),
              ExtractTouchBarGroupIdentifiers(content));

  // Ensure the touchBar is recreated by comparing pointers.

  // Remove the cancel button.
  delegate->SetButtons(ui::DIALOG_BUTTON_OK);
  delegate->DialogModelChanged();
  EXPECT_TRUE(delegate->GetOkButton());
  EXPECT_FALSE(delegate->GetCancelButton());

  NSTouchBar* new_touch_bar = [content touchBar];
  EXPECT_NSNE(touch_bar, new_touch_bar);
  EXPECT_NSEQ((@[ kTouchBarOKId ]), ExtractTouchBarGroupIdentifiers(content));

  delegate->GetWidget()->CloseNow();
}

TEST_F(NativeWidgetMacTest, InitCallback) {
  NativeWidget* observed_native_widget = nullptr;
  const auto callback = base::BindRepeating(
      [](NativeWidget** observed, NativeWidgetMac* native_widget) {
        *observed = native_widget;
      },
      &observed_native_widget);
  NativeWidgetMac::SetInitNativeWidgetCallback(callback);

  Widget* widget_a = CreateTopLevelPlatformWidget();
  EXPECT_EQ(observed_native_widget, widget_a->native_widget());
  Widget* widget_b = CreateTopLevelPlatformWidget();
  EXPECT_EQ(observed_native_widget, widget_b->native_widget());

  auto empty = base::RepeatingCallback<void(NativeWidgetMac*)>();
  DCHECK(empty.is_null());
  NativeWidgetMac::SetInitNativeWidgetCallback(empty);
  observed_native_widget = nullptr;
  Widget* widget_c = CreateTopLevelPlatformWidget();
  // The original callback from above should no longer be firing.
  EXPECT_EQ(observed_native_widget, nullptr);

  widget_a->CloseNow();
  widget_b->CloseNow();
  widget_c->CloseNow();
}

TEST_F(NativeWidgetMacTest, FocusManagerChangeOnReparentNativeView) {
  WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
  Widget* child = CreateChildPlatformWidget(toplevel->GetNativeView());
  WidgetAutoclosePtr target_toplevel(CreateTopLevelPlatformWidget());
  EXPECT_EQ(child->GetFocusManager(), toplevel->GetFocusManager());
  EXPECT_NE(child->GetFocusManager(), target_toplevel->GetFocusManager());
  NativeWidgetMac* child_native_widget =
      static_cast<NativeWidgetMac*>(child->native_widget());
  EXPECT_EQ(GetFocusManager(child_native_widget), child->GetFocusManager());

  Widget::ReparentNativeView(child->GetNativeView(),
                             target_toplevel->GetNativeView());
  EXPECT_EQ(child->GetFocusManager(), target_toplevel->GetFocusManager());
  EXPECT_NE(child->GetFocusManager(), toplevel->GetFocusManager());
  EXPECT_EQ(GetFocusManager(child_native_widget), child->GetFocusManager());
}

}  // namespace test
}  // namespace views

@implementation TestStopAnimationWaiter
- (void)setWindowStateForEnd {
  views::test::ScopedSwizzleWaiter::OriginalSetWindowStateForEnd(self, _cmd);
}
@end

@implementation NativeWidgetMacTestWindow

@synthesize invalidateShadowCount = _invalidateShadowCount;
@synthesize fakeOnInactiveSpace = _fakeOnInactiveSpace;
@synthesize deallocFlag = _deallocFlag;

- (void)dealloc {
  if (_deallocFlag) {
    DCHECK(!*_deallocFlag);
    *_deallocFlag = true;
  }
  [super dealloc];
}

- (void)invalidateShadow {
  ++_invalidateShadowCount;
  [super invalidateShadow];
}

- (BOOL)isOnActiveSpace {
  return !_fakeOnInactiveSpace;
}

@end

@implementation MockBridgedView

@synthesize drawRectCount = _drawRectCount;
@synthesize lastDirtyRect = _lastDirtyRect;

- (void)drawRect:(NSRect)dirtyRect {
  ++_drawRectCount;
  _lastDirtyRect = dirtyRect;
}

@end

@implementation FocusableTestNSView
- (BOOL)acceptsFirstResponder {
  return YES;
}
@end