File: wayland_window_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (5385 lines) | stat: -rw-r--r-- 234,680 bytes parent folder | download | duplicates (2)
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
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.


#include "ui/ozone/platform/wayland/host/wayland_window.h"

#include <cursor-shape-v1-client-protocol.h>
#include <linux/input.h>
#include <wayland-server-core.h>
#include <xdg-shell-server-protocol.h>

#include <array>
#include <cstddef>
#include <memory>
#include <utility>
#include <vector>

#include "base/containers/contains.h"
#include "base/environment.h"
#include "base/files/file_util.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/nix/xdg_util.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_command_line.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/base/hit_test.h"
#include "ui/base/owned_window_anchor.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/ui_base_types.h"
#include "ui/display/display.h"
#include "ui/display/scoped_display_for_new_windows.h"
#include "ui/display/test/test_screen.h"
#include "ui/display/types/display_constants.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/overlay_plane_data.h"
#include "ui/gfx/overlay_priority_hint.h"
#include "ui/gfx/overlay_transform.h"
#include "ui/ozone/common/bitmap_cursor.h"
#include "ui/ozone/common/features.h"
#include "ui/ozone/platform/wayland/common/wayland_overlay_config.h"
#include "ui/ozone/platform/wayland/common/wayland_util.h"
#include "ui/ozone/platform/wayland/host/wayland_async_cursor.h"
#include "ui/ozone/platform/wayland/host/wayland_buffer_handle.h"
#include "ui/ozone/platform/wayland/host/wayland_buffer_manager_host.h"
#include "ui/ozone/platform/wayland/host/wayland_cursor_position.h"
#include "ui/ozone/platform/wayland/host/wayland_cursor_shape.h"
#include "ui/ozone/platform/wayland/host/wayland_event_source.h"
#include "ui/ozone/platform/wayland/host/wayland_output.h"
#include "ui/ozone/platform/wayland/host/wayland_output_manager.h"
#include "ui/ozone/platform/wayland/host/wayland_seat.h"
#include "ui/ozone/platform/wayland/host/wayland_subsurface.h"
#include "ui/ozone/platform/wayland/host/wayland_toplevel_window.h"
#include "ui/ozone/platform/wayland/mojom/wayland_overlay_config.mojom.h"
#include "ui/ozone/platform/wayland/test/mock_pointer.h"
#include "ui/ozone/platform/wayland/test/mock_surface.h"
#include "ui/ozone/platform/wayland/test/mock_wayland_platform_window_delegate.h"
#include "ui/ozone/platform/wayland/test/mock_xdg_surface.h"
#include "ui/ozone/platform/wayland/test/scoped_wl_array.h"
#include "ui/ozone/platform/wayland/test/test_keyboard.h"
#include "ui/ozone/platform/wayland/test/test_output.h"
#include "ui/ozone/platform/wayland/test/test_region.h"
#include "ui/ozone/platform/wayland/test/test_touch.h"
#include "ui/ozone/platform/wayland/test/test_wayland_server_thread.h"
#include "ui/ozone/platform/wayland/test/wayland_connection_test_api.h"
#include "ui/ozone/platform/wayland/test/wayland_test.h"
#include "ui/ozone/public/ozone_switches.h"
#include "ui/platform_window/platform_window.h"
#include "ui/platform_window/platform_window_delegate.h"
#include "ui/platform_window/platform_window_init_properties.h"
#include "ui/platform_window/wm/wm_move_resize_handler.h"

using ::testing::_;
using ::testing::DoAll;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::InvokeWithoutArgs;
using ::testing::Mock;
using ::testing::Return;
using ::testing::SaveArg;
using ::testing::StrEq;
using ::testing::Values;

namespace ui {

namespace {

constexpr float kDefaultCursorScale = 1.f;

struct PopupPosition {
  gfx::Rect anchor_rect;
  gfx::Size size;
  uint32_t anchor = 0;
  uint32_t gravity = 0;
  uint32_t constraint_adjustment = 0;
};

base::ScopedFD MakeFD() {
  base::FilePath temp_path;
  EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
  auto file =
      base::File(temp_path, base::File::FLAG_READ | base::File::FLAG_WRITE |
                                base::File::FLAG_CREATE_ALWAYS);
  return base::ScopedFD(file.TakePlatformFile());
}

// Must happen on the server thread.
wl::TestXdgPopup* GetTestXdgPopupByWindow(wl::TestWaylandServerThread* server,
                                          const uint32_t surface_id) {
  DCHECK(server->task_runner()->BelongsToCurrentThread());
  wl::MockSurface* mock_surface =
      server->GetObject<wl::MockSurface>(surface_id);
  if (mock_surface) {
    auto* mock_xdg_surface = mock_surface->xdg_surface();
    if (mock_xdg_surface) {
      return mock_xdg_surface->xdg_popup();
    }
  }
  return nullptr;
}

void AddStateToWlArray(uint32_t state, wl_array* states) {
  *static_cast<uint32_t*>(wl_array_add(states, sizeof state)) = state;
}

wl::ScopedWlArray InitializeWlArrayWithActivatedState() {
  return wl::ScopedWlArray({XDG_TOPLEVEL_STATE_ACTIVATED});
}

wl::ScopedWlArray MakeStateArray(const std::vector<int32_t> states) {
  return wl::ScopedWlArray(states);
}

class MockCursorShape : public WaylandCursorShape {
 public:
  MockCursorShape() : WaylandCursorShape(nullptr, nullptr) {}
  MockCursorShape(const MockCursorShape&) = delete;
  MockCursorShape& operator=(const MockCursorShape&) = delete;
  ~MockCursorShape() override = default;

  MOCK_METHOD(void, SetCursorShape, (uint32_t), (override));
};

using BoundsChange = PlatformWindowDelegate::BoundsChange;

constexpr BoundsChange kDefaultBoundsChange{false};

scoped_refptr<PlatformCursor> AsPlatformCursor(
    scoped_refptr<BitmapCursor> bitmap_cursor) {
  return base::MakeRefCounted<WaylandAsyncCursor>(bitmap_cursor);
}

using DispatchEventCallback = base::OnceCallback<void(Event*)>;

class TestWaylandWindowDelegate : public PlatformWindowDelegate {
 public:
  void SetDispatchEventCallback(DispatchEventCallback callback) {
    callback_ = std::move(callback);
  }

  // ui::PlatformWindowDelegate implementation.
  void OnBoundsChanged(const BoundsChange& change) override {}
  void OnDamageRect(const gfx::Rect& damaged_region) override {}
  void OnCloseRequest() override {}
  void OnClosed() override {}
  void OnWindowStateChanged(ui::PlatformWindowState old_state,
                            ui::PlatformWindowState new_state) override {}
  void OnLostCapture() override {}
  void OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget) override {}
  void OnWillDestroyAcceleratedWidget() override {}
  void OnAcceleratedWidgetDestroyed() override {}
  void OnActivationChanged(bool active) override {}
  void OnMouseEnter() override {}
  void DispatchEvent(Event* event) override { std::move(callback_).Run(event); }

 private:
  DispatchEventCallback callback_;
};

}  // namespace

class WaylandWindowTest : public WaylandTest {
 public:
  WaylandWindowTest()
      : test_mouse_event_(EventType::kMousePressed,
                          gfx::Point(10, 15),
                          gfx::Point(10, 15),
                          ui::EventTimeStampFromSeconds(123456),
                          EF_LEFT_MOUSE_BUTTON | EF_RIGHT_MOUSE_BUTTON,
                          EF_LEFT_MOUSE_BUTTON) {}

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

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

    buffer_id_gen_ = 0u;
    frame_id_gen_ = 0u;
    surface_id_ = window_->root_surface()->get_surface_id();
    PostToServerAndWait(
        [id = surface_id_](wl::TestWaylandServerThread* server) {
          auto* surface = server->GetObject<wl::MockSurface>(id);
          ASSERT_TRUE(surface);
          ASSERT_TRUE(surface->xdg_surface());
          ASSERT_TRUE(surface->xdg_surface()->xdg_toplevel());
        });
  }

 protected:
  void SendConfigureEventPopup(WaylandWindow* menu_window,
                               const gfx::Rect& bounds) {
    const uint32_t surface_id = menu_window->root_surface()->get_surface_id();
    PostToServerAndWait(
        [surface_id, bounds](wl::TestWaylandServerThread* server) {
          auto* popup = GetTestXdgPopupByWindow(server, surface_id);
          ASSERT_TRUE(popup);
          xdg_popup_send_configure(popup->resource(), bounds.x(), bounds.y(),
                                   bounds.width(), bounds.height());
        });
  }

  // Simulates up to date buffers coming through viz and being latched.
  // Call this after configures or anything where you want wayland or latched
  // state to update.
  void AdvanceFrameToCurrent(
      WaylandWindow* window,
      const MockWaylandPlatformWindowDelegate& delegate) {
    AdvanceFrameToGivenVizSequenceId(window, delegate, delegate.viz_seq());
  }

  void AdvanceFrameToGivenVizSequenceId(
      WaylandWindow* window,
      const MockWaylandPlatformWindowDelegate& delegate,
      int64_t viz_seq) {
    WaylandTestBase::SyncDisplay();
    window->OnSequencePoint(viz_seq);
    window->root_surface()->ApplyPendingState();
  }

  void InitializeWithSupportedHitTestValues(std::vector<int>* hit_tests) {
    hit_tests->push_back(static_cast<int>(HTBOTTOM));
    hit_tests->push_back(static_cast<int>(HTBOTTOMLEFT));
    hit_tests->push_back(static_cast<int>(HTBOTTOMRIGHT));
    hit_tests->push_back(static_cast<int>(HTLEFT));
    hit_tests->push_back(static_cast<int>(HTRIGHT));
    hit_tests->push_back(static_cast<int>(HTTOP));
    hit_tests->push_back(static_cast<int>(HTTOPLEFT));
    hit_tests->push_back(static_cast<int>(HTTOPRIGHT));
  }

  MockCursorShape* InstallMockCursorShape() {
    auto mock_cursor_shapes = std::make_unique<MockCursorShape>();
    MockCursorShape* mock_cursor_shapes_ptr = mock_cursor_shapes.get();
    WaylandConnectionTestApi test_api(connection_.get());
    test_api.SetCursorShape(std::move(mock_cursor_shapes));
    return mock_cursor_shapes_ptr;
  }

  // Verifies and clearis expectations for a toplevel window associated with
  // `delegate` and whose root surface id is `surface_id`. Both client and
  // server-side expectations are checked, including xdg-toplevel as well as
  // wp-viewport.
  void VerifyAndClearExpectations(MockWaylandPlatformWindowDelegate& delegate,
                                  uint32_t surface_id) {
    // Client side verification.
    Mock::VerifyAndClearExpectations(&delegate);

    // Server side verification.
    // `PostToServerAndWait` runs `RoundTripQueue` to wait for the queue to be
    // empty. It makes sure that `VerifyAndClearExpectations` below will run
    // after all requests had been handled.
    PostToServerAndWait([id = surface_id](wl::TestWaylandServerThread* server) {
      wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
      ASSERT_TRUE(mock_surface);
      wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();

      // Verify the expectations for mock objects.
      Mock::VerifyAndClearExpectations(mock_surface);
      Mock::VerifyAndClearExpectations(xdg_surface);
      Mock::VerifyAndClearExpectations(xdg_surface->xdg_toplevel());
      Mock::VerifyAndClearExpectations(mock_surface->viewport());
    });
  }

  // Verifies expectations for `window_` on both client and server. It does not
  // handle all expectations, so more calls to Mock::VerifyAndClearExpectations
  // for other associated mock objects not listed in this method might be
  // needed.
  //
  // Note: It is not required to call this at the end of the test to verify the
  // expectations.
  void VerifyAndClearExpectations() {
    VerifyAndClearExpectations(delegate_, surface_id_);
  }

  void VerifyXdgPopupPosition(WaylandWindow* menu_window,
                              const PopupPosition& position) {
    const uint32_t surface_id = menu_window->root_surface()->get_surface_id();
    PostToServerAndWait([surface_id,
                         position](wl::TestWaylandServerThread* server) {
      auto* popup = GetTestXdgPopupByWindow(server, surface_id);
      ASSERT_TRUE(popup);

      EXPECT_EQ(popup->anchor_rect(), position.anchor_rect);
      EXPECT_EQ(popup->size(), position.size);
      EXPECT_EQ(popup->anchor(), position.anchor);
      EXPECT_EQ(popup->gravity(), position.gravity);
      EXPECT_EQ(popup->constraint_adjustment(), position.constraint_adjustment);
    });
  }

  void VerifyCanDispatchMouseEvents(
      WaylandWindow* dispatching_window,
      const std::vector<WaylandWindow*>& non_dispatching_windows) {
    auto* pointer_focused_window =
        connection_->window_manager()->GetCurrentPointerFocusedWindow();

    ASSERT_TRUE(pointer_focused_window);
    Event::DispatcherApi(&test_mouse_event_).set_target(pointer_focused_window);
    EXPECT_TRUE(dispatching_window->CanDispatchEvent(&test_mouse_event_));
    for (auto* window : non_dispatching_windows) {
      EXPECT_FALSE(window->CanDispatchEvent(&test_mouse_event_));
    }
  }

  void VerifyCanDispatchTouchEvents(
      const std::vector<WaylandWindow*>& dispatching_windows,
      const std::vector<WaylandWindow*>& non_dispatching_windows) {
    ASSERT_LT(dispatching_windows.size(), 2u);
    auto* touch_focused_window =
        connection_->window_manager()->GetCurrentTouchFocusedWindow();
    // There must be focused window to dispatch.
    if (dispatching_windows.size() == 0) {
      EXPECT_FALSE(touch_focused_window);
    }

    PointerDetails pointer_details(EventPointerType::kTouch, 1);
    TouchEvent test_touch_event(EventType::kTouchPressed, {1, 1},
                                base::TimeTicks(), pointer_details);
    if (touch_focused_window) {
      Event::DispatcherApi(&test_touch_event).set_target(touch_focused_window);
    }
    for (auto* window : dispatching_windows) {
      EXPECT_TRUE(window->CanDispatchEvent(&test_touch_event));
    }
    for (auto* window : non_dispatching_windows) {
      // Make sure that the CanDispatcEvent works on release build.
#if DCHECK_IS_ON()
      // Disable DCHECK when enabled.
      window->disable_null_target_dcheck_for_testing();
#endif
      EXPECT_FALSE(window->CanDispatchEvent(&test_touch_event));
    }
  }

  void VerifyCanDispatchKeyEvents(
      const std::vector<WaylandWindow*>& dispatching_windows,
      const std::vector<WaylandWindow*>& non_dispatching_windows) {
    ASSERT_LT(dispatching_windows.size(), 2u);
    auto* keyboard_focused_window =
        connection_->window_manager()->GetCurrentKeyboardFocusedWindow();

    // There must be focused window to dispatch.
    if (dispatching_windows.size() == 0) {
      EXPECT_FALSE(keyboard_focused_window);
    }

    KeyEvent test_key_event(EventType::kKeyPressed, VKEY_0, 0);
    if (keyboard_focused_window) {
      Event::DispatcherApi(&test_key_event).set_target(keyboard_focused_window);
    }

    for (auto* window : dispatching_windows) {
      EXPECT_TRUE(window->CanDispatchEvent(&test_key_event));
    }
    for (auto* window : non_dispatching_windows) {
      // Make sure that the CanDispatcEvent works on release build.
#if DCHECK_IS_ON()
      // Disable DCHECK when enabled.
      window->disable_null_target_dcheck_for_testing();
#endif
      EXPECT_FALSE(window->CanDispatchEvent(&test_key_event));
    }
  }

  uint32_t GetObjIdForOutput(WaylandOutput::Id id) {
    auto* output_manager = connection_->wayland_output_manager();
    auto* wayland_output = output_manager->GetOutput(id);
    if (wayland_output) {
      return wl_proxy_get_id(
          reinterpret_cast<wl_proxy*>(wayland_output->get_output()));
    }
    return 0;
  }

  WaylandBufferHandle* CreateTestShmBuffer(const gfx::Size& buffer_size,
                                           WaylandSurface* surface) {
    CHECK(!buffer_size.IsEmpty());
    CHECK(surface);
    CHECK(connection_->buffer_manager_host());

    auto interface_ptr = connection_->buffer_manager_host()->BindInterface();
    buffer_manager_gpu_->Initialize(std::move(interface_ptr), {},
                                    /*supports_dma_buf=*/false,
                                    /*supports_viewporter=*/true,
                                    /*supports_acquire_fence=*/false,
                                    /*supports_overlays=*/true,
                                    /*supports_single_pixel_buffer=*/true);

    const uint32_t buffer_id = ++buffer_id_gen_;
    auto length = buffer_size.width() * buffer_size.height() * 4;
    buffer_manager_gpu_->CreateShmBasedBuffer(MakeFD(), length, buffer_size,
                                              buffer_id);
    task_environment_.RunUntilIdle();
    return connection_->buffer_manager_host()->EnsureBufferHandle(surface,
                                                                  buffer_id);
  }

  // Emulates a new frame being received from Viz being processed by `window`s
  // frame manager.
  void CreateBufferAndPresentAsNewFrame(
      WaylandWindow* window,
      const MockWaylandPlatformWindowDelegate& delegate,
      const gfx::Size& buffer_size,
      float buffer_scale) {
    CHECK(window);
    CHECK(window->root_surface());
    auto* buffer = CreateTestShmBuffer(buffer_size, window->root_surface());
    ASSERT_TRUE(buffer);
    window->root_surface()->AttachBuffer(buffer);

    const uint32_t frame_id = ++frame_id_gen_;
    wl::WaylandOverlayConfig root_config;
    root_config.buffer_id = buffer->id();
    root_config.bounds_rect = gfx::RectF(buffer_size);
    root_config.damage_region = gfx::Rect(buffer_size);
    root_config.surface_scale_factor = buffer_scale;
    std::vector<wl::WaylandOverlayConfig> configs;
    configs.push_back(std::move(root_config));
    window->CommitOverlays(frame_id, gfx::FrameData(delegate.viz_seq()),
                           configs);
  }

  // Surface id of |window|'s the root surface. Stored for convenience.
  uint32_t surface_id_ = 0u;

  MouseEvent test_mouse_event_;

  // Incremental id used to generate buffer IDs.
  uint32_t buffer_id_gen_ = 0u;
  // Incremental id used to generate frame IDs.
  uint32_t frame_id_gen_ = 0u;
};

// Regression test for crbug.com/1433175
TEST_P(WaylandWindowTest, Shutdown) {
  window_->PrepareForShutdown();
  window_->OnDragSessionClose(mojom::DragOperation::kNone);
}

TEST_P(WaylandWindowTest, SetTitle) {
  window_->SetTitle(u"hello");
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    auto* surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(surface);
    EXPECT_EQ("hello", surface->xdg_surface()->xdg_toplevel()->title());
  });
}

TEST_P(WaylandWindowTest, OnSequencePointConfiguresWaylandWindow) {
  constexpr gfx::Rect kNormalBounds{500, 300};

  // Configure event makes Wayland update bounds, but does not change toplevel
  // input region, opaque region or window geometry immediately. Such actions
  // are postponed to OnSequencePoint();
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));

  PostToServerAndWait([id = surface_id_, bounds = kNormalBounds](
                          wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())))
        .Times(0);
    EXPECT_CALL(*xdg_surface, AckConfigure(_)).Times(0);
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_)).Times(0);
    EXPECT_CALL(*mock_surface, SetInputRegion(_)).Times(0);
  });

  auto state = InitializeWlArrayWithActivatedState();
  constexpr uint32_t kConfigureSerial = 2u;
  SendConfigureEvent(surface_id_, kNormalBounds.size(), state,
                     kConfigureSerial);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_, bounds = kNormalBounds](
                          wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())));
    EXPECT_CALL(*xdg_surface, AckConfigure(kConfigureSerial));
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_));
    EXPECT_CALL(*mock_surface, SetInputRegion(_));
  });
  AdvanceFrameToCurrent(window_.get(), delegate_);
}

// WaylandSurface state changes are sent to wayland compositor when
// ApplyPendingState() is called.
TEST_P(WaylandWindowTest, ApplyPendingStatesAndCommit) {
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    // Set*() calls do not send wl_surface requests.
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_)).Times(0);
    EXPECT_CALL(*mock_surface, SetInputRegion(_)).Times(0);
    EXPECT_CALL(*mock_surface, SetBufferScale(2)).Times(0);
  });

  std::vector<gfx::Rect> region_px = {gfx::Rect{500, 300}};
  window_->root_surface()->set_opaque_region(region_px);
  window_->root_surface()->set_input_region(region_px);
  window_->root_surface()->set_surface_buffer_scale(2);
  VerifyAndClearExpectations();

  WaylandTestBase::SyncDisplay();

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    // ApplyPendingState() generates wl_surface requests and Commit() causes a
    // wayland connection flush.
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_)).Times(1);
    EXPECT_CALL(*mock_surface, SetInputRegion(_)).Times(1);
    EXPECT_CALL(*mock_surface, SetBufferScale(2)).Times(1);
    EXPECT_CALL(*mock_surface, Commit()).Times(1);
  });

  window_->root_surface()->ApplyPendingState();
  window_->root_surface()->Commit();
  VerifyAndClearExpectations();

  WaylandTestBase::SyncDisplay();
}

// Checks that when the window gets some of its edges tiled, it notifies the
// delegate appropriately.
TEST_P(WaylandWindowTest, HandleTiledEdges) {
  constexpr gfx::Rect kWindowBounds{800, 600};

  struct {
    std::vector<xdg_toplevel_state> configured_states;
    WindowTiledEdges expected_tiled_edges;
  } kTestCases[]{
      {{XDG_TOPLEVEL_STATE_TILED_LEFT}, {true, false, false, false}},
      {{XDG_TOPLEVEL_STATE_TILED_RIGHT}, {false, true, false, false}},
      {{XDG_TOPLEVEL_STATE_TILED_TOP}, {false, false, true, false}},
      {{XDG_TOPLEVEL_STATE_TILED_BOTTOM}, {false, false, false, true}},
      {{XDG_TOPLEVEL_STATE_TILED_LEFT, XDG_TOPLEVEL_STATE_TILED_TOP},
       {true, false, true, false}},
      {{XDG_TOPLEVEL_STATE_TILED_LEFT, XDG_TOPLEVEL_STATE_TILED_BOTTOM},
       {true, false, false, true}},
      {{XDG_TOPLEVEL_STATE_TILED_RIGHT, XDG_TOPLEVEL_STATE_TILED_TOP},
       {false, true, true, false}},
      {{XDG_TOPLEVEL_STATE_TILED_RIGHT, XDG_TOPLEVEL_STATE_TILED_BOTTOM},
       {false, true, false, true}},
      {{XDG_TOPLEVEL_STATE_TILED_LEFT, XDG_TOPLEVEL_STATE_TILED_TOP,
        XDG_TOPLEVEL_STATE_TILED_BOTTOM},
       {true, false, true, true}},
      {{XDG_TOPLEVEL_STATE_TILED_RIGHT, XDG_TOPLEVEL_STATE_TILED_TOP,
        XDG_TOPLEVEL_STATE_TILED_BOTTOM},
       {false, true, true, true}},
  };
  for (const auto& test_case : kTestCases) {
    auto configured_states = InitializeWlArrayWithActivatedState();
    for (const auto additional_state : test_case.configured_states) {
      AddStateToWlArray(additional_state, configured_states.get());
    }

    EXPECT_CALL(delegate_,
                OnWindowTiledStateChanged(test_case.expected_tiled_edges))
        .Times(1);
    SendConfigureEvent(surface_id_, kWindowBounds.size(), configured_states);

    VerifyAndClearExpectations();
  }
}

TEST_P(WaylandWindowTest, DisregardUnpassedWindowConfigure) {
  MapSurface(delegate_);

  constexpr gfx::Rect kNormalBounds1{500, 300};
  constexpr gfx::Rect kNormalBounds2{800, 600};
  constexpr gfx::Rect kNormalBounds3{700, 400};
  uint32_t serial = 1;

  // Send 3 configures, and skip OnSequencePoint for the result of the second
  // configure. The second configure should not be acked or have its properties
  // applied.
  PostToServerAndWait(
      [id = surface_id_, bounds1 = kNormalBounds1, bounds2 = kNormalBounds2,
       bounds3 = kNormalBounds3](wl::TestWaylandServerThread* server) {
        wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(surface);
        wl::MockXdgSurface* xdg_surface = surface->xdg_surface();

        EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds1.size())));
        EXPECT_CALL(*xdg_surface, AckConfigure(2));
        EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds2.size())))
            .Times(0);
        EXPECT_CALL(*xdg_surface, AckConfigure(3)).Times(0);
        EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds3.size())));
        EXPECT_CALL(*xdg_surface, AckConfigure(4));
      });

  auto state = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, kNormalBounds1.size(), state, ++serial);
  uint64_t viz_seq1 = delegate_.viz_seq();

  state = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, kNormalBounds2.size(), state, ++serial);

  state = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, kNormalBounds3.size(), state, ++serial);
  uint64_t viz_seq3 = delegate_.viz_seq();

  window_->OnSequencePoint(viz_seq1);
  window_->OnSequencePoint(viz_seq3);
  VerifyAndClearExpectations();
}

TEST_P(WaylandWindowTest, MismatchedSequencePoints) {
  constexpr gfx::Rect kNormalBounds1{500, 300};
  constexpr gfx::Rect kNormalBounds2{800, 600};
  constexpr gfx::Rect kNormalBounds3{700, 400};

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();

    // OnSequencePoint with mismatched sequence points from configure
    // events does not acknowledge toplevel configure.
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(_)).Times(0);
    EXPECT_CALL(*xdg_surface, AckConfigure(_)).Times(0);
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_)).Times(0);
    EXPECT_CALL(*mock_surface, SetInputRegion(_)).Times(0);
  });

  auto state = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, kNormalBounds1.size(), state);
  state = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, kNormalBounds2.size(), state);
  state = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, kNormalBounds3.size(), state);
  // Needs sequence point > 0 to latch.
  window_->OnSequencePoint(0);
  VerifyAndClearExpectations();
}

// Regression test for bugs like crbug.com/413007181 and crbug.com/340363673.
TEST_P(WaylandWindowTest, GeometrySentOnTilingStateChange) {
  constexpr gfx::Rect kBounds{800, 600};

  // Make sure the window has only active state initially.
  auto active = MakeStateArray({XDG_TOPLEVEL_STATE_ACTIVATED});
  SendConfigureEvent(surface_id_, {0, 0}, active);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Now add tiled state and check that the geometry is sent.
  auto active_tiled = MakeStateArray(
      {XDG_TOPLEVEL_STATE_ACTIVATED, XDG_TOPLEVEL_STATE_TILED_LEFT});
  PostToServerAndWait([id = surface_id_,
                       bounds = kBounds](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())));
    EXPECT_CALL(*xdg_surface, AckConfigure(_));
  });
  SendConfigureEvent(surface_id_, kBounds.size(), active_tiled);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Now remove tiled state and check that the geometry is sent.
  PostToServerAndWait([id = surface_id_,
                       bounds = kBounds](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())));
    EXPECT_CALL(*xdg_surface, AckConfigure(_));
  });
  SendConfigureEvent(surface_id_, kBounds.size(), active);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();
}

TEST_P(WaylandWindowTest, OnSequencePointClearsPreviousUnackedConfigures) {
  constexpr gfx::Rect kNormalBounds1{500, 300};
  constexpr gfx::Rect kNormalBounds2{800, 600};
  constexpr gfx::Rect kNormalBounds3{700, 400};
  uint32_t serial = 1;
  auto state = InitializeWlArrayWithActivatedState();

  MapSurface(delegate_);

  // Send 3 configures. Waiting to advance the frame (and call
  // OnSequencePoint(3)) should mean acking and processing the completion of
  // first two configures will be skipped.
  PostToServerAndWait([id = surface_id_, bounds = kNormalBounds1](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())))
        .Times(0);
    EXPECT_CALL(*xdg_surface, AckConfigure(2)).Times(0);
  });
  SendConfigureEvent(surface_id_, kNormalBounds1.size(), state, ++serial);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_, bounds = kNormalBounds2](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())))
        .Times(0);
    EXPECT_CALL(*xdg_surface, AckConfigure(3)).Times(0);
  });
  SendConfigureEvent(surface_id_, kNormalBounds2.size(), state, ++serial);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_, bounds = kNormalBounds3](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())));
    EXPECT_CALL(*xdg_surface, AckConfigure(4));
  });
  SendConfigureEvent(surface_id_, kNormalBounds3.size(), state, ++serial);

  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();
}

// This test used to specifically to guard against origin being set to (0, 0)
// thus lacros could be restored to correct display (crbug.com/1423690).
// TODO(crbug.com/374244479) Given lacros has been deprecated, update this test
// to ignore the origin and only verify the size as origin is not known in
// Wayland world.
TEST_P(WaylandWindowTest, RestoredBoundsSetWithCorrectOrigin) {
  constexpr gfx::Rect kNormalBounds{1376, 10, 500, 300};
  constexpr gfx::Rect kMaximizedBounds{1366, 0, 800, 600};

  // Make sure the window has normal state initially.
  window_->SetBoundsInDIP(kNormalBounds);
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Deactivate the surface.
  auto empty_state = MakeStateArray({});
  SendConfigureEvent(surface_id_, {0, 0}, empty_state);
  AdvanceFrameToCurrent(window_.get(), delegate_);

  WaylandWindow::WindowStates window_states;
  window_states.is_maximized = true;
  window_states.is_activated = true;

  window_->HandleToplevelConfigure(kMaximizedBounds.width(),
                                   kMaximizedBounds.height(), window_states);
  window_->HandleSurfaceConfigure(2);

  EXPECT_EQ(PlatformWindowState::kMaximized, window_->GetPlatformWindowState());
  EXPECT_EQ(window_->GetRestoredBoundsInDIP(), kNormalBounds);
}

TEST_P(WaylandWindowTest, MaximizeAndRestore) {
  constexpr gfx::Rect kNormalBounds{500, 300};
  constexpr gfx::Rect kMaximizedBounds{800, 600};

  // Make sure the window has normal state initially.
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  window_->SetBoundsInDIP(gfx::Rect(kNormalBounds.size()));
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Deactivate the surface.
  auto empty_state = MakeStateArray({});
  SendConfigureEvent(surface_id_, {0, 0}, empty_state);
  AdvanceFrameToCurrent(window_.get(), delegate_);

  auto active_maximized = MakeStateArray(
      {XDG_TOPLEVEL_STATE_ACTIVATED, XDG_TOPLEVEL_STATE_MAXIMIZED});
  PostToServerAndWait([id = surface_id_, bounds = kMaximizedBounds](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), SetMaximized());
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())));
  });
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(true)));
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  // Emulate a piece of behaviour of BrowserDesktopWindowTreeHostLinux, which is
  // the real delegate.  Its OnWindowStateChanged() may (through some chain of
  // calls) invoke SetWindowGeometry(), but that should not happen during the
  // change of the window state.
  // See https://crbug.com/1223005.
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  window_->Maximize();
  SendConfigureEvent(surface_id_, kMaximizedBounds.size(), active_maximized);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  auto inactive_maximized = MakeStateArray({XDG_TOPLEVEL_STATE_MAXIMIZED});
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(_)).Times(0);
  });
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(false)));
  EXPECT_CALL(delegate_, OnBoundsChanged(_)).Times(0);
  SendConfigureEvent(surface_id_, kMaximizedBounds.size(), inactive_maximized);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(_)).Times(0);
  });
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(true)));
  EXPECT_CALL(delegate_, OnBoundsChanged(_)).Times(0);
  SendConfigureEvent(surface_id_, kMaximizedBounds.size(), active_maximized);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_, bounds = kNormalBounds](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())));
  });
  // Emulate a piece of behaviour of BrowserDesktopWindowTreeHostLinux, which is
  // the real delegate.  Its OnWindowStateChanged() may (through some chain of
  // calls) invoke SetWindowGeometry(), but that should not happen during the
  // change of the window state.
  // See https://crbug.com/1223005.
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  EXPECT_CALL(delegate_, OnActivationChanged(_)).Times(0);
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), UnsetMaximized());
  });
  window_->Restore();
  // Reinitialize wl_array, which removes previous old states.
  auto active = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, active);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();
}

TEST_P(WaylandWindowTest, MaximizeAndRestoreWithInsets) {
  constexpr gfx::Rect kNormalBounds{510, 310};
  constexpr gfx::Insets kNormalInsets(5);

  constexpr gfx::Rect kMaximizedBounds{800, 600};
  constexpr gfx::Insets kMaximizedInsets(0);

  // Make sure the window has normal state initially.
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  window_->SetBoundsInDIP(gfx::Rect(kNormalBounds.size()));
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Deactivate the surface.
  auto empty_state = MakeStateArray({});
  SendConfigureEvent(surface_id_, {0, 0}, empty_state);
  AdvanceFrameToCurrent(window_.get(), delegate_);

  auto maximized_geometry = kMaximizedBounds;
  maximized_geometry.Inset(kMaximizedInsets);
  auto active_maximized = MakeStateArray(
      {XDG_TOPLEVEL_STATE_ACTIVATED, XDG_TOPLEVEL_STATE_MAXIMIZED});
  PostToServerAndWait([id = surface_id_, bounds = maximized_geometry](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), SetMaximized());
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())));
  });
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(true)));
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  // Emulate a piece of behaviour of BrowserDesktopWindowTreeHostLinux, which is
  // the real delegate.  Its OnWindowStateChanged() may (through some chain of
  // calls) invoke SetWindowGeometry(), but that should not happen during the
  // change of the window state.
  // See https://crbug.com/1223005.
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kMaximized))
      .WillRepeatedly(Return(kMaximizedInsets));
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  window_->Maximize();
  SendConfigureEvent(surface_id_, maximized_geometry.size(), active_maximized);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  auto inactive_maximized = MakeStateArray({XDG_TOPLEVEL_STATE_MAXIMIZED});
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kMaximized))
      .WillRepeatedly(Return(kMaximizedInsets));
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(_)).Times(0);
  });
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(false)));
  EXPECT_CALL(delegate_, OnBoundsChanged(_)).Times(0);
  SendConfigureEvent(surface_id_, maximized_geometry.size(),
                     inactive_maximized);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kMaximized))
      .WillRepeatedly(Return(kMaximizedInsets));
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(_)).Times(0);
  });
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(true)));
  EXPECT_CALL(delegate_, OnBoundsChanged(_)).Times(0);
  SendConfigureEvent(surface_id_, maximized_geometry.size(), active_maximized);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  auto normal_geometry = kNormalBounds;
  normal_geometry.Inset(kNormalInsets);
  // Emulate a piece of behaviour of BrowserDesktopWindowTreeHostLinux, which is
  // the real delegate.  Its OnWindowStateChanged() may (through some chain of
  // calls) invoke SetWindowGeometry(), but that should not happen during the
  // change of the window state.
  // See https://crbug.com/1223005.
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kNormal))
      .WillRepeatedly(Return(kNormalInsets));
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  EXPECT_CALL(delegate_, OnActivationChanged(_)).Times(0);
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  PostToServerAndWait([id = surface_id_, bounds = normal_geometry](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), UnsetMaximized());
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(bounds));
  });
  window_->Restore();
  // Reinitialize wl_array, which removes previous old states.
  auto active = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, active);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();
}

TEST_P(WaylandWindowTest, Minimize) {
  wl::ScopedWlArray states({});

  MapSurface(delegate_);

  // Make sure the window is initialized to normal state from the beginning.
  ASSERT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), SetMinimized());
  });
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  window_->Minimize();
  EXPECT_EQ(window_->GetPlatformWindowState(), PlatformWindowState::kMinimized);
  VerifyAndClearExpectations();

  // Reinitialize wl_array, which removes previous old states.
  states = wl::ScopedWlArray({});
  SendConfigureEvent(surface_id_, {0, 0}, states);

  // Wayland compositor doesn't notify clients about minimized state, but rather
  // if a window is not activated. Thus, a WaylandToplevelWindow marks itself as
  // being minimized and and sets state to minimized. Thus, the state mustn't
  // change after the configuration event is sent.
  EXPECT_EQ(window_->GetPlatformWindowState(), PlatformWindowState::kMinimized);

  // Send one additional empty configuration event (which means the surface is
  // not maximized, fullscreen or activated) to ensure, WaylandWindow stays in
  // the same minimized state, but the delegate is always notified.
  //
  // TODO(tonikito): Improve filtering of delegate notification here.
  ui::PlatformWindowState state;
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _))
      .WillRepeatedly(DoAll(SaveArg<0>(&state), InvokeWithoutArgs([&]() {
                              EXPECT_EQ(state, PlatformWindowState::kMinimized);
                            })));
  SendConfigureEvent(surface_id_, {0, 0}, states);

  // And one last time to ensure the behaviour.
  SendConfigureEvent(surface_id_, {0, 0}, states);
}

// Tests the event sequence where a toplevel window is minimized and a restore
// event is initiated by the server.
TEST_P(WaylandWindowTest, ServerInitiatedRestoreFromMinimizedState) {
  wl::ScopedWlArray states({});

  // Make sure the window is initialized to the normal state from the beginning.
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());
  SendConfigureEvent(surface_id_, {0, 0}, states);
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());

  // A subsequent minimize event from the server should notify delegates of the
  // window state change.
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  {
    WaylandWindow::WindowStates window_states;
    window_states.is_minimized = true;
    window_->HandleToplevelConfigureWithOrigin(0, 0, 0, 0, window_states);
  }
  window_->HandleSurfaceConfigure(3);
  EXPECT_EQ(PlatformWindowState::kMinimized, window_->GetPlatformWindowState());

  // If the minimized state is not supported, the server initiated restore
  // event with no window activation should not restore the window. It should
  // instead leave the window in the minimized state.
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(0);
  window_->HandleToplevelConfigureWithOrigin(0, 0, 0, 0, {});
  window_->HandleSurfaceConfigure(4);
  EXPECT_EQ(PlatformWindowState::kMinimized, window_->GetPlatformWindowState());
}

TEST_P(WaylandWindowTest, SetFullscreenAndRestore) {
  constexpr gfx::Rect kNormalBounds{500, 300};
  constexpr gfx::Rect kFullscreenBounds{800, 600};

  // Make sure the window is initialized to normal state from the beginning.
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());

  wl::ScopedWlArray states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, kNormalBounds.size(), states);

  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_FULLSCREEN);

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), SetFullscreen());
  });
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  window_->SetFullscreen(true, display::kInvalidDisplayId);
  // Make sure than WaylandWindow manually handles fullscreen states. Check the
  // comment in the WaylandWindow::SetFullscreen.
  VerifyAndClearExpectations();
  SendConfigureEvent(surface_id_, kFullscreenBounds.size(), states);
  EXPECT_EQ(window_->GetPlatformWindowState(),
            PlatformWindowState::kFullScreen);

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), UnsetFullscreen());
  });

  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  window_->Restore();
  VerifyAndClearExpectations();
  // Reinitialize wl_array, which removes previous old states.
  states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, kNormalBounds.size(), states);
  EXPECT_EQ(window_->GetPlatformWindowState(), PlatformWindowState::kNormal);
}

TEST_P(WaylandWindowTest, StartWithFullscreen) {
  MockWaylandPlatformWindowDelegate delegate;
  PlatformWindowInitProperties properties;
  properties.bounds = gfx::Rect(100, 100);
  properties.type = PlatformWindowType::kWindow;
  // We need to create a window avoid calling Show() on it as it is what upper
  // views layer does - when Widget initialize DesktopWindowTreeHost, the Show()
  // is called later down the road, but Maximize may be called earlier. We
  // cannot process them and set a pending state instead, because ShellSurface
  // is not created by that moment.
  auto window =
      delegate.CreateWaylandWindow(connection_.get(), std::move(properties));

  WaylandTestBase::SyncDisplay();

  // Make sure the window is initialized to unknown state initially.
  EXPECT_EQ(PlatformWindowState::kUnknown, window->GetPlatformWindowState());

  // The state must not be changed to the fullscreen before the surface is
  // activated.
  const uint32_t surface_id = window->root_surface()->get_surface_id();
  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_FALSE(surface->xdg_surface());
  });

  // We must receive a state change after SetFullscreen.
  EXPECT_CALL(delegate,
              OnWindowStateChanged(Eq(PlatformWindowState::kUnknown),
                                   Eq(PlatformWindowState::kFullScreen)));

  window->SetFullscreen(true, display::kInvalidDisplayId);
  // The state of the window must already be fullscreen one.
  EXPECT_EQ(window->GetPlatformWindowState(), PlatformWindowState::kFullScreen);

  WaylandTestBase::SyncDisplay();

  Mock::VerifyAndClearExpectations(&delegate);

  // Show and Activate the surface.
  window->Show(false);

  // We mustn't receive any state changes if that does not differ from the last
  // state.
  EXPECT_CALL(delegate, OnWindowStateChanged(_, _)).Times(0);
  wl::ScopedWlArray states = InitializeWlArrayWithActivatedState();
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_FULLSCREEN);
  SendConfigureEvent(surface_id, gfx::Size(1920, 1080), states);

  // It must be still the same state.
  EXPECT_EQ(window->GetPlatformWindowState(), PlatformWindowState::kFullScreen);
  Mock::VerifyAndClearExpectations(&delegate);

  MapSurface(delegate);
}

TEST_P(WaylandWindowTest, StartMaximized) {
  MockWaylandPlatformWindowDelegate delegate;
  PlatformWindowInitProperties properties;
  properties.bounds = gfx::Rect(100, 100);
  properties.type = PlatformWindowType::kWindow;
  // We need to create a window avoid calling Show() on it as it is what upper
  // views layer does - when Widget initialize DesktopWindowTreeHost, the Show()
  // is called later down the road, but Maximize may be called earlier. We
  // cannot process them and set a pending state instead, because ShellSurface
  // is not created by that moment.
  auto window =
      delegate.CreateWaylandWindow(connection_.get(), std::move(properties));

  WaylandTestBase::SyncDisplay();

  // Make sure the window is initialized to normal state from the beginning.
  EXPECT_EQ(PlatformWindowState::kUnknown, window->GetPlatformWindowState());

  // The state gets changed to maximize and the delegate notified.
  const uint32_t surface_id = window->root_surface()->get_surface_id();
  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface =
        server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_FALSE(mock_surface->xdg_surface());
  });

  // We must receive a state change after Show is called.
  EXPECT_CALL(delegate,
              OnWindowStateChanged(Eq(PlatformWindowState::kUnknown),
                                   Eq(PlatformWindowState::kMaximized)))
      .Times(1);

  window->Maximize();
  // The state of the window must already be fullscreen one.
  EXPECT_EQ(window->GetPlatformWindowState(), PlatformWindowState::kMaximized);

  WaylandTestBase::SyncDisplay();

  Mock::VerifyAndClearExpectations(&delegate);

  // Show the window now.
  window->Show(false);

  // Window show state should be already up to date, so delegate is not
  // notified.
  EXPECT_CALL(delegate, OnWindowStateChanged(_, _)).Times(0);
  EXPECT_EQ(window->GetPlatformWindowState(), PlatformWindowState::kMaximized);

  // Activate the surface.
  wl::ScopedWlArray states = InitializeWlArrayWithActivatedState();
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_MAXIMIZED);
  SendConfigureEvent(surface_id, gfx::Size(1920, 1080), states);

  EXPECT_EQ(window->GetPlatformWindowState(), PlatformWindowState::kMaximized);

  Mock::VerifyAndClearExpectations(&delegate);

  MapSurface(delegate);
}

TEST_P(WaylandWindowTest, CompositorSideStateChanges) {
  // Real insets used by default on HiDPI.
  const auto kInsets = gfx::Insets::TLBR(38, 44, 55, 44);
  const auto kNormalBounds = window_->GetBoundsInDIP();

  EXPECT_EQ(window_->GetPlatformWindowState(), PlatformWindowState::kNormal);

  // Set nonzero insets and ensure that they are only used when the window has
  // normal state.
  // See https://crbug.com/1274629
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kMaximized))
      .WillRepeatedly(Return(gfx::Insets()));
  EXPECT_CALL(delegate_,
              OnWindowStateChanged(_, Eq(PlatformWindowState::kMaximized)))
      .Times(1);
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect{2000, 2000}));
  });

  wl::ScopedWlArray states = InitializeWlArrayWithActivatedState();
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_MAXIMIZED);
  SendConfigureEvent(surface_id_, {2000, 2000}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  EXPECT_EQ(window_->GetPlatformWindowState(), PlatformWindowState::kMaximized);
  VerifyAndClearExpectations();

  // Unmaximize
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kNormal))
      .WillRepeatedly(Return(kInsets));
  EXPECT_CALL(delegate_,
              OnWindowStateChanged(_, Eq(PlatformWindowState::kNormal)))
      .Times(1);
  PostToServerAndWait(
      [id = surface_id_, insets = kInsets,
       bounds = kNormalBounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
        EXPECT_CALL(*xdg_surface,
                    SetWindowGeometry(gfx::Rect(
                        insets.left(), insets.top(),
                        bounds.width() - (insets.left() + insets.right()),
                        bounds.height() - (insets.top() + insets.bottom()))));
      });
  states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Now, set to fullscreen.
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kFullScreen))
      .WillRepeatedly(Return(gfx::Insets()));
  EXPECT_CALL(delegate_,
              OnWindowStateChanged(_, Eq(PlatformWindowState::kFullScreen)))
      .Times(1);
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(2005, 2005)));
  });
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_FULLSCREEN);
  SendConfigureEvent(surface_id_, {2005, 2005}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Unfullscreen
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kNormal))
      .WillRepeatedly(Return(kInsets));
  EXPECT_CALL(delegate_,
              OnWindowStateChanged(_, Eq(PlatformWindowState::kNormal)))
      .Times(1);
  PostToServerAndWait(
      [id = surface_id_, insets = kInsets,
       bounds = kNormalBounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
        EXPECT_CALL(*xdg_surface,
                    SetWindowGeometry(gfx::Rect(
                        insets.left(), insets.top(),
                        bounds.width() - (insets.left() + insets.right()),
                        bounds.height() - (insets.top() + insets.bottom()))));
      });
  states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Now, maximize, fullscreen and restore.
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kMaximized))
      .WillRepeatedly(Return(gfx::Insets()));
  EXPECT_CALL(delegate_,
              OnWindowStateChanged(_, Eq(PlatformWindowState::kMaximized)))
      .Times(1);
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(2000, 2000)));
  });
  states = InitializeWlArrayWithActivatedState();
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_MAXIMIZED);
  SendConfigureEvent(surface_id_, {2000, 2000}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kFullScreen))
      .WillRepeatedly(Return(gfx::Insets()));
  EXPECT_CALL(delegate_,
              OnWindowStateChanged(_, Eq(PlatformWindowState::kFullScreen)))
      .Times(1);
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(2005, 2005)));
  });
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_FULLSCREEN);
  SendConfigureEvent(surface_id_, {2005, 2005}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Restore
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kNormal))
      .WillRepeatedly(Return(kInsets));
  EXPECT_CALL(delegate_,
              OnWindowStateChanged(_, Eq(PlatformWindowState::kNormal)))
      .Times(1);
  PostToServerAndWait(
      [id = surface_id_, insets = kInsets,
       bounds = kNormalBounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
        EXPECT_CALL(*xdg_surface,
                    SetWindowGeometry(gfx::Rect(
                        insets.left(), insets.top(),
                        bounds.width() - (insets.left() + insets.right()),
                        bounds.height() - (insets.top() + insets.bottom()))));
      });
  states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();
}

TEST_P(WaylandWindowTest, SetMaximizedFullscreenAndRestore) {
  constexpr gfx::Rect kNormalBounds{500, 300};
  constexpr gfx::Rect kMaximizedBounds{800, 600};

  // Make sure the window has normal state initially.
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  window_->SetBoundsInDIP(gfx::Rect(kNormalBounds.size()));
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Deactivate the surface.
  wl::ScopedWlArray empty_state({});
  SendConfigureEvent(surface_id_, {0, 0}, empty_state);

  auto active_maximized = MakeStateArray(
      {XDG_TOPLEVEL_STATE_ACTIVATED, XDG_TOPLEVEL_STATE_MAXIMIZED});
  PostToServerAndWait([id = surface_id_, bounds = kMaximizedBounds](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), SetMaximized());
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())));
  });
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(true)));
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  window_->Maximize();
  // State changes are synchronous.
  EXPECT_EQ(PlatformWindowState::kMaximized, window_->GetPlatformWindowState());
  SendConfigureEvent(surface_id_, kMaximizedBounds.size(), active_maximized);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  // Verify that the state has not been changed.
  EXPECT_EQ(PlatformWindowState::kMaximized, window_->GetPlatformWindowState());
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), SetFullscreen());
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(_)).Times(0);
  });
  EXPECT_CALL(delegate_, OnBoundsChanged(_)).Times(0);
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  window_->SetFullscreen(true, display::kInvalidDisplayId);
  // State changes are synchronous.
  EXPECT_EQ(PlatformWindowState::kFullScreen,
            window_->GetPlatformWindowState());
  AddStateToWlArray(XDG_TOPLEVEL_STATE_FULLSCREEN, active_maximized.get());
  SendConfigureEvent(surface_id_, kMaximizedBounds.size(), active_maximized);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  // Verify that the state has not been changed.
  EXPECT_EQ(PlatformWindowState::kFullScreen,
            window_->GetPlatformWindowState());
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_, bounds = kNormalBounds](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())));
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), UnsetFullscreen());
  });
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(1);
  window_->Restore();
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());
  // Reinitialize wl_array, which removes previous old states.
  auto active = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, active);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());
}

TEST_P(WaylandWindowTest, RestoreBoundsAfterMaximize) {
  const gfx::Rect current_bounds = window_->GetBoundsInDIP();

  wl::ScopedWlArray states = InitializeWlArrayWithActivatedState();

  gfx::Rect restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_TRUE(restored_bounds.IsEmpty());
  gfx::Rect bounds = window_->GetBoundsInDIP();

  constexpr gfx::Rect kMaximizedBounds(1024, 768);
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  window_->Maximize();
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_MAXIMIZED);
  SendConfigureEvent(surface_id_, kMaximizedBounds.size(), states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(bounds, restored_bounds);

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  // Both in XdgV5 and XdgV6, surfaces implement SetWindowGeometry method.
  // Thus, using a toplevel object in XdgV6 case is not right thing. Use a
  // surface here instead.
  PostToServerAndWait(
      [id = surface_id_, current_bounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
        EXPECT_CALL(*xdg_surface,
                    SetWindowGeometry(gfx::Rect{current_bounds.size()}));
      });
  window_->Restore();
  // Reinitialize wl_array, which removes previous old states.
  states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  bounds = window_->GetBoundsInDIP();
  EXPECT_EQ(bounds, restored_bounds);
  restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(restored_bounds, gfx::Rect());
}

TEST_P(WaylandWindowTest, RestoreBoundsAfterFullscreen) {
  const gfx::Rect current_bounds = window_->GetBoundsInDIP();

  wl::ScopedWlArray states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);

  gfx::Rect restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(restored_bounds, gfx::Rect());
  gfx::Rect bounds = window_->GetBoundsInDIP();

  constexpr gfx::Rect kFullscreenBounds(1280, 720);
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  window_->SetFullscreen(true, display::kInvalidDisplayId);
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_FULLSCREEN);
  SendConfigureEvent(surface_id_, kFullscreenBounds.size(), states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(bounds, restored_bounds);

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  // Both in XdgV5 and XdgV6, surfaces implement SetWindowGeometry method.
  // Thus, using a toplevel object in XdgV6 case is not right thing. Use a
  // surface here instead.
  PostToServerAndWait(
      [id = surface_id_, current_bounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
        EXPECT_CALL(*xdg_surface,
                    SetWindowGeometry(gfx::Rect(current_bounds.size())));
      });
  window_->Restore();
  // Reinitialize wl_array, which removes previous old states.
  states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  bounds = window_->GetBoundsInDIP();
  EXPECT_EQ(bounds, restored_bounds);
  restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(restored_bounds, gfx::Rect());
}

TEST_P(WaylandWindowTest, RestoreBoundsAfterMaximizeAndFullscreen) {
  const gfx::Rect current_bounds = window_->GetBoundsInDIP();

  wl::ScopedWlArray states = InitializeWlArrayWithActivatedState();

  gfx::Rect restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(restored_bounds, gfx::Rect());
  gfx::Rect bounds = window_->GetBoundsInDIP();

  constexpr gfx::Rect kMaximizedBounds(1024, 768);
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  window_->Maximize();
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_MAXIMIZED);
  SendConfigureEvent(surface_id_, kMaximizedBounds.size(), states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(bounds, restored_bounds);

  constexpr gfx::Rect kFullscreenBounds(1280, 720);
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  window_->SetFullscreen(true, display::kInvalidDisplayId);
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_FULLSCREEN);
  SendConfigureEvent(surface_id_, kFullscreenBounds.size(), states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  gfx::Rect fullscreen_restore_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(restored_bounds, fullscreen_restore_bounds);

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  window_->Maximize();
  // Reinitialize wl_array, which removes previous old states.
  states = InitializeWlArrayWithActivatedState();
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_MAXIMIZED);
  SendConfigureEvent(surface_id_, kMaximizedBounds.size(), states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(restored_bounds, fullscreen_restore_bounds);

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  // Both in XdgV5 and XdgV6, surfaces implement SetWindowGeometry method.
  // Thus, using a toplevel object in XdgV6 case is not right thing. Use a
  // surface here instead.
  PostToServerAndWait(
      [id = surface_id_, current_bounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
        EXPECT_CALL(*xdg_surface,
                    SetWindowGeometry(gfx::Rect(current_bounds.size())));
      });
  window_->Restore();
  // Reinitialize wl_array, which removes previous old states.
  states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  bounds = window_->GetBoundsInDIP();
  EXPECT_EQ(bounds, restored_bounds);
  restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(restored_bounds, gfx::Rect());
}

TEST_P(WaylandWindowTest, SendsBoundsOnRequest) {
  const gfx::Rect initial_bounds = window_->GetBoundsInDIP();

  const gfx::Rect new_bounds =
      gfx::Rect(initial_bounds.width() + 10, initial_bounds.height() + 10);
  EXPECT_CALL(delegate_, OnBoundsChanged(kDefaultBoundsChange));

  PostToServerAndWait([id = surface_id_,
                       new_bounds](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(new_bounds.size())))
        .Times(1);
  });
  window_->SetBoundsInDIP(new_bounds);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Restored bounds should keep empty value.
  gfx::Rect restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(restored_bounds, gfx::Rect());
}

TEST_P(WaylandWindowTest, UpdateWindowRegion) {
  // Change bounds.
  const gfx::Rect initial_bounds = window_->GetBoundsInDIP();
  const gfx::Rect new_bounds =
      gfx::Rect(initial_bounds.width() + 10, initial_bounds.height() + 10);
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_)).Times(1);
    EXPECT_CALL(*mock_surface, SetInputRegion(_)).Times(1);
  });
  window_->SetBoundsInDIP(new_bounds);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  PostToServerAndWait(
      [id = surface_id_, new_bounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        EXPECT_EQ(mock_surface->opaque_region(), new_bounds);
        EXPECT_EQ(mock_surface->input_region(), new_bounds);
      });

  // Maximize.
  wl::ScopedWlArray states = InitializeWlArrayWithActivatedState();
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_)).Times(1);
    EXPECT_CALL(*mock_surface, SetInputRegion(_)).Times(1);
  });
  constexpr gfx::Rect kMaximizedBounds(1024, 768);
  window_->Maximize();
  AddStateToWlArray(XDG_TOPLEVEL_STATE_MAXIMIZED, states.get());
  SendConfigureEvent(surface_id_, kMaximizedBounds.size(), states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_,
                       kMaximizedBounds](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    EXPECT_EQ(mock_surface->opaque_region(), kMaximizedBounds);
    EXPECT_EQ(mock_surface->input_region(), kMaximizedBounds);
  });

  // Restore.
  const gfx::Rect restored_bounds = window_->GetRestoredBoundsInDIP();
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_)).Times(1);
    EXPECT_CALL(*mock_surface, SetInputRegion(_)).Times(1);
  });
  window_->Restore();
  // Reinitialize wl_array, which removes previous old states.
  auto active = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, {0, 0}, active);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  PostToServerAndWait(
      [id = surface_id_, restored_bounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        EXPECT_EQ(mock_surface->opaque_region(), restored_bounds);
        EXPECT_EQ(mock_surface->input_region(), restored_bounds);
      });
  AdvanceFrameToCurrent(window_.get(), delegate_);
}

TEST_P(WaylandWindowTest, CanDispatchMouseEventFocus) {
  // SetPointerFocusedWindow requires a WaylandPointer.
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER);
  });
  ASSERT_TRUE(connection_->seat()->pointer());
  SetPointerFocusedWindow(window_.get());
  Event::DispatcherApi(&test_mouse_event_).set_target(window_.get());
  EXPECT_TRUE(window_->CanDispatchEvent(&test_mouse_event_));
}

TEST_P(WaylandWindowTest, SetCursorUsesCursorShapeForCommonTypes) {
  SetPointerFocusedWindow(window_.get());
  MockCursorShape* mock_cursor_shape = InstallMockCursorShape();

  // Verify some commonly-used cursors.
  EXPECT_CALL(*mock_cursor_shape,
              SetCursorShape(WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT));
  auto pointer_cursor = AsPlatformCursor(
      base::MakeRefCounted<BitmapCursor>(mojom::CursorType::kPointer));
  window_->SetCursor(pointer_cursor.get());
  VerifyAndClearExpectations();

  EXPECT_CALL(*mock_cursor_shape,
              SetCursorShape(WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER));
  auto hand_cursor = AsPlatformCursor(
      base::MakeRefCounted<BitmapCursor>(mojom::CursorType::kHand));
  window_->SetCursor(hand_cursor.get());
  VerifyAndClearExpectations();

  EXPECT_CALL(*mock_cursor_shape,
              SetCursorShape(WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT));
  auto ibeam_cursor = AsPlatformCursor(
      base::MakeRefCounted<BitmapCursor>(mojom::CursorType::kIBeam));
  window_->SetCursor(ibeam_cursor.get());
  VerifyAndClearExpectations();
}

TEST_P(WaylandWindowTest, SetCursorCallsCursorShapeOncePerCursor) {
  SetPointerFocusedWindow(window_.get());
  MockCursorShape* mock_cursor_shape = InstallMockCursorShape();
  auto hand_cursor = AsPlatformCursor(
      base::MakeRefCounted<BitmapCursor>(mojom::CursorType::kHand));
  // Setting the same cursor twice on the client only calls the server once.
  EXPECT_CALL(*mock_cursor_shape, SetCursorShape(_)).Times(1);
  window_->SetCursor(hand_cursor.get());
  window_->SetCursor(hand_cursor.get());
}

TEST_P(WaylandWindowTest, SetCursorDoesNotUseCursorShapeForNoneCursor) {
  SetPointerFocusedWindow(window_.get());
  MockCursorShape* mock_cursor_shape = InstallMockCursorShape();
  EXPECT_CALL(*mock_cursor_shape, SetCursorShape(_)).Times(0);
  auto none_cursor = AsPlatformCursor(
      base::MakeRefCounted<BitmapCursor>(mojom::CursorType::kNone));
  window_->SetCursor(none_cursor.get());
}

TEST_P(WaylandWindowTest, SetCursorDoesNotUseCursorShapeForCustomCursors) {
  SetPointerFocusedWindow(window_.get());
  MockCursorShape* mock_cursor_shape = InstallMockCursorShape();

  // Custom cursors require bitmaps, so they do not use server-side cursors.
  EXPECT_CALL(*mock_cursor_shape, SetCursorShape(_)).Times(0);
  auto custom_cursor = AsPlatformCursor(
      base::MakeRefCounted<BitmapCursor>(mojom::CursorType::kCustom, SkBitmap(),
                                         gfx::Point(), kDefaultCursorScale));
  window_->SetCursor(custom_cursor.get());
}

ACTION_P(CloneEvent, ptr) {
  *ptr = arg0->Clone();
}

TEST_P(WaylandWindowTest, DispatchEvent) {
  std::unique_ptr<Event> event;
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce(CloneEvent(&event));
  window_->DispatchEvent(&test_mouse_event_);
  ASSERT_TRUE(event);
  ASSERT_TRUE(event->IsMouseEvent());
  auto* mouse_event = event->AsMouseEvent();
  EXPECT_EQ(mouse_event->location_f(), test_mouse_event_.location_f());
  EXPECT_EQ(mouse_event->root_location_f(),
            test_mouse_event_.root_location_f());
  EXPECT_EQ(mouse_event->time_stamp(), test_mouse_event_.time_stamp());
  EXPECT_EQ(mouse_event->button_flags(), test_mouse_event_.button_flags());
  EXPECT_EQ(mouse_event->changed_button_flags(),
            test_mouse_event_.changed_button_flags());
}

TEST_P(WaylandWindowTest, DispatchEventResult) {
  // Create an arbitrary wayland window with a test delegate.
  TestWaylandWindowDelegate window_delegate;
  PlatformWindowInitProperties properties(gfx::Rect(10, 10));
  auto window = WaylandWindow::Create(&window_delegate, connection_.get(),
                                      std::move(properties));

  KeyEvent event_1(EventType::kKeyPressed, VKEY_0, 0);
  window_delegate.SetDispatchEventCallback(
      base::BindOnce([](Event* event) { event->SetSkipped(); }));
  EXPECT_EQ(window->DispatchEvent(&event_1), POST_DISPATCH_PERFORM_DEFAULT);

  KeyEvent event_2(EventType::kKeyPressed, VKEY_0, 0);
  window_delegate.SetDispatchEventCallback(
      base::BindOnce([](Event* event) { event->StopPropagation(); }));
  EXPECT_EQ(window->DispatchEvent(&event_2), POST_DISPATCH_STOP_PROPAGATION);

  KeyEvent event_3(EventType::kKeyPressed, VKEY_0, 0);
  window_delegate.SetDispatchEventCallback(
      base::BindOnce([](Event* event) { event->SetHandled(); }));
  EXPECT_EQ(window->DispatchEvent(&event_3), POST_DISPATCH_STOP_PROPAGATION);

  KeyEvent event_4(EventType::kKeyPressed, VKEY_0, 0);
  window_delegate.SetDispatchEventCallback(base::BindOnce([](Event* event) {
    // Do nothing.
  }));
  EXPECT_EQ(window->DispatchEvent(&event_4), POST_DISPATCH_NONE);
}

TEST_P(WaylandWindowTest, ConfigureEvent) {
  wl::ScopedWlArray states({});

  // The surface must react on each configure event and send bounds to its
  // delegate.
  constexpr gfx::Size kSize{1000, 1000};
  uint32_t serial = 12u;

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  // Responding to a configure event, the window geometry in here must respect
  // the sizing negotiations specified by the configure event.
  // |xdg_surface| must receive the following calls in both xdg_shell_v5 and
  // xdg_shell_v6. Other calls like SetTitle or SetMaximized are received by
  // xdg_toplevel in xdg_shell_v6 and by xdg_surface in xdg_shell_v5.
  PostToServerAndWait(
      [id = surface_id_, kSize, serial](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        auto* xdg_surface = mock_surface->xdg_surface();
        EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(kSize))).Times(1);
        EXPECT_CALL(*xdg_surface, AckConfigure(serial));
      });
  SendConfigureEvent(surface_id_, kSize, states, serial);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  constexpr gfx::Size kNewSize{1500, 1000};

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  PostToServerAndWait([id = surface_id_, kNewSize,
                       serial](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(kNewSize))).Times(1);
    EXPECT_CALL(*xdg_surface, AckConfigure(serial + 1));
  });
  SendConfigureEvent(surface_id_, kNewSize, states, ++serial);
  AdvanceFrameToCurrent(window_.get(), delegate_);
}

TEST_P(WaylandWindowTest, ConfigureEventWithNulledSize) {
  // Use a new window here as this test case needs to exercise the very first
  // configure sequence handling, which isn't possible with the original
  // `window_` set up at WaylandTest::SetUp.
  window_ = CreateWaylandWindowWithParams(PlatformWindowType::kWindow,
                                          gfx::Rect(400, 400), &delegate_);
  surface_id_ = window_->root_surface()->get_surface_id();
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    auto* xdg_surface = server->GetObject<wl::MockSurface>(id)->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(400, 400)));
    EXPECT_CALL(*xdg_surface, AckConfigure(14u));
  });

  // The first configure sequence (with 0x0 size and activated state) must be
  // acked and window geometry must be set with the bounds provided by the
  // embedder at window initialization.
  wl::ScopedWlArray states({XDG_TOPLEVEL_STATE_ACTIVATED});
  SendConfigureEvent(surface_id_, gfx::Size(), states, 14u);

  // Emulate the corresponding frame processing at client side, by triggering
  // WaylandWindow::OnSequencePoint, which, in production, is handled and done
  // by WaylandFrameManager.
  window_->OnSequencePoint(delegate_.viz_seq());
}

TEST_P(WaylandWindowTest, ConfigureEventIsNotAckedMultipleTimes) {
  constexpr gfx::Rect kNormalBounds{500, 300};
  constexpr gfx::Rect kSecondBounds{600, 600};

  // Configure event makes Wayland update bounds, but does not change toplevel
  // input region, opaque region or window geometry immediately. Such actions
  // are postponed to OnSequencePoint();
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));

  PostToServerAndWait([id = surface_id_, bounds = kNormalBounds](
                          wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())))
        .Times(0);
    EXPECT_CALL(*xdg_surface, AckConfigure(_)).Times(0);
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_)).Times(0);
    EXPECT_CALL(*mock_surface, SetInputRegion(_)).Times(0);
  });

  auto state = InitializeWlArrayWithActivatedState();
  constexpr uint32_t kConfigureSerial = 2u;
  SendConfigureEvent(surface_id_, kNormalBounds.size(), state,
                     kConfigureSerial);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_, bounds = kNormalBounds](
                          wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(bounds));
    EXPECT_CALL(*xdg_surface, AckConfigure(kConfigureSerial));
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_));
    EXPECT_CALL(*mock_surface, SetInputRegion(_));
  });

  // Get the viz sequence ID which will let us ack the configure event.
  auto viz_seq = delegate_.viz_seq();

  // Insert another change which will increase the viz sequence ID here.
  // We want to make sure that when this viz sequence ID is reached, we
  // don't send another ack for the configure.
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));
  window_->SetBoundsInDIP(kSecondBounds);

  AdvanceFrameToGivenVizSequenceId(window_.get(), delegate_, viz_seq);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_, bounds = kSecondBounds](
                          wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(bounds));
    EXPECT_CALL(*xdg_surface, AckConfigure(_)).Times(0);
    EXPECT_CALL(*mock_surface, SetOpaqueRegion(_));
    EXPECT_CALL(*mock_surface, SetInputRegion(_));
  });
  AdvanceFrameToCurrent(window_.get(), delegate_);
}

TEST_P(WaylandWindowTest, ManyConfigureEventsDoesNotCrash) {
  constexpr uint32_t kConfigureSerial = 2u;

  auto state = InitializeWlArrayWithActivatedState();
  gfx::Size size{500, 300};
  for (int i = 0; i < 3000; ++i) {
    SendConfigureEvent(surface_id_, size, state, kConfigureSerial + i);
    size.Enlarge(1, 1);
  }
  AdvanceFrameToCurrent(window_.get(), delegate_);
}

// If the server immediately changes the bounds after a window is initialised,
// make sure that the client doesn't wait for a new frame to be produced.
// See https://crbug.com/1427954.
TEST_P(WaylandWindowTest, InitialConfigureFollowedByBoundsChangeCompletesAck) {
  constexpr gfx::Rect kFirstBounds{0, 0, 800, 600};
  constexpr gfx::Rect kSecondBounds{50, 50, 800, 600};
  constexpr uint32_t kConfigureSerial = 2u;

  MapSurface(delegate_);

  // Make sure that we start off with the initial bounds we expect.
  EXPECT_EQ(kFirstBounds, window_->latched_state().bounds_dip);
  EXPECT_EQ(kFirstBounds, window_->applied_state().bounds_dip);

  // Expect an origin change.
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(BoundsChange{true})));

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, AckConfigure(kConfigureSerial));
  });

  {
    WaylandWindow::WindowStates window_states;
    window_states.is_activated = true;
    window_->HandleToplevelConfigureWithOrigin(
        kSecondBounds.x(), kSecondBounds.y(), kSecondBounds.width(),
        kSecondBounds.height(), window_states);
  }
  window_->HandleSurfaceConfigure(kConfigureSerial);

  // Don't call AdvanceFrameToCurrent here, because just updating the
  // bounds origin won't generate a new frame. The client should ack
  // even if there is no new frame produced.
}

TEST_P(WaylandWindowTest, OnActivationChanged) {
  uint32_t serial = 0;

  MockWaylandPlatformWindowDelegate new_window_delegate;
  auto new_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kWindow, gfx::Rect(100, 100), &new_window_delegate);
  ASSERT_TRUE(new_window);
  auto new_window_surface_id = new_window->root_surface()->get_surface_id();

  MockWaylandPlatformWindowDelegate menu_delegate;
  auto menu = CreateWaylandWindowWithParams(PlatformWindowType::kMenu,
                                            gfx::Rect(100, 100), &menu_delegate,
                                            new_window->GetWidget());
  ASSERT_TRUE(menu);

  wl::ScopedWlArray empty_state({});
  SendConfigureEvent(surface_id_, {0, 0}, empty_state, ++serial);
  SendConfigureEvent(new_window_surface_id, {0, 0}, empty_state, ++serial);

  // Request active decorations.
  wl::ScopedWlArray active_state = InitializeWlArrayWithActivatedState();
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(true)));
  SendConfigureEvent(surface_id_, {0, 0}, active_state, ++serial);
  VerifyAndClearExpectations();

  // Plug keyboard.
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(false)));
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_KEYBOARD);
  });
  VerifyAndClearExpectations();

  // Focus keyboard.
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(true)));
  SetKeyboardFocusedWindow(window_.get());
  VerifyAndClearExpectations();

  // Switch keyboard focus to other window.
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(false)));
  EXPECT_CALL(new_window_delegate, OnActivationChanged(Eq(true)));
  SetKeyboardFocusedWindow(new_window.get());
  VerifyAndClearExpectations();

  // Switch keyboard focus to menu in other window.
  EXPECT_CALL(new_window_delegate, OnActivationChanged(_)).Times(0);
  SetKeyboardFocusedWindow(menu.get());
  VerifyAndClearExpectations();

  // Unfocus keyboard.
  EXPECT_CALL(new_window_delegate, OnActivationChanged(Eq(false)));
  SetKeyboardFocusedWindow(nullptr);
  VerifyAndClearExpectations();

  // Unplug keyboard - should fall back to xdg-shell activated state.
  EXPECT_CALL(delegate_, OnActivationChanged(Eq(true)));
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(), 0);
  });
  VerifyAndClearExpectations();

  // Request inactive decorations.
  EXPECT_CALL(delegate_, OnActivationChanged(false));
  SendConfigureEvent(surface_id_, {0, 0}, empty_state, ++serial);
}

TEST_P(WaylandWindowTest, OnAcceleratedWidgetDestroy) {
  window_.reset();
}

TEST_P(WaylandWindowTest, CanCreateMenuWindow) {
  MockWaylandPlatformWindowDelegate menu_window_delegate;

  // SetPointerFocus(true) requires a WaylandPointer.
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(
        server->seat()->resource(),
        WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_TOUCH);
  });
  ASSERT_TRUE(connection_->seat()->pointer());
  ASSERT_TRUE(connection_->seat()->touch());
  SetPointerFocusedWindow(window_.get());

  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(10, 10), &menu_window_delegate);
  EXPECT_TRUE(menu_window);

  SetPointerFocusedWindow(window_.get());
  window_->set_touch_focus(false);

  // Given that there is no parent passed and we don't have any focused windows,
  // Wayland must still create a window.
  menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(10, 10), &menu_window_delegate);
  EXPECT_TRUE(menu_window);

  window_->set_touch_focus(true);

  menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(10, 10), &menu_window_delegate);
  EXPECT_TRUE(menu_window);
}

TEST_P(WaylandWindowTest, CreateAndDestroyNestedMenuWindow) {
  MockWaylandPlatformWindowDelegate menu_window_delegate;
  gfx::AcceleratedWidget menu_window_widget;
  EXPECT_CALL(menu_window_delegate, OnAcceleratedWidgetAvailable(_))
      .WillOnce(SaveArg<0>(&menu_window_widget));

  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(10, 10), &menu_window_delegate,
      widget_);
  EXPECT_TRUE(menu_window);
  ASSERT_NE(menu_window_widget, gfx::kNullAcceleratedWidget);

  MockWaylandPlatformWindowDelegate nested_menu_window_delegate;
  std::unique_ptr<WaylandWindow> nested_menu_window =
      CreateWaylandWindowWithParams(
          PlatformWindowType::kMenu, gfx::Rect(20, 0, 10, 10),
          &nested_menu_window_delegate, menu_window_widget);
  EXPECT_TRUE(nested_menu_window);
}

TEST_P(WaylandWindowTest, DispatchesLocatedEventsToCapturedWindow) {
  MockWaylandPlatformWindowDelegate menu_window_delegate;
  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(10, 10, 10, 10),
      &menu_window_delegate, widget_);
  EXPECT_TRUE(menu_window);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER);
  });
  ASSERT_TRUE(connection_->seat()->pointer());
  SetPointerFocusedWindow(window_.get());

  // Make sure the events are handled by the window that has the pointer focus.
  VerifyCanDispatchMouseEvents(window_.get(), {menu_window.get()});

  // The |window_| that has the pointer focus must receive the event.
  EXPECT_CALL(menu_window_delegate, DispatchEvent(_)).Times(0);
  std::unique_ptr<Event> event;
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce(CloneEvent(&event));

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // The event is sent in local surface coordinates of the |window|.
    wl_pointer_send_motion(server->seat()->pointer()->resource(),
                           server->GetNextSerial(), wl_fixed_from_double(10.75),
                           wl_fixed_from_double(20.375));
    wl_pointer_send_frame(server->seat()->pointer()->resource());
  });

  ASSERT_TRUE(event->IsLocatedEvent());
  EXPECT_EQ(event->AsLocatedEvent()->location(), gfx::Point(10, 20));

  // Set capture to menu window now.
  menu_window->SetCapture();

  // It's still the |window_| that can dispatch the events, but it will reroute
  // the event to correct window and fix the location.
  VerifyCanDispatchMouseEvents(window_.get(), {menu_window.get()});

  // The |window_| that has the pointer focus must receive the event.
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(0);
  std::unique_ptr<Event> event2;
  EXPECT_CALL(menu_window_delegate, DispatchEvent(_))
      .WillOnce(CloneEvent(&event2));

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // The event is sent in local surface coordinates of the |window|.
    wl_pointer_send_motion(server->seat()->pointer()->resource(),
                           server->GetNextSerial(), wl_fixed_from_double(10.75),
                           wl_fixed_from_double(20.375));
    wl_pointer_send_frame(server->seat()->pointer()->resource());
  });

  ASSERT_TRUE(event2->IsLocatedEvent());
  EXPECT_EQ(event2->AsLocatedEvent()->location(), gfx::Point(0, 10));

  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(0);
  std::unique_ptr<Event> event3;
  EXPECT_CALL(menu_window_delegate, DispatchEvent(_))
      .WillOnce(CloneEvent(&event3));

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // The event is sent in local surface coordinates of the |window|.
    wl_pointer_send_motion(server->seat()->pointer()->resource(),
                           server->GetNextSerial(), wl_fixed_from_double(2.75),
                           wl_fixed_from_double(8.375));
    wl_pointer_send_frame(server->seat()->pointer()->resource());
  });

  ASSERT_TRUE(event3->IsLocatedEvent());
  EXPECT_EQ(event3->AsLocatedEvent()->location(), gfx::Point(-8, -2));

  // If nested menu window is added, the events are still correctly translated
  // to the captured window.
  MockWaylandPlatformWindowDelegate nested_menu_window_delegate;
  std::unique_ptr<WaylandWindow> nested_menu_window =
      CreateWaylandWindowWithParams(
          PlatformWindowType::kMenu, gfx::Rect(15, 18, 10, 10),
          &nested_menu_window_delegate, menu_window->GetWidget());
  EXPECT_TRUE(nested_menu_window);

  SetPointerFocusedWindow(nested_menu_window.get());

  // The event is processed by the window that has the pointer focus, but
  // dispatched by the window that has the capture.
  VerifyCanDispatchMouseEvents(nested_menu_window.get(),
                               {window_.get(), menu_window.get()});
  EXPECT_TRUE(menu_window->HasCapture());

  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(0);
  EXPECT_CALL(nested_menu_window_delegate, DispatchEvent(_)).Times(0);
  std::unique_ptr<Event> event4;
  EXPECT_CALL(menu_window_delegate, DispatchEvent(_))
      .WillOnce(CloneEvent(&event4));

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // The event is sent in local surface coordinates of the
    // |nested_menu_window|.
    wl_pointer_send_motion(server->seat()->pointer()->resource(),
                           server->GetNextSerial(), wl_fixed_from_double(2.75),
                           wl_fixed_from_double(8.375));
    wl_pointer_send_frame(server->seat()->pointer()->resource());
  });

  ASSERT_TRUE(event4->IsLocatedEvent());
  EXPECT_EQ(event4->AsLocatedEvent()->location(), gfx::Point(7, 16));

  nested_menu_window.reset();
  menu_window.reset();
}

// Verify that located events are translated correctly when the windows have
// geometry with non-zero offset.
// See https://crbug.com/1292486.
TEST_P(WaylandWindowTest, ConvertEventToTarget) {
  constexpr gfx::Rect kMainWindowBounds{956, 556};
  const auto kMainWindowInsets = gfx::Insets::TLBR(24, 28, 32, 28);

  auto bounds_with_insets = kMainWindowBounds;
  bounds_with_insets.Inset(kMainWindowInsets);
  EXPECT_CALL(delegate_, OnBoundsChanged(_));
  EXPECT_CALL(delegate_, CalculateInsetsInDIP(PlatformWindowState::kNormal))
      .WillRepeatedly(Return(kMainWindowInsets));
  PostToServerAndWait([id = surface_id_, bounds_with_insets](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(bounds_with_insets));
  });
  window_->SetBoundsInDIP(kMainWindowBounds);
  SendConfigureEvent(surface_id_, bounds_with_insets.size(),
                     MakeStateArray({XDG_TOPLEVEL_STATE_ACTIVATED}));
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Create a menu.
  constexpr gfx::Rect kMenuBounds{100, 100, 80, 50};
  MockWaylandPlatformWindowDelegate menu_window_delegate;
  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, kMenuBounds, &menu_window_delegate, widget_);
  EXPECT_TRUE(menu_window);

  // Now translate the event located at (0, 0) in the parent window into the
  // coordinate system of the menu.  Its coordinates must be equal to:
  //     -(offset of the menu).
  constexpr gfx::PointF kParentPoint{0, 0};
  ui::MouseEvent event(ui::EventType::kMouseMoved, kParentPoint, kParentPoint,
                       {}, ui::EF_NONE, ui::EF_NONE);

  ui::Event::DispatcherApi dispatcher_api(&event);
  dispatcher_api.set_target(window_.get());

  ui::WaylandEventSource::ConvertEventToTarget(menu_window.get(), &event);
  EXPECT_EQ(event.AsLocatedEvent()->x(), -kMenuBounds.x());
  EXPECT_EQ(event.AsLocatedEvent()->y(), -kMenuBounds.y());
}

// Tests that the event grabber gets the events processed by its toplevel parent
// window iff they belong to the same "family". Otherwise, events mustn't be
// rerouted from another toplevel window to the event grabber.
TEST_P(WaylandWindowTest,
       DispatchesLocatedEventsToCapturedWindowInTheSameStack) {
  MockWaylandPlatformWindowDelegate menu_window_delegate;
  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(30, 40, 20, 50),
      &menu_window_delegate, widget_);
  EXPECT_TRUE(menu_window);

  // Second toplevel window has the same bounds as the |window_|.
  MockWaylandPlatformWindowDelegate toplevel_window2_delegate;
  std::unique_ptr<WaylandWindow> toplevel_window2 =
      CreateWaylandWindowWithParams(PlatformWindowType::kWindow,
                                    window_->GetBoundsInDIP(),
                                    &toplevel_window2_delegate);
  EXPECT_TRUE(toplevel_window2);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER);
  });
  ASSERT_TRUE(connection_->seat()->pointer());
  SetPointerFocusedWindow(window_.get());

  // Make sure the events are handled by the window that has the pointer focus.
  VerifyCanDispatchMouseEvents(window_.get(),
                               {menu_window.get(), toplevel_window2.get()});

  menu_window->SetCapture();

  // The |menu_window| that has capture must receive the event.
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(0);
  EXPECT_CALL(toplevel_window2_delegate, DispatchEvent(_)).Times(0);
  std::unique_ptr<Event> event;
  EXPECT_CALL(menu_window_delegate, DispatchEvent(_))
      .WillOnce(CloneEvent(&event));

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // The event is sent in local surface coordinates of the |window|.
    wl_pointer_send_motion(server->seat()->pointer()->resource(),
                           server->GetNextSerial(), wl_fixed_from_double(10.75),
                           wl_fixed_from_double(20.375));
    wl_pointer_send_frame(server->seat()->pointer()->resource());
  });

  ASSERT_TRUE(event->IsLocatedEvent());
  EXPECT_EQ(event->AsLocatedEvent()->location(), gfx::Point(-20, -20));

  // Now, pretend that the second toplevel window gets the pointer focus - the
  // event grabber must be disragerder now.
  SetPointerFocusedWindow(toplevel_window2.get());

  VerifyCanDispatchMouseEvents(toplevel_window2.get(),
                               {menu_window.get(), window_.get()});

  // The |toplevel_window2| that has capture and must receive the event.
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(0);
  EXPECT_CALL(menu_window_delegate, DispatchEvent(_)).Times(0);
  event.reset();
  EXPECT_CALL(toplevel_window2_delegate, DispatchEvent(_))
      .WillOnce(CloneEvent(&event));

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // The event is sent in local surface coordinates of the |toplevel_window2|
    // (they're basically the same as the |window| has.)
    wl_pointer_send_motion(server->seat()->pointer()->resource(),
                           server->GetNextSerial(), wl_fixed_from_double(10.75),
                           wl_fixed_from_double(20.375));
    wl_pointer_send_frame(server->seat()->pointer()->resource());
  });

  ASSERT_TRUE(event->IsLocatedEvent());
  EXPECT_EQ(event->AsLocatedEvent()->location(), gfx::Point(10, 20));
}

TEST_P(WaylandWindowTest, DispatchesKeyboardEventToToplevelWindow) {
  MockWaylandPlatformWindowDelegate menu_window_delegate;
  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(10, 10, 10, 10),
      &menu_window_delegate, widget_);
  EXPECT_TRUE(menu_window);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_KEYBOARD);
  });
  ASSERT_TRUE(connection_->seat()->keyboard());
  SetKeyboardFocusedWindow(menu_window.get());

  // Disable auto-repeat so that it doesn't ruin our expectations.
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_keyboard_send_repeat_info(server->seat()->keyboard()->resource(), 0, 0);
  });

  // Even though the menu window has the keyboard focus, the keyboard events are
  // dispatched by the root parent wayland window in the end.
  VerifyCanDispatchKeyEvents({menu_window.get()}, {window_.get()});
  EXPECT_CALL(menu_window_delegate, DispatchEvent(_)).Times(0);
  std::unique_ptr<Event> event;
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce(CloneEvent(&event));

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_keyboard_send_key(server->seat()->keyboard()->resource(),
                         server->GetNextSerial(), server->GetNextTime(),
                         30 /* a */, WL_KEYBOARD_KEY_STATE_PRESSED);
  });

  ASSERT_TRUE(event->IsKeyEvent());
  VerifyAndClearExpectations();

  EXPECT_CALL(menu_window_delegate, DispatchEvent(_)).Times(0);
  event.reset();
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce(CloneEvent(&event));

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_keyboard_send_key(server->seat()->keyboard()->resource(),
                         server->GetNextSerial(), server->GetNextTime(),
                         30 /* a */, WL_KEYBOARD_KEY_STATE_RELEASED);
  });

  ASSERT_TRUE(event->IsKeyEvent());

  // Setting capture doesn't affect the kbd events.
  menu_window->SetCapture();
  VerifyCanDispatchKeyEvents({menu_window.get()}, {window_.get()});

  EXPECT_CALL(menu_window_delegate, DispatchEvent(_)).Times(0);
  event.reset();
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce(CloneEvent(&event));

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_keyboard_send_key(server->seat()->keyboard()->resource(),
                         server->GetNextSerial(), server->GetNextTime(),
                         30 /* a */, WL_KEYBOARD_KEY_STATE_PRESSED);
  });

  ASSERT_TRUE(event->IsKeyEvent());
  VerifyAndClearExpectations();

  menu_window.reset();
}

// Tests that event is processed by the surface that has the focus. More
// extensive tests are located in wayland touch/keyboard/pointer unittests.
TEST_P(WaylandWindowTest, CanDispatchEvent) {
  MockWaylandPlatformWindowDelegate menu_window_delegate;
  gfx::AcceleratedWidget menu_window_widget;
  EXPECT_CALL(menu_window_delegate, OnAcceleratedWidgetAvailable(_))
      .WillOnce(SaveArg<0>(&menu_window_widget));

  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(10, 10), &menu_window_delegate,
      widget_);
  EXPECT_TRUE(menu_window);

  MockWaylandPlatformWindowDelegate nested_menu_window_delegate;
  std::unique_ptr<WaylandWindow> nested_menu_window =
      CreateWaylandWindowWithParams(
          PlatformWindowType::kMenu, gfx::Rect(20, 0, 10, 10),
          &nested_menu_window_delegate, menu_window_widget);
  EXPECT_TRUE(nested_menu_window);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER |
                                  WL_SEAT_CAPABILITY_KEYBOARD |
                                  WL_SEAT_CAPABILITY_TOUCH);
  });
  ASSERT_TRUE(connection_->seat()->pointer());
  ASSERT_TRUE(connection_->seat()->touch());
  ASSERT_TRUE(connection_->seat()->keyboard());

  // Test that CanDispatchEvent is set correctly.
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* toplevel_surface = server->GetObject<wl::MockSurface>(id);
    wl_pointer_send_enter(server->seat()->pointer()->resource(),
                          server->GetNextSerial(), toplevel_surface->resource(),
                          0, 0);
  });

  // Only |window_| can dispatch MouseEvents.
  VerifyCanDispatchMouseEvents(window_.get(),
                               {menu_window.get(), nested_menu_window.get()});
  VerifyCanDispatchTouchEvents(
      {}, {window_.get(), menu_window.get(), nested_menu_window.get()});
  VerifyCanDispatchKeyEvents(
      {}, {window_.get(), menu_window.get(), nested_menu_window.get()});

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* toplevel_surface = server->GetObject<wl::MockSurface>(id);
    wl::ScopedWlArray empty({});
    wl_keyboard_send_enter(server->seat()->keyboard()->resource(),
                           server->GetNextSerial(),
                           toplevel_surface->resource(), empty.get());
  });

  // Only |window_| can dispatch MouseEvents and KeyEvents.
  VerifyCanDispatchMouseEvents(window_.get(),
                               {menu_window.get(), nested_menu_window.get()});
  VerifyCanDispatchTouchEvents(
      {}, {window_.get(), menu_window.get(), nested_menu_window.get()});
  VerifyCanDispatchKeyEvents({window_.get()},
                             {menu_window.get(), nested_menu_window.get()});

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* toplevel_surface = server->GetObject<wl::MockSurface>(id);
    wl_touch_send_down(server->seat()->touch()->resource(),
                       server->GetNextSerial(), 0, toplevel_surface->resource(),
                       0 /* id */, wl_fixed_from_int(50),
                       wl_fixed_from_int(100));
    wl_touch_send_frame(server->seat()->touch()->resource());
  });

  // Only |window_| can dispatch MouseEvents and KeyEvents.
  VerifyCanDispatchMouseEvents(window_.get(),
                               {menu_window.get(), nested_menu_window.get()});
  VerifyCanDispatchTouchEvents({window_.get()},
                               {menu_window.get(), nested_menu_window.get()});
  VerifyCanDispatchKeyEvents({window_.get()},
                             {menu_window.get(), nested_menu_window.get()});

  const uint32_t menu_window_surface_id =
      menu_window->root_surface()->get_surface_id();
  PostToServerAndWait(
      [toplevel_surface_id = surface_id_,
       menu_window_surface_id](wl::TestWaylandServerThread* server) {
        wl::MockSurface* toplevel_surface =
            server->GetObject<wl::MockSurface>(toplevel_surface_id);
        wl::MockSurface* menu_window_surface =
            server->GetObject<wl::MockSurface>(menu_window_surface_id);
        wl_pointer_send_leave(server->seat()->pointer()->resource(),
                              server->GetNextSerial(),
                              toplevel_surface->resource());
        wl_pointer_send_enter(server->seat()->pointer()->resource(),
                              server->GetNextSerial(),
                              menu_window_surface->resource(), 0, 0);
        wl_touch_send_up(server->seat()->touch()->resource(),
                         server->GetNextSerial(), 1000, 0 /* id */);
        wl_touch_send_frame(server->seat()->touch()->resource());

        wl_keyboard_send_leave(server->seat()->keyboard()->resource(),
                               server->GetNextSerial(),
                               toplevel_surface->resource());
      });

  // Only |menu_window| can dispatch MouseEvents.
  VerifyCanDispatchMouseEvents(menu_window.get(),
                               {window_.get(), nested_menu_window.get()});
  VerifyCanDispatchTouchEvents(
      {}, {window_.get(), menu_window.get(), nested_menu_window.get()});
  VerifyCanDispatchKeyEvents(
      {}, {window_.get(), menu_window.get(), nested_menu_window.get()});

  const uint32_t nested_menu_window_surface_id =
      nested_menu_window->root_surface()->get_surface_id();
  PostToServerAndWait([nested_menu_window_surface_id, menu_window_surface_id](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* menu_window_surface =
        server->GetObject<wl::MockSurface>(menu_window_surface_id);
    wl::MockSurface* nested_menu_window_surface =
        server->GetObject<wl::MockSurface>(nested_menu_window_surface_id);

    wl_pointer_send_leave(server->seat()->pointer()->resource(),
                          server->GetNextSerial(),
                          menu_window_surface->resource());
    wl_pointer_send_enter(server->seat()->pointer()->resource(),
                          server->GetNextSerial(),
                          nested_menu_window_surface->resource(), 0, 0);
  });

  // Only |nested_menu_window| can dispatch MouseEvents.
  VerifyCanDispatchMouseEvents(nested_menu_window.get(),
                               {window_.get(), menu_window.get()});
  VerifyCanDispatchTouchEvents(
      {}, {window_.get(), menu_window.get(), nested_menu_window.get()});
  VerifyCanDispatchKeyEvents(
      {}, {window_.get(), menu_window.get(), nested_menu_window.get()});
}

TEST_P(WaylandWindowTest, DispatchWindowMove) {
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER);
  });
  ASSERT_TRUE(connection_->seat()->pointer());

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    // Focus and press left mouse button, so that serial is sent to client.
    auto* pointer_resource = server->seat()->pointer()->resource();
    wl_pointer_send_enter(pointer_resource, server->GetNextSerial(),
                          surface->resource(), 0, 0);
    wl_pointer_send_button(pointer_resource, server->GetNextSerial(),
                           server->GetNextTime(), BTN_LEFT,
                           WL_POINTER_BUTTON_STATE_PRESSED);
  });

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    auto* xdg_surface = surface->xdg_surface();
    EXPECT_CALL(*xdg_surface->xdg_toplevel(), Move(_));
  });
  ui::GetWmMoveResizeHandler(*window_)->DispatchHostWindowDragMovement(
      HTCAPTION, gfx::Point());
}

// Makes sure hit tests are converted into right edges.
TEST_P(WaylandWindowTest, DispatchWindowResize) {
  std::vector<int> hit_test_values;
  InitializeWithSupportedHitTestValues(&hit_test_values);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER);
  });

  ASSERT_TRUE(connection_->seat()->pointer());

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    // Focus and press left mouse button, so that serial is sent to client.
    auto* pointer_resource = server->seat()->pointer()->resource();
    wl_pointer_send_enter(pointer_resource, server->GetNextSerial(),
                          surface->resource(), 0, 0);
    wl_pointer_send_button(pointer_resource, server->GetNextSerial(),
                           server->GetNextTime(), BTN_LEFT,
                           WL_POINTER_BUTTON_STATE_PRESSED);
  });

  auto* wm_move_resize_handler = ui::GetWmMoveResizeHandler(*window_);
  for (const int value : hit_test_values) {
    {
      uint32_t direction = wl::IdentifyDirection(value);
      PostToServerAndWait(
          [id = surface_id_, direction](wl::TestWaylandServerThread* server) {
            wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
            auto* xdg_surface = surface->xdg_surface();
            EXPECT_CALL(*xdg_surface->xdg_toplevel(), Resize(_, Eq(direction)));
          });
      wm_move_resize_handler->DispatchHostWindowDragMovement(value,
                                                             gfx::Point());
    }
  }
}

TEST_P(WaylandWindowTest, ToplevelWindowUpdateWindowScale) {
  VerifyAndClearExpectations();

  // Surface scale must be 1 when no output has been entered by the window.
  EXPECT_EQ(1, window_->applied_state().window_scale);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // Configure first output with scale 1.
    wl::TestOutput* output1 = server->output();
    output1->SetPhysicalAndLogicalBounds({1920, 1080});
    output1->Flush();

    // Creating an output with scale 2.
    auto* output2 =
        server->CreateAndInitializeOutput(wl::TestOutputMetrics({1920, 1080}));
    output2->SetScale(2);
  });
  WaitForAllDisplaysReady();

  auto* output_manager = connection_->wayland_output_manager();
  EXPECT_EQ(2u, output_manager->GetAllOutputs().size());

  const uint32_t output_id1 =
      GetObjIdForOutput(output_manager->GetAllOutputs().begin()->first);
  PostToServerAndWait(
      [id = surface_id_, output_id1](wl::TestWaylandServerThread* server) {
        wl::TestOutput* output = server->GetObject<wl::TestOutput>(output_id1);
        ASSERT_TRUE(output);

        // Send the window to |output1|.
        wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(surface);
        wl_surface_send_enter(surface->resource(), output->resource());
      });

  // The window's scale and bounds must remain unchanged.
  EXPECT_EQ(1, window_->applied_state().window_scale);
  EXPECT_EQ(gfx::Size(800, 600), window_->applied_state().size_px);
  EXPECT_EQ(gfx::Rect(800, 600), window_->GetBoundsInDIP());

  // Get another output's id.
  const uint32_t output_id2 =
      GetObjIdForOutput(output_manager->GetAllOutputs().rbegin()->first);

  PostToServerAndWait([id = surface_id_, output_id2,
                       output_id1](wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(surface);
    wl::TestOutput* output2 = server->GetObject<wl::TestOutput>(output_id2);
    ASSERT_TRUE(output2);
    wl::TestOutput* output1 = server->GetObject<wl::TestOutput>(output_id1);
    ASSERT_TRUE(output1);
    // Simulating drag process from |output1| to |output2|.
    wl_surface_send_enter(surface->resource(), output2->resource());
    wl_surface_send_leave(surface->resource(), output1->resource());
  });

  // The window must change its scale and bounds to keep DIP bounds the same.
  EXPECT_EQ(2, window_->applied_state().window_scale);
  EXPECT_EQ(gfx::Size(1600, 1200), window_->applied_state().size_px);
  EXPECT_EQ(gfx::Rect(800, 600), window_->GetBoundsInDIP());
}

TEST_P(WaylandWindowTest, WaylandPopupSurfaceScale) {
  VerifyAndClearExpectations();

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // Configure an output with scale 1.
    wl::TestOutput* output1 = server->output();
    output1->SetPhysicalAndLogicalBounds({1920, 1080});
    output1->Flush();

    // Creating an output with scale 2.
    auto* output2 = server->CreateAndInitializeOutput(
        wl::TestOutputMetrics({1920, 0, 1920, 1080}));
    output2->SetScale(2);
  });
  WaitForAllDisplaysReady();

  auto* output_manager = connection_->wayland_output_manager();
  EXPECT_EQ(2u, output_manager->GetAllOutputs().size());

  const uint32_t output_id1 =
      GetObjIdForOutput(output_manager->GetAllOutputs().begin()->first);
  const uint32_t output_id2 =
      GetObjIdForOutput(output_manager->GetAllOutputs().rbegin()->first);

  std::vector<PlatformWindowType> window_types{PlatformWindowType::kMenu,
                                               PlatformWindowType::kTooltip};
  for (const auto& type : window_types) {
    PostToServerAndWait([id = surface_id_,
                         output_id1](wl::TestWaylandServerThread* server) {
      // Send the window to |output1|.
      wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
      ASSERT_TRUE(surface);
      wl::TestOutput* output = server->GetObject<wl::TestOutput>(output_id1);
      wl_surface_send_enter(surface->resource(), output->resource());
    });

    // Creating a wayland_popup on |window_|.
    SetPointerFocusedWindow(window_.get());
    gfx::Rect wayland_popup_bounds(15, 15, 10, 10);
    auto wayland_popup = CreateWaylandWindowWithParams(
        type, wayland_popup_bounds, &delegate_, window_->GetWidget());
    EXPECT_TRUE(wayland_popup);
    wayland_popup->Show(false);

    // the wayland_popup window should inherit its buffer scale from the focused
    // window.
    EXPECT_EQ(1, window_->applied_state().window_scale);
    EXPECT_EQ(window_->applied_state().window_scale,
              wayland_popup->applied_state().window_scale);
    EXPECT_EQ(wayland_popup_bounds.size(),
              wayland_popup->applied_state().size_px);
    EXPECT_EQ(wayland_popup_bounds, wayland_popup->GetBoundsInDIP());
    wayland_popup->Hide();

    PostToServerAndWait([id = surface_id_, output_id1,
                         output_id2](wl::TestWaylandServerThread* server) {
      wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
      ASSERT_TRUE(surface);
      wl::TestOutput* output1 = server->GetObject<wl::TestOutput>(output_id1);
      wl::TestOutput* output2 = server->GetObject<wl::TestOutput>(output_id2);
      // Send the window to |output2|.
      wl_surface_send_enter(surface->resource(), output2->resource());
      wl_surface_send_leave(surface->resource(), output1->resource());
    });

    EXPECT_EQ(2, window_->applied_state().window_scale);
    wayland_popup->Show(false);

    WaylandTestBase::SyncDisplay();

    // |wayland_popup|'s scale and bounds must change whenever its parents
    // scale is changed.
    EXPECT_EQ(window_->applied_state().window_scale,
              wayland_popup->applied_state().window_scale);
    EXPECT_EQ(
        gfx::ScaleToCeiledSize(wayland_popup_bounds.size(),
                               wayland_popup->applied_state().window_scale),
        wayland_popup->applied_state().size_px);

    wayland_popup->Hide();
    SetPointerFocusedWindow(nullptr);

    PostToServerAndWait([id = surface_id_,
                         output_id2](wl::TestWaylandServerThread* server) {
      wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
      ASSERT_TRUE(surface);
      wl::TestOutput* output2 = server->GetObject<wl::TestOutput>(output_id2);
      wl_surface_send_leave(surface->resource(), output2->resource());
    });
  }
}

// Tests that WaylandPopup is able to translate provided bounds via
// PlatformWindowProperties using buffer scale it's going to use that the client
// is not able to determine before PlatformWindow is created. See
// WaylandPopup::OnInitialize for more details.
TEST_P(WaylandWindowTest, WaylandPopupInitialBufferScale) {
  VerifyAndClearExpectations();

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // Configure an output with scale 1.
    wl::TestOutput* main_output = server->output();
    main_output->SetPhysicalAndLogicalBounds({1920, 1080});
    main_output->Flush();

    // Creating an output with scale 1.
    server->CreateAndInitializeOutput(
        wl::TestOutputMetrics({1921, 0, 1920, 1080}));
  });

  auto* output_manager = connection_->wayland_output_manager();
  EXPECT_EQ(2u, output_manager->GetAllOutputs().size());

  const WaylandOutput* main_output =
      output_manager->GetAllOutputs().begin()->second.get();
  const WaylandOutput* secondary_output =
      output_manager->GetAllOutputs().rbegin()->second.get();

  struct {
    raw_ptr<const WaylandOutput> output;
    const char* label;
  } screen[] = {{main_output, "main output"},
                {secondary_output, "secondary output"}};

  for (const auto& entered_output : screen) {
    PostToServerAndWait(
        [id = surface_id_, entered_output_id = GetObjIdForOutput(
                               entered_output.output->output_id())](
            wl::TestWaylandServerThread* server) {
          wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
          ASSERT_TRUE(surface);
          wl::TestOutput* output =
              server->GetObject<wl::TestOutput>(entered_output_id);
          wl_surface_send_enter(surface->resource(), output->resource());
        });
    for (auto main_output_scale = 1; main_output_scale < 5;
         main_output_scale++) {
      for (auto secondary_output_scale = 1; secondary_output_scale < 5;
           secondary_output_scale++) {
        PostToServerAndWait(
            [main_output_id = GetObjIdForOutput(main_output->output_id()),
             secondary_output_id =
                 GetObjIdForOutput(secondary_output->output_id()),
             main_output_scale,
             secondary_output_scale](wl::TestWaylandServerThread* server) {
              wl::TestOutput* main_output =
                  server->GetObject<wl::TestOutput>(main_output_id);
              wl::TestOutput* secondary_output =
                  server->GetObject<wl::TestOutput>(secondary_output_id);
              // Update scale factors first.
              main_output->SetScale(main_output_scale);
              secondary_output->SetScale(secondary_output_scale);

              main_output->Flush();
              secondary_output->Flush();
            });

        gfx::Rect bounds_dip(15, 15, 10, 10);
        // DesktopWindowTreeHostPlatform uses the scale of the current display
        // of the parent window to translate initial bounds of the popup to
        // pixels.
        const int32_t effective_scale = entered_output.output->scale_factor();
        gfx::Transform transform;
        transform.Scale(effective_scale, effective_scale);
        gfx::Rect wayland_popup_bounds = transform.MapRect(bounds_dip);

        std::unique_ptr<WaylandWindow> wayland_popup =
            CreateWaylandWindowWithParams(PlatformWindowType::kMenu, bounds_dip,
                                          &delegate_, window_->GetWidget());
        EXPECT_TRUE(wayland_popup);

        wayland_popup->Show(false);

        gfx::Size expected_px_size = wayland_popup_bounds.size();
        if (entered_output.output == secondary_output) {
          expected_px_size =
              gfx::ScaleToCeiledSize(bounds_dip.size(), secondary_output_scale);
        }

        EXPECT_EQ(expected_px_size, wayland_popup->applied_state().size_px)
            << " when the window is on " << entered_output.label
            << " that has scale " << entered_output.output->scale_factor();
      }
    }
    PostToServerAndWait(
        [id = surface_id_,
         entered_output_id = GetObjIdForOutput(main_output->output_id())](
            wl::TestWaylandServerThread* server) {
          wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
          ASSERT_TRUE(surface);
          wl::TestOutput* output =
              server->GetObject<wl::TestOutput>(entered_output_id);
          wl_surface_send_leave(surface->resource(), output->resource());
        });
  }
}

TEST_P(WaylandWindowTest, WaylandPopupInitialBufferUsesParentScale) {
  VerifyAndClearExpectations();

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // Configure the the first output with scale 1.
    wl::TestOutput* main_output = server->output();
    main_output->SetPhysicalAndLogicalBounds({1920, 1080});
    main_output->Flush();

    // Creating an output with scale 2.
    auto* output2 = server->CreateAndInitializeOutput(
        wl::TestOutputMetrics({1921, 0, 1920, 1080}));
    output2->SetScale(2);
  });
  WaitForAllDisplaysReady();

  auto* output_manager = connection_->wayland_output_manager();
  EXPECT_EQ(2u, output_manager->GetAllOutputs().size());

  const uint32_t secondary_output_id =
      GetObjIdForOutput(output_manager->GetAllOutputs().rbegin()->first);

  PostToServerAndWait([id = surface_id_, secondary_output_id](
                          wl::TestWaylandServerThread* server) {
    // Send the window to |output2|.
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(surface);
    wl::TestOutput* output =
        server->GetObject<wl::TestOutput>(secondary_output_id);

    wl_surface_send_enter(surface->resource(), output->resource());
  });

  constexpr gfx::Rect kBoundsDip{50, 50, 100, 100};
  const gfx::Size expected_size_px =
      gfx::ScaleToCeiledSize(kBoundsDip.size(), 2);

  std::unique_ptr<WaylandWindow> wayland_popup = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, kBoundsDip, &delegate_, window_->GetWidget());
  EXPECT_TRUE(wayland_popup);

  wayland_popup->Show(false);

  EXPECT_EQ(expected_size_px, wayland_popup->applied_state().size_px);

  PostToServerAndWait([id = surface_id_, secondary_output_id](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(surface);
    wl::TestOutput* output =
        server->GetObject<wl::TestOutput>(secondary_output_id);
    wl_surface_send_leave(surface->resource(), output->resource());
  });
}

// Tests that a WaylandWindow uses the entered output with largest scale
// factor as the preferred output. If scale factors are equal, the very first
// entered display is used.
TEST_P(WaylandWindowTest, GetPreferredOutput) {
  VerifyAndClearExpectations();

  // Buffer scale must be 1 when no output has been entered by the window.
  EXPECT_EQ(1, window_->applied_state().window_scale);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // Update first output.
    wl::TestOutput* output1 = server->output();
    output1->SetPhysicalAndLogicalBounds({1920, 1080});
    output1->Flush();

    // Creating a 2nd output.
    server->CreateAndInitializeOutput(
        wl::TestOutputMetrics({1921, 0, 1920, 1080}));
  });

  WaitForAllDisplaysReady();

  // Client side WaylandOutput ids.
  ASSERT_EQ(2u, screen_->GetAllDisplays().size());
  const uint32_t output1_id =
      screen_->GetOutputIdForDisplayId(screen_->GetAllDisplays().at(0).id());
  const uint32_t output2_id =
      screen_->GetOutputIdForDisplayId(screen_->GetAllDisplays().at(1).id());

  // Client side surface.
  WaylandSurface* wayland_surface = window_->root_surface();
  EXPECT_THAT(wayland_surface->entered_outputs(), ElementsAre());

  auto* output_manager = connection_->wayland_output_manager();
  ASSERT_EQ(2u, output_manager->GetAllOutputs().size());

  // Shared wl_output resource ids.
  const uint32_t wl_output1_id = GetObjIdForOutput(output1_id);
  const uint32_t wl_output2_id = GetObjIdForOutput(output2_id);

  PostToServerAndWait([id = surface_id_, wl_output1_id,
                       wl_output2_id](wl::TestWaylandServerThread* server) {
    // Send the window to |output1| and |output2|.
    wl_surface_send_enter(
        server->GetObject<wl::MockSurface>(id)->resource(),
        server->GetObject<wl::TestOutput>(wl_output1_id)->resource());
    wl_surface_send_enter(
        server->GetObject<wl::MockSurface>(id)->resource(),
        server->GetObject<wl::TestOutput>(wl_output2_id)->resource());
  });

  // The window entered two outputs.
  EXPECT_THAT(wayland_surface->entered_outputs(),
              ElementsAre(output1_id, output2_id));

  // The window must prefer the output that it entered first.
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output1_id);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // Create the third output.
    server->CreateAndInitializeOutput(
        wl::TestOutputMetrics({0, 1081, 1920, 1080}));
  });

  WaitForAllDisplaysReady();

  ASSERT_EQ(3u, screen_->GetAllDisplays().size());
  const uint32_t output3_id =
      screen_->GetOutputIdForDisplayId(screen_->GetAllDisplays().at(2).id());

  EXPECT_EQ(3u, output_manager->GetAllOutputs().size());
  const uint32_t wl_output3_id = GetObjIdForOutput(output3_id);

  PostToServerAndWait(
      [id = surface_id_, wl_output3_id](wl::TestWaylandServerThread* server) {
        // Send window into 3rd output.
        wl_surface_send_enter(
            server->GetObject<wl::MockSurface>(id)->resource(),
            server->GetObject<wl::TestOutput>(wl_output3_id)->resource());
      });

  // The window entered three outputs...
  EXPECT_THAT(wayland_surface->entered_outputs(),
              ElementsAre(output1_id, output2_id, output3_id));

  // but it still must prefer the output that it entered first.
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output1_id);

  PostToServerAndWait([wl_output2_id](wl::TestWaylandServerThread* server) {
    wl::TestOutput* output2 = server->GetObject<wl::TestOutput>(wl_output2_id);
    // Pretend that the output2 has scale factor equals to 2 now.
    output2->SetScale(2);
    output2->Flush();
  });

  // Entered outputs remain the same.
  EXPECT_THAT(wayland_surface->entered_outputs(),
              ElementsAre(output1_id, output2_id, output3_id));

  // It must be the second entered output now.
  EXPECT_EQ(2, connection_->wayland_output_manager()
                   ->GetOutput(output2_id)
                   ->scale_factor());

  // The window_ must return the output with largest scale.
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output2_id);

  PostToServerAndWait([wl_output1_id](wl::TestWaylandServerThread* server) {
    wl::TestOutput* output1 = server->GetObject<wl::TestOutput>(wl_output1_id);
    // Now, the output1 changes its scale factor to 2 as well.
    output1->SetScale(2);
    output1->Flush();
  });

  // It must be the very first output now.
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output1_id);

  PostToServerAndWait([wl_output1_id](wl::TestWaylandServerThread* server) {
    wl::TestOutput* output1 = server->GetObject<wl::TestOutput>(wl_output1_id);
    // Now, the output1 changes its scale factor back to 1.
    output1->SetScale(1);
    output1->Flush();
  });

  // It must be the very the second output now.
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output2_id);

  PostToServerAndWait([wl_output2_id](wl::TestWaylandServerThread* server) {
    wl::TestOutput* output2 = server->GetObject<wl::TestOutput>(wl_output2_id);
    // All outputs have scale factor of 1. window_ prefers the output that
    // it entered first again.
    output2->SetScale(1);
    output2->Flush();
  });

  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output1_id);
}

TEST_P(WaylandWindowTest, GetChildrenPreferredOutput) {
  VerifyAndClearExpectations();

  // Buffer scale must be 1 when no output has been entered by the window.
  EXPECT_EQ(1, window_->applied_state().window_scale);

  MockWaylandPlatformWindowDelegate menu_window_delegate;
  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(10, 10, 10, 10),
      &menu_window_delegate, window_->GetWidget());

  menu_window->Show(false);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    // Update the first output.
    wl::TestOutput* output1 = server->output();
    output1->SetPhysicalAndLogicalBounds({1920, 1080});
    output1->Flush();

    // Create a 2nd output.
    server->CreateAndInitializeOutput(
        wl::TestOutputMetrics({1921, 0, 1920, 1080}));
  });

  WaitForAllDisplaysReady();

  // Client side WaylandOutput ids.
  ASSERT_EQ(2u, screen_->GetAllDisplays().size());
  const uint32_t output1_id =
      screen_->GetOutputIdForDisplayId(screen_->GetAllDisplays().at(0).id());
  const uint32_t output2_id =
      screen_->GetOutputIdForDisplayId(screen_->GetAllDisplays().at(1).id());

  auto* output_manager = connection_->wayland_output_manager();
  ASSERT_EQ(2u, output_manager->GetAllOutputs().size());

  // Shared wl_output resource ids.
  const uint32_t wl_output1_id = GetObjIdForOutput(output1_id);
  const uint32_t wl_output2_id = GetObjIdForOutput(output2_id);

  // Client side surfaces.
  WaylandSurface* root_surface = window_->root_surface();
  WaylandSurface* menu_surface = menu_window->root_surface();
  const uint32_t menu_surface_id = menu_surface->get_surface_id();

  // Neither surface should have entered any output.
  EXPECT_THAT(root_surface->entered_outputs(), ElementsAre());
  EXPECT_THAT(menu_surface->entered_outputs(), ElementsAre());

  // Send the toplevel window into output1.
  PostToServerAndWait(
      [id = surface_id_, wl_output1_id](wl::TestWaylandServerThread* server) {
        wl_surface_send_enter(
            server->GetObject<wl::MockSurface>(id)->resource(),
            server->GetObject<wl::TestOutput>(wl_output1_id)->resource());
      });

  // The toplevel window entered the output.
  EXPECT_THAT(root_surface->entered_outputs(), ElementsAre(output1_id));
  EXPECT_THAT(menu_surface->entered_outputs(), ElementsAre());

  // The menu also thinks it entered the same output.
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output1_id);
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(),
            menu_window->GetPreferredEnteredOutputId());

  // Send the menu window into output2, while the toplevel is still on output1.
  PostToServerAndWait(
      [menu_surface_id, wl_output2_id](wl::TestWaylandServerThread* server) {
        wl_surface_send_enter(
            server->GetObject<wl::MockSurface>(menu_surface_id)->resource(),
            server->GetObject<wl::TestOutput>(wl_output2_id)->resource());
      });

  // The menu surface should be aware of the output that Wayland sent it.
  EXPECT_THAT(root_surface->entered_outputs(), ElementsAre(output1_id));
  EXPECT_THAT(menu_surface->entered_outputs(), ElementsAre(output2_id));

  // The menu still prefers output1.
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output1_id);
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(),
            menu_window->GetPreferredEnteredOutputId());

  // Send the toplevel window into output2.
  PostToServerAndWait(
      [id = surface_id_, wl_output2_id](wl::TestWaylandServerThread* server) {
        wl_surface_send_enter(
            server->GetObject<wl::MockSurface>(id)->resource(),
            server->GetObject<wl::TestOutput>(wl_output2_id)->resource());
      });

  // The toplevel window has now entered 2 outputs, in chronological order.
  EXPECT_THAT(root_surface->entered_outputs(),
              ElementsAre(output1_id, output2_id));
  EXPECT_THAT(menu_surface->entered_outputs(), ElementsAre(output2_id));

  // With the same scale factor, the toplevel window prefers the earlier output.
  // The menu window always prefers whatever the parent prefers.
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output1_id);
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(),
            menu_window->GetPreferredEnteredOutputId());

  PostToServerAndWait([wl_output2_id](wl::TestWaylandServerThread* server) {
    wl::TestOutput* output2 = server->GetObject<wl::TestOutput>(wl_output2_id);
    // Now, the output2 changes its scale factor to 2.
    output2->SetScale(2);
    output2->Flush();
  });

  // The toplevel window prefers the output with higher scale factor.
  // The menu window still prefers whatever the parent prefers.
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(), output2_id);
  EXPECT_EQ(window_->GetPreferredEnteredOutputId(),
            menu_window->GetPreferredEnteredOutputId());
}

// Tests that xdg_popup is configured with default anchor properties and bounds
// if delegate doesn't have anchor properties set.
TEST_P(WaylandWindowTest, PopupPassesDefaultAnchorInformation) {
  PopupPosition menu_window_positioner, nested_menu_window_positioner;

  menu_window_positioner = {gfx::Rect(439, 46, 1, 1), gfx::Size(287, 409),
                            XDG_POSITIONER_ANCHOR_TOP_LEFT,
                            XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT,
                            XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_Y};
  nested_menu_window_positioner = {gfx::Rect(285, 1, 1, 1), gfx::Size(305, 99),
                                   XDG_POSITIONER_ANCHOR_TOP_LEFT,
                                   XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT,
                                   XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_Y};

  auto* toplevel_window = window_.get();
  toplevel_window->SetBoundsInDIP(gfx::Rect(739, 574));

  // Case 1: properties are not provided. In this case, bounds' origin must
  // be used as anchor rect and anchor position, gravity and constraints should
  // be normal.
  MockWaylandPlatformWindowDelegate menu_window_delegate;
  EXPECT_CALL(menu_window_delegate, GetOwnedWindowAnchorAndRectInDIP())
      .WillOnce(Return(std::nullopt));
  gfx::Rect menu_window_bounds(gfx::Point(439, 46),
                               menu_window_positioner.size);
  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, menu_window_bounds, &menu_window_delegate,
      toplevel_window->GetWidget());
  EXPECT_TRUE(menu_window);

  VerifyXdgPopupPosition(menu_window.get(), menu_window_positioner);

  EXPECT_CALL(menu_window_delegate, OnBoundsChanged(_)).Times(0);
  SendConfigureEventPopup(menu_window.get(), menu_window_bounds);

  EXPECT_EQ(menu_window->GetBoundsInDIP(), menu_window_bounds);

  // Case 2: the nested menu window is positioned normally.
  MockWaylandPlatformWindowDelegate nested_menu_window_delegate;
  gfx::Rect nested_menu_window_bounds(gfx::Point(724, 47),
                                      nested_menu_window_positioner.size);
  std::unique_ptr<WaylandWindow> nested_menu_window =
      CreateWaylandWindowWithParams(
          PlatformWindowType::kMenu, nested_menu_window_bounds,
          &nested_menu_window_delegate, menu_window->GetWidget());
  EXPECT_TRUE(nested_menu_window);

  VerifyXdgPopupPosition(nested_menu_window.get(),
                         nested_menu_window_positioner);
}

// Tests that xdg_popup is configured with anchor properties received from
// delegate.
TEST_P(WaylandWindowTest, PopupPassesSetAnchorInformation) {
  PopupPosition menu_window_positioner, nested_menu_window_positioner;

  menu_window_positioner = {gfx::Rect(468, 46, 28, 28), gfx::Size(320, 404),
                            XDG_POSITIONER_ANCHOR_BOTTOM_RIGHT,
                            XDG_POSITIONER_GRAVITY_BOTTOM_LEFT,
                            XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_Y};
  nested_menu_window_positioner = {
      gfx::Rect(4, 83, 312, 1), gfx::Size(480, 294),
      XDG_POSITIONER_ANCHOR_TOP_RIGHT, XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT,
      XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_Y |
          XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_X};

  auto* toplevel_window = window_.get();
  toplevel_window->SetBoundsInDIP(gfx::Rect(508, 212));

  MockWaylandPlatformWindowDelegate menu_window_delegate;
  ui::OwnedWindowAnchor anchor = {
      gfx::Rect(menu_window_positioner.anchor_rect),
      OwnedWindowAnchorPosition::kBottomRight,
      OwnedWindowAnchorGravity::kBottomLeft,
      OwnedWindowConstraintAdjustment::kAdjustmentFlipY};
  EXPECT_CALL(menu_window_delegate, GetOwnedWindowAnchorAndRectInDIP())
      .WillOnce(Return(anchor));
  gfx::Rect menu_window_bounds(gfx::Point(176, 74),
                               menu_window_positioner.size);
  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, menu_window_bounds, &menu_window_delegate,
      toplevel_window->GetWidget());
  EXPECT_TRUE(menu_window);

  VerifyXdgPopupPosition(menu_window.get(), menu_window_positioner);

  MockWaylandPlatformWindowDelegate nested_menu_window_delegate;
  anchor = {{180, 157, 312, 1},
            OwnedWindowAnchorPosition::kTopRight,
            OwnedWindowAnchorGravity::kBottomRight,
            OwnedWindowConstraintAdjustment::kAdjustmentFlipY |
                OwnedWindowConstraintAdjustment::kAdjustmentFlipX};
  EXPECT_CALL(nested_menu_window_delegate, GetOwnedWindowAnchorAndRectInDIP())
      .WillOnce(Return(anchor));
  gfx::Rect nested_menu_window_bounds(gfx::Point(492, 157),
                                      nested_menu_window_positioner.size);
  std::unique_ptr<WaylandWindow> nested_menu_window =
      CreateWaylandWindowWithParams(
          PlatformWindowType::kMenu, nested_menu_window_bounds,
          &nested_menu_window_delegate, menu_window->GetWidget());
  EXPECT_TRUE(nested_menu_window);

  VerifyXdgPopupPosition(nested_menu_window.get(),
                         nested_menu_window_positioner);
}

TEST_P(WaylandWindowTest, SetBoundsResizesEmptySizes) {
  display::test::TestScreen test_screen_{/*create_display=*/true,
                                         /*register_screen=*/true};
  auto* toplevel_window = window_.get();
  toplevel_window->SetBoundsInDIP(gfx::Rect(666, 666));

  testing::NiceMock<MockWaylandPlatformWindowDelegate> popup_delegate;
  gfx::Rect menu_window_bounds(gfx::Point(0, 0), {0, 0});
  std::unique_ptr<WaylandWindow> popup = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, menu_window_bounds, &popup_delegate,
      toplevel_window->GetWidget());
  EXPECT_TRUE(popup);

  popup->SetBoundsInDIP({0, 0, 0, 0});

  VerifyXdgPopupPosition(
      popup.get(),
      {gfx::Rect(0, 0, 1, 1), gfx::Size(1, 1), XDG_POSITIONER_ANCHOR_TOP_LEFT,
       XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT,
       XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_Y});
}

TEST_P(WaylandWindowTest, SetOpaqueRegion) {
  gfx::Rect new_bounds(500, 600);
  SkIRect rect =
      SkIRect::MakeXYWH(0, 0, new_bounds.width(), new_bounds.height());
  auto state_array = MakeStateArray({XDG_TOPLEVEL_STATE_ACTIVATED});
  SendConfigureEvent(surface_id_, new_bounds.size(), state_array);
  AdvanceFrameToCurrent(window_.get(), delegate_);

  VerifyAndClearExpectations();
  PostToServerAndWait(
      [id = surface_id_, new_bounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        EXPECT_EQ(mock_surface->opaque_region(), new_bounds);
      });

  new_bounds.set_size(gfx::Size(1000, 534));
  rect = SkIRect::MakeXYWH(0, 0, new_bounds.width(), new_bounds.height());
  SendConfigureEvent(surface_id_, new_bounds.size(), state_array);
  AdvanceFrameToCurrent(window_.get(), delegate_);

  VerifyAndClearExpectations();
  PostToServerAndWait(
      [id = surface_id_, new_bounds](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface);
        EXPECT_EQ(mock_surface->opaque_region(), new_bounds);
      });
}

TEST_P(WaylandWindowTest, OnCloseRequest) {
  EXPECT_CALL(delegate_, OnCloseRequest());

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    wl::MockXdgSurface* xdg_surface = mock_surface->xdg_surface();
    xdg_toplevel_send_close(xdg_surface->xdg_toplevel()->resource());
  });
}

TEST_P(WaylandWindowTest, WaylandPopupSimpleParent) {
  VerifyAndClearExpectations();

  // WaylandPopup must ignore the parent provided by aura and should always
  // use focused window instead.
  gfx::Rect wayland_popup_bounds(gfx::Point(15, 15), gfx::Size(10, 10));
  std::unique_ptr<WaylandWindow> wayland_popup = CreateWaylandWindowWithParams(
      PlatformWindowType::kTooltip, wayland_popup_bounds, &delegate_,
      window_->GetWidget());
  EXPECT_TRUE(wayland_popup);

  wayland_popup->Show(false);

  PostToServerAndWait(
      [id = wayland_popup->root_surface()->get_surface_id(),
       wayland_popup_bounds](wl::TestWaylandServerThread* server) {
        auto* mock_surface_popup = server->GetObject<wl::MockSurface>(id);
        auto* mock_xdg_popup = mock_surface_popup->xdg_surface()->xdg_popup();

        EXPECT_EQ(mock_xdg_popup->anchor_rect().origin(),
                  wayland_popup_bounds.origin());
        EXPECT_EQ(mock_surface_popup->opaque_region(),
                  gfx::Rect(wayland_popup_bounds.size()));
      });

  wayland_popup->Hide();
}

TEST_P(WaylandWindowTest, WaylandPopupNestedParent) {
  VerifyAndClearExpectations();

  gfx::Rect menu_window_bounds(gfx::Point(10, 10), gfx::Size(100, 100));
  auto menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, menu_window_bounds, &delegate_,
      window_->GetWidget());
  EXPECT_TRUE(menu_window);

  VerifyAndClearExpectations();
  SetPointerFocusedWindow(menu_window.get());

  std::vector<PlatformWindowType> window_types{PlatformWindowType::kMenu,
                                               PlatformWindowType::kTooltip};
  for (const auto& type : window_types) {
    gfx::Rect nested_wayland_popup_bounds(gfx::Point(15, 15),
                                          gfx::Size(10, 10));
    auto nested_wayland_popup =
        CreateWaylandWindowWithParams(type, nested_wayland_popup_bounds,
                                      &delegate_, menu_window->GetWidget());
    EXPECT_TRUE(nested_wayland_popup);

    VerifyAndClearExpectations();

    nested_wayland_popup->Show(false);

    PostToServerAndWait(
        [id = nested_wayland_popup->root_surface()->get_surface_id(),
         nested_wayland_popup_bounds,
         menu_window_bounds](wl::TestWaylandServerThread* server) {
          auto* mock_surface_nested = server->GetObject<wl::MockSurface>(id);
          auto* mock_xdg_popup_nested =
              mock_surface_nested->xdg_surface()->xdg_popup();

          auto new_origin = nested_wayland_popup_bounds.origin() -
                            menu_window_bounds.origin().OffsetFromOrigin();
          EXPECT_EQ(mock_xdg_popup_nested->anchor_rect().origin(), new_origin);
          EXPECT_EQ(mock_surface_nested->opaque_region(),
                    gfx::Rect(nested_wayland_popup_bounds.size()));
        });

    SetPointerFocusedWindow(nullptr);
    nested_wayland_popup->Hide();
  }
}

// Tests that size constraints returned by the `ui::PlatformWindowDelegate` are
// obeyed by the window when its bounds are set internally via its
// SetBoundsInDIP() implementation.
TEST_P(WaylandWindowTest, SizeConstraintsInternal) {
  constexpr gfx::Size kMinSize{100, 100};
  constexpr gfx::Size kMaxSize{300, 300};

  window_->SetBoundsInDIP({0, 0, 200, 200});

  gfx::Rect even_smaller_bounds(kMinSize);
  even_smaller_bounds.Inset(10);
  even_smaller_bounds.set_origin({0, 0});

  EXPECT_CALL(delegate_, GetMinimumSizeForWindow()).WillOnce(Return(kMinSize));
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));

  window_->SetBoundsInDIP(even_smaller_bounds);

  VerifyAndClearExpectations();

  gfx::Rect even_greater_bounds(kMaxSize);
  even_greater_bounds.Outset(10);
  even_greater_bounds.set_origin({0, 0});

  EXPECT_CALL(delegate_, GetMaximumSizeForWindow()).WillOnce(Return(kMaxSize));
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));

  window_->SetBoundsInDIP(even_greater_bounds);
}

// Tests that size constraints returned by the `ui::PlatformWindowDelegate` are
// obeyed by the window when its bounds are set externally via the configure
// event sent by the compositor.
TEST_P(WaylandWindowTest, SizeConstraintsExternal) {
  constexpr gfx::Size kMinSize{100, 100};
  constexpr gfx::Size kMaxSize{300, 300};

  MapSurface(delegate_);

  EXPECT_CALL(delegate_, GetMinimumSizeForWindow())
      .WillRepeatedly(Return(kMinSize));
  EXPECT_CALL(delegate_, GetMaximumSizeForWindow())
      .WillRepeatedly(Return(kMaxSize));

  window_->SetBoundsInDIP({0, 0, 200, 200});

  auto state = InitializeWlArrayWithActivatedState();

  gfx::Rect even_smaller_bounds(kMinSize);
  even_smaller_bounds.Inset(10);
  even_smaller_bounds.set_origin({0, 0});

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));

  SendConfigureEvent(surface_id_, even_smaller_bounds.size(), state);
  VerifyAndClearExpectations();

  EXPECT_CALL(delegate_, GetMinimumSizeForWindow())
      .WillRepeatedly(Return(kMinSize));
  EXPECT_CALL(delegate_, GetMaximumSizeForWindow())
      .WillRepeatedly(Return(kMaxSize));

  gfx::Rect even_greater_bounds(kMaxSize);
  even_greater_bounds.Outset(10);
  even_greater_bounds.set_origin({0, 0});

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange)));

  SendConfigureEvent(surface_id_, even_greater_bounds.size(), state);
}

TEST_P(WaylandWindowTest, OnSizeConstraintsChanged) {
  const bool kBooleans[] = {false, true};
  for (bool has_min_size : kBooleans) {
    for (bool has_max_size : kBooleans) {
      std::optional<gfx::Size> min_size =
          has_min_size ? std::optional<gfx::Size>(gfx::Size(100, 200))
                       : std::nullopt;
      std::optional<gfx::Size> max_size =
          has_max_size ? std::optional<gfx::Size>(gfx::Size(300, 400))
                       : std::nullopt;
      EXPECT_CALL(delegate_, GetMinimumSizeForWindow())
          .WillOnce(Return(min_size));
      EXPECT_CALL(delegate_, GetMaximumSizeForWindow())
          .WillOnce(Return(max_size));

      PostToServerAndWait([id = surface_id_, has_min_size,
                           has_max_size](wl::TestWaylandServerThread* server) {
        auto* mock_surface = server->GetObject<wl::MockSurface>(id);
        auto* mock_xdg_surface = mock_surface->xdg_surface();
        EXPECT_CALL(*mock_xdg_surface->xdg_toplevel(), SetMinSize(100, 200))
            .Times(has_min_size ? 1 : 0);
        EXPECT_CALL(*mock_xdg_surface->xdg_toplevel(), SetMaxSize(300, 400))
            .Times(has_max_size ? 1 : 0);
      });

      window_->SizeConstraintsChanged();
      VerifyAndClearExpectations();
    }
  }
}

TEST_P(WaylandWindowTest, DestroysCreatesSurfaceOnHideShow) {
  MockWaylandPlatformWindowDelegate delegate;
  auto window = CreateWaylandWindowWithParams(PlatformWindowType::kWindow,
                                              gfx::Rect(100, 100), &delegate);
  ASSERT_TRUE(window);

  const uint32_t surface_id = window->root_surface()->get_surface_id();
  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_TRUE(mock_surface->xdg_surface());
    EXPECT_TRUE(mock_surface->xdg_surface()->xdg_toplevel());
  });

  window->Hide();

  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_FALSE(mock_surface->xdg_surface());
  });

  window->Show(false);

  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_TRUE(mock_surface->xdg_surface());
    EXPECT_TRUE(mock_surface->xdg_surface()->xdg_toplevel());
  });
}

TEST_P(WaylandWindowTest, DestroysCreatesPopupsOnHideShow) {
  MockWaylandPlatformWindowDelegate delegate;
  auto window = CreateWaylandWindowWithParams(PlatformWindowType::kMenu,
                                              gfx::Rect(50, 50), &delegate,
                                              window_->GetWidget());
  ASSERT_TRUE(window);

  const uint32_t surface_id = window->root_surface()->get_surface_id();
  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_TRUE(mock_surface->xdg_surface());
    EXPECT_TRUE(mock_surface->xdg_surface()->xdg_popup());
  });

  window->Hide();

  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_FALSE(mock_surface->xdg_surface());
  });

  window->Show(false);

  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_TRUE(mock_surface->xdg_surface());
    EXPECT_TRUE(mock_surface->xdg_surface()->xdg_popup());
  });
}

TEST_P(WaylandWindowTest, ReattachesBackgroundOnShow) {
  EXPECT_TRUE(connection_->buffer_manager_host());

  auto interface_ptr = connection_->buffer_manager_host()->BindInterface();
  buffer_manager_gpu_->Initialize(std::move(interface_ptr), {},
                                  /*supports_dma_buf=*/false,
                                  /*supports_viewporter=*/true,
                                  /*supports_acquire_fence=*/false,
                                  /*supports_overlays=*/true,
                                  /*supports_single_pixel_buffer=*/true);

  // Setup wl_buffers.
  constexpr uint32_t buffer_id1 = 1;
  constexpr uint32_t buffer_id2 = 2;
  gfx::Size buffer_size(1024, 768);
  auto length = 1024 * 768 * 4;
  buffer_manager_gpu_->CreateShmBasedBuffer(MakeFD(), length, buffer_size,
                                            buffer_id1);
  buffer_manager_gpu_->CreateShmBasedBuffer(MakeFD(), length, buffer_size,
                                            buffer_id2);

  base::RunLoop().RunUntilIdle();

  // Create window.
  MockWaylandPlatformWindowDelegate delegate;
  auto window = CreateWaylandWindowWithParams(PlatformWindowType::kWindow,
                                              gfx::Rect(100, 100), &delegate);
  ASSERT_TRUE(window);
  auto states = InitializeWlArrayWithActivatedState();

  // Configure window to be ready to attach wl_buffers.
  const uint32_t surface_id = window->root_surface()->get_surface_id();
  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_TRUE(mock_surface->xdg_surface());
    EXPECT_TRUE(mock_surface->xdg_surface()->xdg_toplevel());
  });
  SendConfigureEvent(surface_id, {100, 100}, states);

  // Commit a frame with only background.
  std::vector<wl::WaylandOverlayConfig> overlays;
  wl::WaylandOverlayConfig background;
  background.z_order = INT32_MIN;
  background.buffer_id = buffer_id1;
  overlays.push_back(std::move(background));
  buffer_manager_gpu_->CommitOverlays(window->GetWidget(), 1u, gfx::FrameData(),
                                      std::move(overlays));

  // Let mojo messages from gpu to host go through.
  base::RunLoop().RunUntilIdle();

  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    mock_surface->SendFrameCallback();
  });

  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    EXPECT_NE(mock_surface->attached_buffer(), nullptr);
  });

  window->Hide();
  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    mock_surface->SendFrameCallback();
  });

  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    // `WaylandToplevelWindow::Hide()` should have already released the buffer.
    EXPECT_EQ(mock_surface->attached_buffer(), nullptr);
  });
  window->Show(false);

  SendConfigureEvent(surface_id, {100, 100}, states);

  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    // Expects to receive an attach request on next frame.
    EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(1);
  });

  // Commit a frame with only the primary_plane.
  overlays.clear();
  wl::WaylandOverlayConfig primary;
  primary.z_order = 0;
  primary.buffer_id = buffer_id2;
  overlays.push_back(std::move(primary));
  buffer_manager_gpu_->CommitOverlays(window->GetWidget(), 2u, gfx::FrameData(),
                                      std::move(overlays));

  // Let mojo messages from gpu to host go through.
  base::RunLoop().RunUntilIdle();

  PostToServerAndWait([surface_id](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    // WaylandWindow should automatically reattach the background.
    EXPECT_NE(mock_surface->attached_buffer(), nullptr);
  });
}

// Tests that if the window gets hidden and shown again, the title, app id and
// size constraints remain the same.
TEST_P(WaylandWindowTest, SetsPropertiesOnShow) {
  constexpr char kAppId[] = "wayland_test";
  const std::u16string kTitle(u"WaylandWindowTest");

  PlatformWindowInitProperties properties;
  properties.bounds = gfx::Rect(100, 100);
  properties.type = PlatformWindowType::kWindow;
  properties.wm_class_class = kAppId;

  MockWaylandPlatformWindowDelegate delegate;
  auto window =
      delegate.CreateWaylandWindow(connection_.get(), std::move(properties));
  ASSERT_TRUE(window);
  window->Show(false);

  const uint32_t surface_id = window->root_surface()->get_surface_id();
  PostToServerAndWait([surface_id, app_id = window->GetWindowUniqueId()](
                          wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    auto* mock_xdg_toplevel = mock_surface->xdg_surface()->xdg_toplevel();
    // Only app id must be set now.
    EXPECT_EQ(app_id, mock_xdg_toplevel->app_id());
    EXPECT_TRUE(mock_xdg_toplevel->title().empty());
    EXPECT_TRUE(mock_xdg_toplevel->min_size().IsEmpty());
    EXPECT_TRUE(mock_xdg_toplevel->max_size().IsEmpty());
  });

  // Now, propagate size constraints and title.
  std::optional<gfx::Size> min_size(gfx::Size(1, 1));
  std::optional<gfx::Size> max_size(gfx::Size(100, 100));
  EXPECT_CALL(delegate, GetMinimumSizeForWindow())
      .WillRepeatedly(Return(min_size));
  EXPECT_CALL(delegate, GetMaximumSizeForWindow())
      .WillRepeatedly(Return(max_size));

  PostToServerAndWait([surface_id, min_size, max_size,
                       kTitle](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    auto* mock_xdg_toplevel = mock_surface->xdg_surface()->xdg_toplevel();
    EXPECT_CALL(*mock_xdg_toplevel, SetMinSize(min_size.value().width(),
                                               min_size.value().height()));
    EXPECT_CALL(*mock_xdg_toplevel, SetMaxSize(max_size.value().width(),
                                               max_size.value().height()));
    EXPECT_CALL(*mock_xdg_toplevel, SetTitle(base::UTF16ToUTF8(kTitle)));
  });

  window->SetTitle(kTitle);
  window->SizeConstraintsChanged();
  VerifyAndClearExpectations();

  window->Hide();

  WaylandTestBase::SyncDisplay();

  window->Show(false);

  PostToServerAndWait([surface_id, min_size, max_size, kTitle,
                       app_id = window->GetWindowUniqueId()](
                          wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(surface_id);
    auto* mock_xdg_toplevel = mock_surface->xdg_surface()->xdg_toplevel();

    mock_xdg_toplevel = mock_surface->xdg_surface()->xdg_toplevel();
    // We can't mock all those methods above as long as the xdg_toplevel is
    // created and destroyed on each show and hide call. However, it is the same
    // WaylandToplevelWindow object that cached the values we set and must
    // restore them on Show().
    EXPECT_EQ(mock_xdg_toplevel->min_size(), min_size.value());
    EXPECT_EQ(mock_xdg_toplevel->max_size(), max_size.value());
    EXPECT_EQ(app_id, mock_xdg_toplevel->app_id());
    EXPECT_EQ(mock_xdg_toplevel->title(), base::UTF16ToUTF8(kTitle));
  });
}

// Tests that a popup window is created using the serial of button press
// events as required by the Wayland protocol spec.
TEST_P(WaylandWindowTest, CreatesPopupOnButtonPressSerial) {
  for (bool use_explicit_grab : {false, true}) {
    base::test::ScopedCommandLine command_line_;
    if (use_explicit_grab) {
      command_line_.GetProcessCommandLine()->AppendSwitch(
          switches::kUseWaylandExplicitGrab);
    }

    PostToServerAndWait([](wl::TestWaylandServerThread* server) {
      wl_seat_send_capabilities(
          server->seat()->resource(),
          WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_KEYBOARD);
    });

    constexpr uint32_t keyboard_enter_serial = 1;
    constexpr uint32_t pointer_enter_serial = 2;
    constexpr uint32_t button_press_serial = 3;
    constexpr uint32_t button_release_serial = 4;

    PostToServerAndWait([id =
                             surface_id_](wl::TestWaylandServerThread* server) {
      wl::MockSurface* toplevel_surface =
          server->GetObject<wl::MockSurface>(id);
      wl::ScopedWlArray empty({});
      wl_keyboard_send_enter(server->seat()->keyboard()->resource(),
                             keyboard_enter_serial,
                             toplevel_surface->resource(), empty.get());

      wl_pointer_send_enter(server->seat()->pointer()->resource(),
                            pointer_enter_serial, toplevel_surface->resource(),
                            wl_fixed_from_int(0), wl_fixed_from_int(0));

      // Send two events - button down and button up.
      wl_pointer_send_button(server->seat()->pointer()->resource(),
                             button_press_serial, 1002, BTN_LEFT,
                             WL_POINTER_BUTTON_STATE_PRESSED);
      wl_pointer_send_button(server->seat()->pointer()->resource(),
                             button_release_serial, 1004, BTN_LEFT,
                             WL_POINTER_BUTTON_STATE_RELEASED);
    });

    // Create a popup window and verify the client used correct serial.
    MockWaylandPlatformWindowDelegate delegate;
    auto popup = CreateWaylandWindowWithParams(PlatformWindowType::kMenu,
                                               gfx::Rect(50, 50), &delegate,
                                               window_->GetWidget());
    ASSERT_TRUE(popup);

    const uint32_t surface_id = popup->root_surface()->get_surface_id();
    // Unfortunately, everything has to be captured as |use_explicit_grab| may
    // not be used and |maybe_unused| doesn't work with lambda captures.
    PostToServerAndWait([&](wl::TestWaylandServerThread* server) {
      auto* test_popup = GetTestXdgPopupByWindow(server, surface_id);
      ASSERT_TRUE(test_popup);

      if (use_explicit_grab) {
        EXPECT_NE(test_popup->grab_serial(), button_release_serial);
        EXPECT_EQ(test_popup->grab_serial(), button_press_serial);
      } else {
        EXPECT_EQ(test_popup->grab_serial(), 0U);
      }
    });
  }
}

// Tests that a popup window is created using the serial of touch down events
// as required by the Wayland protocol spec.
TEST_P(WaylandWindowTest, CreatesPopupOnTouchDownSerial) {
  for (bool use_explicit_grab : {false, true}) {
    base::test::ScopedCommandLine command_line_;
    if (use_explicit_grab) {
      command_line_.GetProcessCommandLine()->AppendSwitch(
          switches::kUseWaylandExplicitGrab);
    }
    PostToServerAndWait([](wl::TestWaylandServerThread* server) {
      wl_seat_send_capabilities(
          server->seat()->resource(),
          WL_SEAT_CAPABILITY_TOUCH | WL_SEAT_CAPABILITY_KEYBOARD);
    });

    constexpr uint32_t enter_serial = 1;
    constexpr uint32_t touch_down_serial = 2;
    constexpr uint32_t touch_up_serial = 3;

    PostToServerAndWait([id =
                             surface_id_](wl::TestWaylandServerThread* server) {
      wl::MockSurface* toplevel_surface =
          server->GetObject<wl::MockSurface>(id);
      wl::ScopedWlArray empty({});
      wl_keyboard_send_enter(server->seat()->keyboard()->resource(),
                             enter_serial, toplevel_surface->resource(),
                             empty.get());

      // Send two events - touch down and touch up.
      wl_touch_send_down(server->seat()->touch()->resource(), touch_down_serial,
                         0, toplevel_surface->resource(), 0 /* id */,
                         wl_fixed_from_int(50), wl_fixed_from_int(100));
      wl_touch_send_frame(server->seat()->touch()->resource());

      wl_touch_send_up(server->seat()->touch()->resource(), touch_up_serial,
                       1000, 0 /* id */);
      wl_touch_send_frame(server->seat()->touch()->resource());
    });

    // Create a popup window and verify the client used correct serial.
    MockWaylandPlatformWindowDelegate delegate;
    auto popup = CreateWaylandWindowWithParams(PlatformWindowType::kMenu,
                                               gfx::Rect(50, 50), &delegate,
                                               window_->GetWidget());
    ASSERT_TRUE(popup);

    const uint32_t surface_id = popup->root_surface()->get_surface_id();
    // Unfortunately, everything has to be captured as |use_explicit_grab| may
    // not be used and |maybe_unused| doesn't work with lambda captures.
    PostToServerAndWait([&](wl::TestWaylandServerThread* server) {
      auto* test_popup = GetTestXdgPopupByWindow(server, surface_id);
      ASSERT_TRUE(test_popup);
      // Unless the use-wayland-explicit-grab switch is set, touch events
      // are the exception, i.e: the serial sent before the "up" event
      // (latest) cannot be used, otherwise, some compositors may dismiss
      // popups.
      if (!use_explicit_grab) {
        EXPECT_EQ(test_popup->grab_serial(), 0U);
      }
    });

    popup->Hide();

    PostToServerAndWait([id =
                             surface_id_](wl::TestWaylandServerThread* server) {
      wl::MockSurface* toplevel_surface =
          server->GetObject<wl::MockSurface>(id);
      // Send a single down event now.
      wl_touch_send_down(server->seat()->touch()->resource(), touch_down_serial,
                         0, toplevel_surface->resource(), 0 /* id */,
                         wl_fixed_from_int(50), wl_fixed_from_int(100));
      wl_touch_send_frame(server->seat()->touch()->resource());
    });

    popup->Show(false);

    // Unfortunately, everything has to be captured as |use_explicit_grab| may
    // not be used and |maybe_unused| doesn't work with lambda captures.
    PostToServerAndWait([&](wl::TestWaylandServerThread* server) {
      auto* test_popup = GetTestXdgPopupByWindow(server, surface_id);
      ASSERT_TRUE(test_popup);

      uint32_t expected_serial = touch_down_serial;
      auto env = base::Environment::Create();
      if (base::nix::GetDesktopEnvironment(env.get()) ==
          base::nix::DESKTOP_ENVIRONMENT_GNOME) {
        // We do not grab with touch events on gnome shell.
        expected_serial = 0u;
      }
      if (use_explicit_grab) {
        EXPECT_EQ(test_popup->grab_serial(), expected_serial);
      } else {
        EXPECT_EQ(test_popup->grab_serial(), 0U);
      }
    });
  }
}

// Tests nested menu windows get the topmost window in the stack of windows
// within the same family/tree.
TEST_P(WaylandWindowTest, NestedPopupWindowsGetCorrectParent) {
  VerifyAndClearExpectations();

  gfx::Rect menu_window_bounds(gfx::Rect(10, 20, 20, 20));
  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, menu_window_bounds, &delegate_,
      window_->GetWidget());
  EXPECT_TRUE(menu_window);

  EXPECT_TRUE(menu_window->parent_window() == window_.get());

  gfx::Rect menu_window_bounds2(gfx::Rect(20, 40, 30, 20));
  std::unique_ptr<WaylandWindow> menu_window2 = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, menu_window_bounds2, &delegate_,
      menu_window->GetWidget());
  EXPECT_TRUE(menu_window2);

  EXPECT_TRUE(menu_window2->parent_window() == menu_window.get());

  gfx::Rect menu_window_bounds3(gfx::Rect(30, 40, 30, 20));
  std::unique_ptr<WaylandWindow> menu_window3 = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, menu_window_bounds3, &delegate_,
      menu_window2->GetWidget());
  EXPECT_TRUE(menu_window3);

  EXPECT_TRUE(menu_window3->parent_window() == menu_window2.get());

  gfx::Rect menu_window_bounds4(gfx::Rect(40, 40, 30, 20));
  std::unique_ptr<WaylandWindow> menu_window4 = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, menu_window_bounds4, &delegate_,
      menu_window3->GetWidget());
  EXPECT_TRUE(menu_window4);

  EXPECT_TRUE(menu_window4->parent_window() == menu_window3.get());
}

TEST_P(WaylandWindowTest, DoesNotGrabPopupIfNoSeat) {
  // Create a popup window and verify the grab serial is not set.
  MockWaylandPlatformWindowDelegate delegate;
  auto popup = CreateWaylandWindowWithParams(PlatformWindowType::kMenu,
                                             gfx::Rect(50, 50), &delegate,
                                             window_->GetWidget());
  ASSERT_TRUE(popup);

  PostToServerAndWait([surface_id = popup->root_surface()->get_surface_id()](
                          wl::TestWaylandServerThread* server) {
    auto* test_popup = GetTestXdgPopupByWindow(server, surface_id);
    ASSERT_TRUE(test_popup);
    EXPECT_EQ(test_popup->grab_serial(), 0u);
  });
}

// Regression test for https://crbug.com/1247799.
TEST_P(WaylandWindowTest, DoesNotGrabPopupUnlessParentHasGrab) {
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER);
  });
  ASSERT_TRUE(connection_->seat()->pointer());
  SetPointerFocusedWindow(window_.get());

  // Emulate a root menu creation with no serial available and ensure
  // ozone/wayland does not attempt to grab it.
  connection_->serial_tracker().ClearForTesting();

  MockWaylandPlatformWindowDelegate delegate;
  std::unique_ptr<WaylandWindow> root_menu;
  root_menu = CreateWaylandWindowWithParams(PlatformWindowType::kMenu,
                                            gfx::Rect(50, 50), &delegate,
                                            window_->GetWidget());
  VerifyAndClearExpectations();
  Mock::VerifyAndClearExpectations(&delegate);
  ASSERT_TRUE(root_menu);

  PostToServerAndWait(
      [surface_id = root_menu->root_surface()->get_surface_id()](
          wl::TestWaylandServerThread* server) {
        auto* server_root_menu = GetTestXdgPopupByWindow(server, surface_id);
        ASSERT_TRUE(server_root_menu);
        EXPECT_EQ(server_root_menu->grab_serial(), 0u);
      });

  // Emulate a nested menu creation triggered by a mouse button event and ensure
  // ozone/wayland does not attempt to grab it, as its parent also has not grab.
  EXPECT_CALL(delegate, DispatchEvent(_)).Times(2);
  PostToServerAndWait(
      [surface_id = root_menu->root_surface()->get_surface_id()](
          wl::TestWaylandServerThread* server) {
        auto* server_root_menu_surface =
            server->GetObject<wl::MockSurface>(surface_id);
        ASSERT_TRUE(server_root_menu_surface);

        auto* pointer_resource = server->seat()->pointer()->resource();
        wl_pointer_send_enter(pointer_resource, 3u /*serial*/,
                              server_root_menu_surface->resource(), 0, 0);
        wl_pointer_send_frame(pointer_resource);
        wl_pointer_send_button(pointer_resource, 4u /*serial*/, 1, BTN_LEFT,
                               WL_POINTER_BUTTON_STATE_PRESSED);
        wl_pointer_send_frame(pointer_resource);
      });
  Mock::VerifyAndClearExpectations(&delegate);

  MockWaylandPlatformWindowDelegate delegate_2;
  std::unique_ptr<WaylandWindow> child_menu;
  child_menu = CreateWaylandWindowWithParams(PlatformWindowType::kMenu,
                                             gfx::Rect(10, 10), &delegate_2,
                                             root_menu->GetWidget());
  VerifyAndClearExpectations();
  Mock::VerifyAndClearExpectations(&delegate_2);
  ASSERT_TRUE(child_menu);

  PostToServerAndWait(
      [surface_id = child_menu->root_surface()->get_surface_id(),
       root_menu_id = root_menu->root_surface()->get_surface_id()](
          wl::TestWaylandServerThread* server) {
        auto* server_child_menu = GetTestXdgPopupByWindow(server, surface_id);
        ASSERT_TRUE(server_child_menu);
        EXPECT_EQ(server_child_menu->grab_serial(), 0u);

        auto* pointer_resource = server->seat()->pointer()->resource();
        auto* server_root_menu_surface =
            server->GetObject<wl::MockSurface>(root_menu_id);
        wl_pointer_send_leave(pointer_resource, 5u /*serial*/,
                              server_root_menu_surface->resource());
        wl_pointer_send_frame(pointer_resource);
      });
}

TEST_P(WaylandWindowTest, InitialBounds) {
  testing::NiceMock<MockWaylandPlatformWindowDelegate> delegate_2;
  auto toplevel = CreateWaylandWindowWithParams(
      PlatformWindowType::kWindow, gfx::Rect(10, 10, 200, 200), &delegate_2);
  {
    WaylandWindow::WindowStates window_states;
    window_states.is_maximized = false;
    window_states.is_fullscreen = false;
    window_states.is_activated = true;
    toplevel->HandleToplevelConfigureWithOrigin(0, 0, 0, 0, window_states);
  }
  toplevel->HandleSurfaceConfigure(2);
  EXPECT_EQ(gfx::Rect(10, 10, 200, 200), toplevel->GetBoundsInDIP());
}

namespace {

class WaylandSubsurfaceTest : public WaylandWindowTest {
 public:
  WaylandSubsurfaceTest() = default;
  ~WaylandSubsurfaceTest() override = default;

 protected:
  void OneWaylandSubsurfaceTestHelper(
      const gfx::RectF& subsurface_bounds,
      const gfx::RectF& expected_subsurface_bounds) {
    VerifyAndClearExpectations();

    std::unique_ptr<WaylandWindow> window = CreateWaylandWindowWithParams(
        PlatformWindowType::kWindow, gfx::Rect(640, 480), &delegate_);
    EXPECT_TRUE(window);

    bool result = window->RequestSubsurface();
    EXPECT_TRUE(result);
    connection_->Flush();

    WaylandSubsurface* wayland_subsurface =
        window->wayland_subsurfaces().begin()->get();

    PostToServerAndWait(
        [subsurface_id =
             wayland_subsurface->wayland_surface()->get_surface_id()](
            wl::TestWaylandServerThread* server) {
          auto* mock_surface_subsurface =
              server->GetObject<wl::MockSurface>(subsurface_id);
          EXPECT_TRUE(mock_surface_subsurface);
        });
    wayland_subsurface->ConfigureAndShowSurface(
        subsurface_bounds, gfx::RectF(0, 0, 640, 480) /*parent_bounds_px*/,
        1.f /*buffer_scale*/, nullptr, nullptr);
    connection_->Flush();

    PostToServerAndWait(
        [surface_id = window->root_surface()->get_surface_id(),
         subsurface_id =
             wayland_subsurface->wayland_surface()->get_surface_id(),
         expected_subsurface_bounds](wl::TestWaylandServerThread* server) {
          auto* mock_surface_root_window =
              server->GetObject<wl::MockSurface>(surface_id);
          auto* mock_surface_subsurface =
              server->GetObject<wl::MockSurface>(subsurface_id);
          EXPECT_TRUE(mock_surface_subsurface);
          auto* test_subsurface = mock_surface_subsurface->sub_surface();
          EXPECT_TRUE(test_subsurface);
          auto* parent_resource = mock_surface_root_window->resource();
          EXPECT_EQ(parent_resource, test_subsurface->parent_resource());
          // The conversion from double to fixed and back is necessary because
          // it
          // happens during the roundtrip, and it creates significant error.
          gfx::PointF expected_position(wl_fixed_to_double(wl_fixed_from_double(
                                            expected_subsurface_bounds.x())),
                                        wl_fixed_to_double(wl_fixed_from_double(
                                            expected_subsurface_bounds.y())));
          EXPECT_EQ(test_subsurface->position(), expected_position);
          EXPECT_TRUE(test_subsurface->sync());
        });
  }

  std::vector<WaylandSubsurface*> RequestWaylandSubsurface(uint32_t n) {
    VerifyAndClearExpectations();
    std::vector<WaylandSubsurface*> res =
        std::vector<WaylandSubsurface*>{window_->primary_subsurface()};
    for (uint32_t i = 0; i < n - 1; ++i) {
      window_->RequestSubsurface();
    }
    for (auto& subsurface : window_->wayland_subsurfaces()) {
      res.push_back(subsurface.get());
    }
    return res;
  }
};

}  // namespace

// Tests integer and non integer size/position support. Ozone/Wayland is
// expected to ceil the bounds.
TEST_P(WaylandSubsurfaceTest, OneWaylandSubsurfaceBoundsCeil) {
  constexpr std::array<std::array<gfx::RectF, 2>, 4> test_data = {
      {{gfx::RectF({15.12, 15.912}, {10.351, 10.742}),
        gfx::RectF({16, 16}, {11, 11})},
       {gfx::RectF({7.041, 8.583}, {13.452, 20.231}),
        gfx::RectF({8, 9}, {14, 21})},
       {gfx::RectF({15, 15}, {10, 10}), gfx::RectF({15, 15}, {10, 10})},
       {gfx::RectF({7, 8}, {16, 18}), gfx::RectF({7, 8}, {16, 18})}}};

  for (const auto& item : test_data) {
    OneWaylandSubsurfaceTestHelper(item[0] /* subsurface_bounds */,
                                   item[1] /* expected_subsurface_bounds */);
  };
}

TEST_P(WaylandSubsurfaceTest, NoDuplicateSubsurfaceRequests) {
  if (!connection_->ShouldUseOverlayDelegation()) {
    GTEST_SKIP();
  }
  auto subsurfaces = RequestWaylandSubsurface(3);
  for (auto* subsurface : subsurfaces) {
    subsurface->ConfigureAndShowSurface(gfx::RectF(1.f, 2.f, 10.f, 20.f),
                                        gfx::RectF(0.f, 0.f, 800.f, 600.f), 1.f,
                                        nullptr, nullptr);
  }
  connection_->Flush();

  PostToServerAndWait(
      [subsurface_id1 = subsurfaces[0]->wayland_surface()->get_surface_id(),
       subsurface_id2 = subsurfaces[1]->wayland_surface()->get_surface_id(),
       subsurface_id3 = subsurfaces[2]->wayland_surface()->get_surface_id()](
          wl::TestWaylandServerThread* server) {
        // From top to bottom: subsurfaces[2], subsurfaces[1], subsurfaces[0].
        std::array<wl::TestSubSurface*, 3> test_subs = {
            server->GetObject<wl::MockSurface>(subsurface_id1)->sub_surface(),
            server->GetObject<wl::MockSurface>(subsurface_id2)->sub_surface(),
            server->GetObject<wl::MockSurface>(subsurface_id3)->sub_surface(),
        };

        EXPECT_CALL(*test_subs[0], PlaceAbove(_)).Times(1);
        EXPECT_CALL(*test_subs[0], PlaceBelow(_)).Times(0);
        EXPECT_CALL(*test_subs[0], SetPosition(_, _)).Times(1);
        EXPECT_CALL(*test_subs[1], PlaceAbove(_)).Times(0);
        EXPECT_CALL(*test_subs[1], PlaceBelow(_)).Times(0);
        EXPECT_CALL(*test_subs[1], SetPosition(_, _)).Times(0);
        EXPECT_CALL(*test_subs[2], PlaceAbove(_)).Times(0);
        EXPECT_CALL(*test_subs[2], PlaceBelow(_)).Times(0);
        EXPECT_CALL(*test_subs[2], SetPosition(_, _)).Times(0);
      });

  // Stack subsurfaces[0] to be from bottom to top, and change its position.
  subsurfaces[0]->ConfigureAndShowSurface(gfx::RectF(0.f, 0.f, 10.f, 20.f),
                                          gfx::RectF(0.f, 0.f, 800.f, 600.f),
                                          1.f, subsurfaces[2], nullptr);
  subsurfaces[1]->ConfigureAndShowSurface(gfx::RectF(1.f, 2.f, 10.f, 20.f),
                                          gfx::RectF(0.f, 0.f, 800.f, 600.f),
                                          1.f, nullptr, subsurfaces[2]);
  subsurfaces[2]->ConfigureAndShowSurface(gfx::RectF(1.f, 2.f, 10.f, 20.f),
                                          gfx::RectF(0.f, 0.f, 800.f, 600.f),
                                          1.f, nullptr, subsurfaces[0]);
  connection_->Flush();

  VerifyAndClearExpectations();
}

TEST_P(WaylandWindowTest, NoDuplicateViewporterRequests) {
  EXPECT_TRUE(connection_->buffer_manager_host());

  auto interface_ptr = connection_->buffer_manager_host()->BindInterface();
  buffer_manager_gpu_->Initialize(std::move(interface_ptr), {},
                                  /*supports_dma_buf=*/false,
                                  /*supports_viewporter=*/true,
                                  /*supports_acquire_fence=*/false,
                                  /*supports_overlays=*/true,
                                  /*supports_single_pixel_buffer=*/true);

  // Setup wl_buffers.
  constexpr uint32_t buffer_id = 1;
  gfx::Size buffer_size(1024, 768);
  auto length = 1024 * 768 * 4;
  buffer_manager_gpu_->CreateShmBasedBuffer(MakeFD(), length, buffer_size,
                                            buffer_id);
  base::RunLoop().RunUntilIdle();

  auto* surface = window_->root_surface();
  PostToServerAndWait([surface_id = surface->get_surface_id()](
                          wl::TestWaylandServerThread* server) {
    auto* test_viewport =
        server->GetObject<wl::MockSurface>(surface_id)->viewport();

    // Set viewport src and dst.
    EXPECT_CALL(*test_viewport, SetSource(512, 384, 512, 384)).Times(1);
    EXPECT_CALL(*test_viewport, SetDestination(800, 600)).Times(1);
  });

  surface->AttachBuffer(connection_->buffer_manager_host()->EnsureBufferHandle(
      surface, buffer_id));

  surface->set_buffer_crop({0.5, 0.5, 0.5, 0.5});
  surface->set_viewport_destination({800, 600});
  surface->ApplyPendingState();
  surface->Commit();
  connection_->Flush();

  VerifyAndClearExpectations();

  PostToServerAndWait([surface_id = surface->get_surface_id()](
                          wl::TestWaylandServerThread* server) {
    auto* test_viewport =
        server->GetObject<wl::MockSurface>(surface_id)->viewport();
    Mock::VerifyAndClearExpectations(test_viewport);
    // Duplicate viewport requests are not sent.
    EXPECT_CALL(*test_viewport, SetSource(_, _, _, _)).Times(0);
    EXPECT_CALL(*test_viewport, SetDestination(_, _)).Times(0);
  });

  surface->AttachBuffer(connection_->buffer_manager_host()->EnsureBufferHandle(
      surface, buffer_id));

  surface->set_buffer_crop({0.5, 0.5, 0.5, 0.5});
  surface->set_viewport_destination({800, 600});
  surface->ApplyPendingState();
  surface->Commit();
  connection_->Flush();

  VerifyAndClearExpectations();

  PostToServerAndWait([surface_id = surface->get_surface_id()](
                          wl::TestWaylandServerThread* server) {
    auto* test_viewport =
        server->GetObject<wl::MockSurface>(surface_id)->viewport();
    Mock::VerifyAndClearExpectations(test_viewport);
    // Unset viewport src and dst.
    EXPECT_CALL(*test_viewport, SetSource(-1, -1, -1, -1)).Times(1);
    EXPECT_CALL(*test_viewport, SetDestination(-1, -1)).Times(1);
  });

  surface->AttachBuffer(connection_->buffer_manager_host()->EnsureBufferHandle(
      surface, buffer_id));

  surface->set_buffer_crop({0., 0., 1., 1.});
  surface->set_viewport_destination({1024, 768});
  surface->ApplyPendingState();
  surface->Commit();
  connection_->Flush();

  VerifyAndClearExpectations();

  PostToServerAndWait([surface_id = surface->get_surface_id()](
                          wl::TestWaylandServerThread* server) {
    auto* test_viewport =
        server->GetObject<wl::MockSurface>(surface_id)->viewport();
    Mock::VerifyAndClearExpectations(test_viewport);
    // Duplicate viewport requests are not sent.
    EXPECT_CALL(*test_viewport, SetSource(_, _, _, _)).Times(0);
    EXPECT_CALL(*test_viewport, SetDestination(_, _)).Times(0);
  });

  surface->AttachBuffer(connection_->buffer_manager_host()->EnsureBufferHandle(
      surface, buffer_id));

  surface->set_buffer_crop({0., 0., 1., 1.});
  surface->set_viewport_destination({1024, 768});
  surface->ApplyPendingState();
  surface->Commit();
  connection_->Flush();

  VerifyAndClearExpectations();
}

// Tests that WaylandPopups can be repositioned.
TEST_P(WaylandWindowTest, RepositionPopups) {
  VerifyAndClearExpectations();

  gfx::Rect menu_window_bounds(gfx::Rect(6, 20, 8, 20));
  std::unique_ptr<WaylandWindow> menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, menu_window_bounds, &delegate_,
      window_->GetWidget());
  EXPECT_TRUE(menu_window);
  EXPECT_TRUE(menu_window->IsVisible());

  PostToServerAndWait(
      [id = menu_window->root_surface()->get_surface_id(),
       menu_window_bounds](wl::TestWaylandServerThread* server) {
        auto* mock_surface_popup = server->GetObject<wl::MockSurface>(id);
        auto* mock_xdg_popup = mock_surface_popup->xdg_surface()->xdg_popup();

        EXPECT_EQ(mock_xdg_popup->anchor_rect().origin(),
                  menu_window_bounds.origin());
        EXPECT_EQ(mock_xdg_popup->size(), menu_window_bounds.size());
        EXPECT_EQ(mock_surface_popup->opaque_region(),
                  gfx::Rect(menu_window_bounds.size()));
      });

  VerifyAndClearExpectations();

  const gfx::Rect damage_rect{menu_window_bounds.width(),
                              menu_window_bounds.height()};
  EXPECT_CALL(delegate_, OnDamageRect(Eq(damage_rect))).Times(1);
  menu_window_bounds.set_origin({10, 10});
  menu_window->SetBoundsInDIP(menu_window_bounds);

  PostToServerAndWait(
      [id = menu_window->root_surface()->get_surface_id(),
       menu_window_bounds](wl::TestWaylandServerThread* server) {
        // Xdg objects can be recreated depending on the version of the xdg
        // shell.
        auto* mock_surface_popup = server->GetObject<wl::MockSurface>(id);
        auto* mock_xdg_popup = mock_surface_popup->xdg_surface()->xdg_popup();

        EXPECT_EQ(mock_xdg_popup->anchor_rect().origin(),
                  menu_window_bounds.origin());
        EXPECT_EQ(mock_xdg_popup->size(), menu_window_bounds.size());
        EXPECT_EQ(mock_surface_popup->opaque_region(),
                  gfx::Rect(menu_window_bounds.size()));
      });

  // This will send a configure event for the xdg_surface that backs the
  // xdg_popup. Size and state are not used there.
  SendConfigureEvent(menu_window->root_surface()->get_surface_id(), {0, 0},
                     wl::ScopedWlArray({}));

  VerifyAndClearExpectations();
}

// If buffers are not attached (aka WaylandBufferManagerHost is not used for
// buffer management), WaylandSurface::Commit mustn't result in creation of
// surface sync.
TEST_P(WaylandWindowTest, DoesNotCreateSurfaceSyncOnCommitWithoutBuffers) {
  EXPECT_THAT(window_->root_surface()->surface_sync_, nullptr);
  window_->root_surface()->Commit();
  EXPECT_THAT(window_->root_surface()->surface_sync_, nullptr);
}

TEST_P(WaylandWindowTest, StartWithMinimized) {
  MapSurface(delegate_);

  // Make sure the window is initialized to normal state from the beginning.
  EXPECT_EQ(PlatformWindowState::kNormal, window_->GetPlatformWindowState());

  SendConfigureEvent(surface_id_, {0, 0},
                     InitializeWlArrayWithActivatedState());

  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _));
  window_->Minimize();
  VerifyAndClearExpectations();

  // The state of the window has to be already minimized.
  EXPECT_EQ(window_->GetPlatformWindowState(), PlatformWindowState::kMinimized);

  // We don't receive any state change if that does not differ from the last
  // state.
  EXPECT_CALL(delegate_, OnWindowStateChanged(_, _)).Times(0);
  // It must be still the same minimized state.
  EXPECT_EQ(window_->GetPlatformWindowState(), PlatformWindowState::kMinimized);
  EXPECT_EQ(gfx::Rect(800, 600), window_->GetBoundsInDIP());

  // The window geometry has to be set to the current bounds of the window for
  // minimized state.
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    auto* surface = server->GetObject<wl::MockSurface>(id);
    auto* xdg_surface = surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(_)).Times(0);
  });
  // Send one additional empty configuration event for minimized state.
  // (which means the surface is not maximized, fullscreen or activated)
  SendConfigureEvent(surface_id_, {0, 0}, wl::ScopedWlArray({}));
}

class BlockableWaylandToplevelWindow : public WaylandToplevelWindow {
 public:
  BlockableWaylandToplevelWindow(MockWaylandPlatformWindowDelegate* delegate,
                                 WaylandConnection* connection)
      : WaylandToplevelWindow(delegate, connection) {}

  static std::unique_ptr<BlockableWaylandToplevelWindow> Create(
      const gfx::Rect& bounds,
      WaylandConnection* connection,
      MockWaylandPlatformWindowDelegate* delegate) {
    auto window =
        std::make_unique<BlockableWaylandToplevelWindow>(delegate, connection);

    PlatformWindowInitProperties properties;
    properties.bounds = bounds;
    properties.type = PlatformWindowType::kWindow;
    properties.parent_widget = gfx::kNullAcceleratedWidget;
    window->Initialize(std::move(properties));
    window->Show(false);
    return window;
  }

  // WaylandToplevelWindow overrides:
  uint32_t DispatchEvent(const PlatformEvent& platform_event) override {
    ui::Event* event(platform_event);
    if (event->type() == EventType::kTouchReleased && !blocked_) {
      base::RunLoop run_loop{base::RunLoop::Type::kNestableTasksAllowed};
      blocked_ = true;

      base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE,
          base::BindOnce(std::move(async_task_), run_loop.QuitClosure()));
      run_loop.Run();
      blocked_ = false;
    }

    return WaylandToplevelWindow::DispatchEvent(platform_event);
  }

  void SetAsyncTask(
      base::RepeatingCallback<void(base::OnceClosure)> async_task) {
    async_task_ = std::move(async_task);
  }

 private:
  bool blocked_ = false;
  base::RepeatingCallback<void(base::OnceClosure)> async_task_;
};

// This test ensures that Ozone/Wayland does not crash while handling a
// sequence of two or more touch down/up actions, where the first one blocks
// unfinished before the second pair comes in.
//
// This mimics the behavior of a modal dialog that comes up as a result of
// the first touch down/up action, and blocks the original flow, before it gets
// handled completely.
TEST_P(WaylandWindowTest, BlockingTouchDownUp_NoCrash) {
  window_.reset();

  MockWaylandPlatformWindowDelegate delegate;
  auto window = BlockableWaylandToplevelWindow::Create(
      gfx::Rect(800, 600), connection_.get(), &delegate);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(
        server->seat()->resource(),
        WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_TOUCH);
  });
  ASSERT_TRUE(connection_->seat()->pointer());
  ASSERT_TRUE(connection_->seat()->touch());
  window->set_touch_focus(true);

  // Test that CanDispatchEvent is set correctly.
  VerifyCanDispatchTouchEvents({window.get()}, {});

  // Steps to be executed after the handling of the first touch down/up
  // pair blocks.
  auto async_task = base::BindLambdaForTesting([&](base::OnceClosure closure) {
    PostToServerAndWait([id = window->root_surface()->get_surface_id()](
                            wl::TestWaylandServerThread* server) {
      wl::MockSurface* toplevel_surface =
          server->GetObject<wl::MockSurface>(id);
      wl_touch_send_down(server->seat()->touch()->resource(),
                         server->GetNextSerial(), 0,
                         toplevel_surface->resource(), 0 /* id */,
                         wl_fixed_from_int(100), wl_fixed_from_int(100));
      wl_touch_send_up(server->seat()->touch()->resource(),
                       server->GetNextSerial(), 2000, 0 /* id */);
      wl_touch_send_frame(server->seat()->touch()->resource());
    });

    std::move(closure).Run();
  });
  window->SetAsyncTask(std::move(async_task));

  PostToServerAndWait([id = window->root_surface()->get_surface_id()](
                          wl::TestWaylandServerThread* server) {
    wl::MockSurface* toplevel_surface = server->GetObject<wl::MockSurface>(id);
    // Start executing the first touch down/up pair.
    wl_touch_send_down(server->seat()->touch()->resource(),
                       server->GetNextSerial(), 0, toplevel_surface->resource(),
                       0 /* id */, wl_fixed_from_int(50),
                       wl_fixed_from_int(50));
    wl_touch_send_up(server->seat()->touch()->resource(),
                     server->GetNextSerial(), 1000, 0 /* id */);
    wl_touch_send_frame(server->seat()->touch()->resource());
  });
}

// Make sure that changing focus during dispatch will not re-dispatch the event
// to the newly focused window. (crbug.com/1339082);
// Flaky on device/VM: https://crbug.com/1348046
TEST_P(WaylandWindowTest, ChangeFocusDuringDispatch) {
  MockPlatformWindowDelegate other_delegate;
  gfx::AcceleratedWidget other_widget = gfx::kNullAcceleratedWidget;
  EXPECT_CALL(other_delegate, OnAcceleratedWidgetAvailable(_))
      .WillOnce(SaveArg<0>(&other_widget));

  PlatformWindowInitProperties properties;
  properties.bounds = gfx::Rect(10, 10);
  properties.type = PlatformWindowType::kWindow;
  auto other_window = WaylandWindow::Create(&other_delegate, connection_.get(),
                                            std::move(properties));
  ASSERT_NE(other_widget, gfx::kNullAcceleratedWidget);

  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER);
  });

  ASSERT_TRUE(connection_->seat()->pointer());

  int count = 0;
  EXPECT_CALL(other_delegate, DispatchEvent(_)).Times(1);
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillRepeatedly([&](Event* event) {
    count++;
    if (event->type() == ui::EventType::kMousePressed) {
      PostToServerAndWait(
          [id = surface_id_,
           other_id = other_window->root_surface()->get_surface_id()](
              wl::TestWaylandServerThread* server) {
            wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
            ASSERT_TRUE(surface);
            wl::MockSurface* other_surface =
                server->GetObject<wl::MockSurface>(other_id);
            ASSERT_TRUE(other_surface);
            auto* pointer = server->seat()->pointer();
            wl_pointer_send_leave(pointer->resource(), 3, surface->resource());
            wl_pointer_send_frame(pointer->resource());

            wl_pointer_send_enter(pointer->resource(), 4,
                                  other_surface->resource(), 0, 0);
            wl_pointer_send_frame(pointer->resource());
          });
    }
  });

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(surface);
    auto* pointer = server->seat()->pointer();

    wl_pointer_send_enter(pointer->resource(), 1, surface->resource(), 0, 0);
    // The Enter event is coupled with the frame event.
    wl_pointer_send_frame(pointer->resource());
    wl_pointer_send_button(pointer->resource(), 2, 1004, BTN_LEFT,
                           WL_POINTER_BUTTON_STATE_PRESSED);
    wl_pointer_send_frame(pointer->resource());
  });

  EXPECT_EQ(count, 3);
}

TEST_P(WaylandWindowTest, WindowMovedResized) {
  MapSurface(delegate_);

  const gfx::Rect initial_bounds = window_->GetBoundsInDIP();

  gfx::Rect new_bounds(initial_bounds);
  new_bounds.set_x(new_bounds.origin().x() + 10);
  new_bounds.set_y(new_bounds.origin().y() + 10);
  // Configure is not necessary to just move.
  EXPECT_CALL(delegate_, OnBoundsChanged(BoundsChange(true)));
  PostToServerAndWait([id = surface_id_,
                       new_bounds](wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    auto* xdg_surface = surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(new_bounds.size())))
        .Times(0);
  });
  window_->SetBoundsInDIP(new_bounds);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  // Resize and move.
  new_bounds.Inset(5);
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(BoundsChange(true)))).Times(1);
  PostToServerAndWait([id = surface_id_,
                       new_bounds](wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    auto* xdg_surface = surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(new_bounds.size())))
        .Times(0);
  });
  window_->SetBoundsInDIP(new_bounds);
  VerifyAndClearExpectations();

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(BoundsChange(true)))).Times(1);
  PostToServerAndWait([id = surface_id_,
                       new_bounds](wl::TestWaylandServerThread* server) {
    wl::MockSurface* surface = server->GetObject<wl::MockSurface>(id);
    auto* xdg_surface = surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(new_bounds.size())))
        .Times(1);
  });
  wl::ScopedWlArray states = InitializeWlArrayWithActivatedState();
  SendConfigureEvent(surface_id_, new_bounds.size(), states);
  AdvanceFrameToCurrent(window_.get(), delegate_);
}

// Make sure that creating a window with DIP bounds creates a window with
// the same DIP bounds with various fractional scales.
TEST_P(WaylandWindowTest, NoRoundingErrorInDIP) {
  VerifyAndClearExpectations();
  auto* primary_output =
      connection_->wayland_output_manager()->GetPrimaryOutput();
  constexpr float kScales[] = {display::kDsf_1_777, display::kDsf_2_252,
                               display::kDsf_2_666, display::kDsf_1_8};
  for (float scale : kScales) {
    primary_output->SetScaleFactorForTesting(scale);
    // Update to delegate to use the correct scale;
    window_->UpdateWindowScale(true);

    testing::NiceMock<MockWaylandPlatformWindowDelegate> delegate;
    std::unique_ptr<WaylandWindow> wayland_window =
        CreateWaylandWindowWithParams(PlatformWindowType::kWindow,
                                      gfx::Rect(20, 0, 100, 100), &delegate);
    for (int i = 100; i < 3000; i++) {
      const gfx::Rect kBoundsDip{20, 0, i, 3000 - i};
      const gfx::Rect bounds_in_px =
          delegate_.ConvertRectToPixels(gfx::Rect(kBoundsDip.size()));
      wayland_window->SetBoundsInDIP(kBoundsDip);
      AdvanceFrameToCurrent(wayland_window.get(), delegate);
      EXPECT_EQ(bounds_in_px.size(), wayland_window->applied_state().size_px);
      EXPECT_EQ(kBoundsDip, wayland_window->GetBoundsInDIP());
    }
  }
  VerifyAndClearExpectations();
}

// Make sure that the window scale change is applied on the latest
// in_flight_requests.
TEST_P(WaylandWindowTest, ScaleChangeWhenStateRequestThrottoled) {
  VerifyAndClearExpectations();

  gfx::Rect bounds_dip;
  auto* toplevel = static_cast<WaylandToplevelWindow*>(window_.get());
  for (int i = 300; i <= 600; i++) {
    bounds_dip = {0, 0, i, 900 - i};
    toplevel->HandleToplevelConfigure(bounds_dip.width(), bounds_dip.height(),
                                      {});
    toplevel->HandleSurfaceConfigure(i);
  }
  // latest bounds_dip is throttled, and not applied, scale factor is 1.
  EXPECT_NE(bounds_dip.size(), toplevel->applied_state().bounds_dip.size());
  EXPECT_EQ(bounds_dip.size(),
            delegate_.ConvertRectToPixels(bounds_dip).size());

  // Update to delegate to use the correct scale;
  constexpr float kScale = display::kDsf_1_777;
  auto* primary_output =
      connection_->wayland_output_manager()->GetPrimaryOutput();
  primary_output->SetScaleFactorForTesting(kScale);
  toplevel->UpdateWindowScale(true);
  AdvanceFrameToCurrent(window_.get(), delegate_);

  // bounds_dip advances to be applied, and scaled correctly.
  EXPECT_EQ(bounds_dip.size(), toplevel->applied_state().bounds_dip.size());
  EXPECT_NE(bounds_dip.size(),
            delegate_.ConvertRectToPixels(bounds_dip).size());
  EXPECT_EQ(window_->applied_state().size_px,
            delegate_.ConvertRectToPixels(bounds_dip).size());
  VerifyAndClearExpectations();
}

// Tests that a re-entrant state update is handled serially by `WaylandWindow`
// and does not crash.
TEST_P(WaylandWindowTest, ReentrantApplyStateWorks) {
  constexpr gfx::Rect kBounds1{123, 234};
  constexpr gfx::Rect kBounds2{234, 345};
  constexpr gfx::Rect kBounds3{345, 456};

  MapSurface(delegate_);

  PostToServerAndWait([id = surface_id_,
                       bounds = kBounds1](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())))
        .Times(1);
    EXPECT_CALL(*xdg_surface, AckConfigure(_)).Times(0);
  });

  window_->SetBoundsInDIP(kBounds1);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_,
                       bounds = kBounds3](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())))
        .Times(1);
    EXPECT_CALL(*xdg_surface, AckConfigure(_)).Times(0);
  });

  delegate_.set_on_state_update_callback(
      base::BindLambdaForTesting([&]() { window_->SetBoundsInDIP(kBounds3); }));
  window_->SetBoundsInDIP(kBounds2);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();
}

// Tests that configuring twice with the same state immediately acks and
// commits.
TEST_P(WaylandWindowTest, ConfigureWithSameStateAcksAndCommitsImmediately) {
  constexpr gfx::Rect kBounds{123, 234};
  auto state = InitializeWlArrayWithActivatedState();
  constexpr uint32_t kConfigureSerial1 = 2u;
  constexpr uint32_t kConfigureSerial2 = 3u;

  PostToServerAndWait([id = surface_id_,
                       bounds = kBounds](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(gfx::Rect(bounds.size())))
        .Times(1);
    EXPECT_CALL(*xdg_surface, AckConfigure(kConfigureSerial1)).Times(1);
  });

  SendConfigureEvent(surface_id_, kBounds.size(), state, kConfigureSerial1);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  VerifyAndClearExpectations();

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    auto* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    auto* xdg_surface = mock_surface->xdg_surface();
    EXPECT_CALL(*xdg_surface, SetWindowGeometry(_)).Times(0);
    EXPECT_CALL(*xdg_surface, AckConfigure(kConfigureSerial2)).Times(1);
    EXPECT_CALL(*mock_surface, Commit()).Times(1);
  });

  SendConfigureEvent(surface_id_, kBounds.size(), state, kConfigureSerial2);
  // We deliberately do not advance frame to current here, because it should
  // immediately ack and commit, which also implies that there should be no
  // frame too.
  VerifyAndClearExpectations();
}

// Test that creates a screen with two displays, with work areas configured to
// be side-by-side horizontally.
class MultiDisplayWaylandWindowTest : public WaylandWindowTest {
 public:
  static constexpr int64_t kPrimaryDisplayId = 1;
  static constexpr int64_t kSecondaryDisplayId = 2;
  static constexpr gfx::Rect kPrimaryDisplayBounds{0, 0, 800, 600};
  static constexpr gfx::Rect kSecondaryDisplayBounds{800, 0, 800, 600};

  // WaylandWindowTest:
  void SetUp() override {
    test_screen_.display_list().AddDisplay(
        display::Display(kPrimaryDisplayId, kPrimaryDisplayBounds),
        display::DisplayList::Type::PRIMARY);
    test_screen_.display_list().AddDisplay(
        display::Display(kSecondaryDisplayId, kSecondaryDisplayBounds),
        display::DisplayList::Type::NOT_PRIMARY);
    EXPECT_EQ(2, test_screen_.GetNumDisplays());
    WaylandWindowTest::SetUp();
  }

 private:
  display::test::TestScreen test_screen_{/*create_display=*/false,
                                         /*register_screen=*/true};
};

// Asserts new windows ignore the display for new windows if bounds have been
// explicitly specified.
TEST_P(MultiDisplayWaylandWindowTest, NewWindowsRespectInitParamBounds) {
  MockWaylandPlatformWindowDelegate delegate;

  // Set the secondary display as the new window target.
  const display::ScopedDisplayForNewWindows scoped_display_new_windows(
      kSecondaryDisplayId);

  // Init a new window with non-empty bounds.
  constexpr gfx::Rect kInitBounds(100, 100, 100, 100);
  const auto window = delegate.CreateWaylandWindow(
      connection_.get(), PlatformWindowInitProperties(kInitBounds));
  ASSERT_TRUE(window);

  // Assert the window is placed at the specified bounds, ignoring the display
  // for new windows.
  EXPECT_EQ(kInitBounds, window->GetBoundsInDIP());
}

class PerSurfaceScaleWaylandWindowTest : public WaylandWindowTest {
 public:
  PerSurfaceScaleWaylandWindowTest() = default;
  ~PerSurfaceScaleWaylandWindowTest() override = default;

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

  void SetUp() override {
    CHECK(!base::Contains(
        enabled_features_,
        base::test::FeatureRef(features::kWaylandPerSurfaceScale)));
    enabled_features_.push_back(features::kWaylandPerSurfaceScale);

    WaylandWindowTest::SetUp();
    MapSurface(delegate_);
  }

  void TearDown() override {
    WaylandWindowTest::TearDown();

    CHECK(enabled_features_.back() == features::kWaylandPerSurfaceScale);
    enabled_features_.pop_back();
  }
};

TEST_P(PerSurfaceScaleWaylandWindowTest, UsePreferredSurfaceScale) {
  ASSERT_TRUE(connection_->UsePerSurfaceScaling());
  EXPECT_EQ(1u, screen_->GetAllDisplays().size());
  EXPECT_EQ(1.0f, screen_->GetDisplayForAcceleratedWidget(window_->GetWidget())
                      .device_scale_factor());
  EXPECT_EQ(1.0f, window_->applied_state().window_scale);
  ASSERT_EQ(gfx::Size(800, 600), window_->applied_state().size_px);

  // GetPreferredScaleFactorForAcceleratedWidget must return the ui scale value
  // until the preferred surface scale hasn't been received yet.
  EXPECT_FALSE(window_->GetPreferredScaleFactor().has_value());
  EXPECT_EQ(
      1.0f,
      screen_->GetPreferredScaleFactorForAcceleratedWidget(window_->GetWidget())
          .value_or(0.f));

  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange))).Times(1);

  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    ASSERT_TRUE(mock_surface->fractional_scale());
    mock_surface->fractional_scale()->SendPreferredScale(1.5f);
  });

  SyncDisplay();
  Mock::VerifyAndClearExpectations(&delegate_);

  // Once preferred surface scale is received, the screen API starts returning
  // the composed scale value, ie: ui_scale * window_scale.
  EXPECT_EQ(1.5f, window_->GetPreferredScaleFactor().value_or(0.f));
  EXPECT_EQ(
      1.5f,
      screen_->GetPreferredScaleFactorForAcceleratedWidget(window_->GetWidget())
          .value_or(0.f));
  // The preferred scale is then reflected in state's `window_scale` when
  // notifying the bounds change.
  EXPECT_EQ(1.5f, window_->applied_state().window_scale);
  ASSERT_EQ(gfx::Size(1200, 900), window_->applied_state().size_px);

  // Ensure state (including scale and bounds) gets latched only when the
  // corresponding frame comes in.
  EXPECT_EQ(1.0f, window_->latched_state().window_scale);
  ASSERT_EQ(gfx::Size(800, 600), window_->latched_state().size_px);
  AdvanceFrameToCurrent(window_.get(), delegate_);
  EXPECT_EQ(1.5f, window_->latched_state().window_scale);
  ASSERT_EQ(gfx::Size(1200, 900), window_->latched_state().size_px);

  // GetDisplayForAcceleratedWidget keeps returning the entered output, whose
  // scale is unchanged in this case.
  EXPECT_EQ(1.0f, screen_->GetDisplayForAcceleratedWidget(window_->GetWidget())
                      .device_scale_factor());
}

TEST_P(PerSurfaceScaleWaylandWindowTest, UiScale_HandleFontScaleChange) {
  base::test::ScopedFeatureList enable_ui_scaling(features::kWaylandUiScale);
  ASSERT_TRUE(connection_->IsUiScaleEnabled());

  // Required for emulating mouse events.
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER);
  });
  ASSERT_TRUE(connection_->seat()->pointer());

  // Ensure the initial `window_` and its underlying root surface state is set
  // as expected.
  EXPECT_EQ(1.0f, window_->applied_state().ui_scale);
  EXPECT_EQ(1.0f, window_->applied_state().window_scale);
  EXPECT_EQ(gfx::Size(800, 600), window_->applied_state().bounds_dip.size());
  EXPECT_EQ(gfx::Size(800, 600), window_->applied_state().size_px);
  EXPECT_EQ(window_->applied_state(), window_->latched_state());
  // Ensure WaylandScreen::GetPreferredScaleFactorForAcceleratedWidget returns
  // the ui scale value while preferred surface scale hasn't been received yet.
  EXPECT_FALSE(window_->GetPreferredScaleFactor().has_value());
  EXPECT_EQ(
      1.0f,
      screen_->GetPreferredScaleFactorForAcceleratedWidget(window_->GetWidget())
          .value_or(0.f));

  // Receiving a `wp_fractional_scale_v1::preferred_scale` with scale 1.0
  // shouldn't lead to `OnBoundsChanged` calls, as no change did actually occur.
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange))).Times(0);
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    ASSERT_TRUE(mock_surface->fractional_scale());
    mock_surface->fractional_scale()->SendPreferredScale(1.0f);
  });
  WaylandTestBase::SyncDisplay();
  Mock::VerifyAndClearExpectations(&delegate_);
  // Once preferred surface scale is received, the screen API starts returning
  // the composed scale value, ie: ui_scale * window_scale.
  EXPECT_EQ(1.0f, window_->GetPreferredScaleFactor().value_or(0.f));
  EXPECT_EQ(
      1.0f,
      screen_->GetPreferredScaleFactorForAcceleratedWidget(window_->GetWidget())
          .value_or(0.f));

  // Setting font scale to 1.25 (which usually happens when 'large-text' system
  // setting is turned on) leads to bounds change with the expectations set
  // below.
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange))).Times(1);
  ASSERT_TRUE(!!connection_->window_manager());
  connection_->window_manager()->SetFontScale(1.25f);
  Mock::VerifyAndClearExpectations(&delegate_);
  // Ensure that once preferred surface scale is received, the screen
  // GetPreferredScaleFactorForAcceleratedWidget API returns the composed scale
  // value, ie: ui_scale * window_scale.
  EXPECT_EQ(1.0f, window_->GetPreferredScaleFactor().value_or(0.f));
  EXPECT_EQ(
      1.25f,
      screen_->GetPreferredScaleFactorForAcceleratedWidget(window_->GetWidget())
          .value_or(0.f));

  EXPECT_EQ(1.25f, window_->applied_state().ui_scale);
  EXPECT_EQ(1.0f, window_->applied_state().window_scale);
  // DIP size gets downscaled by the composed scale, such that the pixel size
  // keeps the same.
  EXPECT_EQ(gfx::Size(640, 480), window_->applied_state().bounds_dip.size());
  EXPECT_EQ(gfx::Size(800, 600), window_->applied_state().size_px);
  EXPECT_EQ(window_->root_surface()->state_.buffer_scale_float, 1.0f);
  EXPECT_NE(window_->applied_state(), window_->latched_state());

  // Verifies both event dispatching and screen "cursor location" API work as
  // expected with ui_scale > 1. Regression test fo https://crbug.com/396457560.
  std::unique_ptr<Event> event;
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillRepeatedly(CloneEvent(&event));
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    auto* pointer_resource = server->seat()->pointer()->resource();
    auto* toplevel_surface = server->GetObject<wl::MockSurface>(id);
    wl_pointer_send_enter(pointer_resource, server->GetNextSerial(),
                          toplevel_surface->resource(), 0, 0);
    wl_pointer_send_motion(pointer_resource, server->GetNextSerial(),
                           wl_fixed_from_double(100.0f),
                           wl_fixed_from_double(100.0f));
  });
  ASSERT_TRUE(event->IsMouseEvent());
  ASSERT_EQ(event->type(), ui::EventType::kMouseMoved);
  // Event dispatching API expects pixel coordinates.
  EXPECT_EQ(event->AsLocatedEvent()->location(), gfx::Point(100, 100));
  // Internal cursor position tracker uses Wayland DIP coordinates.
  ASSERT_TRUE(connection_->wayland_cursor_position());
  EXPECT_EQ(connection_->wayland_cursor_position()->GetCursorSurfacePoint(),
            gfx::Point(100, 100));
  // Screen API uses UI DIP coordinates.
  EXPECT_EQ(screen_->GetCursorScreenPoint(), gfx::Point(80, 80));

  // Applied state gets latched when the corresponding produced frame is
  // received from Viz and processed by `window_`s frame manager, which is
  // emulated in this test by the `CreateShmBasedBuffer` + `CommitOverlays`
  // calls below. After that, several expectations are checked, eg: latched
  // state, surface state (scale) as well as the relevant wayland requests
  // issued during the process.
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    EXPECT_CALL(*mock_surface, Damage(0, 0, 800, 600)).Times(1);
    ASSERT_TRUE(mock_surface->viewport());
    EXPECT_CALL(*mock_surface->viewport(), SetSource(_, _, _, _)).Times(0);
    EXPECT_CALL(*mock_surface->viewport(), SetDestination(_, _)).Times(0);
    ASSERT_TRUE(mock_surface->xdg_surface());
    EXPECT_CALL(*mock_surface->xdg_surface(),
                SetWindowGeometry(gfx::Rect(800, 600)));
    EXPECT_CALL(*mock_surface->xdg_surface(), AckConfigure(_)).Times(0);
  });
  CreateBufferAndPresentAsNewFrame(window_.get(), delegate_,
                                   /*buffer_size=*/gfx::Size(800, 600),
                                   /*buffer_scale=*/1.25f);
  // Sync with the test wayland compositor and verify the expectations.
  VerifyAndClearExpectations();
  EXPECT_EQ(window_->applied_state(), window_->latched_state());
  EXPECT_EQ(window_->latched_state().ui_scale, 1.25f);
  EXPECT_EQ(window_->latched_state().window_scale, 1.0f);
  EXPECT_EQ(window_->root_surface()->state_.buffer_scale_float, 1.0f);
}

TEST_P(PerSurfaceScaleWaylandWindowTest,
       UiScale_HandleServerTriggeredBoundsChange) {
  base::test::ScopedFeatureList enable_ui_scaling(features::kWaylandUiScale);
  ASSERT_TRUE(connection_->IsUiScaleEnabled());

  // Initialize surface preferred scale.
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(mock_surface);
    ASSERT_TRUE(mock_surface->fractional_scale());
    mock_surface->fractional_scale()->SendPreferredScale(1.0f);
  });
  WaylandTestBase::SyncDisplay();
  EXPECT_EQ(1.0f, window_->GetPreferredScaleFactor().value_or(0));

  // Set font scale to 1.25.
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange))).Times(1);
  connection_->window_manager()->SetFontScale(1.25f);
  VerifyAndClearExpectations();

  // Emulate a server-triggered bounds change.
  constexpr uint32_t kConfigureSerial = 55u;
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange))).Times(1);
  SendConfigureEvent(surface_id_, gfx::Size(1000, 1000), wl::ScopedWlArray({}),
                     kConfigureSerial);
  VerifyAndClearExpectations();
  // Ensure a bounds change request was issued, where DIP bounds is downsized
  // proportionally to `ui_scale`, while pixel bounds keeps unchanged.
  EXPECT_EQ(1.25f, window_->applied_state().ui_scale);
  EXPECT_EQ(1.0f, window_->applied_state().window_scale);
  EXPECT_EQ(gfx::Size(800, 800), window_->applied_state().bounds_dip.size());
  EXPECT_EQ(gfx::Size(1000, 1000), window_->applied_state().size_px);
  // Verify that correct values are used for wayland requests issued when
  // applying surface state, even though Viz' buffer scale factor is 1.25, i.e:
  // `ui_scale * window_scale`.
  PostToServerAndWait([id = surface_id_](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
    EXPECT_CALL(*mock_surface, Damage(0, 0, 1000, 1000));
    EXPECT_CALL(*mock_surface->xdg_surface(),
                SetWindowGeometry(gfx::Rect(1000, 1000)));
    EXPECT_CALL(*mock_surface->xdg_surface(),
                AckConfigure(Eq(kConfigureSerial)));
  });
  CreateBufferAndPresentAsNewFrame(window_.get(), delegate_,
                                   /*buffer_size=*/gfx::Size(1000, 1000),
                                   /*buffer_scale=*/1.25f);
  // Sync display and verify the expectations.
  VerifyAndClearExpectations();
  EXPECT_EQ(window_->latched_state().ui_scale, 1.25f);
  EXPECT_EQ(window_->latched_state().window_scale, 1.0f);
  EXPECT_EQ(window_->root_surface()->state_.buffer_scale_float, 1.0f);
}

TEST_P(PerSurfaceScaleWaylandWindowTest, UiScale_InitScaleAndBounds) {
  base::test::ScopedFeatureList enable_ui_scaling(features::kWaylandUiScale);
  ASSERT_TRUE(connection_->IsUiScaleEnabled());

  // Set font scale to 1.25.
  connection_->window_manager()->SetFontScale(1.25f);

  // Create a new toplelvel `window`.
  testing::NiceMock<MockWaylandPlatformWindowDelegate> new_window_delegate;
  EXPECT_CALL(new_window_delegate, OnAcceleratedWidgetAvailable(_));
  EXPECT_CALL(new_window_delegate, OnBoundsChanged(_)).Times(0);
  PlatformWindowInitProperties properties(gfx::Rect(800, 800));
  auto new_window = new_window_delegate.CreateWaylandWindow(
      connection_.get(), std::move(properties));
  WaylandTestBase::SyncDisplay();
  Mock::VerifyAndClearExpectations(&new_window_delegate);
  const uint32_t new_window_surface_id =
      new_window->root_surface()->get_surface_id();
  ASSERT_NE(new_window_surface_id, 0u);

  // Upon initialization, even though the window scale is assumed as 1 (and
  // updated asynchronously per wayland events), the UI scale must be set to the
  // current font scale straight away (see WaylandWindow::Initialize comments
  // for more context) and pixel size must be computed based on the DIP bounds
  // passed in.
  EXPECT_EQ(gfx::Size(800, 800), new_window->applied_state().bounds_dip.size());
  EXPECT_EQ(gfx::Size(1000, 1000), new_window->applied_state().size_px);
  EXPECT_EQ(new_window->applied_state().ui_scale, 1.25f);
  EXPECT_EQ(new_window->applied_state().window_scale, 1.0f);
  EXPECT_EQ(new_window->applied_state(), new_window->latched_state());
  PlatformWindowDelegate::State initial_state(new_window->applied_state());
  // Ensure ui_scale is returned while preferred surface scale has not been
  // received yet.
  EXPECT_EQ(1.25f, screen_
                       ->GetPreferredScaleFactorForAcceleratedWidget(
                           new_window->GetWidget())
                       .value_or(0.f));

  // Request window to be shown and verify initial state is set as expected,
  // including ui scale.
  EXPECT_CALL(new_window_delegate, OnBoundsChanged(_)).Times(0);
  new_window->Show(/*inactive=*/false);
  Mock::VerifyAndClearExpectations(&new_window_delegate);
  VerifyAndClearExpectations(new_window_delegate, new_window_surface_id);
  EXPECT_EQ(new_window->applied_state(), initial_state);
  EXPECT_EQ(new_window->applied_state(), new_window->latched_state());
  EXPECT_EQ(new_window->root_surface()->state_.buffer_scale_float, 1.0f);

  // Send the initial activation configure events sequence, with (0, 0) size,
  // such that the client-requested size is used, i.e (1000, 1000) set above.
  // Then, emulate a new frame coming from Viz and verify the correct Wayland
  // requests and parameters are used in response to it.
  constexpr uint32_t kConfigureSerial = 11u;
  EXPECT_CALL(new_window_delegate, OnBoundsChanged(_)).Times(0);
  PostToServerAndWait(
      [id = new_window_surface_id](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        EXPECT_CALL(*mock_surface, Damage(0, 0, 1000, 1000));
        EXPECT_CALL(*mock_surface->xdg_surface(),
                    AckConfigure(Eq(kConfigureSerial)));
        EXPECT_CALL(*mock_surface->xdg_surface(),
                    SetWindowGeometry(gfx::Rect(1000, 1000)));
      });
  ActivateSurface(new_window_delegate, kConfigureSerial);
  CreateBufferAndPresentAsNewFrame(new_window.get(), new_window_delegate,
                                   /*buffer_size=*/gfx::Size(2000, 2000),
                                   /*buffer_scale=*/2.5f);

  // Emulate a wayland change of preferred fractional scale of 2.0 for
  // `new_window`.
  EXPECT_CALL(new_window_delegate, OnBoundsChanged(_));
  PostToServerAndWait(
      [id = new_window_surface_id](wl::TestWaylandServerThread* server) {
        wl::MockSurface* mock_surface = server->GetObject<wl::MockSurface>(id);
        ASSERT_TRUE(mock_surface->fractional_scale());
        mock_surface->fractional_scale()->SendPreferredScale(2.0f);
        // No new xdg_surface.set_window_geometry requests expected, as DIP
        // geometry didn't change.
        EXPECT_CALL(*mock_surface->xdg_surface(), SetWindowGeometry(_))
            .Times(0);
        mock_surface->AllowResettingFrameCallback();
      });
  VerifyAndClearExpectations(new_window_delegate, new_window_surface_id);
  EXPECT_EQ(gfx::Size(800, 800), new_window->applied_state().bounds_dip.size());
  EXPECT_EQ(gfx::Size(2000, 2000), new_window->applied_state().size_px);
  EXPECT_EQ(new_window->applied_state().ui_scale, 1.25);
  EXPECT_EQ(new_window->applied_state().window_scale, 2.0f);
  EXPECT_EQ(2.5, screen_
                     ->GetPreferredScaleFactorForAcceleratedWidget(
                         new_window->GetWidget())
                     .value_or(0.f));
  CreateBufferAndPresentAsNewFrame(new_window.get(), new_window_delegate,
                                   /*buffer_size=*/gfx::Size(2000, 2000),
                                   /*buffer_scale=*/2.5f);

  // Sync display and verify the expectations.
  VerifyAndClearExpectations(new_window_delegate, new_window_surface_id);
  EXPECT_EQ(new_window->applied_state(), new_window->latched_state());
  EXPECT_EQ(new_window->latched_state().ui_scale, 1.25f);
  EXPECT_EQ(new_window->latched_state().window_scale, 2.0f);
  EXPECT_EQ(new_window->root_surface()->state_.buffer_scale_float, 2.0f);
}

TEST_P(PerSurfaceScaleWaylandWindowTest, UiScale_HandlePopupGeometry) {
  base::test::ScopedFeatureList enable_ui_scaling(features::kWaylandUiScale);
  ASSERT_TRUE(connection_->IsUiScaleEnabled());

  // Required for emulating mouse events.
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    wl_seat_send_capabilities(server->seat()->resource(),
                              WL_SEAT_CAPABILITY_POINTER);
  });
  ASSERT_TRUE(connection_->seat()->pointer());

  // Set font scale to 1.25.
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange))).Times(1);
  connection_->window_manager()->SetFontScale(1.25f);
  Mock::VerifyAndClearExpectations(&delegate_);
  WaylandTestBase::SyncDisplay();
  EXPECT_EQ(1.25f, window_->applied_state().ui_scale);
  EXPECT_EQ(1.0f, window_->applied_state().window_scale);
  EXPECT_EQ(gfx::Size(640, 480), window_->applied_state().bounds_dip.size());
  EXPECT_EQ(gfx::Size(800, 600), window_->applied_state().size_px);

  // Initialize create and show a 20x80 popup at (100, 100) ui size/location
  // (1.25 ui inv-scaled). So it must be positioned at (125, 125) with 25x100
  // dip wayland pixels.
  auto* toplevel = window_.get();
  testing::NiceMock<MockWaylandPlatformWindowDelegate> menu_delegate;
  ui::OwnedWindowAnchor anchor{
      .anchor_rect = gfx::Rect(100, 100, 20, 20),
      .anchor_position = OwnedWindowAnchorPosition::kBottomRight,
      .anchor_gravity = OwnedWindowAnchorGravity::kBottomLeft};
  EXPECT_CALL(menu_delegate, GetOwnedWindowAnchorAndRectInDIP())
      .WillOnce(Return(anchor));
  auto menu_window = CreateWaylandWindowWithParams(
      PlatformWindowType::kMenu, gfx::Rect(100, 100, 20, 80), &menu_delegate,
      toplevel->GetWidget());
  ASSERT_TRUE(menu_window);
  const uint32_t menu_surface_id =
      menu_window->root_surface()->get_surface_id();
  PostToServerAndWait([menu_surface_id](wl::TestWaylandServerThread* server) {
    auto* popup = GetTestXdgPopupByWindow(server, menu_surface_id);
    ASSERT_TRUE(popup);
    EXPECT_EQ(popup->anchor_rect(), gfx::Rect(125, 125, 25, 25));
    EXPECT_EQ(popup->size(), gfx::Size(25, 100));
  });
  PlatformWindowDelegate::State initial_state(menu_window->applied_state());

  // Emulate a popup configure with empty geometry rectangle, in which case the
  // current popup bounds is expected to be used.
  SendConfigureEvent(menu_surface_id, gfx::Size(0, 0), wl::ScopedWlArray({}));
  initial_state.window_state = PlatformWindowState::kNormal;
  EXPECT_EQ(initial_state.ToString(), menu_window->applied_state().ToString());

  // Now emulate a popup configure with a 100x200 geometry, and verifies that:
  // 1. A state change request is triggered with the ui_scale'd equivalent dip
  // geometry 80x160.
  // 2. The expected wayland requests (along with the correct geometry and scale
  // related parameters) are issued once the new frame is received from Viz.
  const uint32_t kLatestConfigureSerial = 11u;
  PostToServerAndWait([menu_surface_id](wl::TestWaylandServerThread* server) {
    wl::MockSurface* mock_surface =
        server->GetObject<wl::MockSurface>(menu_surface_id);
    ASSERT_TRUE(mock_surface->xdg_surface());
    EXPECT_CALL(*mock_surface, Damage(0, 0, 100, 200));
    EXPECT_CALL(*mock_surface->xdg_surface(),
                SetWindowGeometry(gfx::Rect(100, 200)));
    EXPECT_CALL(*mock_surface->xdg_surface(),
                AckConfigure(Eq(kLatestConfigureSerial)));
  });
  // Configure popup window to origin 100,100 and size 100x200.
  PostToServerAndWait([id = menu_surface_id](
                          wl::TestWaylandServerThread* server) {
    auto* surface = server->GetObject<wl::MockSurface>(id);
    ASSERT_TRUE(surface);
    auto* xdg_surface = surface->xdg_surface();
    ASSERT_TRUE(xdg_surface);
    ASSERT_TRUE(xdg_surface->xdg_popup()->resource());
    xdg_popup_send_configure(xdg_surface->xdg_popup()->resource(), 100, 100,
                             100, 200);
    xdg_surface_send_configure(xdg_surface->resource(), kLatestConfigureSerial);
  });

  EXPECT_EQ(menu_window->applied_state().bounds_dip,
            gfx::Rect(80, 80, 80, 160));
  CreateBufferAndPresentAsNewFrame(menu_window.get(), menu_delegate,
                                   /*buffer_size=*/gfx::Size(100, 200),
                                   /*buffer_scale=*/1.25f);
  // Sync display and verify the expectations.
  VerifyAndClearExpectations(menu_delegate, menu_surface_id);
  EXPECT_EQ(menu_window->applied_state(), menu_window->latched_state());
  EXPECT_EQ(menu_window->latched_state().ui_scale, 1.25f);
  EXPECT_EQ(menu_window->latched_state().window_scale, 1.0f);
  EXPECT_EQ(menu_window->root_surface()->state_.buffer_scale_float, 1.0f);

  // Verifies both event dispatching and screen "cursor location" API works` as
  // expected with ui_scale > 1. Regression test fo https://crbug.com/396457560.
  std::unique_ptr<Event> event;
  EXPECT_CALL(menu_delegate, DispatchEvent(_))
      .WillRepeatedly(CloneEvent(&event));
  PostToServerAndWait(
      [id = menu_surface_id](wl::TestWaylandServerThread* server) {
        auto* pointer_resource = server->seat()->pointer()->resource();
        auto* menu_surface = server->GetObject<wl::MockSurface>(id);
        wl_pointer_send_enter(pointer_resource, server->GetNextSerial(),
                              menu_surface->resource(), 0, 0);
        wl_pointer_send_motion(pointer_resource, server->GetNextSerial(),
                               wl_fixed_from_double(10.0f),
                               wl_fixed_from_double(10.0f));
      });
  ASSERT_TRUE(event);
  ASSERT_TRUE(event->IsMouseEvent());
  ASSERT_EQ(event->type(), ui::EventType::kMouseMoved);
  // Event dispatching API expects pixel coordinates.
  EXPECT_EQ(event->AsLocatedEvent()->location(), gfx::Point(10, 10));
  EXPECT_EQ(event->AsLocatedEvent()->root_location(), gfx::Point(10, 10));
  // Internal cursor position tracker uses Wayland DIP coordinates.
  ASSERT_TRUE(connection_->wayland_cursor_position());
  EXPECT_EQ(connection_->wayland_cursor_position()->GetCursorSurfacePoint(),
            gfx::Point(110, 110));
  // Screen API uses UI DIP coordinates.
  EXPECT_EQ(screen_->GetCursorScreenPoint(), gfx::Point(88, 88));
}

TEST_P(PerSurfaceScaleWaylandWindowTest, UiScale_SanitizeFontScale) {
  base::test::ScopedFeatureList enable_ui_scaling(features::kWaylandUiScale);
  ASSERT_TRUE(connection_->IsUiScaleEnabled());

  auto test_font_scale = [&](float requested_font_scale,
                             float sanitized_font_scale) {
    EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange))).Times(1);
    connection_->window_manager()->SetFontScale(requested_font_scale);
    Mock::VerifyAndClearExpectations(&delegate_);
    WaylandTestBase::SyncDisplay();
    EXPECT_EQ(sanitized_font_scale, window_->applied_state().ui_scale);
    EXPECT_EQ(1.0f, window_->applied_state().window_scale);
  };

  // Set arbitrary font scale values and verify expectations.
  test_font_scale(20.0f, 3.0f);
  test_font_scale(0.10f, 0.5f);
  test_font_scale(1.5f, 1.5f);
  test_font_scale(-1.0f, 0.5f);
}

TEST_P(PerSurfaceScaleWaylandWindowTest, UiScale_ForceDeviceScaleFactor) {
  // When enabled, it must take precedence over font scale.
  ASSERT_TRUE(connection_->IsUiScaleEnabled());
  display::Display::SetForceDeviceScaleFactor(2.0);
  EXPECT_EQ(2.0f, connection_->window_manager()->DetermineUiScale());
  EXPECT_CALL(delegate_, OnBoundsChanged(Eq(kDefaultBoundsChange))).Times(1);
  SendConfigureEvent(surface_id_, gfx::Size(1000, 1000), wl::ScopedWlArray({}));
  VerifyAndClearExpectations();
  // Ensure the forced scale factor takes precedence (over font scale) and
  // gets used as ui scale when firing the bounds change triggered by the
  // server, in this case.
  EXPECT_EQ(2.0f, window_->applied_state().ui_scale);
  EXPECT_EQ(1.0f, window_->applied_state().window_scale);
  EXPECT_EQ(gfx::Size(500, 500), window_->applied_state().bounds_dip.size());
  EXPECT_EQ(gfx::Size(1000, 1000), window_->applied_state().size_px);
  PlatformWindowDelegate::State previous_state(window_->applied_state());

  // Font scale changes should not trigger bounds change when
  // force-device-scale-factor is in use.
  EXPECT_CALL(delegate_, OnBoundsChanged(_)).Times(0);
  connection_->window_manager()->SetFontScale(1.25f);
  Mock::VerifyAndClearExpectations(&delegate_);
  EXPECT_EQ(2.0f, connection_->window_manager()->DetermineUiScale());
  EXPECT_EQ(window_->applied_state(), previous_state);
}

INSTANTIATE_TEST_SUITE_P(XdgVersionStableTest,
                         WaylandWindowTest,
                         Values(wl::ServerConfig{}));
INSTANTIATE_TEST_SUITE_P(XdgVersionStableTest,
                         MultiDisplayWaylandWindowTest,
                         Values(wl::ServerConfig{}));
INSTANTIATE_TEST_SUITE_P(XdgVersionStableTest,
                         PerSurfaceScaleWaylandWindowTest,
                         Values(wl::ServerConfig{
                             .supports_viewporter_surface_scaling = true}));
INSTANTIATE_TEST_SUITE_P(XdgVersionStableTest,
                         WaylandSubsurfaceTest,
                         Values(wl::ServerConfig{}));

}  // namespace ui