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
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560
 7561
 7562
 7563
 7564
 7565
 7566
 7567
 7568
 7569
 7570
 7571
 7572
 7573
 7574
 7575
 7576
 7577
 7578
 7579
 7580
 7581
 7582
 7583
 7584
 7585
 7586
 7587
 7588
 7589
 7590
 7591
 7592
 7593
 7594
 7595
 7596
 7597
 7598
 7599
 7600
 7601
 7602
 7603
 7604
 7605
 7606
 7607
 7608
 7609
 7610
 7611
 7612
 7613
 7614
 7615
 7616
 7617
 7618
 7619
 7620
 7621
 7622
 7623
 7624
 7625
 7626
 7627
 7628
 7629
 7630
 7631
 7632
 7633
 7634
 7635
 7636
 7637
 7638
 7639
 7640
 7641
 7642
 7643
 7644
 7645
 7646
 7647
 7648
 7649
 7650
 7651
 7652
 7653
 7654
 7655
 7656
 7657
 7658
 7659
 7660
 7661
 7662
 7663
 7664
 7665
 7666
 7667
 7668
 7669
 7670
 7671
 7672
 7673
 7674
 7675
 7676
 7677
 7678
 7679
 7680
 7681
 7682
 7683
 7684
 7685
 7686
 7687
 7688
 7689
 7690
 7691
 7692
 7693
 7694
 7695
 7696
 7697
 7698
 7699
 7700
 7701
 7702
 7703
 7704
 7705
 7706
 7707
 7708
 7709
 7710
 7711
 7712
 7713
 7714
 7715
 7716
 7717
 7718
 7719
 7720
 7721
 7722
 7723
 7724
 7725
 7726
 7727
 7728
 7729
 7730
 7731
 7732
 7733
 7734
 7735
 7736
 7737
 7738
 7739
 7740
 7741
 7742
 7743
 7744
 7745
 7746
 7747
 7748
 7749
 7750
 7751
 7752
 7753
 7754
 7755
 7756
 7757
 7758
 7759
 7760
 7761
 7762
 7763
 7764
 7765
 7766
 7767
 7768
 7769
 7770
 7771
 7772
 7773
 7774
 7775
 7776
 7777
 7778
 7779
 7780
 7781
 7782
 7783
 7784
 7785
 7786
 7787
 7788
 7789
 7790
 7791
 7792
 7793
 7794
 7795
 7796
 7797
 7798
 7799
 7800
 7801
 7802
 7803
 7804
 7805
 7806
 7807
 7808
 7809
 7810
 7811
 7812
 7813
 7814
 7815
 7816
 7817
 7818
 7819
 7820
 7821
 7822
 7823
 7824
 7825
 7826
 7827
 7828
 7829
 7830
 7831
 7832
 7833
 7834
 7835
 7836
 7837
 7838
 7839
 7840
 7841
 7842
 7843
 7844
 7845
 7846
 7847
 7848
 7849
 7850
 7851
 7852
 7853
 7854
 7855
 7856
 7857
 7858
 7859
 7860
 7861
 7862
 7863
 7864
 7865
 7866
 7867
 7868
 7869
 7870
 7871
 7872
 7873
 7874
 7875
 7876
 7877
 7878
 7879
 7880
 7881
 7882
 7883
 7884
 7885
 7886
 7887
 7888
 7889
 7890
 7891
 7892
 7893
 7894
 7895
 7896
 7897
 7898
 7899
 7900
 7901
 7902
 7903
 7904
 7905
 7906
 7907
 7908
 7909
 7910
 7911
 7912
 7913
 7914
 7915
 7916
 7917
 7918
 7919
 7920
 7921
 7922
 7923
 7924
 7925
 7926
 7927
 7928
 7929
 7930
 7931
 7932
 7933
 7934
 7935
 7936
 7937
 7938
 7939
 7940
 7941
 7942
 7943
 7944
 7945
 7946
 7947
 7948
 7949
 7950
 7951
 7952
 7953
 7954
 7955
 7956
 7957
 7958
 7959
 7960
 7961
 7962
 7963
 7964
 7965
 7966
 7967
 7968
 7969
 7970
 7971
 7972
 7973
 7974
 7975
 7976
 7977
 7978
 7979
 7980
 7981
 7982
 7983
 7984
 7985
 7986
 7987
 7988
 7989
 7990
 7991
 7992
 7993
 7994
 7995
 7996
 7997
 7998
 7999
 8000
 8001
 8002
 8003
 8004
 8005
 8006
 8007
 8008
 8009
 8010
 8011
 8012
 8013
 8014
 8015
 8016
 8017
 8018
 8019
 8020
 8021
 8022
 8023
 8024
 8025
 8026
 8027
 8028
 8029
 8030
 8031
 8032
 8033
 8034
 8035
 8036
 8037
 8038
 8039
 8040
 8041
 8042
 8043
 8044
 8045
 8046
 8047
 8048
 8049
 8050
 8051
 8052
 8053
 8054
 8055
 8056
 8057
 8058
 8059
 8060
 8061
 8062
 8063
 8064
 8065
 8066
 8067
 8068
 8069
 8070
 8071
 8072
 8073
 8074
 8075
 8076
 8077
 8078
 8079
 8080
 8081
 8082
 8083
 8084
 8085
 8086
 8087
 8088
 8089
 8090
 8091
 8092
 8093
 8094
 8095
 8096
 8097
 8098
 8099
 8100
 8101
 8102
 8103
 8104
 8105
 8106
 8107
 8108
 8109
 8110
 8111
 8112
 8113
 8114
 8115
 8116
 8117
 8118
 8119
 8120
 8121
 8122
 8123
 8124
 8125
 8126
 8127
 8128
 8129
 8130
 8131
 8132
 8133
 8134
 8135
 8136
 8137
 8138
 8139
 8140
 8141
 8142
 8143
 8144
 8145
 8146
 8147
 8148
 8149
 8150
 8151
 8152
 8153
 8154
 8155
 8156
 8157
 8158
 8159
 8160
 8161
 8162
 8163
 8164
 8165
 8166
 8167
 8168
 8169
 8170
 8171
 8172
 8173
 8174
 8175
 8176
 8177
 8178
 8179
 8180
 8181
 8182
 8183
 8184
 8185
 8186
 8187
 8188
 8189
 8190
 8191
 8192
 8193
 8194
 8195
 8196
 8197
 8198
 8199
 8200
 8201
 8202
 8203
 8204
 8205
 8206
 8207
 8208
 8209
 8210
 8211
 8212
 8213
 8214
 8215
 8216
 8217
 8218
 8219
 8220
 8221
 8222
 8223
 8224
 8225
 8226
 8227
 8228
 8229
 8230
 8231
 8232
 8233
 8234
 8235
 8236
 8237
 8238
 8239
 8240
 8241
 8242
 8243
 8244
 8245
 8246
 8247
 8248
 8249
 8250
 8251
 8252
 8253
 8254
 8255
 8256
 8257
 8258
 8259
 8260
 8261
 8262
 8263
 8264
 8265
 8266
 8267
 8268
 8269
 8270
 8271
 8272
 8273
 8274
 8275
 8276
 8277
 8278
 8279
 8280
 8281
 8282
 8283
 8284
 8285
 8286
 8287
 8288
 8289
 8290
 8291
 8292
 8293
 8294
 8295
 8296
 8297
 8298
 8299
 8300
 8301
 8302
 8303
 8304
 8305
 8306
 8307
 8308
 8309
 8310
 8311
 8312
 8313
 8314
 8315
 8316
 8317
 8318
 8319
 8320
 8321
 8322
 8323
 8324
 8325
 8326
 8327
 8328
 8329
 8330
 8331
 8332
 8333
 8334
 8335
 8336
 8337
 8338
 8339
 8340
 8341
 8342
 8343
 8344
 8345
 8346
 8347
 8348
 8349
 8350
 8351
 8352
 8353
 8354
 8355
 8356
 8357
 8358
 8359
 8360
 8361
 8362
 8363
 8364
 8365
 8366
 8367
 8368
 8369
 8370
 8371
 8372
 8373
 8374
 8375
 8376
 8377
 8378
 8379
 8380
 8381
 8382
 8383
 8384
 8385
 8386
 8387
 8388
 8389
 8390
 8391
 8392
 8393
 8394
 8395
 8396
 8397
 8398
 8399
 8400
 8401
 8402
 8403
 8404
 8405
 8406
 8407
 8408
 8409
 8410
 8411
 8412
 8413
 8414
 8415
 8416
 8417
 8418
 8419
 8420
 8421
 8422
 8423
 8424
 8425
 8426
 8427
 8428
 8429
 8430
 8431
 8432
 8433
 8434
 8435
 8436
 8437
 8438
 8439
 8440
 8441
 8442
 8443
 8444
 8445
 8446
 8447
 8448
 8449
 8450
 8451
 8452
 8453
 8454
 8455
 8456
 8457
 8458
 8459
 8460
 8461
 8462
 8463
 8464
 8465
 8466
 8467
 8468
 8469
 8470
 8471
 8472
 8473
 8474
 8475
 8476
 8477
 8478
 8479
 8480
 8481
 8482
 8483
 8484
 8485
 8486
 8487
 8488
 8489
 8490
 8491
 8492
 8493
 8494
 8495
 8496
 8497
 8498
 8499
 8500
 8501
 8502
 8503
 8504
 8505
 8506
 8507
 8508
 8509
 8510
 8511
 8512
 8513
 8514
 8515
 8516
 8517
 8518
 8519
 8520
 8521
 8522
 8523
 8524
 8525
 8526
 8527
 8528
 8529
 8530
 8531
 8532
 8533
 8534
 8535
 8536
 8537
 8538
 8539
 8540
 8541
 8542
 8543
 8544
 8545
 8546
 8547
 8548
 8549
 8550
 8551
 8552
 8553
 8554
 8555
 8556
 8557
 8558
 8559
 8560
 8561
 8562
 8563
 8564
 8565
 8566
 8567
 8568
 8569
 8570
 8571
 8572
 8573
 8574
 8575
 8576
 8577
 8578
 8579
 8580
 8581
 8582
 8583
 8584
 8585
 8586
 8587
 8588
 8589
 8590
 8591
 8592
 8593
 8594
 8595
 8596
 8597
 8598
 8599
 8600
 8601
 8602
 8603
 8604
 8605
 8606
 8607
 8608
 8609
 8610
 8611
 8612
 8613
 8614
 8615
 8616
 8617
 8618
 8619
 8620
 8621
 8622
 8623
 8624
 8625
 8626
 8627
 8628
 8629
 8630
 8631
 8632
 8633
 8634
 8635
 8636
 8637
 8638
 8639
 8640
 8641
 8642
 8643
 8644
 8645
 8646
 8647
 8648
 8649
 8650
 8651
 8652
 8653
 8654
 8655
 8656
 8657
 8658
 8659
 8660
 8661
 8662
 8663
 8664
 8665
 8666
 8667
 8668
 8669
 8670
 8671
 8672
 8673
 8674
 8675
 8676
 8677
 8678
 8679
 8680
 8681
 8682
 8683
 8684
 8685
 8686
 8687
 8688
 8689
 8690
 8691
 8692
 8693
 8694
 8695
 8696
 8697
 8698
 8699
 8700
 8701
 8702
 8703
 8704
 8705
 8706
 8707
 8708
 8709
 8710
 8711
 8712
 8713
 8714
 8715
 8716
 8717
 8718
 8719
 8720
 8721
 8722
 8723
 8724
 8725
 8726
 8727
 8728
 8729
 8730
 8731
 8732
 8733
 8734
 8735
 8736
 8737
 8738
 8739
 8740
 8741
 8742
 8743
 8744
 8745
 8746
 8747
 8748
 8749
 8750
 8751
 8752
 8753
 8754
 8755
 8756
 8757
 8758
 8759
 8760
 8761
 8762
 8763
 8764
 8765
 8766
 8767
 8768
 8769
 8770
 8771
 8772
 8773
 8774
 8775
 8776
 8777
 8778
 8779
 8780
 8781
 8782
 8783
 8784
 8785
 8786
 8787
 8788
 8789
 8790
 8791
 8792
 8793
 8794
 8795
 8796
 8797
 8798
 8799
 8800
 8801
 8802
 8803
 8804
 8805
 8806
 8807
 8808
 8809
 8810
 8811
 8812
 8813
 8814
 8815
 8816
 8817
 8818
 8819
 8820
 8821
 8822
 8823
 8824
 8825
 8826
 8827
 8828
 8829
 8830
 8831
 8832
 8833
 8834
 8835
 8836
 8837
 8838
 8839
 8840
 8841
 8842
 8843
 8844
 8845
 8846
 8847
 8848
 8849
 8850
 8851
 8852
 8853
 8854
 8855
 8856
 8857
 8858
 8859
 8860
 8861
 8862
 8863
 8864
 8865
 8866
 8867
 8868
 8869
 8870
 8871
 8872
 8873
 8874
 8875
 8876
 8877
 8878
 8879
 8880
 8881
 8882
 8883
 8884
 8885
 8886
 8887
 8888
 8889
 8890
 8891
 8892
 8893
 8894
 8895
 8896
 8897
 8898
 8899
 8900
 8901
 8902
 8903
 8904
 8905
 8906
 8907
 8908
 8909
 8910
 8911
 8912
 8913
 8914
 8915
 8916
 8917
 8918
 8919
 8920
 8921
 8922
 8923
 8924
 8925
 8926
 8927
 8928
 8929
 8930
 8931
 8932
 8933
 8934
 8935
 8936
 8937
 8938
 8939
 8940
 8941
 8942
 8943
 8944
 8945
 8946
 8947
 8948
 8949
 8950
 8951
 8952
 8953
 8954
 8955
 8956
 8957
 8958
 8959
 8960
 8961
 8962
 8963
 8964
 8965
 8966
 8967
 8968
 8969
 8970
 8971
 8972
 8973
 8974
 8975
 8976
 8977
 8978
 8979
 8980
 8981
 8982
 8983
 8984
 8985
 8986
 8987
 8988
 8989
 8990
 8991
 8992
 8993
 8994
 8995
 8996
 8997
 8998
 8999
 9000
 9001
 9002
 9003
 9004
 9005
 9006
 9007
 9008
 9009
 9010
 9011
 9012
 9013
 9014
 9015
 9016
 9017
 9018
 9019
 9020
 9021
 9022
 9023
 9024
 9025
 9026
 9027
 9028
 9029
 9030
 9031
 9032
 9033
 9034
 9035
 9036
 9037
 9038
 9039
 9040
 9041
 9042
 9043
 9044
 9045
 9046
 9047
 9048
 9049
 9050
 9051
 9052
 9053
 9054
 9055
 9056
 9057
 9058
 9059
 9060
 9061
 9062
 9063
 9064
 9065
 9066
 9067
 9068
 9069
 9070
 9071
 9072
 9073
 9074
 9075
 9076
 9077
 9078
 9079
 9080
 9081
 9082
 9083
 9084
 9085
 9086
 9087
 9088
 9089
 9090
 9091
 9092
 9093
 9094
 9095
 9096
 9097
 9098
 9099
 9100
 9101
 9102
 9103
 9104
 9105
 9106
 9107
 9108
 9109
 9110
 9111
 9112
 9113
 9114
 9115
 9116
 9117
 9118
 9119
 9120
 9121
 9122
 9123
 9124
 9125
 9126
 9127
 9128
 9129
 9130
 9131
 9132
 9133
 9134
 9135
 9136
 9137
 9138
 9139
 9140
 9141
 9142
 9143
 9144
 9145
 9146
 9147
 9148
 9149
 9150
 9151
 9152
 9153
 9154
 9155
 9156
 9157
 9158
 9159
 9160
 9161
 9162
 9163
 9164
 9165
 9166
 9167
 9168
 9169
 9170
 9171
 9172
 9173
 9174
 9175
 9176
 9177
 9178
 9179
 9180
 9181
 9182
 9183
 9184
 9185
 9186
 9187
 9188
 9189
 9190
 9191
 9192
 9193
 9194
 9195
 9196
 9197
 9198
 9199
 9200
 9201
 9202
 9203
 9204
 9205
 9206
 9207
 9208
 9209
 9210
 9211
 9212
 9213
 9214
 9215
 9216
 9217
 9218
 9219
 9220
 9221
 9222
 9223
 9224
 9225
 9226
 9227
 9228
 9229
 9230
 9231
 9232
 9233
 9234
 9235
 9236
 9237
 9238
 9239
 9240
 9241
 9242
 9243
 9244
 9245
 9246
 9247
 9248
 9249
 9250
 9251
 9252
 9253
 9254
 9255
 9256
 9257
 9258
 9259
 9260
 9261
 9262
 9263
 9264
 9265
 9266
 9267
 9268
 9269
 9270
 9271
 9272
 9273
 9274
 9275
 9276
 9277
 9278
 9279
 9280
 9281
 9282
 9283
 9284
 9285
 9286
 9287
 9288
 9289
 9290
 9291
 9292
 9293
 9294
 9295
 9296
 9297
 9298
 9299
 9300
 9301
 9302
 9303
 9304
 9305
 9306
 9307
 9308
 9309
 9310
 9311
 9312
 9313
 9314
 9315
 9316
 9317
 9318
 9319
 9320
 9321
 9322
 9323
 9324
 9325
 9326
 9327
 9328
 9329
 9330
 9331
 9332
 9333
 9334
 9335
 9336
 9337
 9338
 9339
 9340
 9341
 9342
 9343
 9344
 9345
 9346
 9347
 9348
 9349
 9350
 9351
 9352
 9353
 9354
 9355
 9356
 9357
 9358
 9359
 9360
 9361
 9362
 9363
 9364
 9365
 9366
 9367
 9368
 9369
 9370
 9371
 9372
 9373
 9374
 9375
 9376
 9377
 9378
 9379
 9380
 9381
 9382
 9383
 9384
 9385
 9386
 9387
 9388
 9389
 9390
 9391
 9392
 9393
 9394
 9395
 9396
 9397
 9398
 9399
 9400
 9401
 9402
 9403
 9404
 9405
 9406
 9407
 9408
 9409
 9410
 9411
 9412
 9413
 9414
 9415
 9416
 9417
 9418
 9419
 9420
 9421
 9422
 9423
 9424
 9425
 9426
 9427
 9428
 9429
 9430
 9431
 9432
 9433
 9434
 9435
 9436
 9437
 9438
 9439
 9440
 9441
 9442
 9443
 9444
 9445
 9446
 9447
 9448
 9449
 9450
 9451
 9452
 9453
 9454
 9455
 9456
 9457
 9458
 9459
 9460
 9461
 9462
 9463
 9464
 9465
 9466
 9467
 9468
 9469
 9470
 9471
 9472
 9473
 9474
 9475
 9476
 9477
 9478
 9479
 9480
 9481
 9482
 9483
 9484
 9485
 9486
 9487
 9488
 9489
 9490
 9491
 9492
 9493
 9494
 9495
 9496
 9497
 9498
 9499
 9500
 9501
 9502
 9503
 9504
 9505
 9506
 9507
 9508
 9509
 9510
 9511
 9512
 9513
 9514
 9515
 9516
 9517
 9518
 9519
 9520
 9521
 9522
 9523
 9524
 9525
 9526
 9527
 9528
 9529
 9530
 9531
 9532
 9533
 9534
 9535
 9536
 9537
 9538
 9539
 9540
 9541
 9542
 9543
 9544
 9545
 9546
 9547
 9548
 9549
 9550
 9551
 9552
 9553
 9554
 9555
 9556
 9557
 9558
 9559
 9560
 9561
 9562
 9563
 9564
 9565
 9566
 9567
 9568
 9569
 9570
 9571
 9572
 9573
 9574
 9575
 9576
 9577
 9578
 9579
 9580
 9581
 9582
 9583
 9584
 9585
 9586
 9587
 9588
 9589
 9590
 9591
 9592
 9593
 9594
 9595
 9596
 9597
 9598
 9599
 9600
 9601
 9602
 9603
 9604
 9605
 9606
 9607
 9608
 9609
 9610
 9611
 9612
 9613
 9614
 9615
 9616
 9617
 9618
 9619
 9620
 9621
 9622
 9623
 9624
 9625
 9626
 9627
 9628
 9629
 9630
 9631
 9632
 9633
 9634
 9635
 9636
 9637
 9638
 9639
 9640
 9641
 9642
 9643
 9644
 9645
 9646
 9647
 9648
 9649
 9650
 9651
 9652
 9653
 9654
 9655
 9656
 9657
 9658
 9659
 9660
 9661
 9662
 9663
 9664
 9665
 9666
 9667
 9668
 9669
 9670
 9671
 9672
 9673
 9674
 9675
 9676
 9677
 9678
 9679
 9680
 9681
 9682
 9683
 9684
 9685
 9686
 9687
 9688
 9689
 9690
 9691
 9692
 9693
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963

ash / wm / desks / desks_unittests.cc [blame]

// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include <memory>
#include <string>
#include <vector>

#include "ash/accessibility/accessibility_controller.h"
#include "ash/accessibility/sticky_keys/sticky_keys_controller.h"
#include "ash/accessibility/ui/accessibility_confirmation_dialog.h"
#include "ash/app_list/app_list_controller_impl.h"
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/display/screen_orientation_controller.h"
#include "ash/display/screen_orientation_controller_test_api.h"
#include "ash/keyboard/ui/keyboard_ui_controller.h"
#include "ash/keyboard/ui/test/keyboard_test_util.h"
#include "ash/multi_user/multi_user_window_manager_impl.h"
#include "ash/public/cpp/ash_prefs.h"
#include "ash/public/cpp/event_rewriter_controller.h"
#include "ash/public/cpp/multi_user_window_manager.h"
#include "ash/public/cpp/multi_user_window_manager_delegate.h"
#include "ash/public/cpp/shelf_model.h"
#include "ash/public/cpp/shelf_prefs.h"
#include "ash/public/cpp/shelf_types.h"
#include "ash/public/cpp/test/test_desk_profiles_delegate.h"
#include "ash/public/cpp/test/test_shelf_item_delegate.h"
#include "ash/public/cpp/window_finder.h"
#include "ash/root_window_controller.h"
#include "ash/screen_util.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shelf/hotseat_widget.h"
#include "ash/shelf/scroll_arrow_view.h"
#include "ash/shelf/scrollable_shelf_view.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_layout_manager.h"
#include "ash/shelf/shelf_navigation_widget.h"
#include "ash/shelf/shelf_test_util.h"
#include "ash/shelf/shelf_view.h"
#include "ash/shelf/shelf_view_test_api.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "ash/strings/grit/ash_strings.h"
#include "ash/style/ash_color_provider.h"
#include "ash/style/close_button.h"
#include "ash/style/color_util.h"
#include "ash/test/ash_test_base.h"
#include "ash/test/ash_test_helper.h"
#include "ash/test/ash_test_util.h"
#include "ash/test/test_widget_builder.h"
#include "ash/wm/desks/default_desk_button.h"
#include "ash/wm/desks/desk.h"
#include "ash/wm/desks/desk_action_button.h"
#include "ash/wm/desks/desk_action_context_menu.h"
#include "ash/wm/desks/desk_action_view.h"
#include "ash/wm/desks/desk_animation_base.h"
#include "ash/wm/desks/desk_bar_controller.h"
#include "ash/wm/desks/desk_bar_view_base.h"
#include "ash/wm/desks/desk_button/desk_button.h"
#include "ash/wm/desks/desk_button/desk_button_container.h"
#include "ash/wm/desks/desk_button/desk_switch_button.h"
#include "ash/wm/desks/desk_button_base.h"
#include "ash/wm/desks/desk_icon_button.h"
#include "ash/wm/desks/desk_mini_view.h"
#include "ash/wm/desks/desk_name_view.h"
#include "ash/wm/desks/desk_preview_view.h"
#include "ash/wm/desks/desk_profiles_button.h"
#include "ash/wm/desks/desk_textfield.h"
#include "ash/wm/desks/desks_controller.h"
#include "ash/wm/desks/desks_histogram_enums.h"
#include "ash/wm/desks/desks_restore_util.h"
#include "ash/wm/desks/desks_test_api.h"
#include "ash/wm/desks/desks_test_util.h"
#include "ash/wm/desks/desks_util.h"
#include "ash/wm/desks/overview_desk_bar_view.h"
#include "ash/wm/desks/root_window_desk_switch_animator_test_api.h"
#include "ash/wm/desks/scroll_arrow_button.h"
#include "ash/wm/desks/templates/saved_desk_test_helper.h"
#include "ash/wm/desks/templates/saved_desk_test_util.h"
#include "ash/wm/desks/templates/saved_desk_util.h"
#include "ash/wm/mru_window_tracker.h"
#include "ash/wm/overview/overview_controller.h"
#include "ash/wm/overview/overview_grid.h"
#include "ash/wm/overview/overview_grid_test_api.h"
#include "ash/wm/overview/overview_item.h"
#include "ash/wm/overview/overview_session.h"
#include "ash/wm/overview/overview_test_util.h"
#include "ash/wm/overview/overview_window_drag_controller.h"
#include "ash/wm/splitview/split_view_controller.h"
#include "ash/wm/splitview/split_view_drag_indicators.h"
#include "ash/wm/splitview/split_view_types.h"
#include "ash/wm/splitview/split_view_utils.h"
#include "ash/wm/tablet_mode/tablet_mode_controller_test_api.h"
#include "ash/wm/window_state.h"
#include "ash/wm/window_util.h"
#include "ash/wm/wm_event.h"
#include "ash/wm/workspace/backdrop_controller.h"
#include "ash/wm/workspace/workspace_layout_manager.h"
#include "ash/wm/workspace_controller.h"
#include "base/containers/contains.h"
#include "base/functional/callback_forward.h"
#include "base/i18n/rtl.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/time/time.h"
#include "chromeos/constants/chromeos_features.h"
#include "chromeos/ui/frame/caption_buttons/snap_controller.h"
#include "chromeos/ui/frame/desks/move_to_desks_menu_delegate.h"
#include "chromeos/ui/frame/desks/move_to_desks_menu_model.h"
#include "chromeos/ui/wm/desks/chromeos_desks_histogram_enums.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/prefs/testing_pref_service.h"
#include "components/session_manager/session_manager_types.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/window_parenting_client.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/base/clipboard/clipboard_buffer.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/base/ime/ash/fake_ime_keyboard.h"
#include "ui/base/mojom/ui_base_types.mojom-shared.h"
#include "ui/base/ui_base_types.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/compositor/test/layer_animation_stopped_waiter.h"
#include "ui/compositor_extra/shadow.h"
#include "ui/display/display.h"
#include "ui/display/display_switches.h"
#include "ui/display/screen.h"
#include "ui/display/test/display_manager_test_api.h"
#include "ui/events/ash/event_rewriter_ash.h"
#include "ui/events/ash/fake_event_rewriter_ash_delegate.h"
#include "ui/events/devices/device_data_manager.h"
#include "ui/events/devices/device_data_manager_test_api.h"
#include "ui/events/devices/input_device.h"
#include "ui/events/event_constants.h"
#include "ui/events/keycodes/keyboard_codes_posix.h"
#include "ui/events/test/event_generator.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/image/image_unittest_util.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/widget/any_widget_observer.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
#include "ui/wm/core/shadow_controller.h"
#include "ui/wm/core/window_modality_controller.h"
#include "ui/wm/core/window_util.h"

namespace ash {

namespace {

using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::ValuesIn;

std::unique_ptr<aura::Window> CreateTransientWindow(
    aura::Window* transient_parent,
    const gfx::Rect& bounds) {
  std::unique_ptr<aura::Window> window =
      std::make_unique<aura::Window>(nullptr, aura::client::WINDOW_TYPE_POPUP);
  window->Init(ui::LAYER_NOT_DRAWN);
  window->SetBounds(bounds);
  ::wm::AddTransientChild(transient_parent, window.get());
  aura::client::ParentWindowWithContext(window.get(),
                                        transient_parent->GetRootWindow(),
                                        bounds, display::kInvalidDisplayId);
  window->Show();
  return window;
}

std::unique_ptr<aura::Window> CreateTransientModalChildWindow(
    aura::Window* transient_parent) {
  auto child =
      CreateTransientWindow(transient_parent, gfx::Rect(20, 30, 200, 150));
  child->SetProperty(aura::client::kModalKey, ui::mojom::ModalType::kWindow);
  ::wm::SetModalParent(child.get(), transient_parent);
  return child;
}

bool DoesActiveDeskContainWindow(aura::Window* window) {
  return base::Contains(DesksController::Get()->active_desk()->windows(),
                        window);
}

// Combines or closes a desk.
void CloseDeskFromMiniView(DeskMiniView* desk_mini_view,
                           ui::test::EventGenerator* event_generator) {
  DCHECK(desk_mini_view);
  DeskBarViewBase* desk_bar_view = desk_mini_view->owner_bar();
  // Move to the center of the mini view so that the close button shows up.
  const gfx::Point mini_view_center =
      desk_mini_view->GetBoundsInScreen().CenterPoint();
  event_generator->MoveMouseTo(mini_view_center);

  // This is the combine button if available, close button otherwise.
  const CloseButton* close_button =
      GetCloseDeskButtonForMiniView(desk_mini_view);
  EXPECT_TRUE(close_button->GetVisible());

  // Move to the center of the close button and click.
  event_generator->MoveMouseTo(close_button->GetBoundsInScreen().CenterPoint());
  event_generator->ClickLeftButton();
  views::test::RunScheduledLayout(desk_bar_view);
}

void DoubleClickOnView(const views::View* view,
                       ui::test::EventGenerator* event_generator) {
  DCHECK(view);

  const gfx::Point view_center = view->GetBoundsInScreen().CenterPoint();
  event_generator->MoveMouseTo(view_center);
  event_generator->DoubleClickLeftButton();
}

void SendAccessibleActionToView(views::View* view, ax::mojom::Action action) {
  ui::AXActionData action_data;
  action_data.action = action;
  view->HandleAccessibleAction(action_data);
}

BackdropController* GetDeskBackdropController(const Desk* desk,
                                              aura::Window* root) {
  auto* workspace_controller =
      GetWorkspaceController(desk->GetDeskContainerForRoot(root));
  WorkspaceLayoutManager* layout_manager =
      workspace_controller->layout_manager();
  return layout_manager->backdrop_controller();
}

// Simulate pressing on a desk preview.
void LongTapOnDeskPreview(const DeskMiniView* desk_mini_view,
                          ui::test::EventGenerator* event_generator) {
  DCHECK(desk_mini_view);

  gfx::Point desk_preview_center =
      desk_mini_view->GetPreviewBoundsInScreen().CenterPoint();

  LongGestureTap(desk_preview_center, event_generator, /*release_touch=*/false);
}

// Simulate drag on a desk preview.
void StartDragDeskPreview(const DeskMiniView* desk_mini_view,
                          ui::test::EventGenerator* event_generator) {
  DCHECK(desk_mini_view);

  gfx::Point desk_preview_center =
      desk_mini_view->GetPreviewBoundsInScreen().CenterPoint();
  event_generator->set_current_screen_location(desk_preview_center);

  event_generator->PressLeftButton();
  event_generator->MoveMouseBy(0, 50);
}

TestDeskProfilesDelegate& GetDeskProfilesTestDelegate() {
  CHECK(chromeos::features::IsDeskProfilesEnabled());
  return *static_cast<TestDeskProfilesDelegate*>(
      Shell::Get()->GetDeskProfilesDelegate());
}

uint64_t GetDummyLacrosDeskProfileId(size_t index) {
  static constexpr uint64_t kLacrosProfileIdBase = 1001;
  return kLacrosProfileIdBase + index * 2;
}

// Adds `count` dummy lacros profiles to the test delegate.
void AddDummyLacrosDeskProfiles(size_t count) {
  for (size_t i = 0; i != count; ++i) {
    LacrosProfileSummary summary;
    summary.profile_id = GetDummyLacrosDeskProfileId(i);
    summary.name =
        base::UTF8ToUTF16(base::StringPrintf("Lacros user %lu", i + 1));
    summary.email =
        base::UTF8ToUTF16(base::StringPrintf("email%lu@gmail.com", i + 1));
    summary.icon = gfx::test::CreateImageSkia(32, 32);

    GetDeskProfilesTestDelegate().UpdateTestProfile(std::move(summary));
  }
}

// Sends tab keys (or shift+tab) until the passed predicate becomes true, or a
// fixed max is hit.
template <class Predicate>
bool TabUntil(bool reverse,
              Predicate&& predicate,
              ui::test::EventGenerator* generator) {
  for (int i = 0; i != 100; ++i) {
    if (predicate()) {
      return true;
    }

    SendKey(ui::VKEY_TAB, generator, reverse ? ui::EF_SHIFT_DOWN : ui::EF_NONE);
  }
  return false;
}

// Returns a predicate that will return true if the given `view` is focused.
auto ViewFocused(views::View* view) {
  return [view] { return view->HasFocus(); };
}

// Defines an observer to test DesksController notifications.
class TestObserver : public DesksController::Observer {
 public:
  TestObserver() = default;

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

  ~TestObserver() override = default;

  const std::vector<raw_ptr<const Desk, VectorExperimental>>& desks() const {
    return desks_;
  }
  int desk_name_changed_notify_counts() const {
    return desk_name_changed_notify_counts_;
  }

  // DesksController::Observer:
  void OnDeskAdded(const Desk* desk, bool from_undo) override {
    const size_t new_desk_index = DesksController::Get()->GetDeskIndex(desk);
    if (new_desk_index > desks_.size()) {
      desks_.emplace_back(desk);
    } else {
      desks_.insert(desks_.begin() + new_desk_index, desk);
    }
    EXPECT_TRUE(DesksController::Get()->AreDesksBeingModified());
  }
  void OnDeskRemoved(const Desk* desk) override {
    std::erase(desks_, desk);
    EXPECT_TRUE(DesksController::Get()->AreDesksBeingModified());
  }
  void OnDeskActivationChanged(const Desk* activated,
                               const Desk* deactivated) override {
    EXPECT_TRUE(DesksController::Get()->AreDesksBeingModified());
  }
  void OnDeskSwitchAnimationFinished() override {
    EXPECT_FALSE(DesksController::Get()->AreDesksBeingModified());
  }
  void OnDeskNameChanged(const Desk* desk,
                         const std::u16string& new_name) override {
    ++desk_name_changed_notify_counts_;
  }

 private:
  std::vector<raw_ptr<const Desk, VectorExperimental>> desks_;

  int desk_name_changed_notify_counts_ = 0;
};

class TestDeskObserver : public Desk::Observer {
 public:
  TestDeskObserver() = default;

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

  ~TestDeskObserver() override = default;

  int notify_counts() const { return notify_counts_; }

  const std::vector<uint64_t>& lacros_profile_id_updates() const {
    return lacros_profile_id_updates_;
  }

  // Desk::Observer:
  void OnContentChanged() override { ++notify_counts_; }
  void OnDeskDestroyed(const Desk* desk) override {}
  void OnDeskNameChanged(const std::u16string& new_name) override {}
  void OnDeskProfileChanged(uint64_t lacros_profile_id) override {
    lacros_profile_id_updates_.push_back(lacros_profile_id);
  }

 private:
  int notify_counts_ = 0;
  std::vector<uint64_t> lacros_profile_id_updates_;
};

class FullScreenStateObserver : public ShellObserver {
 public:
  FullScreenStateObserver() { Shell::Get()->AddShellObserver(this); }

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

  ~FullScreenStateObserver() override {
    Shell::Get()->RemoveShellObserver(this);
  }

  // ShellObserver:
  void OnFullscreenStateChanged(bool is_fullscreen,
                                aura::Window* container) override {
    is_fullscreen_ = is_fullscreen;
  }

  bool is_fullscreen() const { return is_fullscreen_; }

 private:
  bool is_fullscreen_ = false;
};

// A widget delegate that refuses to close.
class StuckWidgetDelegate : public views::WidgetDelegate {
 public:
  StuckWidgetDelegate() {
    SetCanMaximize(true);
    SetCanMinimize(true);
    SetCanResize(true);
    SetOwnedByWidget(true);
  }
  StuckWidgetDelegate(const StuckWidgetDelegate& other) = delete;
  StuckWidgetDelegate& operator=(const StuckWidgetDelegate& other) = delete;
  ~StuckWidgetDelegate() override = default;

  // Overridden from WidgetDelegate:
  std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
      views::Widget* widget) override {
    return Shell::Get()->CreateDefaultNonClientFrameView(widget);
  }

  bool OnCloseRequested(views::Widget::ClosedReason close_reason) override {
    return false;
  }
};

struct DesksTestParams {
  bool use_touch_gestures = false;
  bool use_16_desks = false;
  bool per_desk_shelf = false;
};

// Defines a parameterized test fixture to test Virtual Desks behavior.
class DesksTest : public AshTestBase,
                  public ::testing::WithParamInterface<DesksTestParams> {
 public:
  enum class DeskBarScrollDirection { kLeft, kRight };

  DesksTest() = default;
  explicit DesksTest(base::test::TaskEnvironment::TimeSource time)
      : AshTestBase(time) {}

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

  ~DesksTest() override = default;

  void SetUp() override {
    // This allows us to snap to the bottom in portrait mode.
    base::CommandLine::ForCurrentProcess()->AppendSwitch(
        ::switches::kUseFirstDisplayAsInternal);

    scoped_feature_list_.InitWithFeatureStates(
        {{features::kFeatureManagement16Desks, GetParam().use_16_desks},
         {features::kPerDeskShelf, GetParam().per_desk_shelf},
         {chromeos::features::kOverviewSessionInitOptimizations, true}});

    AshTestBase::SetUp();
    SetVirtualKeyboardEnabled(true);

    // Wait for the desk model to have completed its initialization. Not doing
    // this would lead to flaky tests.
    ash_test_helper()->saved_desk_test_helper()->WaitForDeskModels();
  }

  void TearDown() override {
    AshTestBase::TearDown();
    scoped_feature_list_.Reset();
  }

  void VerifyZeroStateNewDeskButtonVisibility(const DeskBarViewBase* bar_view,
                                              bool expected_visibility) {
    const auto state = bar_view->new_desk_button()->state();
    EXPECT_TRUE(expected_visibility ? state == DeskIconButton::State::kZero
                                    : state != DeskIconButton::State::kZero);
  }

  void VerifyExpandedStateNewDeskButtonVisibility(
      const DeskBarViewBase* bar_view,
      bool expected_visibility) {
    const auto state = bar_view->new_desk_button()->state();
    EXPECT_TRUE(expected_visibility
                    ? state == DeskIconButton::State::kExpanded
                    : state != DeskIconButton::State::kExpanded);
  }

  SkColor GetNewDeskButtonBackgroundColor(const DeskBarViewBase* bar_view) {
    return bar_view->new_desk_button()->background()->get_color();
  }

  void TryScrollOverviewDeskBar(DeskBarScrollDirection scroll_direction,
                                bool do_left_click = true) {
    ScrollArrowButton* scroll_button = nullptr;
    switch (scroll_direction) {
      case DeskBarScrollDirection::kLeft:
        scroll_button = DesksTestApi::GetDeskBarLeftScrollButton(
            DeskBarViewBase::Type::kOverview);
        break;
      case DeskBarScrollDirection::kRight:
        scroll_button = DesksTestApi::GetDeskBarRightScrollButton(
            DeskBarViewBase::Type::kOverview);
        break;
    }
    if (!scroll_button || !scroll_button->GetVisible()) {
      return;
    }
    if (do_left_click) {
      LeftClickOn(scroll_button);
    } else {
      GestureTapOn(scroll_button);
    }
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_P(DesksTest, DesksCreationAndRemoval) {
  TestObserver observer;
  auto* controller = DesksController::Get();
  controller->AddObserver(&observer);

  // There's always a default pre-existing desk that cannot be removed.
  EXPECT_EQ(1u, controller->desks().size());
  EXPECT_FALSE(controller->CanRemoveDesks());
  EXPECT_TRUE(controller->CanCreateDesks());

  // Add desks until no longer possible.
  while (controller->CanCreateDesks()) {
    NewDesk();
  }

  // Expect we've reached the max number of desks, and we've been notified only
  // with the newly created desks.
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks(), controller->desks().size());
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks() - 1, observer.desks().size());
  EXPECT_TRUE(controller->CanRemoveDesks());

  // Remove all desks until no longer possible, and expect that there's always
  // one default desk remaining.
  while (controller->CanRemoveDesks()) {
    RemoveDesk(observer.desks().back());
  }

  EXPECT_EQ(1u, controller->desks().size());
  EXPECT_FALSE(controller->CanRemoveDesks());
  EXPECT_TRUE(controller->CanCreateDesks());
  EXPECT_TRUE(observer.desks().empty());

  controller->RemoveObserver(&observer);
}

TEST_P(DesksTest, DeskRemovalLifetimeHistogram) {
  base::HistogramTester histogram_tester;

  auto* controller = DesksController::Get();

  // Create a new desk and give it a creation time in the past.
  NewDesk();
  auto* desk = controller->desks().back().get();
  desk->set_creation_time(base::Time::Now() - base::Hours(8));

  RemoveDesk(desk);
  histogram_tester.ExpectBucketCount("Ash.Desks.DeskLifetime_2", 8, 1);
}

// Regression test for a crash reported at https://crbug.com/1267069. If a
// window was created while the MRU tracker is paused (so it's not tracked), and
// later the desk on which this window resides is removed, that window will be
// moved to an adjacent desk, and its order in the MRU tracker is updated. But
// the MRU tracker was not tracking it to begin with, so this case has to be
// handled.
TEST_P(DesksTest, DeskRemovalWithPausedMruTracker) {
  NewDesk();
  auto* controller = DesksController::Get();
  EXPECT_EQ(2u, controller->desks().size());

  auto* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);
  const auto win_bounds = gfx::Rect{10, 20, 250, 100};
  auto win1 = CreateAppWindow(win_bounds);
  auto* mru_tracker = Shell::Get()->mru_window_tracker();
  // Pause the MRU tracking and create a new window.
  mru_tracker->SetIgnoreActivations(true);
  auto win2 = CreateAppWindow(win_bounds);

  // Enter overview and remove `desk_2`. A crash should not be observed.
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
  RemoveDesk(desk_2);
}

// Verifies that desk's name change notifies |DesksController::Observer|.
TEST_P(DesksTest, OnDeskNameChanged) {
  TestObserver observer;
  auto* controller = DesksController::Get();
  controller->AddObserver(&observer);

  NewDesk();
  controller->GetDeskAtIndex(0)->SetName(u"test1", /*set_by_user=*/true);
  controller->GetDeskAtIndex(1)->SetName(u"test2", /*set_by_user=*/true);

  // Verify that desk name change will trigger
  // |TestObserver::OnDeskNameChanged()|. Notice when creating a new desk
  // and setting its name, it also triggers the call. Thus
  // |desk_name_changed_notify_counts_| is 3.
  ASSERT_EQ(3, observer.desk_name_changed_notify_counts());
  controller->RemoveObserver(&observer);
}

TEST_P(DesksTest, DesksTextfieldAddTooltipText) {
  NewDesk();

  auto* controller = DesksController::Get();

  // Set the first desk with a name which is short enough to be fit in the desk
  // name view.
  controller->GetDeskAtIndex(0)->SetName(u"test1", /*set_by_user=*/true);

  // Set the second desk with a name which is long enough to be truncated in the
  // desk name view.
  std::u16string desk_name2(
      u"test2 a very long desk name to test tooltip text");
  controller->GetDeskAtIndex(1)->SetName(desk_name2, /*set_by_user=*/true);

  // Start overview.
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  // Expect there to be no tooltip when the desk name is short enough.
  auto* desks_bar_view =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  auto* desk_name_view1 = desks_bar_view->mini_views()[0]->desk_name_view();
  EXPECT_TRUE(desk_name_view1->GetTooltipText(gfx::Point()).empty());

  auto* desk_name_view2 = desks_bar_view->mini_views()[1]->desk_name_view();
  EXPECT_EQ(desk_name2, desk_name_view2->GetTooltipText(gfx::Point()));
}

TEST_P(DesksTest, DesksBarViewDeskCreation) {
  auto* controller = DesksController::Get();

  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());

  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());

  const auto* desks_bar_view = overview_grid->desks_bar_view();
  EXPECT_FALSE(overview_grid->IsDesksBarViewActive());

  DCHECK(desks_bar_view);
  EXPECT_TRUE(desks_bar_view->mini_views().empty());

  auto* event_generator = GetEventGenerator();
  LeftClickOn(desks_bar_view->default_desk_button());
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_FALSE(desks_bar_view->IsZeroState());

  auto* new_desk_button = desks_bar_view->new_desk_button();
  EXPECT_TRUE(new_desk_button->GetEnabled());

  // Click many times on the expanded new desk button and expect only the max
  // number of desks will be created, and the button is no longer enabled.
  for (size_t i = 0; i < desks_util::GetMaxNumberOfDesks() + 2; ++i) {
    LeftClickOn(new_desk_button);
    RunScheduledLayoutForAllOverviewDeskBars();
    TryScrollOverviewDeskBar(DeskBarScrollDirection::kRight);
    RunScheduledLayoutForAllOverviewDeskBars();
  }

  EXPECT_TRUE(overview_grid->IsDesksBarViewActive());
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks(), controller->desks().size());
  EXPECT_EQ(controller->desks().size(), desks_bar_view->mini_views().size());
  EXPECT_FALSE(controller->CanCreateDesks());
  EXPECT_TRUE(controller->CanRemoveDesks());
  EXPECT_FALSE(new_desk_button->GetEnabled());
  EXPECT_EQ(views::Button::STATE_DISABLED, new_desk_button->GetState());

  // Hover over one of the mini_views, and expect that the desk action interface
  // becomes visible.
  auto* mini_view = desks_bar_view->mini_views().back().get();
  EXPECT_FALSE(GetDeskActionVisibilityForMiniView(mini_view));
  const gfx::Point mini_view_center =
      mini_view->GetBoundsInScreen().CenterPoint();
  event_generator->MoveMouseTo(mini_view_center);
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_TRUE(GetDeskActionVisibilityForMiniView(mini_view));

  // Use the close button to close the desk.
  CloseDeskFromMiniView(mini_view, event_generator);
  RunScheduledLayoutForAllOverviewDeskBars();

  // The new desk button is now enabled again.
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks() - 1, controller->desks().size());
  EXPECT_EQ(controller->desks().size(), desks_bar_view->mini_views().size());
  EXPECT_TRUE(controller->CanCreateDesks());
  EXPECT_TRUE(new_desk_button->GetEnabled());
  EXPECT_EQ(views::Button::STATE_NORMAL, new_desk_button->GetState());

  // Exit overview mode and re-enter. Since we have more than one pre-existing
  // desks, their mini_views should be created upon construction of the desks
  // bar.
  ExitOverview();
  EXPECT_FALSE(overview_controller->InOverviewSession());
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());

  // Get the new grid and the new desk_bar_view.
  overview_grid =
      overview_controller->overview_session()->GetGridWithRootWindow(
          Shell::GetPrimaryRootWindow());
  EXPECT_TRUE(overview_grid->IsDesksBarViewActive());
  desks_bar_view = overview_grid->desks_bar_view();

  DCHECK(desks_bar_view);
  EXPECT_EQ(controller->desks().size(), desks_bar_view->mini_views().size());
  EXPECT_TRUE(desks_bar_view->new_desk_button()->GetEnabled());
}

TEST_P(DesksTest, RemoveDeskWithEmptyName) {
  auto* controller = DesksController::Get();

  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());

  const auto* desks_bar_view = overview_grid->desks_bar_view();

  auto* event_generator = GetEventGenerator();

  // Create a new desk by using button with empty name.
  controller->NewDesk(DesksCreationRemovalSource::kButton);
  EXPECT_EQ(2u, controller->desks().size());

  // Close the newly created desk with the close button.
  auto* mini_view = desks_bar_view->mini_views().back().get();
  CloseDeskFromMiniView(mini_view, event_generator);
  EXPECT_EQ(1u, controller->desks().size());
}

// Tests that removing a non-active desk updates the window workspaces for
// desks restore correctly.
TEST_P(DesksTest, RemovingNonActiveDeskUpdatesWindowWorkspaces) {
  auto* controller = DesksController::Get();

  // Create two new desks.
  NewDesk();
  NewDesk();
  EXPECT_EQ(3u, controller->desks().size());

  // Create one window in each desk.
  std::vector<std::unique_ptr<aura::Window>> windows;
  for (int i = 0; i < 3; i++) {
    windows.push_back(CreateAppWindow());
    controller->SendToDeskAtIndex(windows[i].get(), i);
    EXPECT_EQ(i, windows[i]->GetProperty(aura::client::kWindowWorkspaceKey));
  }

  // Switch to the third desk.
  ActivateDesk(controller->GetDeskAtIndex(2));

  // Close the second desk.
  RemoveDesk(controller->GetDeskAtIndex(1));
  EXPECT_EQ(2u, controller->desks().size());

  // The window in the first desk remain unaffected by the second desk removal.
  EXPECT_EQ(0, windows[0]->GetProperty(aura::client::kWindowWorkspaceKey));
  // The window in the removed second desk should move to the active desk, the
  // third desk, which just becomes the second desk after the removal.
  EXPECT_EQ(1, windows[1]->GetProperty(aura::client::kWindowWorkspaceKey));
  // The window in the third desk update its workspace to index - 1.
  EXPECT_EQ(1, windows[2]->GetProperty(aura::client::kWindowWorkspaceKey));
}

// Tests that removing an active desk updates the window workspaces for desks
// restore correctly.
TEST_P(DesksTest, RemovingActiveDeskUpdatesWindowWorkspaces) {
  auto* controller = DesksController::Get();

  // Create three new desks.
  NewDesk();
  NewDesk();
  NewDesk();
  EXPECT_EQ(4u, controller->desks().size());

  // Create one window in each desk.
  std::vector<std::unique_ptr<aura::Window>> windows;
  for (int i = 0; i < 4; i++) {
    windows.push_back(CreateAppWindow());
    controller->SendToDeskAtIndex(windows[i].get(), i);
    EXPECT_EQ(i, windows[i]->GetProperty(aura::client::kWindowWorkspaceKey));
  }

  // Switch to the second desk.
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);

  // Close the second desk.
  RemoveDesk(desk_2);
  EXPECT_EQ(3u, controller->desks().size());

  // The previous desk (first) becomes active after closing the second desk.
  EXPECT_EQ(controller->GetDeskAtIndex(0), controller->active_desk());

  // The window in the first desk remain unaffected by the second desk removal.
  EXPECT_EQ(0, windows[0]->GetProperty(aura::client::kWindowWorkspaceKey));
  // The window from the removed second desk moves to the active, first desk.
  EXPECT_EQ(0, windows[1]->GetProperty(aura::client::kWindowWorkspaceKey));
  // The desk indices of the third and forth desks are decreased by one, so
  // the workspace values of windows in those desks are reduced by one.
  EXPECT_EQ(1, windows[2]->GetProperty(aura::client::kWindowWorkspaceKey));
  EXPECT_EQ(2, windows[3]->GetProperty(aura::client::kWindowWorkspaceKey));
}

// Test that gesture taps do not reset the button state to normal when the
// button is disabled. https://crbug.com/1084241.
TEST_P(DesksTest, GestureTapOnNewDeskButton) {
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());

  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  LeftClickOn(desks_bar_view->default_desk_button());
  auto* new_desk_button = desks_bar_view->new_desk_button();
  EXPECT_TRUE(new_desk_button->GetEnabled());

  // Gesture tap multiple times on the new desk button until it's disabled,
  // and verify the button state.
  for (size_t i = 0; i < desks_util::GetMaxNumberOfDesks() + 2; ++i) {
    GestureTapOn(new_desk_button);
    RunScheduledLayoutForAllOverviewDeskBars();
    TryScrollOverviewDeskBar(DeskBarScrollDirection::kRight,
                             /*do_left_click=*/false);
  }

  EXPECT_FALSE(new_desk_button->GetEnabled());
  EXPECT_EQ(views::Button::STATE_DISABLED, new_desk_button->GetState());
}

TEST_P(DesksTest, DeskActivation) {
  auto* controller = DesksController::Get();
  ASSERT_EQ(1u, controller->desks().size());
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  EXPECT_EQ(desk_1, controller->active_desk());
  EXPECT_TRUE(desk_1->is_active());

  auto* root = Shell::GetPrimaryRootWindow();
  EXPECT_TRUE(desk_1->GetDeskContainerForRoot(root)->IsVisible());
  EXPECT_EQ(desks_util::GetActiveDeskContainerForRoot(root),
            desk_1->GetDeskContainerForRoot(root));

  // Create three new desks, and activate one of the middle ones.
  NewDesk();
  NewDesk();
  NewDesk();
  ASSERT_EQ(4u, controller->desks().size());
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  const Desk* desk_3 = controller->GetDeskAtIndex(2);
  const Desk* desk_4 = controller->GetDeskAtIndex(3);
  EXPECT_FALSE(controller->AreDesksBeingModified());
  ActivateDesk(desk_2);
  EXPECT_FALSE(controller->AreDesksBeingModified());
  EXPECT_EQ(desk_2, controller->active_desk());
  EXPECT_FALSE(desk_1->is_active());
  EXPECT_TRUE(desk_2->is_active());
  EXPECT_FALSE(desk_3->is_active());
  EXPECT_FALSE(desk_4->is_active());
  EXPECT_FALSE(desk_1->GetDeskContainerForRoot(root)->IsVisible());
  EXPECT_TRUE(desk_2->GetDeskContainerForRoot(root)->IsVisible());
  EXPECT_FALSE(desk_3->GetDeskContainerForRoot(root)->IsVisible());
  EXPECT_FALSE(desk_4->GetDeskContainerForRoot(root)->IsVisible());

  // Remove the active desk, which is in the middle, activation should move to
  // the left, so desk 1 should be activated.
  EXPECT_FALSE(controller->AreDesksBeingModified());
  RemoveDesk(desk_2);
  EXPECT_FALSE(controller->AreDesksBeingModified());
  ASSERT_EQ(3u, controller->desks().size());
  EXPECT_EQ(desk_1, controller->active_desk());
  EXPECT_TRUE(desk_1->is_active());
  EXPECT_FALSE(desk_3->is_active());
  EXPECT_FALSE(desk_4->is_active());
  EXPECT_TRUE(desk_1->GetDeskContainerForRoot(root)->IsVisible());
  EXPECT_FALSE(desk_3->GetDeskContainerForRoot(root)->IsVisible());
  EXPECT_FALSE(desk_4->GetDeskContainerForRoot(root)->IsVisible());

  // Remove the active desk, it's the first one on the left, so desk_3 (on the
  // right) will be activated.
  EXPECT_FALSE(controller->AreDesksBeingModified());
  RemoveDesk(desk_1);
  EXPECT_FALSE(controller->AreDesksBeingModified());
  ASSERT_EQ(2u, controller->desks().size());
  EXPECT_EQ(desk_3, controller->active_desk());
  EXPECT_TRUE(desk_3->is_active());
  EXPECT_FALSE(desk_4->is_active());
  EXPECT_TRUE(desk_3->GetDeskContainerForRoot(root)->IsVisible());
  EXPECT_FALSE(desk_4->GetDeskContainerForRoot(root)->IsVisible());
}

TEST_P(DesksTest, TestWindowPositioningPaused) {
  auto* controller = DesksController::Get();
  NewDesk();

  // Create two windows whose window positioning is managed.
  const auto win0_bounds = gfx::Rect{10, 20, 250, 100};
  const auto win1_bounds = gfx::Rect{50, 50, 200, 200};
  auto win0 = CreateAppWindow(win0_bounds);
  auto win1 = CreateAppWindow(win1_bounds);
  WindowState* window_state = WindowState::Get(win0.get());
  window_state->SetWindowPositionManaged(true);
  window_state = WindowState::Get(win1.get());
  window_state->SetWindowPositionManaged(true);
  EXPECT_EQ(win0_bounds, win0->GetBoundsInScreen());
  EXPECT_EQ(win1_bounds, win1->GetBoundsInScreen());

  // Moving one window to the second desk should not affect the bounds of either
  // windows.
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  controller->MoveWindowFromActiveDeskTo(
      win1.get(), desk_2, win1->GetRootWindow(),
      DesksMoveWindowFromActiveDeskSource::kDragAndDrop);
  EXPECT_EQ(win0_bounds, win0->GetBoundsInScreen());
  EXPECT_EQ(win1_bounds, win1->GetBoundsInScreen());

  // Removing a desk, which results in moving its windows to another desk should
  // not affect the positions of those managed windows.
  RemoveDesk(desk_2);
  EXPECT_EQ(win0_bounds, win0->GetBoundsInScreen());
  EXPECT_EQ(win1_bounds, win1->GetBoundsInScreen());
}

// This test makes sure we have coverage for that desk switch animation when run
// with multiple displays.
TEST_P(DesksTest, DeskActivationDualDisplay) {
  UpdateDisplay("700x600,400x500");

  auto* controller = DesksController::Get();
  ASSERT_EQ(1u, controller->desks().size());
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  EXPECT_EQ(desk_1, controller->active_desk());
  EXPECT_TRUE(desk_1->is_active());

  // Create three new desks, and activate one of the middle ones.
  NewDesk();
  NewDesk();
  NewDesk();
  ASSERT_EQ(4u, controller->desks().size());
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  const Desk* desk_3 = controller->GetDeskAtIndex(2);
  const Desk* desk_4 = controller->GetDeskAtIndex(3);
  EXPECT_FALSE(controller->AreDesksBeingModified());
  ActivateDesk(desk_2);
  EXPECT_FALSE(controller->AreDesksBeingModified());
  EXPECT_EQ(desk_2, controller->active_desk());
  EXPECT_FALSE(desk_1->is_active());
  EXPECT_TRUE(desk_2->is_active());
  EXPECT_FALSE(desk_3->is_active());
  EXPECT_FALSE(desk_4->is_active());

  auto roots = Shell::GetAllRootWindows();
  ASSERT_EQ(2u, roots.size());
  EXPECT_FALSE(desk_1->GetDeskContainerForRoot(roots[0])->IsVisible());
  EXPECT_FALSE(desk_1->GetDeskContainerForRoot(roots[1])->IsVisible());
  EXPECT_TRUE(desk_2->GetDeskContainerForRoot(roots[0])->IsVisible());
  EXPECT_TRUE(desk_2->GetDeskContainerForRoot(roots[1])->IsVisible());
  EXPECT_FALSE(desk_3->GetDeskContainerForRoot(roots[0])->IsVisible());
  EXPECT_FALSE(desk_3->GetDeskContainerForRoot(roots[1])->IsVisible());
  EXPECT_FALSE(desk_4->GetDeskContainerForRoot(roots[0])->IsVisible());
  EXPECT_FALSE(desk_4->GetDeskContainerForRoot(roots[1])->IsVisible());
}

TEST_P(DesksTest, TransientWindows) {
  auto* controller = DesksController::Get();
  ASSERT_EQ(1u, controller->desks().size());
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  EXPECT_EQ(desk_1, controller->active_desk());
  EXPECT_TRUE(desk_1->is_active());

  // Create two windows, one is a transient child of the other.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateTransientWindow(win0.get(), gfx::Rect(100, 100, 100, 100));

  EXPECT_EQ(2u, desk_1->windows().size());
  EXPECT_TRUE(DoesActiveDeskContainWindow(win0.get()));
  EXPECT_TRUE(DoesActiveDeskContainWindow(win1.get()));

  auto* root = Shell::GetPrimaryRootWindow();
  EXPECT_EQ(desks_util::GetActiveDeskContainerForRoot(root),
            desks_util::GetDeskContainerForContext(win0.get()));
  EXPECT_EQ(desks_util::GetActiveDeskContainerForRoot(root),
            desks_util::GetDeskContainerForContext(win1.get()));

  // Create a new desk and activate it.
  NewDesk();
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  EXPECT_TRUE(desk_2->windows().empty());
  ActivateDesk(desk_2);
  EXPECT_FALSE(desk_1->is_active());
  EXPECT_TRUE(desk_2->is_active());

  // Create another transient child of the earlier transient child, and confirm
  // it's tracked in desk_1 (even though desk_2 is the currently active one).
  // This is because the transient parent exists in desk_1.
  auto win2 = CreateTransientWindow(win1.get(), gfx::Rect(100, 100, 50, 50));
  EXPECT_FALSE(controller->AreDesksBeingModified());
  EXPECT_EQ(3u, desk_1->windows().size());
  EXPECT_TRUE(desk_2->windows().empty());
  EXPECT_FALSE(DoesActiveDeskContainWindow(win2.get()));
  auto* desk_1_container = desk_1->GetDeskContainerForRoot(root);
  EXPECT_EQ(win0.get(), desk_1_container->children()[0]);
  EXPECT_EQ(win1.get(), desk_1_container->children()[1]);
  EXPECT_EQ(win2.get(), desk_1_container->children()[2]);

  // Remove the inactive desk 1, and expect that its windows, including
  // transient will move to desk 2.
  RemoveDesk(desk_1);
  EXPECT_EQ(1u, controller->desks().size());
  EXPECT_EQ(desk_2, controller->active_desk());
  EXPECT_EQ(3u, desk_2->windows().size());
  auto* desk_2_container = desk_2->GetDeskContainerForRoot(root);
  EXPECT_EQ(win0.get(), desk_2_container->children()[0]);
  EXPECT_EQ(win1.get(), desk_2_container->children()[1]);
  EXPECT_EQ(win2.get(), desk_2_container->children()[2]);
}

TEST_P(DesksTest, WindowStackingAfterWindowMoveToAnotherDesk) {
  auto* controller = DesksController::Get();
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));

  NewDesk();
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);

  auto win1 = CreateAppWindow(gfx::Rect(10, 10, 250, 100));
  auto win2 = CreateTransientWindow(win1.get(), gfx::Rect(100, 100, 100, 100));
  wm::ActivateWindow(win2.get());
  auto win3 = CreateAppWindow(gfx::Rect(20, 20, 250, 100));

  // Move back to desk_1, so |win0| becomes the most recent.
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  ActivateDesk(desk_1);
  EXPECT_EQ(win0.get(), window_util::GetActiveWindow());

  // The global MRU order should be {win0, win3, win2, win1}.
  auto* mru_tracker = Shell::Get()->mru_window_tracker();
  EXPECT_EQ(mru_tracker->BuildMruWindowList(DesksMruType::kAllDesks),
            aura::WindowTracker::WindowList({
                win0.get(),
                win3.get(),
                win2.get(),
                win1.get(),
            }));

  // Now move back to desk_2, and move its windows to desk_1. Their window
  // stacking should match their order in the MRU.
  ActivateDesk(desk_2);
  // The global MRU order is updated to be {win3, win0, win2, win1}.
  EXPECT_EQ(mru_tracker->BuildMruWindowList(DesksMruType::kAllDesks),
            aura::WindowTracker::WindowList({
                win3.get(),
                win0.get(),
                win2.get(),
                win1.get(),
            }));

  // Moving |win2| should be enough to get its transient parent |win1| moved as
  // well.
  desk_2->MoveWindowToDesk(win2.get(), desk_1, win1->GetRootWindow(),
                           /*unminimize=*/true);
  desk_2->MoveWindowToDesk(win3.get(), desk_1, win1->GetRootWindow(),
                           /*unminimize=*/true);
  EXPECT_TRUE(window_util::IsStackedBelow(win1.get(), win2.get()));
  EXPECT_TRUE(window_util::IsStackedBelow(win2.get(), win0.get()));
  EXPECT_TRUE(window_util::IsStackedBelow(win0.get(), win3.get()));
}

TEST_P(DesksTest, TransientModalChildren) {
  auto* controller = DesksController::Get();
  NewDesk();
  NewDesk();
  ASSERT_EQ(3u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  Desk* desk_3 = controller->GetDeskAtIndex(2);
  EXPECT_EQ(desk_1, controller->active_desk());
  EXPECT_TRUE(desk_1->is_active());

  // Create three windows, one of them is a modal transient child.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateTransientModalChildWindow(win0.get());
  EXPECT_EQ(win1.get(), ::wm::GetModalTransient(win0.get()));
  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 200, 100));
  ASSERT_EQ(3u, desk_1->windows().size());
  auto* root = Shell::GetPrimaryRootWindow();
  auto* desk_1_container = desk_1->GetDeskContainerForRoot(root);
  EXPECT_EQ(win0.get(), desk_1_container->children()[0]);
  EXPECT_EQ(win1.get(), desk_1_container->children()[1]);
  EXPECT_EQ(win2.get(), desk_1_container->children()[2]);

  // Remove desk_1, and expect that all its windows (including the transient
  // modal child and its parent) are moved to desk_2, and that their z-order
  // within the container is preserved.
  RemoveDesk(desk_1);
  EXPECT_EQ(desk_2, controller->active_desk());
  ASSERT_EQ(3u, desk_2->windows().size());
  auto* desk_2_container = desk_2->GetDeskContainerForRoot(root);
  EXPECT_EQ(win0.get(), desk_2_container->children()[0]);
  EXPECT_EQ(win1.get(), desk_2_container->children()[1]);
  EXPECT_EQ(win2.get(), desk_2_container->children()[2]);
  EXPECT_EQ(win1.get(), ::wm::GetModalTransient(win0.get()));

  // Move only the modal child window to desk_3, and expect that its parent will
  // move along with it, and their z-order is preserved.
  controller->MoveWindowFromActiveDeskTo(
      win1.get(), desk_3, win1->GetRootWindow(),
      DesksMoveWindowFromActiveDeskSource::kDragAndDrop);
  ASSERT_EQ(1u, desk_2->windows().size());
  ASSERT_EQ(2u, desk_3->windows().size());
  EXPECT_EQ(win2.get(), desk_2_container->children()[0]);
  auto* desk_3_container = desk_3->GetDeskContainerForRoot(root);
  EXPECT_EQ(win0.get(), desk_3_container->children()[0]);
  EXPECT_EQ(win1.get(), desk_3_container->children()[1]);

  // The modality remains the same.
  ActivateDesk(desk_3);
  EXPECT_EQ(win1.get(), ::wm::GetModalTransient(win0.get()));
}

TEST_P(DesksTest, WindowActivation) {
  // Create three windows.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  auto win2 = CreateAppWindow(gfx::Rect(100, 100, 100, 100));

  EXPECT_TRUE(DoesActiveDeskContainWindow(win0.get()));
  EXPECT_TRUE(DoesActiveDeskContainWindow(win1.get()));
  EXPECT_TRUE(DoesActiveDeskContainWindow(win2.get()));

  // Activate win0 and expects that it remains activated until we switch desks.
  wm::ActivateWindow(win0.get());

  // Create a new desk and activate it. Expect it's not tracking any windows
  // yet.
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  EXPECT_EQ(desk_1, controller->active_desk());
  EXPECT_EQ(3u, desk_1->windows().size());
  EXPECT_TRUE(desk_2->windows().empty());
  EXPECT_EQ(win0.get(), window_util::GetActiveWindow());

  // Activate the newly-added desk. Expect that the tracked windows per each
  // desk will remain the same.
  ActivateDesk(desk_2);
  EXPECT_EQ(desk_2, controller->active_desk());
  EXPECT_EQ(3u, desk_1->windows().size());
  EXPECT_TRUE(desk_2->windows().empty());

  // `desk_2` has no windows, so now no window should be active. However,
  // windows on `desk_1` are activateable.
  EXPECT_EQ(nullptr, window_util::GetActiveWindow());
  EXPECT_TRUE(wm::CanActivateWindow(win0.get()));
  EXPECT_TRUE(wm::CanActivateWindow(win1.get()));
  EXPECT_TRUE(wm::CanActivateWindow(win2.get()));

  // Create two new windows, they should now go to desk_2.
  auto win3 = CreateAppWindow(gfx::Rect(0, 0, 300, 200));
  auto win4 = CreateAppWindow(gfx::Rect(10, 30, 400, 200));
  wm::ActivateWindow(win3.get());
  EXPECT_EQ(2u, desk_2->windows().size());
  EXPECT_TRUE(DoesActiveDeskContainWindow(win3.get()));
  EXPECT_TRUE(DoesActiveDeskContainWindow(win4.get()));
  EXPECT_FALSE(DoesActiveDeskContainWindow(win0.get()));
  EXPECT_FALSE(DoesActiveDeskContainWindow(win1.get()));
  EXPECT_FALSE(DoesActiveDeskContainWindow(win2.get()));
  EXPECT_EQ(win3.get(), window_util::GetActiveWindow());

  // Delete `win0` and expect that `desk_1`'s windows will be updated.
  win0.reset();
  EXPECT_EQ(2u, desk_1->windows().size());
  EXPECT_EQ(2u, desk_2->windows().size());
  // No change in the activation.
  EXPECT_EQ(win3.get(), window_util::GetActiveWindow());

  // Switch back to `desk_1`. Now we can activate its windows.
  ActivateDesk(desk_1);
  EXPECT_EQ(desk_1, controller->active_desk());
  EXPECT_TRUE(wm::CanActivateWindow(win1.get()));
  EXPECT_TRUE(wm::CanActivateWindow(win2.get()));
  EXPECT_TRUE(wm::CanActivateWindow(win3.get()));
  EXPECT_TRUE(wm::CanActivateWindow(win4.get()));

  // After `win0` has been deleted, `win2` is next on the MRU list.
  EXPECT_EQ(win2.get(), window_util::GetActiveWindow());

  // Remove `desk_2` and expect that its windows will be moved to the active
  // desk.
  TestDeskObserver observer;
  desk_1->AddObserver(&observer);
  RemoveDesk(desk_2);
  EXPECT_EQ(1u, controller->desks().size());
  EXPECT_EQ(desk_1, controller->active_desk());
  EXPECT_EQ(4u, desk_1->windows().size());
  // Even though two new windows have been added to desk_1, observers should be
  // notified only once.
  EXPECT_EQ(1, observer.notify_counts());
  desk_1->RemoveObserver(&observer);
  EXPECT_TRUE(DoesActiveDeskContainWindow(win3.get()));
  EXPECT_TRUE(DoesActiveDeskContainWindow(win4.get()));

  // `desk_2`'s windows moved to `desk_1`, but that should not change the
  // already active window.
  EXPECT_EQ(win2.get(), window_util::GetActiveWindow());

  // Moved windows can still be activated.
  EXPECT_TRUE(wm::CanActivateWindow(win3.get()));
  EXPECT_TRUE(wm::CanActivateWindow(win4.get()));
}

TEST_P(DesksTest, ActivateDeskFromOverview) {
  auto* controller = DesksController::Get();
  auto* overview_controller = OverviewController::Get();
  auto* event_generator = GetEventGenerator();

  // Create three desks other than the default initial desk.
  NewDesk();
  NewDesk();
  NewDesk();
  ASSERT_EQ(4u, controller->desks().size());

  // Create two windows on desk_1.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  wm::ActivateWindow(win1.get());
  EXPECT_EQ(win1.get(), window_util::GetActiveWindow());

  // Test that left-click on desk mini view activates the specified desk.
  {
    // Enter overview mode, and expect the desk bar is shown with exactly four
    // desks mini views, and there are exactly two windows in the overview mode
    // grid.
    EnterOverview();
    EXPECT_TRUE(overview_controller->InOverviewSession());
    const auto* overview_grid =
        GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
    const auto* desks_bar_view = overview_grid->desks_bar_view();
    ASSERT_TRUE(desks_bar_view);
    ASSERT_EQ(4u, desks_bar_view->mini_views().size());
    EXPECT_EQ(2u, overview_grid->item_list().size());

    // Activate desk_4 (last one on the right) by clicking on its mini view.
    const Desk* desk_4 = controller->GetDeskAtIndex(3);
    EXPECT_EQ(0, controller->GetActiveDeskIndex());
    auto* mini_view = desks_bar_view->mini_views().back().get();
    EXPECT_EQ(desk_4, mini_view->desk());
    EXPECT_FALSE(GetDeskActionVisibilityForMiniView(mini_view));
    DeskSwitchAnimationWaiter waiter;
    LeftClickOn(mini_view);
    waiter.Wait();

    // Expect that desk_4 is now active, and overview mode exited.
    EXPECT_EQ(3, controller->GetActiveDeskIndex());
    EXPECT_FALSE(overview_controller->InOverviewSession());
    // Exiting overview mode should not restore focus to a window on a
    // now-inactive desk. Run a loop since the overview session is destroyed
    // async and until that happens, focus will be on the dummy
    // "OverviewModeFocusedWidget".
    base::RunLoop().RunUntilIdle();
    EXPECT_EQ(nullptr, window_util::GetActiveWindow());

    // Create one window in desk_4 and enter overview mode. Expect the grid is
    // showing exactly one window.
    auto win2 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
    wm::ActivateWindow(win2.get());
    EnterOverview();
    EXPECT_TRUE(overview_controller->InOverviewSession());
    overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
    EXPECT_EQ(1u, overview_grid->item_list().size());

    // When exiting overview mode without changing desks, the focus should be
    // restored to the same window.
    ExitOverview();
    EXPECT_FALSE(overview_controller->InOverviewSession());
    // Run a loop since the overview session is destroyed async and until that
    // happens, focus will be on the dummy "OverviewModeFocusedWidget".
    base::RunLoop().RunUntilIdle();
    EXPECT_EQ(win2.get(), window_util::GetActiveWindow());
  }

  // Test double click on desk mini view does not crash.
  {
    EnterOverview();
    const auto* overview_grid =
        GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
    DeskSwitchAnimationWaiter waiter;
    DoubleClickOnView(overview_grid->desks_bar_view()->mini_views().front(),
                      event_generator);
    waiter.Wait();
    EXPECT_EQ(0, controller->GetActiveDeskIndex());
    EXPECT_FALSE(overview_controller->InOverviewSession());
  }

  // Test that using ChromeVox on a desk mini view does not crash.
  {
    EnterOverview();
    const auto* overview_grid =
        GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
    DeskSwitchAnimationWaiter waiter;
    SendAccessibleActionToView(
        overview_grid->desks_bar_view()->mini_views()[1]->desk_preview(),
        ax::mojom::Action::kDoDefault);
    waiter.Wait();
    EXPECT_EQ(1, controller->GetActiveDeskIndex());
    EXPECT_FALSE(overview_controller->InOverviewSession());
  }
}

// This test makes sure we have coverage for that desk switch animation when run
// with multiple displays while overview mode is active.
TEST_P(DesksTest, ActivateDeskFromOverviewDualDisplay) {
  UpdateDisplay("700x600,400x500");

  auto* controller = DesksController::Get();

  // Create three desks other than the default initial desk.
  NewDesk();
  NewDesk();
  NewDesk();
  ASSERT_EQ(4u, controller->desks().size());

  // Enter overview mode.
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());

  auto roots = Shell::GetAllRootWindows();
  ASSERT_EQ(2u, roots.size());
  // Use secondary display grid.
  const auto* overview_grid = GetOverviewGridForRoot(roots[1]);
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_EQ(4u, desks_bar_view->mini_views().size());

  // Activate desk_4 (last one on the right) by clicking on its mini view.
  const Desk* desk_4 = controller->GetDeskAtIndex(3);
  EXPECT_FALSE(desk_4->is_active());
  const auto* mini_view = desks_bar_view->mini_views().back().get();
  const gfx::Point mini_view_center =
      mini_view->GetBoundsInScreen().CenterPoint();
  auto* event_generator = GetEventGenerator();
  event_generator->MoveMouseTo(mini_view_center);
  DeskSwitchAnimationWaiter waiter;
  event_generator->ClickLeftButton();
  waiter.Wait();

  // Expect that desk_4 is now active, and overview mode exited.
  EXPECT_TRUE(desk_4->is_active());
  EXPECT_FALSE(overview_controller->InOverviewSession());
}

TEST_P(DesksTest, RemoveInactiveDeskFromOverview) {
  auto* controller = DesksController::Get();

  // Create three desks other than the default initial desk.
  NewDesk();
  NewDesk();
  NewDesk();
  ASSERT_EQ(4u, controller->desks().size());

  // Create 3 windows on desk_1.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  auto win2 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  wm::ActivateWindow(win0.get());
  EXPECT_EQ(win0.get(), window_util::GetActiveWindow());

  auto* mru_tracker = Shell::Get()->mru_window_tracker();
  EXPECT_THAT(mru_tracker->BuildMruWindowList(DesksMruType::kActiveDesk),
              ElementsAre(win0.get(), win2.get(), win1.get()));

  // Active desk_4 and enter overview mode, and add a single window.
  Desk* desk_4 = controller->GetDeskAtIndex(3);
  ActivateDesk(desk_4);
  auto* overview_controller = OverviewController::Get();
  auto win3 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  EXPECT_EQ(1u, overview_grid->item_list().size());

  // Remove desk_1 using the close button on its mini view. desk_1 is currently
  // inactive. Its windows should be moved to desk_4 and added to the overview
  // grid in the MRU order (win0, win2, and win1) at the end after desk_4's
  // existing window (win3).
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_EQ(4u, desks_bar_view->mini_views().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  auto* mini_view = desks_bar_view->mini_views().front().get();
  EXPECT_EQ(desk_1, mini_view->desk());

  // Setup observers of both the active and inactive desks to make sure
  // refreshing the mini_view is requested only *once* for the active desk, and
  // never for the to-be-removed inactive desk.
  TestDeskObserver desk_4_observer;
  desk_4->AddObserver(&desk_4_observer);
  TestDeskObserver desk_1_observer;
  desk_1->AddObserver(&desk_1_observer);

  if (features::IsSavedDeskUiRevampEnabled()) {
    views::MenuItemView* menu_item =
        DesksTestApi::OpenDeskContextMenuAndGetMenuItem(
            Shell::GetPrimaryRootWindow(), DeskBarViewBase::Type::kOverview,
            /*index=*/0u, DeskActionContextMenu::CommandId::kCombineDesks);
    LeftClickOn(menu_item);
  } else {
    // This will combine `desk_1` into `desk_4`.
    CloseDeskFromMiniView(mini_view, GetEventGenerator());
  }

  EXPECT_EQ(0, desk_1_observer.notify_counts());
  EXPECT_EQ(1, desk_4_observer.notify_counts());

  ASSERT_EQ(3u, desks_bar_view->mini_views().size());
  EXPECT_TRUE(overview_controller->InOverviewSession());
  ASSERT_EQ(4u, overview_grid->item_list().size());
  EXPECT_TRUE(overview_grid->GetOverviewItemContaining(win0.get()));
  EXPECT_TRUE(overview_grid->GetOverviewItemContaining(win1.get()));
  EXPECT_TRUE(overview_grid->GetOverviewItemContaining(win2.get()));
  EXPECT_TRUE(overview_grid->GetOverviewItemContaining(win3.get()));
  // Expected order of items: win3, win0, win2, win1.
  EXPECT_EQ(overview_grid->GetOverviewItemContaining(win3.get()),
            overview_grid->item_list()[0].get());
  EXPECT_EQ(overview_grid->GetOverviewItemContaining(win0.get()),
            overview_grid->item_list()[1].get());
  EXPECT_EQ(overview_grid->GetOverviewItemContaining(win2.get()),
            overview_grid->item_list()[2].get());
  EXPECT_EQ(overview_grid->GetOverviewItemContaining(win1.get()),
            overview_grid->item_list()[3].get());

  // Make sure overview mode remains active.
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(overview_controller->InOverviewSession());

  // Removing a desk with no windows should not result in any new mini_views
  // updates.
  mini_view = desks_bar_view->mini_views().front();
  EXPECT_TRUE(mini_view->desk()->windows().empty());
  CloseDeskFromMiniView(mini_view, GetEventGenerator());
  EXPECT_EQ(1, desk_4_observer.notify_counts());

  // Exiting overview mode should not cause any mini_views refreshes, since the
  // destroyed overview-specific windows do not show up in the mini_view.
  ExitOverview();
  EXPECT_FALSE(overview_controller->InOverviewSession());
  EXPECT_EQ(1, desk_4_observer.notify_counts());
  desk_4->RemoveObserver(&desk_4_observer);

  // Verify that the stacking order is correct (top-most comes last, and
  // top-most is the same as MRU).
  EXPECT_THAT(mru_tracker->BuildMruWindowList(DesksMruType::kActiveDesk),
              ElementsAre(win3.get(), win0.get(), win2.get(), win1.get()));
  EXPECT_THAT(desk_4->GetDeskContainerForRoot(Shell::GetPrimaryRootWindow())
                  ->children(),
              ElementsAre(win1.get(), win2.get(), win0.get(), win3.get()));
}

TEST_P(DesksTest, RemoveActiveDeskFromOverview) {
  auto* controller = DesksController::Get();

  // Create one desk other than the default initial desk.
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());

  // Create two windows on desk_1.
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  wm::ActivateWindow(win0.get());
  EXPECT_EQ(win0.get(), window_util::GetActiveWindow());

  // Activate desk_2 and create one more window.
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);
  auto win2 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  auto win3 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  wm::ActivateWindow(win2.get());
  EXPECT_EQ(win2.get(), window_util::GetActiveWindow());

  // The MRU across all desks is now {win2, win3, win0, win1}.
  auto* mru_tracker = Shell::Get()->mru_window_tracker();
  EXPECT_THAT(mru_tracker->BuildMruWindowList(DesksMruType::kAllDesks),
              ElementsAre(win2.get(), win3.get(), win0.get(), win1.get()));

  // Enter overview mode, and remove desk_2 from its mini-view close button.
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  EXPECT_EQ(2u, overview_grid->item_list().size());
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_EQ(2u, desks_bar_view->mini_views().size());
  auto* mini_view = desks_bar_view->mini_views().back().get();
  EXPECT_EQ(desk_2, mini_view->desk());

  // Setup observers of both the active and inactive desks to make sure
  // refreshing the mini_view is requested only *once* for the soon-to-be active
  // desk_1, and never for the to-be-removed currently active desk_2.
  TestDeskObserver desk_1_observer;
  desk_1->AddObserver(&desk_1_observer);
  TestDeskObserver desk_2_observer;
  desk_2->AddObserver(&desk_2_observer);

  if (features::IsSavedDeskUiRevampEnabled()) {
    views::MenuItemView* menu_item =
        DesksTestApi::OpenDeskContextMenuAndGetMenuItem(
            Shell::GetPrimaryRootWindow(), DeskBarViewBase::Type::kOverview,
            /*index=*/1u, DeskActionContextMenu::CommandId::kCombineDesks);
    LeftClickOn(menu_item);
  } else {
    // This will combine `desk_2` into `desk_1`.
    CloseDeskFromMiniView(mini_view, GetEventGenerator());
  }

  EXPECT_EQ(1, desk_1_observer.notify_counts());
  EXPECT_EQ(0, desk_2_observer.notify_counts());

  // Make sure that the desks_bar_view window is still visible, i.e. it moved to
  // the newly-activated desk's container.
  EXPECT_TRUE(desks_bar_view->GetWidget()->IsVisible());
  EXPECT_TRUE(DoesActiveDeskContainWindow(
      desks_bar_view->GetWidget()->GetNativeWindow()));

  // desk_1 will become active, and windows from desk_2 will move to desk_1 such
  // that they become last in MRU order, and therefore appended at the end of
  // the overview grid. Desks bar should go back to zero state since there is a
  // single desk after removing.
  ASSERT_EQ(1u, controller->desks().size());
  ASSERT_EQ(1u, desks_bar_view->mini_views().size());
  EXPECT_TRUE(desk_1->is_active());
  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_EQ(4u, overview_grid->item_list().size());
  EXPECT_TRUE(overview_grid->GetOverviewItemContaining(win0.get()));
  EXPECT_TRUE(overview_grid->GetOverviewItemContaining(win1.get()));
  EXPECT_TRUE(overview_grid->GetOverviewItemContaining(win2.get()));
  EXPECT_TRUE(overview_grid->GetOverviewItemContaining(win3.get()));

  // The new MRU order is {win0, win1, win2, win3}.
  EXPECT_THAT(mru_tracker->BuildMruWindowList(DesksMruType::kActiveDesk),
              ElementsAre(win0.get(), win1.get(), win2.get(), win3.get()));
  EXPECT_EQ(overview_grid->GetOverviewItemContaining(win0.get()),
            overview_grid->item_list()[0].get());
  EXPECT_EQ(overview_grid->GetOverviewItemContaining(win1.get()),
            overview_grid->item_list()[1].get());
  EXPECT_EQ(overview_grid->GetOverviewItemContaining(win2.get()),
            overview_grid->item_list()[2].get());
  EXPECT_EQ(overview_grid->GetOverviewItemContaining(win3.get()),
            overview_grid->item_list()[3].get());

  // Make sure overview mode remains active.
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(overview_controller->InOverviewSession());

  // Exiting overview mode should not cause any mini_views refreshes, since the
  // destroyed overview-specific windows do not show up in the mini_view.
  ExitOverview();
  EXPECT_FALSE(overview_controller->InOverviewSession());
  EXPECT_EQ(1, desk_1_observer.notify_counts());
  desk_1->RemoveObserver(&desk_1_observer);
}

// Test that there is no crash when closing active desk with a all desk window
// right after creating a desk with empty name.
// Regression test for b/266147233.
TEST_P(DesksTest,
       RemoveActiveDeskWithAllDeskWindowFromOverviewWithNewDeskOfEmptyName) {
  auto* controller = DesksController::Get();

  NewDesk();
  auto win1 = CreateAppWindow();
  views::Widget::GetWidgetForNativeWindow(win1.get())
      ->SetVisibleOnAllWorkspaces(true);
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(win1.get()));

  EnterOverview();
  LeftClickOn(GetPrimaryRootDesksBarView()->new_desk_button());
  ASSERT_EQ(3u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  Desk* desk_3 = controller->GetDeskAtIndex(2);
  ASSERT_TRUE(desk_1->is_active());

  controller->RemoveDesk(desk_1, DesksCreationRemovalSource::kButton,
                         DeskCloseType::kCloseAllWindowsAndWait);
  ASSERT_EQ(desk_2, controller->GetTargetActiveDesk());
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  controller->RemoveDesk(desk_2, DesksCreationRemovalSource::kButton,
                         DeskCloseType::kCloseAllWindowsAndWait);
  ASSERT_EQ(desk_3, controller->GetTargetActiveDesk());
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
  // The desk bar doesn't switch to zero state.
  EXPECT_EQ(1u, GetPrimaryRootDesksBarView()->mini_views().size());
}

TEST_P(DesksTest, ActivateActiveDeskFromOverview) {
  auto* controller = DesksController::Get();

  // Create one more desk other than the default initial desk, so the desks bar
  // shows up in overview mode.
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());

  // Enter overview mode, and click on `desk_1`'s mini_view, and expect that
  // overview mode exits since this is the already active desk.
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  const auto* mini_view = desks_bar_view->mini_views().front().get();
  LeftClickOn(mini_view);
  EXPECT_FALSE(overview_controller->InOverviewSession());
  EXPECT_TRUE(desk_1->is_active());
  EXPECT_EQ(desk_1, controller->active_desk());
}

TEST_P(DesksTest, MinimizedWindow) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  const Desk* desk_2 = controller->GetDeskAtIndex(1);

  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(win0.get());
  EXPECT_EQ(win0.get(), window_util::GetActiveWindow());

  auto* window_state = WindowState::Get(win0.get());
  window_state->Minimize();
  EXPECT_TRUE(window_state->IsMinimized());

  // Minimized windows on the active desk show up in the MRU list...
  EXPECT_EQ(1u, Shell::Get()
                    ->mru_window_tracker()
                    ->BuildMruWindowList(kActiveDesk)
                    .size());

  ActivateDesk(desk_2);

  // ... But they don't once their desk is inactive.
  EXPECT_TRUE(Shell::Get()
                  ->mru_window_tracker()
                  ->BuildMruWindowList(kActiveDesk)
                  .empty());

  // Switching back to their desk should neither activate them nor unminimize
  // them.
  ActivateDesk(desk_1);
  EXPECT_TRUE(window_state->IsMinimized());
  EXPECT_NE(win0.get(), window_util::GetActiveWindow());
}

// Tests that the app list stays open when switching desks. Regression test for
// http://crbug.com/1138982.
TEST_P(DesksTest, AppListStaysOpenInClamshell) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());

  // Create one app window on each desk.
  auto win0 = CreateAppWindow(gfx::Rect(400, 400));
  ActivateDesk(controller->GetDeskAtIndex(1));
  auto win1 = CreateAppWindow(gfx::Rect(400, 400));

  // Open the app list.
  auto* app_list_controller = Shell::Get()->app_list_controller();
  app_list_controller->ShowAppList(AppListShowSource::kSearchKey);
  ASSERT_TRUE(app_list_controller->IsVisible());

  // Switch back to desk 1. Test that the app list is still open.
  ActivateDesk(controller->GetDeskAtIndex(0));
  EXPECT_TRUE(app_list_controller->IsVisible());
}

// Tests that the app list correctly loses focus in tablet mode when switching
// desks. Regression test for https://crbug.com/1206030.
TEST_P(DesksTest, AppListActivationInTablet) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());

  // Create one app window on desk 1.
  auto window = CreateAppWindow(gfx::Rect(400, 400));
  ASSERT_EQ(window.get(), window_util::GetActiveWindow());

  // Enter tablet mode and switch to desk 2. Verify the app list has activation
  // as there are no app windows.
  TabletModeControllerTestApi().EnterTabletMode();
  ActivateDesk(controller->GetDeskAtIndex(1));
  auto* app_list_controller = Shell::Get()->app_list_controller();
  ASSERT_EQ(app_list_controller->GetWindow(), window_util::GetActiveWindow());

  // Switch back to desk 1. `window` should have activation now.
  ActivateDesk(controller->GetDeskAtIndex(0));
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());
}

TEST_P(DesksTest, DragWindowToDesk) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  const Desk* desk_2 = controller->GetDeskAtIndex(1);

  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 200, 150));
  wm::ActivateWindow(win1.get());
  EXPECT_EQ(win1.get(), window_util::GetActiveWindow());

  ui::Shadow* shadow = ::wm::ShadowController::GetShadowForWindow(win1.get());
  ASSERT_TRUE(shadow);
  ASSERT_TRUE(shadow->layer());
  EXPECT_TRUE(shadow->layer()->GetTargetVisibility());

  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  EXPECT_EQ(2u, overview_grid->GetNumWindows());

  // While in overview mode, the window's shadow is hidden.
  EXPECT_FALSE(shadow->layer()->GetTargetVisibility());

  auto* overview_session = overview_controller->overview_session();
  auto* overview_item = overview_session->GetOverviewItemForWindow(win1.get());
  ASSERT_TRUE(overview_item);
  const gfx::RectF target_bounds_before_drag = overview_item->target_bounds();

  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_EQ(2u, desks_bar_view->mini_views().size());
  auto* desk_1_mini_view = desks_bar_view->mini_views()[0].get();
  EXPECT_EQ(desk_1, desk_1_mini_view->desk());
  // Drag it and drop it on its same desk's mini_view. Nothing happens, it
  // should be returned back to its original target bounds.
  auto* event_generator = GetEventGenerator();
  DragItemToPoint(overview_item,
                  desk_1_mini_view->GetBoundsInScreen().CenterPoint(),
                  event_generator, GetParam().use_touch_gestures);
  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_EQ(2u, overview_grid->GetNumWindows());
  EXPECT_EQ(target_bounds_before_drag, overview_item->target_bounds());
  EXPECT_TRUE(DoesActiveDeskContainWindow(win1.get()));

  // Now drag it to desk_2's mini_view. The overview grid should now have only
  // `win2`, and `win1` should move to desk_2.
  auto* desk_2_mini_view = desks_bar_view->mini_views()[1].get();
  EXPECT_EQ(desk_2, desk_2_mini_view->desk());
  DragItemToPoint(overview_item,
                  desk_2_mini_view->GetBoundsInScreen().CenterPoint(),
                  event_generator, GetParam().use_touch_gestures);
  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_EQ(1u, overview_grid->GetNumWindows());
  EXPECT_FALSE(DoesActiveDeskContainWindow(win1.get()));
  EXPECT_TRUE(base::Contains(desk_2->windows(), win1.get()));
  EXPECT_FALSE(overview_grid->drop_target());

  // After dragging an item outside of overview to another desk, the focus
  // should not be given to another window in overview, and should remain on the
  // OverviewModeFocusedWidget.
  EXPECT_EQ(overview_session->GetOverviewFocusWindow(),
            window_util::GetActiveWindow());

  // It is possible to select the remaining window which will activate it and
  // exit overview.
  overview_item = overview_session->GetOverviewItemForWindow(win2.get());
  ASSERT_TRUE(overview_item);
  const auto window_center =
      gfx::ToFlooredPoint(overview_item->target_bounds().CenterPoint());
  if (GetParam().use_touch_gestures) {
    event_generator->GestureTapAt(window_center);
  } else {
    event_generator->MoveMouseTo(window_center);
    event_generator->ClickLeftButton();
  }
  EXPECT_FALSE(overview_controller->InOverviewSession());
  EXPECT_EQ(win2.get(), window_util::GetActiveWindow());

  // After the window is dropped onto another desk, its shadow should be
  // restored properly.
  EXPECT_TRUE(shadow->layer()->GetTargetVisibility());
}

// Tests that theme change during drag to close does not trigger any crashes.
// Regression test for b/270171802.
TEST_P(DesksTest, DragWindowToCloseWithThemeChange) {
  // Create two windows.
  auto win1 = CreateAppWindow();
  auto win2 = CreateAppWindow();

  // Enter overview.
  EnterOverview();
  auto* overview_item = Shell::Get()
                            ->overview_controller()
                            ->overview_session()
                            ->GetOverviewItemForWindow(win1.get());
  ASSERT_TRUE(overview_item);

  // Drag `win1` to close and simulate multiple theme changes at the same time.
  // There should not be any crashes.
  auto* event_generator = GetEventGenerator();
  event_generator->set_current_screen_location(
      gfx::ToRoundedPoint(overview_item->target_bounds().CenterPoint()));
  event_generator->PressTouch();
  overview_item->item_widget()->ThemeChanged();
  event_generator->MoveTouchBy(0, -50);
  overview_item->item_widget()->ThemeChanged();
  event_generator->MoveTouchBy(0, -200);
  overview_item->item_widget()->ThemeChanged();
  event_generator->ReleaseTouch();
  overview_item->item_widget()->ThemeChanged();
}

TEST_P(DesksTest, DragMinimizedWindowToDesk) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  const Desk* desk_2 = controller->GetDeskAtIndex(1);

  auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(window.get());
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  // Minimize the window before entering Overview Mode.
  auto* window_state = WindowState::Get(window.get());
  window_state->Minimize();
  ASSERT_TRUE(window_state->IsMinimized());

  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  auto* overview_session = overview_controller->overview_session();
  auto* overview_item =
      overview_session->GetOverviewItemForWindow(window.get());
  ASSERT_TRUE(overview_item);
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_EQ(2u, desks_bar_view->mini_views().size());

  // Drag the window to desk_2's mini_view and activate desk_2. Expect that the
  // window will be in an unminimized state and all its visibility and layer
  // opacity attributes are correct.
  auto* desk_2_mini_view = desks_bar_view->mini_views()[1].get();
  EXPECT_EQ(desk_2, desk_2_mini_view->desk());
  DragItemToPoint(overview_item,
                  desk_2_mini_view->GetBoundsInScreen().CenterPoint(),
                  GetEventGenerator(), GetParam().use_touch_gestures);
  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_TRUE(overview_grid->empty());
  EXPECT_TRUE(base::Contains(desk_2->windows(), window.get()));
  EXPECT_FALSE(overview_grid->drop_target());
  DeskSwitchAnimationWaiter waiter;
  LeftClickOn(desk_2_mini_view);
  waiter.Wait();
  EXPECT_FALSE(overview_controller->InOverviewSession());
  EXPECT_TRUE(desk_2->is_active());

  EXPECT_FALSE(window_state->IsMinimized());
  EXPECT_TRUE(window->IsVisible());
  EXPECT_TRUE(window->layer()->GetTargetVisibility());
  EXPECT_EQ(1.f, window->layer()->GetTargetOpacity());
}

TEST_P(DesksTest, DragAllOverviewWindowsToOtherDesksNotEndOverview) {
  NewDesk();
  ASSERT_EQ(2u, DesksController::Get()->desks().size());
  auto win = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto* overview_controller = OverviewController::Get();
  ASSERT_TRUE(EnterOverview());
  auto* overview_session = overview_controller->overview_session();
  DragItemToPoint(overview_session->GetOverviewItemForWindow(win.get()),
                  GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())
                      ->desks_bar_view()
                      ->mini_views()[1]
                      ->GetBoundsInScreen()
                      .CenterPoint(),
                  GetEventGenerator(), GetParam().use_touch_gestures);
  EXPECT_FALSE(DoesActiveDeskContainWindow(win.get()));
  ASSERT_TRUE(overview_controller->InOverviewSession());
  EXPECT_TRUE(overview_session->IsEmpty());
}

TEST_P(DesksTest, DragWindowToNonMiniViewPoints) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());

  auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(window.get());
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  EXPECT_EQ(1u, overview_grid->GetNumWindows());

  auto* overview_session = overview_controller->overview_session();
  auto* overview_item =
      overview_session->GetOverviewItemForWindow(window.get());
  ASSERT_TRUE(overview_item);
  const gfx::RectF target_bounds_before_drag = overview_item->target_bounds();

  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);

  // Drag it and drop it on the center of the bottom of the display. Also,
  // nothing should happen.
  DragItemToPoint(overview_item,
                  window->GetRootWindow()->GetBoundsInScreen().bottom_center(),
                  GetEventGenerator(), GetParam().use_touch_gestures);
  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_EQ(1u, overview_grid->GetNumWindows());
  EXPECT_EQ(target_bounds_before_drag, overview_item->target_bounds());
  EXPECT_TRUE(DoesActiveDeskContainWindow(window.get()));
}

// Tests that dragging and dropping window to new desk while desks bar view is
// at zero state.
TEST_P(DesksTest, DragWindowAtZeroState) {
  auto* controller = DesksController::Get();
  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));

  ASSERT_EQ(1u, controller->desks().size());
  auto* overview_controller = OverviewController::Get();
  EnterOverview();

  ASSERT_TRUE(overview_controller->InOverviewSession());
  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);

  // Since we only have one desk, there should be 0 desk mini view and the zero
  // state default desk button and new desk button should be visible.
  ASSERT_EQ(0u, desks_bar_view->mini_views().size());
  auto* default_desk_button = desks_bar_view->default_desk_button();
  auto* new_desk_button = desks_bar_view->new_desk_button();
  EXPECT_TRUE(default_desk_button->GetVisible());
  VerifyZeroStateNewDeskButtonVisibility(desks_bar_view, true);
  VerifyExpandedStateNewDeskButtonVisibility(desks_bar_view, false);

  auto* overview_item1 = overview_grid->GetOverviewItemContaining(win1.get());
  auto* event_generator = GetEventGenerator();

  // Start dragging `overview_item1` without dropping it. Make sure the square
  // length between `overview_item1` and `zero_state_new_desk_button` is longer
  // than `kExpandDesksBarThreshold`. Verify that the desks bar is still at zero
  // state in this use case.
  DragItemToPoint(
      overview_item1,
      gfx::ToRoundedPoint(overview_item1->target_bounds().CenterPoint() +
                          gfx::Vector2d(100, -100)),
      event_generator,
      /*by_touch_gestures=*/false, /*drop=*/false);
  // The desk bar will expand immediately at the beginning of the drag.
  EXPECT_FALSE(default_desk_button->GetVisible());
  VerifyZeroStateNewDeskButtonVisibility(desks_bar_view, false);
  VerifyExpandedStateNewDeskButtonVisibility(desks_bar_view, true);

  const gfx::Point new_desk_button_center_point =
      new_desk_button->GetBoundsInScreen().CenterPoint();
  // The new desk button will be scaled up as a drop target for `overview_item1`
  // when `overview_item1` it's being hovered on top it over 500 milliseconds.
  // Drag `overview_item1` to hover on the new desk button, and wait for 200
  // milliseconds, verify that new desk button is still at the expanded state
  // and the new desk label is not shown.
  const gfx::Point new_desk_button_bottom_left =
      new_desk_button->GetBoundsInScreen().bottom_left();
  DragItemToPoint(overview_item1,
                  new_desk_button_bottom_left + gfx::Vector2d(10, -10),
                  event_generator, /*by_touch_gestures=*/false,
                  /*drop=*/false);
  WaitForMilliseconds(200);
  EXPECT_EQ(DeskIconButton::State::kExpanded, new_desk_button->state());
  EXPECT_FALSE(IsLazyInitViewVisible(desks_bar_view->new_desk_button_label()));
  // Now fire the timer directly to skip the wait time. Verify that the new desk
  // button is scaled up and at the active state and the new desk label is shown
  // now.
  overview_controller->overview_session()
      ->window_drag_controller()
      ->new_desk_button_scale_up_timer_for_test()
      ->FireNow();
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_EQ(DeskIconButton::State::kActive, new_desk_button->state());
  EXPECT_TRUE(IsLazyInitViewVisible(desks_bar_view->new_desk_button_label()));

  // Keep dragging `overview_item1` to the center of the new desk button to make
  // it a drop target.
  DragItemToPoint(overview_item1,
                  new_desk_button_center_point + gfx::Vector2d(10, 10),
                  event_generator, /*by_touch_gestures=*/false,
                  /*drop=*/false);

  // Now drop |overview_item1|, a new desk which contains |win1| will be
  // created.
  event_generator->ReleaseLeftButton();
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_EQ(2u, desks_bar_view->mini_views().size());
  EXPECT_EQ(2u, controller->desks().size());
  EXPECT_TRUE(
      base::Contains(controller->GetDeskAtIndex(1)->windows(), win1.get()));
  // The active desk should still be the first desk, even though a new desk
  // is created.
  EXPECT_EQ(DesksController::Get()->active_desk(),
            controller->GetDeskAtIndex(0));
  // |overview_grid| should have size equals to 0 now, since |overview_item1|
  // havs been moved to a new desk.
  EXPECT_EQ(0u, overview_grid->GetNumWindows());
}

// Tests that dragging a window at zero state but without dropping it on the new
// desk button, the window being dragged will fall back to the existing desk and
// no new desk should be created.
TEST_P(DesksTest, DragWindowAtZeroStateWithoutDroppingItOnTheNewDesk) {
  auto* controller = DesksController::Get();
  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));

  ASSERT_EQ(1u, controller->desks().size());
  auto* overview_controller = OverviewController::Get();
  EnterOverview();

  ASSERT_TRUE(overview_controller->InOverviewSession());
  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);

  // Make sure the desks bar is at zero state in the beginning.
  auto* default_desk_button = desks_bar_view->default_desk_button();
  auto* new_desk_button = desks_bar_view->new_desk_button();
  EXPECT_TRUE(default_desk_button->GetVisible());
  VerifyZeroStateNewDeskButtonVisibility(desks_bar_view, true);
  VerifyExpandedStateNewDeskButtonVisibility(desks_bar_view, false);

  auto* overview_item1 = overview_grid->GetOverviewItemContaining(win1.get());
  auto* event_generator = GetEventGenerator();

  // Start dragging `overview_item1`, verify desks bar expands immediately and
  // the new desk button is transformed to the expanded state;
  DragItemToPoint(
      overview_item1,
      gfx::ToRoundedPoint(overview_item1->target_bounds().CenterPoint() +
                          gfx::Vector2d(100, -100)),
      event_generator,
      /*by_touch_gestures=*/false, /*drop=*/false);
  EXPECT_FALSE(desks_bar_view->IsZeroState());
  EXPECT_EQ(DeskIconButton::State::kExpanded, new_desk_button->state());
  EXPECT_FALSE(IsLazyInitViewVisible(desks_bar_view->new_desk_button_label()));

  // Keep dragging `overview_item1` to hover on the new desk button, immediately
  // fire the time to skip to wait time. Verify that new desk button is
  // transformed to the active state and the new desk label is shown now.
  const gfx::Point new_desk_button_center_point =
      new_desk_button->GetBoundsInScreen().CenterPoint();
  DragItemToPoint(overview_item1,
                  gfx::Point(new_desk_button_center_point.x() + 10,
                             new_desk_button_center_point.y() + 10),
                  event_generator, /*by_touch_gestures=*/false,
                  /*drop=*/false);
  overview_controller->overview_session()
      ->window_drag_controller()
      ->new_desk_button_scale_up_timer_for_test()
      ->FireNow();
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_EQ(DeskIconButton::State::kActive, new_desk_button->state());
  EXPECT_TRUE(IsLazyInitViewVisible(desks_bar_view->new_desk_button_label()));

  // Now keep dragging `overview_item1` and make it not able to be dropped on
  // the new desk, then drop it. Check that `overview_item1` is dropped back to
  // the existing desk, there's no new desk created, and desks bar is
  // transformed back to the zero state.
  const gfx::Point expanded_new_desk_button_center_point =
      new_desk_button->GetBoundsInScreen().CenterPoint();
  DragItemToPoint(overview_item1,
                  gfx::Point(expanded_new_desk_button_center_point.x() + 200,
                             expanded_new_desk_button_center_point.y() + 200),
                  event_generator, /*by_touch_gestures=*/false, /*drop=*/true);
  RunScheduledLayoutForAllOverviewDeskBars();
  // The desk bar never goes back to the zero state from the expanded state even
  // these's only one desk. Verify that the new desk label is invisible now.
  EXPECT_FALSE(desks_bar_view->IsZeroState());
  EXPECT_FALSE(IsLazyInitViewVisible(desks_bar_view->new_desk_button_label()));
  EXPECT_EQ(1u, controller->desks().size());
  EXPECT_TRUE(
      base::Contains(controller->GetDeskAtIndex(0)->windows(), win1.get()));
}

// Tests that dragging and dropping window to new desk while desks bar view is
// at expanded state.
TEST_P(DesksTest, DragWindowAtExpandedState) {
  auto* controller = DesksController::Get();
  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  NewDesk();

  ASSERT_EQ(2u, controller->desks().size());
  auto* overview_controller = OverviewController::Get();
  EnterOverview();

  ASSERT_TRUE(overview_controller->InOverviewSession());
  const auto* desks_bar_view =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);

  ASSERT_EQ(2u, desks_bar_view->mini_views().size());
  auto* new_desk_button = desks_bar_view->new_desk_button();
  VerifyExpandedStateNewDeskButtonVisibility(desks_bar_view, true);

  auto* event_generator = GetEventGenerator();
  // Drag `overview_item1` on that new desk button, and fire the timer
  // immediately and then drops it. A new desk which contains `win1` will be
  // created.
  DragItemToPoint(
      overview_controller->overview_session()->GetOverviewItemForWindow(
          win1.get()),
      new_desk_button->GetBoundsInScreen().CenterPoint(), GetEventGenerator(),
      /*by_touch_gestures=*/false,
      /*drop=*/false);
  overview_controller->overview_session()
      ->window_drag_controller()
      ->new_desk_button_scale_up_timer_for_test()
      ->FireNow();
  event_generator->ReleaseLeftButton();

  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_EQ(3u, desks_bar_view->mini_views().size());
  EXPECT_EQ(3u, controller->desks().size());
  EXPECT_TRUE(
      base::Contains(controller->GetDeskAtIndex(2)->windows(), win1.get()));
}

// Tests that dragging and dropping a window on the new desk button does not
// create a new desk if we are already at the maximum number of desks.
TEST_P(DesksTest, DragWindowAtMaximumDesksState) {
  // Set a display mode that forces vertical layout of split view drag
  // indicators. This is so that we are able to drop an overview item on the
  // "new desk" button even if it's right up to the edge.
  UpdateDisplay("800x801");

  auto* controller = DesksController::Get();
  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  while (controller->desks().size() < desks_util::GetMaxNumberOfDesks()) {
    NewDesk();
  }

  ASSERT_EQ(desks_util::GetMaxNumberOfDesks(), controller->desks().size());
  auto* overview_controller = OverviewController::Get();
  EnterOverview();

  ASSERT_TRUE(overview_controller->InOverviewSession());
  const auto* desks_bar_view =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);

  auto* event_generator = GetEventGenerator();
  for (int i = 0; i != 3; ++i) {
    TryScrollOverviewDeskBar(DeskBarScrollDirection::kRight);
  }

  // Drag and drop the overview to the new desk button. Since we already have
  // maximum number of desks, this won't create a new desk, and the dragged
  // window will fall back to the desk where it's from. Dragging here is not
  // done using `DragItemToPoint`. This is because once a drag has been
  // initiated, the split view drag indicators will show and shift the position
  // of the desks bar, which includes the new desk button. In other words, we
  // have to initiate the drag before we can know where to drop.
  const gfx::Point overview_item_center =
      gfx::ToRoundedPoint(overview_controller->overview_session()
                              ->GetOverviewItemForWindow(win1.get())
                              ->target_bounds()
                              .CenterPoint());

  // Pick up the item and move it a little bit to initiate a drag.
  event_generator->set_current_screen_location(overview_item_center);
  event_generator->PressLeftButton();
  event_generator->MoveMouseBy(20, 0);

  // Move the item to the new desk button and drop it.
  event_generator->MoveMouseTo(
      desks_bar_view->new_desk_button()->GetBoundsInScreen().CenterPoint());
  event_generator->ReleaseLeftButton();

  // We should still be in overview mode. We should still have the max number of
  // desks. And `win1` should still belong to the first desk.
  ASSERT_TRUE(overview_controller->InOverviewSession());
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks(),
            desks_bar_view->mini_views().size());
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks(), controller->desks().size());
  EXPECT_TRUE(
      base::Contains(controller->GetDeskAtIndex(0)->windows(), win1.get()));
}

TEST_P(DesksTest, MruWindowTracker) {
  // Create two desks with two windows in each.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);
  EXPECT_EQ(desk_2, controller->active_desk());
  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 300, 200));
  auto win3 = CreateAppWindow(gfx::Rect(10, 30, 400, 200));

  // Build active desk's MRU window list.
  auto* mru_window_tracker = Shell::Get()->mru_window_tracker();
  auto window_list = mru_window_tracker->BuildWindowForCycleList(kActiveDesk);
  ASSERT_EQ(2u, window_list.size());
  EXPECT_EQ(win3.get(), window_list[0]);
  EXPECT_EQ(win2.get(), window_list[1]);

  // Build the global MRU window list.
  window_list = mru_window_tracker->BuildWindowForCycleList(kAllDesks);
  ASSERT_EQ(4u, window_list.size());
  EXPECT_EQ(win3.get(), window_list[0]);
  EXPECT_EQ(win2.get(), window_list[1]);
  EXPECT_EQ(win1.get(), window_list[2]);
  EXPECT_EQ(win0.get(), window_list[3]);

  // Switch back to desk_1 and test both MRU list types.
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  ActivateDesk(desk_1);
  window_list = mru_window_tracker->BuildWindowForCycleList(kActiveDesk);
  ASSERT_EQ(2u, window_list.size());
  EXPECT_EQ(win1.get(), window_list[0]);
  EXPECT_EQ(win0.get(), window_list[1]);
  // TODO(afakhry): Check with UX if we should favor active desk's windows in
  // the global MRU list (i.e. put them first in the list).
  window_list = mru_window_tracker->BuildWindowForCycleList(kAllDesks);
  ASSERT_EQ(4u, window_list.size());
  EXPECT_EQ(win1.get(), window_list[0]);
  EXPECT_EQ(win3.get(), window_list[1]);
  EXPECT_EQ(win2.get(), window_list[2]);
  EXPECT_EQ(win0.get(), window_list[3]);
}

TEST_P(DesksTest, NextActivatable) {
  // Create two desks with two windows in each.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);
  EXPECT_EQ(desk_2, controller->active_desk());
  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 300, 200));
  auto win3 = CreateAppWindow(gfx::Rect(10, 30, 400, 200));
  EXPECT_EQ(win3.get(), window_util::GetActiveWindow());

  // When deactivating a window, the next activatable window should be on the
  // same desk.
  wm::DeactivateWindow(win3.get());
  EXPECT_EQ(win2.get(), window_util::GetActiveWindow());
  wm::DeactivateWindow(win2.get());
  EXPECT_EQ(win3.get(), window_util::GetActiveWindow());

  // Similarly for desk_1.
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  ActivateDesk(desk_1);
  EXPECT_EQ(win1.get(), window_util::GetActiveWindow());
  win1.reset();
  EXPECT_EQ(win0.get(), window_util::GetActiveWindow());
  win0.reset();
  EXPECT_EQ(nullptr, window_util::GetActiveWindow());
}

TEST_P(DesksTest, NoMiniViewsUpdateOnOverviewEnter) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  auto* desk_1 = controller->GetDeskAtIndex(0);
  auto* desk_2 = controller->GetDeskAtIndex(1);

  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  wm::ActivateWindow(win1.get());
  EXPECT_EQ(win1.get(), window_util::GetActiveWindow());

  TestDeskObserver desk_1_observer;
  TestDeskObserver desk_2_observer;
  desk_1->AddObserver(&desk_1_observer);
  desk_2->AddObserver(&desk_2_observer);
  EXPECT_EQ(0, desk_1_observer.notify_counts());
  EXPECT_EQ(0, desk_2_observer.notify_counts());

  // The widgets created by overview mode, whose windows are added to the active
  // desk's container, should never result in mini_views updates since they're
  // not mirrored there at all.
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  EXPECT_EQ(0, desk_1_observer.notify_counts());
  EXPECT_EQ(0, desk_2_observer.notify_counts());

  desk_1->RemoveObserver(&desk_1_observer);
  desk_2->RemoveObserver(&desk_2_observer);
}

// Tests that the consecutive daily visits metric is properly recorded.
TEST_P(DesksTest, ConsecutiveDailyVisitsMetric) {
  constexpr char kConsecutiveDailyVisitsHistogram[] =
      "Ash.Desks.ConsecutiveDailyVisits";
  auto* desks_controller = DesksController::Get();
  base::HistogramTester histogram_tester;
  base::SimpleTestClock test_clock;

  // Set the time to 00:00:00 local time the next day, override the current
  // desk's clock and reset its visited metrics.
  test_clock.SetNow(base::Time::Now().LocalMidnight());
  test_clock.Advance(base::Hours(1));
  auto* active_desk = desks_controller->active_desk();
  desks_restore_util::OverrideClockForTesting(&test_clock);
  DesksTestApi::ResetDeskVisitedMetrics(const_cast<Desk*>(active_desk));
  EXPECT_EQ(
      0u,
      histogram_tester.GetAllSamples(kConsecutiveDailyVisitsHistogram).size());

  // Create a new desk and don't visit it.
  active_desk = desks_controller->active_desk();
  NewDesk();
  ASSERT_EQ(active_desk, desks_controller->active_desk());

  // Fast forward by two days then remove the active desk. This should record an
  // entry for two days since we stayed on the active desk the whole time.
  // Additionally, there shouldn't be a record for the desk we switch to since
  // we haven't visited it yet.
  test_clock.Advance(base::Days(2));
  RemoveDesk(active_desk);
  histogram_tester.ExpectBucketCount(kConsecutiveDailyVisitsHistogram, 3, 1);
  EXPECT_EQ(
      1u,
      histogram_tester.GetAllSamples(kConsecutiveDailyVisitsHistogram).size());

  // Create a new desk and remove the active desk. This should record an entry
  // for one day since we visited the active desk before removing it.
  active_desk = desks_controller->active_desk();
  NewDesk();
  RemoveDesk(active_desk);
  histogram_tester.ExpectBucketCount(kConsecutiveDailyVisitsHistogram, 1, 1);
  EXPECT_EQ(
      2u,
      histogram_tester.GetAllSamples(kConsecutiveDailyVisitsHistogram).size());

  // Create a new desk and switch to it. Then fast forward two days and revisit
  // the previous desk. Since it's been more than one day since the last visit,
  // a one day entry should be recorded for the previous desk.
  NewDesk();
  ActivateDesk(desks_controller->GetNextDesk());
  test_clock.Advance(base::Days(2));
  ActivateDesk(desks_controller->GetPreviousDesk());
  histogram_tester.ExpectBucketCount(kConsecutiveDailyVisitsHistogram, 1, 2);
  EXPECT_EQ(
      2u,
      histogram_tester.GetAllSamples(kConsecutiveDailyVisitsHistogram).size());

  // Go back in time to simulate a user switching timezones and then switch to
  // the next desk. Since the current time is before the |last_day_visited_|
  // field of the next desk, its visited fields should be reset.
  test_clock.Advance(base::Days(-2));
  ActivateDesk(desks_controller->GetNextDesk());
  active_desk = desks_controller->active_desk();
  const int current_date = desks_restore_util::GetDaysFromLocalEpoch();
  EXPECT_EQ(current_date, active_desk->first_day_visited());
  EXPECT_EQ(current_date, active_desk->last_day_visited());
  desks_restore_util::OverrideClockForTesting(nullptr);
}

// Tests that the new desk button's state and color are as expected.
TEST_P(DesksTest, NewDeskButtonStateAndColor) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());

  EnterOverview();
  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  const auto* new_desk_button = desks_bar_view->new_desk_button();

  // Tests that with one or two desks, the new desk button has an enabled state
  // and color.
  auto* color_provider = new_desk_button->GetColorProvider();
  SkColor background_color =
      color_provider->GetColor(cros_tokens::kCrosSysPrimary);

  const SkColor disabled_background_color =
      ColorUtil::GetDisabledColor(background_color);
  EXPECT_TRUE(new_desk_button->GetEnabled());
  EXPECT_EQ(background_color, GetNewDeskButtonBackgroundColor(desks_bar_view));

  LeftClickOn(new_desk_button);
  EXPECT_TRUE(new_desk_button->GetEnabled());
  EXPECT_EQ(background_color, GetNewDeskButtonBackgroundColor(desks_bar_view));

  // Tests that adding desks until we reach the desks limit should change the
  // state and color of the new desk button.
  size_t prev_size = controller->desks().size();
  while (controller->CanCreateDesks()) {
    LeftClickOn(new_desk_button);
    EXPECT_EQ(prev_size + 1, controller->desks().size());
    prev_size = controller->desks().size();
    RunScheduledLayoutForAllOverviewDeskBars();
    TryScrollOverviewDeskBar(DeskBarScrollDirection::kRight);
    RunScheduledLayoutForAllOverviewDeskBars();
  }
  EXPECT_FALSE(new_desk_button->GetEnabled());
  EXPECT_EQ(disabled_background_color,
            GetNewDeskButtonBackgroundColor(desks_bar_view));
}

// Tests that the fullscreen state in shell is updated when switching between
// desks that have active windows in different fullscreen states.
TEST_P(DesksTest, FullscreenStateUpdatedAcrossDesks) {
  FullScreenStateObserver full_screen_state_observer;
  auto* controller = DesksController::Get();
  WMEvent event_toggle_fullscreen(WM_EVENT_TOGGLE_FULLSCREEN);

  // Create one new desks.
  NewDesk();
  EXPECT_EQ(2u, controller->desks().size());

  // Create one window in each desk.
  std::vector<std::unique_ptr<aura::Window>> windows;
  for (int i = 0; i < 2; i++) {
    windows.push_back(CreateAppWindow());
    controller->SendToDeskAtIndex(windows[i].get(), i);
    EXPECT_EQ(i, windows[i]->GetProperty(aura::client::kWindowWorkspaceKey));
  }

  WindowState* win0_state = WindowState::Get(windows[0].get());
  WindowState* win1_state = WindowState::Get(windows[1].get());

  EXPECT_FALSE(full_screen_state_observer.is_fullscreen());

  // Set window on desk 0 to fullscreen.
  win0_state->OnWMEvent(&event_toggle_fullscreen);
  EXPECT_EQ(windows[0].get(), window_util::GetActiveWindow());
  EXPECT_TRUE(win0_state->IsFullscreen());
  EXPECT_TRUE(full_screen_state_observer.is_fullscreen());

  // Switch to desk 1 and expect the fullscreen state to change.
  ActivateDesk(controller->GetDeskAtIndex(1));

  EXPECT_EQ(windows[1].get(), window_util::GetActiveWindow());
  EXPECT_FALSE(win1_state->IsFullscreen());
  EXPECT_FALSE(full_screen_state_observer.is_fullscreen());

  // Cycle back to desk 0 and expect the fullscreen state to change back.
  ActivateDesk(controller->GetDeskAtIndex(0));

  EXPECT_EQ(windows[0].get(), window_util::GetActiveWindow());
  EXPECT_TRUE(win0_state->IsFullscreen());
  EXPECT_TRUE(full_screen_state_observer.is_fullscreen());
}

// Tests the Ash.Desks.AnimationLatency.DeskActivation histogram.
TEST_P(DesksTest, AnimationLatencyDeskActivation) {
  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(2u, controller->desks().size());

  base::HistogramTester histogram_tester;
  ActivateDesk(controller->GetDeskAtIndex(1));
  histogram_tester.ExpectTotalCount("Ash.Desks.AnimationLatency.DeskActivation",
                                    1);
}

// Tests the Ash.Desks.AnimationLatency.DeskRemoval histogram.
TEST_P(DesksTest, AnimationLatencyDeskRemoval) {
  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(2u, controller->desks().size());

  base::HistogramTester histogram_tester;
  RemoveDesk(controller->GetDeskAtIndex(0));
  histogram_tester.ExpectTotalCount("Ash.Desks.AnimationLatency.DeskRemoval",
                                    1);
}

// Tests that the MRU window in a desk is focused when that desk is activated.
TEST_P(DesksTest, MruFocusedOnDeskSwitchDualDisplay) {
  UpdateDisplay("700x600,400x500");
  auto* controller = DesksController::Get();
  auto roots = Shell::GetAllRootWindows();

  // Create two desks, each with 2 windows
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  auto win2 = CreateAppWindow(gfx::Rect(750, 50, 200, 200));

  // Ensure there is one window on each display.
  ASSERT_EQ(win1->GetRootWindow(), roots[0]);
  ASSERT_EQ(win2->GetRootWindow(), roots[1]);

  // Focus window 2
  win2->Focus();

  // Create and switch to the second desk.
  NewDesk();
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);
  auto win3 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  auto win4 = CreateAppWindow(gfx::Rect(750, 50, 200, 200));
  ASSERT_EQ(win3->GetRootWindow(), roots[0]);
  ASSERT_EQ(win4->GetRootWindow(), roots[1]);

  // Focus window 3
  win3->Focus();

  // Switch back to desk 1 and ensure window 2 regains focus.
  ActivateDesk(desk_1);
  ASSERT_TRUE(win2->HasFocus());
  ASSERT_FALSE(win1->HasFocus());
  ASSERT_FALSE(win3->HasFocus());
  ASSERT_FALSE(win4->HasFocus());

  // Switch back to desk 2 and ensure window 3 regains focus.
  ActivateDesk(desk_2);
  ASSERT_TRUE(win3->HasFocus());
  ASSERT_FALSE(win1->HasFocus());
  ASSERT_FALSE(win2->HasFocus());
  ASSERT_FALSE(win4->HasFocus());
}

// Tests that we can set a lacros profile ID on a desk and that observers get
// notified.
TEST_P(DesksTest, LacrosProfileId) {
  auto* controller = DesksController::Get();
  Desk* desk = controller->GetDeskAtIndex(0);

  TestDeskObserver desk_observer;
  desk->AddObserver(&desk_observer);

  desk->SetLacrosProfileId(1001);
  EXPECT_THAT(desk_observer.lacros_profile_id_updates(),
              testing::ElementsAre(1001));

  // Setting the same ID does not result in observer notifications.
  desk->SetLacrosProfileId(1001);
  EXPECT_THAT(desk_observer.lacros_profile_id_updates(),
              testing::ElementsAre(1001));

  desk->SetLacrosProfileId(2001);
  EXPECT_THAT(desk_observer.lacros_profile_id_updates(),
              testing::ElementsAre(1001, 2001));

  desk->RemoveObserver(&desk_observer);
}

// Tests that a display can be removed during a desk switch.
TEST_P(DesksTest, RemoveDisplayWhileSwitchingDesks) {
  auto* controller = DesksController::Get();

  // Set up two desks and two displays. We're then going to switch to the second
  // desk and during the switch, remove one of the displays.
  UpdateDisplay("800x600,800x600");
  NewDesk();

  ui::ScopedAnimationDurationScaleMode animation_scale(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  DeskSwitchAnimationWaiter desk_switch_waiter;

  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  controller->ActivateDesk(desk_2, DesksSwitchSource::kMiniViewButton);

  // Updating to one display. This will cause the root window for the second
  // display to be destroyed.
  UpdateDisplay("800x600");

  desk_switch_waiter.Wait();
  EXPECT_EQ(desk_2, controller->active_desk());
}

// Tests that creating a new desk while overview is exiting doesn't cause a
// crash. Regression test for http://b/365546169
TEST_P(DesksTest, AddDeskWhileExitingOverview) {
  UpdateDisplay("800x600");

  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  ui::ScopedAnimationDurationScaleMode animation_scale(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  // Exit overview (with an animation) and immediately create a second desk.
  ExitOverview();
  NewDesk();
}

class DesksWithMultiDisplayOverview : public AshTestBase {
 public:
  DesksWithMultiDisplayOverview() = default;
  ~DesksWithMultiDisplayOverview() override = default;

  // AshTestBase:
  void SetUp() override {
    AshTestBase::SetUp();

    // Start the test with two displays and two desks.
    UpdateDisplay("700x600,400x500");
    NewDesk();
  }
};

TEST_F(DesksWithMultiDisplayOverview, DropOnSameDeskInOtherDisplay) {
  auto roots = Shell::GetAllRootWindows();
  ASSERT_EQ(2u, roots.size());

  auto win = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  auto* overview_session = overview_controller->overview_session();
  auto* overview_item = overview_session->GetOverviewItemForWindow(win.get());
  ASSERT_TRUE(overview_item);

  // The window should exist on the grid of the first display.
  auto* grid1 = GetOverviewGridForRoot(roots[0]);
  auto* grid2 = GetOverviewGridForRoot(roots[1]);
  EXPECT_EQ(1u, grid1->GetNumWindows());
  EXPECT_EQ(grid1, overview_item->overview_grid());
  EXPECT_EQ(0u, grid2->GetNumWindows());

  // Drag the item and drop it on the mini view of the same desk (i.e. desk 1)
  // on the second display. The window should not change desks, but it should
  // change displays (i.e. it should be removed from |grid1| and added to
  // |grid2|).
  const auto* desks_bar_view = grid2->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_EQ(2u, desks_bar_view->mini_views().size());
  auto* desk_1_mini_view = desks_bar_view->mini_views()[0].get();
  auto* event_generator = GetEventGenerator();
  DragItemToPoint(overview_item,
                  desk_1_mini_view->GetBoundsInScreen().CenterPoint(),
                  event_generator,
                  /*by_touch_gestures=*/false);
  // A new item should have been created for the window on the second grid.
  EXPECT_TRUE(overview_controller->InOverviewSession());
  overview_item = overview_session->GetOverviewItemForWindow(win.get());
  ASSERT_TRUE(overview_item);
  EXPECT_EQ(0u, grid1->GetNumWindows());
  EXPECT_EQ(grid2, overview_item->overview_grid());
  EXPECT_EQ(1u, grid2->GetNumWindows());
  EXPECT_TRUE(DoesActiveDeskContainWindow(win.get()));
  EXPECT_EQ(roots[1], win->GetRootWindow());
}

TEST_F(DesksWithMultiDisplayOverview, DropOnOtherDeskInOtherDisplay) {
  auto roots = Shell::GetAllRootWindows();
  ASSERT_EQ(2u, roots.size());

  auto win = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  auto* overview_session = overview_controller->overview_session();
  auto* overview_item = overview_session->GetOverviewItemForWindow(win.get());
  ASSERT_TRUE(overview_item);

  // The window should exist on the grid of the first display.
  auto* grid1 = GetOverviewGridForRoot(roots[0]);
  auto* grid2 = GetOverviewGridForRoot(roots[1]);
  EXPECT_EQ(1u, grid1->GetNumWindows());
  EXPECT_EQ(grid1, overview_item->overview_grid());
  EXPECT_EQ(0u, grid2->GetNumWindows());

  const auto* desks_bar_view = grid2->desks_bar_view();
  auto* desk_2_mini_view = desks_bar_view->mini_views()[1].get();
  gfx::Point desk_2_mini_view_center =
      desk_2_mini_view->GetBoundsInScreen().CenterPoint();
  // When |chromeos::wm::features::kVerticalSnap| is enabled, one of two drag
  // indicators show up on the top instead of the left side of the display. Such
  // top indicator pushes the desks bar down, so we need to drag the item to the
  // area that triggers drag indicators without dropping first to get the
  // updated position of the mini view before dropping the window on it.
  DragItemToPoint(overview_item, desk_2_mini_view_center, GetEventGenerator(),
                  /*by_touch_gestures=*/false,
                  /*drop=*/false);
  EXPECT_TRUE(overview_controller->InOverviewSession());
  // Validate that before dropping, the SplitView indicators and the drop target
  // widget are created.
  EXPECT_EQ(
      SplitViewDragIndicators::WindowDraggingState::kFromOverview,
      grid2->split_view_drag_indicators()->current_window_dragging_state());
  desk_2_mini_view_center = desk_2_mini_view->GetBoundsInScreen().CenterPoint();
  // Now drop the window to desk 2 mini view in the second display.
  DragItemToPoint(overview_item, desk_2_mini_view_center, GetEventGenerator(),
                  /*by_touch_gestures=*/false,
                  /*drop=*/true);

  // The item should no longer be in any grid, since it moved to an inactive
  // desk.
  EXPECT_TRUE(overview_controller->InOverviewSession());
  overview_item = overview_session->GetOverviewItemForWindow(win.get());
  ASSERT_FALSE(overview_item);
  EXPECT_EQ(0u, grid1->GetNumWindows());
  EXPECT_EQ(0u, grid2->GetNumWindows());
  EXPECT_FALSE(DoesActiveDeskContainWindow(win.get()));
  EXPECT_EQ(roots[1], win->GetRootWindow());
  EXPECT_FALSE(win->IsVisible());
  auto* controller = DesksController::Get();
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  EXPECT_TRUE(base::Contains(desk_2->windows(), win.get()));
}

// Tests that closing a desk while in overview before the overview starting
// animation finishes on a second display does not cause a crash. Regression
// test for https://crbug.com/1346154.
TEST_F(DesksWithMultiDisplayOverview, CloseDeskBeforeAnimationFinishes) {
  // We need a non-zero duration to ensure we can close the desk before the
  // animation completes.
  ui::ScopedAnimationDurationScaleMode animation_scale(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  // Create a maximized window on Desk 1. This means that when entering
  // overview, we skip the wallpaper animation for Desk 1, so that the
  // desks_bar_view for RootWindow-0 will initialize before RootWindow-1.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  const WMEvent toggle_maximize_event(WM_EVENT_TOGGLE_MAXIMIZE);
  WindowState::Get(win0.get())->OnWMEvent(&toggle_maximize_event);
  ASSERT_TRUE(WindowState::Get(win0.get())->IsMaximized());

  EnterOverview();
  auto* overview_controller = OverviewController::Get();
  ASSERT_TRUE(overview_controller->InOverviewSession());

  // Check that the desk bar on our first root window has finished initializing,
  // while the second desk bar hasn't been initialized yet since the enter
  // animation hasn't finished for the second root window.
  auto root_windows = Shell::GetAllRootWindows();
  ASSERT_EQ(2u, root_windows.size());
  const auto* desks_bar_view_1 =
      GetOverviewGridForRoot(root_windows[0])->desks_bar_view();
  ASSERT_EQ(2u, desks_bar_view_1->mini_views().size());
  ASSERT_EQ(nullptr, GetOverviewGridForRoot(root_windows[1])->desks_bar_view());

  // Close the first desk. Previously, this would result in a crash since the
  // desk is deleted before `desks_bar_view_2` is initialized, resulting in the
  // `desk_1_mini_view` not being created for `desks_bar_view_2`. When
  // `OnDeskRemoved` is then called for the second desk bar, we now return early
  // if that miniview can't be found.
  // To prevent flakiness in this test, we wait until `desks_bar_view_2` is
  // initialized and shown before we check the state.
  views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{},
                                       "OverviewDeskBarWidget");
  auto* desk_1_mini_view = desks_bar_view_1->mini_views()[0].get();
  CloseDeskFromMiniView(desk_1_mini_view, GetEventGenerator());
  waiter.WaitIfNeededAndGet();

  // Verify that we are still in overview mode and that both desks bars are in
  // the zero state.
  ASSERT_TRUE(overview_controller->InOverviewSession());
  // The desk bar never goes back to zero state after it's initialized.
  ASSERT_FALSE(desks_bar_view_1->IsZeroState());
  const auto* desks_bar_view_2 =
      GetOverviewGridForRoot(root_windows[1])->desks_bar_view();
  ASSERT_TRUE(desks_bar_view_2->IsZeroState());
}

PrefService* GetPrimaryUserPrefService() {
  return Shell::Get()->session_controller()->GetPrimaryUserPrefService();
}

// Returns the desk names in the given `user_prefs`.
std::vector<std::string> GetDeskRestoreNames(PrefService* user_prefs) {
  const base::Value::List& desk_restore_names =
      user_prefs->GetList(prefs::kDesksNamesList);

  std::vector<std::string> names;
  for (const auto& value : desk_restore_names) {
    names.push_back(value.GetString());
  }
  return names;
}

// Returns the GUIDs in the given `user_prefs`.
std::vector<base::Uuid> GetDeskRestoreGuids(PrefService* user_prefs) {
  const base::Value::List& desks_restore_guids =
      user_prefs->GetList(prefs::kDesksGuidsList);

  std::vector<base::Uuid> guids;
  for (const base::Value& value : desks_restore_guids) {
    guids.emplace_back(base::Uuid::ParseLowercase(value.GetString()));
  }
  return guids;
}

// Returns the lacros profile IDs in the given `user_prefs`.
std::vector<uint64_t> GetDeskRestoreLacrosProfileIds(PrefService* user_prefs) {
  const base::Value::List& lacros_profile_ids_list =
      user_prefs->GetList(prefs::kDesksLacrosProfileIdList);

  std::vector<uint64_t> lacros_profile_ids;
  for (const base::Value& value : lacros_profile_ids_list) {
    uint64_t lacros_profile_id = 0;
    if (base::StringToUint64(value.GetString(), &lacros_profile_id)) {
      lacros_profile_ids.push_back(lacros_profile_id);
    } else {
      lacros_profile_ids.push_back(0);
    }
  }
  return lacros_profile_ids;
}

class DesksEditableNamesTest : public DesksTest {
 public:
  DesksEditableNamesTest() = default;
  DesksEditableNamesTest(const DesksEditableNamesTest&) = delete;
  DesksEditableNamesTest& operator=(const DesksEditableNamesTest&) = delete;
  ~DesksEditableNamesTest() override = default;

  DesksController* controller() { return controller_; }
  OverviewGrid* overview_grid() { return overview_grid_; }
  const DeskBarViewBase* desks_bar_view() { return desks_bar_view_; }

  // DesksTest:
  void SetUp() override {
    DesksTest::SetUp();

    // Begin all tests with two desks and start overview.
    NewDesk();
    controller_ = DesksController::Get();

    EnterOverview();
    overview_grid_ = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
    desks_bar_view_ = overview_grid_->desks_bar_view();
    ASSERT_TRUE(desks_bar_view_);
  }

  void ClickOnDeskNameViewAtIndex(size_t index) {
    ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
    ASSERT_LT(index, desks_bar_view_->mini_views().size());

    auto* desk_name_view =
        desks_bar_view_->mini_views()[index]->desk_name_view();
    auto* generator = GetEventGenerator();
    generator->MoveMouseTo(desk_name_view->GetBoundsInScreen().CenterPoint());
    generator->ClickLeftButton();
  }

 private:
  raw_ptr<DesksController, DanglingUntriaged> controller_ = nullptr;
  raw_ptr<OverviewGrid, DanglingUntriaged> overview_grid_ = nullptr;
  raw_ptr<const DeskBarViewBase, DanglingUntriaged> desks_bar_view_ = nullptr;
};

TEST_P(DesksEditableNamesTest, DefaultNameChangeAborted) {
  ASSERT_EQ(2u, controller()->desks().size());
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // Click on the desk name view of the second mini view.
  auto* desk_name_view_2 = desks_bar_view()->mini_views()[1]->desk_name_view();
  EXPECT_FALSE(overview_grid()->IsDeskNameBeingModified());
  ClickOnDeskNameViewAtIndex(1);
  EXPECT_TRUE(overview_grid()->IsDeskNameBeingModified());
  EXPECT_TRUE(desk_name_view_2->HasFocus());

  // Pressing enter now without making any changes should not change the
  // `is_name_set_by_user_` bit.
  PressAndReleaseKey(ui::VKEY_RETURN);
  EXPECT_FALSE(overview_grid()->IsDeskNameBeingModified());
  EXPECT_FALSE(desk_name_view_2->HasFocus());
  auto* desk_2 = controller()->GetDeskAtIndex(1);
  EXPECT_FALSE(desk_2->is_name_set_by_user());

  // Desks restore data should reflect two default-named desks.
  EXPECT_THAT(GetDeskRestoreNames(GetPrimaryUserPrefService()),
              ElementsAre("", ""));
}

TEST_P(DesksEditableNamesTest, NamesSetByUsersAreNotOverwritten) {
  ASSERT_EQ(2u, controller()->desks().size());
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // Change the name of the first desk. Adding/removing desks or
  // exiting/reentering overview should not cause changes to the desk's name.
  // All other names should be the default.
  ClickOnDeskNameViewAtIndex(0);
  // Select all and delete.
  PressAndReleaseKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  PressAndReleaseKey(ui::VKEY_BACK);
  // Type " code  " (with one space at the beginning and two spaces at the end)
  // and hit enter.
  PressAndReleaseKey(ui::VKEY_SPACE);
  PressAndReleaseKey(ui::VKEY_C);
  PressAndReleaseKey(ui::VKEY_O);
  PressAndReleaseKey(ui::VKEY_D);
  PressAndReleaseKey(ui::VKEY_E);
  PressAndReleaseKey(ui::VKEY_SPACE);
  PressAndReleaseKey(ui::VKEY_SPACE);
  PressAndReleaseKey(ui::VKEY_RETURN);

  // Extra whitespace should be trimmed.
  auto* desk_1 = controller()->GetDeskAtIndex(0);
  auto* desk_2 = controller()->GetDeskAtIndex(1);
  EXPECT_EQ(u"code", desk_1->name());
  EXPECT_EQ(u"Desk 2", desk_2->name());
  EXPECT_TRUE(desk_1->is_name_set_by_user());
  EXPECT_FALSE(desk_2->is_name_set_by_user());

  // Renaming desks via the mini views trigger an update to the desks restore
  // prefs.
  EXPECT_THAT(GetDeskRestoreNames(GetPrimaryUserPrefService()),
              ElementsAre("code", ""));

  // Add a third desk and remove the second. Both operations should not affect
  // the user-modified desk names.
  NewDesk();
  auto* desk_3 = controller()->GetDeskAtIndex(2);
  EXPECT_EQ(u"Desk 3", desk_3->name());
  EXPECT_TRUE(desk_1->is_name_set_by_user());
  EXPECT_FALSE(desk_2->is_name_set_by_user());
  EXPECT_FALSE(desk_3->is_name_set_by_user());

  // Adding a desk triggers an update to the restore prefs.
  EXPECT_THAT(GetDeskRestoreNames(GetPrimaryUserPrefService()),
              ElementsAre("code", "", ""));

  RemoveDesk(desk_2);
  EXPECT_TRUE(desk_1->is_name_set_by_user());
  EXPECT_FALSE(desk_3->is_name_set_by_user());
  // Desk 3 will now be renamed to "Desk 2".
  EXPECT_EQ(u"Desk 2", desk_3->name());
  EXPECT_THAT(GetDeskRestoreNames(GetPrimaryUserPrefService()),
              ElementsAre("code", ""));

  ExitOverview();
  EnterOverview();
  EXPECT_TRUE(desk_1->is_name_set_by_user());
  EXPECT_FALSE(desk_3->is_name_set_by_user());
  EXPECT_EQ(u"code", desk_1->name());
  EXPECT_EQ(u"Desk 2", desk_3->name());
}

TEST_P(DesksEditableNamesTest, DontAllowEmptyNames) {
  ASSERT_EQ(2u, controller()->desks().size());
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // Change the name of a desk to an empty string.
  ClickOnDeskNameViewAtIndex(0);
  // Select all and delete.
  PressAndReleaseKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  PressAndReleaseKey(ui::VKEY_BACK);
  // Commit with the enter key.
  PressAndReleaseKey(ui::VKEY_RETURN);
  // The name should now revert back to the default value.
  auto* desk_1 = controller()->GetDeskAtIndex(0);
  EXPECT_FALSE(desk_1->name().empty());
  EXPECT_FALSE(desk_1->is_name_set_by_user());
  EXPECT_EQ(u"Desk 1", desk_1->name());
  EXPECT_THAT(GetDeskRestoreNames(GetPrimaryUserPrefService()),
              ElementsAre("", ""));
}

TEST_P(DesksEditableNamesTest, RevertDeskNameOnEscape) {
  ASSERT_EQ(2u, controller()->desks().size());
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // Select first desk name view.
  ClickOnDeskNameViewAtIndex(0);
  // Edit the name of the desk.
  PressAndReleaseKey(ui::VKEY_E);
  PressAndReleaseKey(ui::VKEY_S);
  PressAndReleaseKey(ui::VKEY_C);
  // Press escape key.
  PressAndReleaseKey(ui::VKEY_ESCAPE);
  // Name should be previous value.
  auto* desk_1 = controller()->GetDeskAtIndex(0);
  EXPECT_FALSE(desk_1->is_name_set_by_user());
  EXPECT_EQ(u"Desk 1", desk_1->name());
}

TEST_P(DesksEditableNamesTest, SelectAllOnFocus) {
  ASSERT_EQ(2u, controller()->desks().size());
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  ClickOnDeskNameViewAtIndex(0);

  auto* desk_name_view = desks_bar_view()->mini_views()[0]->desk_name_view();
  EXPECT_TRUE(desk_name_view->HasFocus());
  EXPECT_TRUE(desk_name_view->HasSelection());
  auto* desk_1 = controller()->GetDeskAtIndex(0);
  EXPECT_EQ(desk_1->name(), desk_name_view->GetSelectedText());
}

TEST_P(DesksEditableNamesTest, EventsThatCommitChanges) {
  ASSERT_EQ(2u, controller()->desks().size());
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  ClickOnDeskNameViewAtIndex(0);
  auto* desk_name_view = desks_bar_view()->mini_views()[0]->desk_name_view();
  EXPECT_TRUE(desk_name_view->HasFocus());

  // Creating a new desk commits the changes.
  auto* new_desk_button = desks_bar_view()->new_desk_button();
  LeftClickOn(new_desk_button);
  RunScheduledLayoutForAllOverviewDeskBars();
  ASSERT_EQ(3u, controller()->desks().size());
  EXPECT_FALSE(desk_name_view->HasFocus());

  // Deleting a desk commits the changes.
  ClickOnDeskNameViewAtIndex(0);
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_TRUE(desk_name_view->HasFocus());
  auto* event_generator = GetEventGenerator();
  CloseDeskFromMiniView(desks_bar_view()->mini_views()[2], event_generator);
  RunScheduledLayoutForAllOverviewDeskBars();
  ASSERT_EQ(2u, controller()->desks().size());
  EXPECT_FALSE(desk_name_view->HasFocus());

  // Clicking in the empty area of the desks bar also commits the changes.
  ClickOnDeskNameViewAtIndex(0);
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_TRUE(desk_name_view->HasFocus());
  event_generator->MoveMouseTo(gfx::Point(2, 2));
  event_generator->ClickLeftButton();
  EXPECT_FALSE(desk_name_view->HasFocus());
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
}

TEST_P(DesksEditableNamesTest, MaxLength) {
  ASSERT_EQ(2u, controller()->desks().size());
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  ClickOnDeskNameViewAtIndex(0);
  // Select all and delete.
  PressAndReleaseKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  PressAndReleaseKey(ui::VKEY_BACK);

  // Simulate user is typing text beyond the max length.
  std::u16string expected_desk_name(DeskTextfield::kMaxLength, L'a');
  for (size_t i = 0; i < DeskTextfield::kMaxLength + 10; ++i) {
    PressAndReleaseKey(ui::VKEY_A);
  }
  PressAndReleaseKey(ui::VKEY_RETURN);

  // Desk name has been trimmed.
  auto* desk_1 = controller()->GetDeskAtIndex(0);
  EXPECT_EQ(DeskTextfield::kMaxLength, desk_1->name().size());
  EXPECT_EQ(expected_desk_name, desk_1->name());
  EXPECT_TRUE(desk_1->is_name_set_by_user());

  // Test that pasting a large amount of text is trimmed at the max length.
  std::u16string clipboard_text(DeskTextfield::kMaxLength + 10, L'b');
  expected_desk_name = std::u16string(DeskTextfield::kMaxLength, L'b');
  EXPECT_GT(clipboard_text.size(), DeskTextfield::kMaxLength);
  ui::ScopedClipboardWriter(ui::ClipboardBuffer::kCopyPaste)
      .WriteText(clipboard_text);

  ClickOnDeskNameViewAtIndex(0);
  // Select all and delete.
  PressAndReleaseKey(ui::VKEY_A, ui::EF_CONTROL_DOWN);
  PressAndReleaseKey(ui::VKEY_BACK);

  // Paste text.
  PressAndReleaseKey(ui::VKEY_V, ui::EF_CONTROL_DOWN);
  PressAndReleaseKey(ui::VKEY_RETURN);
  EXPECT_EQ(DeskTextfield::kMaxLength, desk_1->name().size());
  EXPECT_EQ(expected_desk_name, desk_1->name());
}

class TabletModeDesksTest : public DesksTest {
 public:
  TabletModeDesksTest() = default;

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

  ~TabletModeDesksTest() override = default;

  // DesksTest:
  void SetUp() override {
    DesksTest::SetUp();

    // Enter tablet mode after detaching all mouse devices, as this is needed
    // when running these tests on an actual workstation.
    TabletModeControllerTestApi tablet_mode_test_api;
    tablet_mode_test_api.DetachAllMice();
    tablet_mode_test_api.EnterTabletMode();
  }

  SplitViewController* split_view_controller() {
    return SplitViewController::Get(Shell::GetPrimaryRootWindow());
  }
};

// Triggers a callback when the visibility of an observed window changes for the
// first time since creation of this observer.
class WindowVisibilityObserver : public aura::WindowObserver {
 public:
  WindowVisibilityObserver(aura::Window* window, base::OnceClosure callback)
      : on_visibility_changed_callback_(std::move(callback)) {
    DCHECK(on_visibility_changed_callback_);
    observer_.Observe(window);
  }
  WindowVisibilityObserver(const WindowVisibilityObserver&) = delete;
  WindowVisibilityObserver& operator=(const WindowVisibilityObserver&) = delete;
  ~WindowVisibilityObserver() override = default;

  // aura::WindowObserver:
  void OnWindowVisibilityChanged(aura::Window* window, bool visible) override {
    if (observer_.IsObservingSource(window) &&
        on_visibility_changed_callback_) {
      std::move(on_visibility_changed_callback_).Run();
    }
  }

  void OnWindowDestroying(aura::Window* window) override {
    DCHECK(observer_.IsObservingSource(window));
    observer_.Reset();
  }

 private:
  base::ScopedObservation<aura::Window, aura::WindowObserver> observer_{this};

  base::OnceClosure on_visibility_changed_callback_;
};

// Regression test for https://crbug.com/1368587.
TEST_P(TabletModeDesksTest, CantDestroyBackdropWhileHiding) {
  auto* controller = DesksController::Get();
  ASSERT_EQ(1u, controller->desks().size());
  const Desk* desk_1 = controller->GetDeskAtIndex(0);

  auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(window.get());
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  // Verify that there is a visible backdrop for the app window on the current
  // desk.
  auto* desk_1_backdrop_controller =
      GetDeskBackdropController(desk_1, Shell::GetPrimaryRootWindow());
  auto* backdrop_window = desk_1_backdrop_controller->backdrop_window();
  ASSERT_TRUE(backdrop_window);
  EXPECT_TRUE(backdrop_window->IsVisible());

  // Intercept the visibility change notification of the backdrop (which will
  // happen when we enter overview below), and hide the app window. This
  // triggers an update of the backdrop while still in the process of hiding
  // it. Now that the single app window available is hidden, the backdrop
  // controller will try to destroy the backdrop. This should be prevented as
  // we don't allow `BackdropController::Hide()` to be called recursively.
  auto* app_window = window.get();
  WindowVisibilityObserver observer{
      backdrop_window,
      base::BindLambdaForTesting([app_window, backdrop_window]() {
        app_window->Hide();
        EXPECT_FALSE(backdrop_window->IsVisible());
      })};

  // Enter overview and expect that the backdrop is still present for desk_1 but
  // hidden.
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
  ASSERT_TRUE(desk_1_backdrop_controller->backdrop_window());
  EXPECT_FALSE(desk_1_backdrop_controller->backdrop_window()->IsVisible());
}

TEST_P(TabletModeDesksTest, Backdrops) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  const Desk* desk_2 = controller->GetDeskAtIndex(1);

  auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(window.get());
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  // Enter tablet mode and expect that the backdrop is created only for desk_1,
  // since it's the one that has a window in it.
  auto* desk_1_backdrop_controller =
      GetDeskBackdropController(desk_1, Shell::GetPrimaryRootWindow());
  auto* desk_2_backdrop_controller =
      GetDeskBackdropController(desk_2, Shell::GetPrimaryRootWindow());
  ASSERT_TRUE(desk_1_backdrop_controller->backdrop_window());
  EXPECT_TRUE(desk_1_backdrop_controller->backdrop_window()->IsVisible());
  EXPECT_FALSE(desk_2_backdrop_controller->backdrop_window());

  // Enter overview and expect that the backdrop is still present for desk_1 but
  // hidden.
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  ASSERT_TRUE(desk_1_backdrop_controller->backdrop_window());
  EXPECT_FALSE(desk_1_backdrop_controller->backdrop_window()->IsVisible());

  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  EXPECT_EQ(1u, overview_grid->GetNumWindows());

  auto* overview_session = overview_controller->overview_session();
  auto* overview_item =
      overview_session->GetOverviewItemForWindow(window.get());
  ASSERT_TRUE(overview_item);
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);

  // Now drag it to desk_2's mini_view, so that it moves to desk_2. Expect that
  // desk_1's backdrop is destroyed, while created (but still hidden) for
  // desk_2.
  auto* desk_2_mini_view = desks_bar_view->mini_views()[1].get();
  EXPECT_EQ(desk_2, desk_2_mini_view->desk());
  DragItemToPoint(overview_item,
                  desk_2_mini_view->GetBoundsInScreen().CenterPoint(),
                  GetEventGenerator());
  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_TRUE(base::Contains(desk_2->windows(), window.get()));
  EXPECT_FALSE(desk_1_backdrop_controller->backdrop_window());
  ASSERT_TRUE(desk_2_backdrop_controller->backdrop_window());
  EXPECT_FALSE(desk_2_backdrop_controller->backdrop_window()->IsVisible());

  // Exit overview, and expect that desk_2's backdrop remains hidden since the
  // desk is not activated yet.
  ExitOverview(OverviewEnterExitType::kImmediateExit);
  EXPECT_FALSE(overview_controller->InOverviewSession());
  EXPECT_FALSE(desk_1_backdrop_controller->backdrop_window());
  ASSERT_TRUE(desk_2_backdrop_controller->backdrop_window());
  EXPECT_FALSE(desk_2_backdrop_controller->backdrop_window()->IsVisible());

  // Activate desk_2 and expect that its backdrop is now visible.
  ActivateDesk(desk_2);
  EXPECT_FALSE(desk_1_backdrop_controller->backdrop_window());
  ASSERT_TRUE(desk_2_backdrop_controller->backdrop_window());
  EXPECT_TRUE(desk_2_backdrop_controller->backdrop_window()->IsVisible());

  // No backdrops after exiting tablet mode.
  TabletModeControllerTestApi().LeaveTabletMode();
  EXPECT_FALSE(desk_1_backdrop_controller->backdrop_window());
  EXPECT_FALSE(desk_2_backdrop_controller->backdrop_window());
}

TEST_P(TabletModeDesksTest,
       BackdropStackingAndMiniviewsUpdatesWithOverviewDragDrop) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(window.get());
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());
  auto* desk_1_backdrop_controller =
      GetDeskBackdropController(desk_1, Shell::GetPrimaryRootWindow());
  auto* desk_2_backdrop_controller =
      GetDeskBackdropController(desk_2, Shell::GetPrimaryRootWindow());

  // Enter overview and expect that |desk_1| has a backdrop stacked under
  // |window| while desk_2 has none.
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  ASSERT_TRUE(desk_1_backdrop_controller->backdrop_window());
  EXPECT_FALSE(desk_2_backdrop_controller->backdrop_window());
  EXPECT_EQ(window.get(), desk_1_backdrop_controller->window_having_backdrop());
  EXPECT_FALSE(desk_2_backdrop_controller->window_having_backdrop());
  EXPECT_TRUE(window_util::IsStackedBelow(
      desk_1_backdrop_controller->backdrop_window(), window.get()));

  // Prepare to drag and drop |window| on desk_2's mini view.
  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  EXPECT_EQ(1u, overview_grid->GetNumWindows());
  auto* overview_session = overview_controller->overview_session();
  auto* overview_item =
      overview_session->GetOverviewItemForWindow(window.get());
  ASSERT_TRUE(overview_item);
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  auto* desk_2_mini_view = desks_bar_view->mini_views()[1].get();

  // Observe how many times a drag and drop operation updates the mini views.
  TestDeskObserver observer1;
  TestDeskObserver observer2;
  desk_1->AddObserver(&observer1);
  desk_2->AddObserver(&observer2);
  {
    // For this test to fail the stacking test below, we need to drag and drop
    // while animations are enabled. https://crbug.com/1055732.
    ui::ScopedAnimationDurationScaleMode normal_anim(
        ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION);
    DragItemToPoint(overview_item,
                    desk_2_mini_view->GetBoundsInScreen().CenterPoint(),
                    GetEventGenerator());
  }
  // The backdrop should be destroyed for |desk_1|, and a new one should be
  // created for |window| in desk_2 and should be stacked below it.
  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_TRUE(base::Contains(desk_2->windows(), window.get()));
  EXPECT_FALSE(desk_1_backdrop_controller->backdrop_window());
  ASSERT_TRUE(desk_2_backdrop_controller->backdrop_window());
  EXPECT_FALSE(desk_1_backdrop_controller->window_having_backdrop());
  EXPECT_EQ(window.get(), desk_2_backdrop_controller->window_having_backdrop());
  EXPECT_TRUE(window_util::IsStackedBelow(
      desk_2_backdrop_controller->backdrop_window(), window.get()));

  // The mini views should only be updated once for both desks.
  EXPECT_EQ(1, observer1.notify_counts());
  EXPECT_EQ(1, observer2.notify_counts());
  desk_1->RemoveObserver(&observer1);
  desk_2->RemoveObserver(&observer2);
}

TEST_P(TabletModeDesksTest, NoDesksBarInTabletModeWithOneDesk) {
  // Initially there's only one desk.
  auto* controller = DesksController::Get();
  ASSERT_EQ(1u, controller->desks().size());

  auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(window.get());
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  // Enter overview and expect that the DesksBar widget won't be created.
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_FALSE(desks_bar_view);

  // It's possible to drag the window without any crashes.
  auto* overview_session = overview_controller->overview_session();
  auto* overview_item =
      overview_session->GetOverviewItemForWindow(window.get());
  DragItemToPoint(overview_item, window->GetBoundsInScreen().CenterPoint(),
                  GetEventGenerator(), /*by_touch_gestures=*/true);

  // Exit overview and add a new desk, then re-enter overview. Expect that now
  // the desks bar is visible.
  ExitOverview();
  EXPECT_FALSE(overview_controller->InOverviewSession());
  NewDesk();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_EQ(2u, desks_bar_view->mini_views().size());
}

TEST_P(TabletModeDesksTest, DesksCreationRemovalCycle) {
  auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(window.get());
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  // Create and remove desks in a cycle while in overview mode. Expect as the
  // containers are reused for new desks, their backdrop state are always
  // correct, and there are no crashes as desks are removed.
  auto* desks_controller = DesksController::Get();
  for (size_t i = 0; i < 2 * desks_util::GetMaxNumberOfDesks(); ++i) {
    NewDesk();
    ASSERT_EQ(2u, desks_controller->desks().size());
    const Desk* desk_1 = desks_controller->GetDeskAtIndex(0);
    const Desk* desk_2 = desks_controller->GetDeskAtIndex(1);
    auto* desk_1_backdrop_controller =
        GetDeskBackdropController(desk_1, Shell::GetPrimaryRootWindow());
    auto* desk_2_backdrop_controller =
        GetDeskBackdropController(desk_2, Shell::GetPrimaryRootWindow());
    {
      SCOPED_TRACE("Check backdrops after desk creation");
      ASSERT_TRUE(desk_1_backdrop_controller->backdrop_window());
      EXPECT_TRUE(desk_1_backdrop_controller->backdrop_window()->IsVisible());
      EXPECT_FALSE(desk_2_backdrop_controller->backdrop_window());
    }
    // Remove the active desk, and expect that now desk_2 should have a hidden
    // backdrop, while the container of the removed desk_1 should have none.
    RemoveDesk(desk_1);
    {
      SCOPED_TRACE("Check backdrops after desk removal");
      EXPECT_TRUE(desk_2->is_active());
      EXPECT_TRUE(DoesActiveDeskContainWindow(window.get()));
      EXPECT_FALSE(desk_1_backdrop_controller->backdrop_window());
      ASSERT_TRUE(desk_2_backdrop_controller->backdrop_window());
      EXPECT_TRUE(desk_2_backdrop_controller->backdrop_window()->IsVisible());
    }
  }
}

TEST_P(TabletModeDesksTest, RestoreSplitViewOnDeskSwitch) {
  // Create two desks with two snapped windows in each.
  auto* desks_controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, desks_controller->desks().size());
  Desk* desk_1 = desks_controller->GetDeskAtIndex(0);
  Desk* desk_2 = desks_controller->GetDeskAtIndex(1);

  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  split_view_controller()->SnapWindow(win1.get(), SnapPosition::kPrimary);
  split_view_controller()->SnapWindow(win2.get(), SnapPosition::kSecondary);
  EXPECT_EQ(win1.get(), split_view_controller()->primary_window());
  EXPECT_EQ(win2.get(), split_view_controller()->secondary_window());

  // Desk 2 has no windows, so the SplitViewController should be tracking no
  // windows.
  ActivateDesk(desk_2);
  EXPECT_EQ(nullptr, split_view_controller()->primary_window());
  EXPECT_EQ(nullptr, split_view_controller()->secondary_window());
  // However, the snapped windows on desk 1 should retain their snapped state.
  EXPECT_TRUE(WindowState::Get(win1.get())->IsSnapped());
  EXPECT_TRUE(WindowState::Get(win2.get())->IsSnapped());

  // Snap two other windows in desk 2.
  auto win3 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win4 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  split_view_controller()->SnapWindow(win3.get(), SnapPosition::kPrimary);
  split_view_controller()->SnapWindow(win4.get(), SnapPosition::kSecondary);
  EXPECT_EQ(win3.get(), split_view_controller()->primary_window());
  EXPECT_EQ(win4.get(), split_view_controller()->secondary_window());

  // Switch back to desk 1, and expect the snapped windows are restored.
  ActivateDesk(desk_1);
  EXPECT_EQ(win1.get(), split_view_controller()->primary_window());
  EXPECT_EQ(win2.get(), split_view_controller()->secondary_window());
  EXPECT_TRUE(WindowState::Get(win3.get())->IsSnapped());
  EXPECT_TRUE(WindowState::Get(win4.get())->IsSnapped());
}

TEST_P(
    TabletModeDesksTest,
    SnappedStateRetainedOnSwitchingDesksWithOverviewFullOfUnsnappableWindows) {
  auto* desks_controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, desks_controller->desks().size());

  // Create one window for snapping, and two windows whose minimum size is too
  // big for half snap.
  const gfx::Rect work_area =
      screen_util::GetDisplayWorkAreaBoundsInScreenForActiveDeskContainer(
          Shell::GetPrimaryRootWindow());
  const gfx::Size big(work_area.width() * 2 / 3, work_area.height() * 2 / 3);
  const gfx::Size small(250, 100);
  std::unique_ptr<aura::Window> win1 = CreateTestWindow(gfx::Rect(small));
  aura::test::TestWindowDelegate win2_delegate;
  win2_delegate.set_minimum_size(big);
  std::unique_ptr<aura::Window> win2(CreateTestWindowInShellWithDelegate(
      &win2_delegate, /*id=*/-1, gfx::Rect(big)));
  aura::test::TestWindowDelegate win3_delegate;
  win3_delegate.set_minimum_size(big);
  std::unique_ptr<aura::Window> win3(CreateTestWindowInShellWithDelegate(
      &win3_delegate, /*id=*/-1, gfx::Rect(big)));

  ASSERT_TRUE(EnterOverview());
  split_view_controller()->SnapWindow(win1.get(), SnapPosition::kPrimary);
  EXPECT_EQ(win1.get(), split_view_controller()->primary_window());
  EXPECT_FALSE(split_view_controller()->CanSnapWindow(
      win2.get(), chromeos::kDefaultSnapRatio));
  EXPECT_FALSE(split_view_controller()->CanSnapWindow(
      win3.get(), chromeos::kDefaultSnapRatio));

  // Use `Search + ]` to switch to `desk2`. Split view should end, but `win1`
  // should retain its snapped state.
  PressAndReleaseKey(ui::VKEY_OEM_6, ui::EF_COMMAND_DOWN);
  DeskSwitchAnimationWaiter().Wait();
  EXPECT_TRUE(WindowState::Get(win1.get())->IsSnapped());
  EXPECT_EQ(SplitViewController::State::kNoSnap,
            split_view_controller()->state());

  // Use `Search + [` to switch back to `desk_1` and verify that split view is
  // arranged as before.
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  PressAndReleaseKey(ui::VKEY_OEM_4, ui::EF_COMMAND_DOWN);
  DeskSwitchAnimationWaiter().Wait();

  EXPECT_TRUE(WindowState::Get(win1.get())->IsSnapped());
  EXPECT_EQ(SplitViewController::State::kPrimarySnapped,
            split_view_controller()->state());
  EXPECT_EQ(win1.get(), split_view_controller()->primary_window());
}

TEST_P(TabletModeDesksTest, OverviewStateOnSwitchToDeskWithSplitView) {
  // Setup two desks, one (desk_1) with two snapped windows, and the other
  // (desk_2) with only one snapped window.
  auto* desks_controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, desks_controller->desks().size());
  Desk* desk_1 = desks_controller->GetDeskAtIndex(0);
  Desk* desk_2 = desks_controller->GetDeskAtIndex(1);
  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  split_view_controller()->SnapWindow(win1.get(), SnapPosition::kPrimary);
  split_view_controller()->SnapWindow(win2.get(), SnapPosition::kSecondary);
  EXPECT_EQ(win1.get(), split_view_controller()->primary_window());
  EXPECT_EQ(win2.get(), split_view_controller()->secondary_window());
  auto* overview_controller = OverviewController::Get();
  EXPECT_FALSE(overview_controller->InOverviewSession());
  ActivateDesk(desk_2);
  EXPECT_FALSE(overview_controller->InOverviewSession());
  auto win3 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  split_view_controller()->SnapWindow(win3.get(), SnapPosition::kPrimary);
  EXPECT_EQ(win3.get(), split_view_controller()->primary_window());
  EXPECT_EQ(nullptr, split_view_controller()->secondary_window());

  // Switching to the desk that has only one snapped window to be restored in
  // SplitView should enter overview mode, whereas switching to one that has two
  // snapped windows should exit overview.
  ActivateDesk(desk_1);
  EXPECT_FALSE(overview_controller->InOverviewSession());
  ActivateDesk(desk_2);
  EXPECT_TRUE(overview_controller->InOverviewSession());
  ActivateDesk(desk_1);
  EXPECT_FALSE(overview_controller->InOverviewSession());
}

TEST_P(TabletModeDesksTest, RemovingDesksWithSplitView) {
  auto* desks_controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, desks_controller->desks().size());
  Desk* desk_2 = desks_controller->GetDeskAtIndex(1);
  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  split_view_controller()->SnapWindow(win1.get(), SnapPosition::kPrimary);
  EXPECT_EQ(win1.get(), split_view_controller()->primary_window());
  EXPECT_EQ(nullptr, split_view_controller()->secondary_window());
  ActivateDesk(desk_2);
  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  split_view_controller()->SnapWindow(win2.get(), SnapPosition::kSecondary);
  EXPECT_EQ(nullptr, split_view_controller()->primary_window());
  EXPECT_EQ(win2.get(), split_view_controller()->secondary_window());

  // Removing desk_2 will cause both snapped windows to merge in SplitView.
  RemoveDesk(desk_2);
  EXPECT_EQ(win1.get(), split_view_controller()->primary_window());
  EXPECT_EQ(win2.get(), split_view_controller()->secondary_window());
  EXPECT_EQ(SplitViewController::State::kBothSnapped,
            split_view_controller()->state());
}

TEST_P(TabletModeDesksTest, RemoveDeskWithMaximizedWindowAndMergeWithSnapped) {
  auto* desks_controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, desks_controller->desks().size());
  Desk* desk_2 = desks_controller->GetDeskAtIndex(1);
  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  split_view_controller()->SnapWindow(win1.get(), SnapPosition::kPrimary);
  EXPECT_EQ(win1.get(), split_view_controller()->primary_window());
  EXPECT_EQ(nullptr, split_view_controller()->secondary_window());
  ActivateDesk(desk_2);
  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  EXPECT_EQ(nullptr, split_view_controller()->primary_window());
  EXPECT_EQ(nullptr, split_view_controller()->secondary_window());
  EXPECT_TRUE(WindowState::Get(win2.get())->IsMaximized());

  // Removing desk_2 will cause us to enter overview mode without any crashes.
  // SplitView will remain left snapped.
  RemoveDesk(desk_2);
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
  EXPECT_EQ(win1.get(), split_view_controller()->primary_window());
  EXPECT_EQ(nullptr, split_view_controller()->secondary_window());
  EXPECT_EQ(SplitViewController::State::kPrimarySnapped,
            split_view_controller()->state());
}

// Tests that closing the active desk while in overview does not quit overview.
// Regression test for https://crbug.com/1309175.
TEST_P(TabletModeDesksTest, RemovingActiveDeskDoesNotExitOverview) {
  auto* desks_controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, desks_controller->desks().size());
  Desk* desk_2 = desks_controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);

  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  ASSERT_TRUE(overview_controller->InOverviewSession());

  // Remove `desk_2`, which is the active test. We should stay in overview.
  RemoveDesk(desk_2);
  EXPECT_TRUE(overview_controller->InOverviewSession());
}

TEST_P(TabletModeDesksTest, BackdropsStacking) {
  auto* desks_controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, desks_controller->desks().size());
  Desk* desk_1 = desks_controller->GetDeskAtIndex(0);
  Desk* desk_2 = desks_controller->GetDeskAtIndex(1);

  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  split_view_controller()->SnapWindow(win1.get(), SnapPosition::kPrimary);
  split_view_controller()->SnapWindow(win2.get(), SnapPosition::kSecondary);
  auto* desk_1_backdrop_controller =
      GetDeskBackdropController(desk_1, Shell::GetPrimaryRootWindow());
  auto* desk_2_backdrop_controller =
      GetDeskBackdropController(desk_2, Shell::GetPrimaryRootWindow());
  ASSERT_TRUE(desk_1_backdrop_controller->backdrop_window());
  EXPECT_FALSE(desk_2_backdrop_controller->backdrop_window());

  // The backdrop window should be stacked below both snapped windows.
  auto* desk_1_backdrop = desk_1_backdrop_controller->backdrop_window();
  EXPECT_TRUE(window_util::IsStackedBelow(desk_1_backdrop, win1.get()));
  EXPECT_TRUE(window_util::IsStackedBelow(desk_1_backdrop, win2.get()));

  // Switching to another desk doesn't change the backdrop state of the inactive
  // desk.
  ActivateDesk(desk_2);
  ASSERT_TRUE(desk_1_backdrop_controller->backdrop_window());
  EXPECT_FALSE(desk_2_backdrop_controller->backdrop_window());
  EXPECT_TRUE(window_util::IsStackedBelow(desk_1_backdrop, win1.get()));
  EXPECT_TRUE(window_util::IsStackedBelow(desk_1_backdrop, win2.get()));

  // Snapping new windows in desk_2 should update the backdrop state of desk_2,
  // but should not affect desk_1.
  auto win3 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win4 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  split_view_controller()->SnapWindow(win3.get(), SnapPosition::kPrimary);
  split_view_controller()->SnapWindow(win4.get(), SnapPosition::kSecondary);
  ASSERT_TRUE(desk_1_backdrop_controller->backdrop_window());
  ASSERT_TRUE(desk_2_backdrop_controller->backdrop_window());
  auto* desk_2_backdrop = desk_2_backdrop_controller->backdrop_window();
  EXPECT_TRUE(window_util::IsStackedBelow(desk_2_backdrop, win3.get()));
  EXPECT_TRUE(window_util::IsStackedBelow(desk_2_backdrop, win4.get()));
}

TEST_P(TabletModeDesksTest, RestoringUnsnappableWindowsInSplitView) {
  UpdateDisplay("600x400");
  display::test::DisplayManagerTestApi(display_manager())
      .SetFirstDisplayAsInternalDisplay();

  // Setup an app window that cannot be snapped in landscape orientation, but
  // can be snapped in portrait orientation.
  auto window = CreateAppWindow(gfx::Rect(350, 350));
  views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window.get());
  widget->widget_delegate()->GetContentsView()->SetPreferredSize(
      gfx::Size(350, 100));
  EXPECT_FALSE(split_view_controller()->CanSnapWindow(
      window.get(), chromeos::kDefaultSnapRatio));

  // Change to a portrait orientation and expect it's possible to snap the
  // window.
  ScreenOrientationControllerTestApi test_api(
      Shell::Get()->screen_orientation_controller());
  test_api.SetDisplayRotation(display::Display::ROTATE_270,
                              display::Display::RotationSource::ACTIVE);
  EXPECT_EQ(test_api.GetCurrentOrientation(),
            chromeos::OrientationType::kPortraitPrimary);
  EXPECT_TRUE(split_view_controller()->CanSnapWindow(
      window.get(), chromeos::kDefaultSnapRatio));

  // Snap the window in this orientation.
  split_view_controller()->SnapWindow(window.get(), SnapPosition::kPrimary);
  EXPECT_EQ(window.get(), split_view_controller()->primary_window());
  EXPECT_TRUE(split_view_controller()->InSplitViewMode());

  // Create a second desk, switch to it, and change back the orientation to
  // landscape, in which the window is not snappable. The window still exists on
  // the first desk, so nothing should change.
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);
  EXPECT_EQ(desk_2, controller->active_desk());
  test_api.SetDisplayRotation(display::Display::ROTATE_0,
                              display::Display::RotationSource::ACTIVE);
  EXPECT_EQ(test_api.GetCurrentOrientation(),
            chromeos::OrientationType::kLandscapePrimary);

  // Switch back to the first desk, and expect that SplitView is not restored,
  // since the only available window on that desk is not snappable.
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  ActivateDesk(desk_1);
  EXPECT_EQ(desk_1, controller->active_desk());
  EXPECT_FALSE(split_view_controller()->InSplitViewMode());
  EXPECT_TRUE(WindowState::Get(window.get())->IsMaximized());
}

TEST_P(DesksTest, MiniViewsTouchGestures) {
  auto* controller = DesksController::Get();
  NewDesk();
  NewDesk();
  ASSERT_EQ(3u, controller->desks().size());
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_EQ(3u, desks_bar_view->mini_views().size());
  auto* desk_1_mini_view = desks_bar_view->mini_views()[0].get();
  auto* desk_2_mini_view = desks_bar_view->mini_views()[1].get();
  auto* desk_3_mini_view = desks_bar_view->mini_views()[2].get();

  // Long gesture tapping on one desk preview shows its desk action interface,
  // and hides those of other mini views.
  auto* event_generator = GetEventGenerator();
  const gfx::Point desk_1_preview_center =
      desk_1_mini_view->desk_preview()->GetBoundsInScreen().CenterPoint();
  const gfx::Point desk_2_preview_center =
      desk_2_mini_view->desk_preview()->GetBoundsInScreen().CenterPoint();

  LongGestureTap(desk_1_preview_center, event_generator);

  // The context menu appears on the first long press and after the user taps
  // away the buttons will show. So we need to tap away and wait for the context
  // menu to disappear before checking whether the desk action interfaces are
  // visible.
  event_generator->GestureTapDownAndUp(desk_1_preview_center);
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(GetDeskActionVisibilityForMiniView(desk_1_mini_view));
  EXPECT_FALSE(GetDeskActionVisibilityForMiniView(desk_2_mini_view));
  EXPECT_FALSE(GetDeskActionVisibilityForMiniView(desk_3_mini_view));

  LongGestureTap(desk_2_preview_center, event_generator);

  event_generator->GestureTapDownAndUp(desk_2_preview_center);
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(GetDeskActionVisibilityForMiniView(desk_1_mini_view));
  EXPECT_TRUE(GetDeskActionVisibilityForMiniView(desk_2_mini_view));
  EXPECT_FALSE(GetDeskActionVisibilityForMiniView(desk_3_mini_view));

  // Tapping on the visible close button closes the desk rather than
  // switches to that desk.
  GestureTapOn(GetCloseDeskButtonForMiniView(desk_2_mini_view));
  ASSERT_EQ(2u, controller->desks().size());
  ASSERT_EQ(2u, desks_bar_view->mini_views().size());
  EXPECT_TRUE(overview_controller->InOverviewSession());

  // Tapping on the invisible close button should not result in closing
  // that desk; rather activating that desk.
  EXPECT_FALSE(GetDeskActionVisibilityForMiniView(desk_1_mini_view));
  GestureTapOn(GetCloseDeskButtonForMiniView(desk_1_mini_view));
  ASSERT_EQ(2u, controller->desks().size());
  EXPECT_FALSE(overview_controller->InOverviewSession());
  EXPECT_TRUE(controller->GetDeskAtIndex(0)->is_active());
}

TEST_P(DesksTest, AutohiddenShelfAnimatesAfterDeskSwitch) {
  Shelf* shelf = GetPrimaryShelf();
  ShelfWidget* shelf_widget = shelf->shelf_widget();
  const gfx::Rect shown_shelf_bounds = shelf_widget->GetWindowBoundsInScreen();

  shelf->SetAutoHideBehavior(ShelfAutoHideBehavior::kAlways);

  // Enable animations so that we can make sure that they occur.
  ui::ScopedAnimationDurationScaleMode non_zero_animation(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  NewDesk();

  // Create a window on the first desk so that the shelf will auto-hide there.
  std::unique_ptr<views::Widget> widget =
      CreateTestWidget(views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET);
  widget->Maximize();
  // LayoutShelf() forces the animation to completion, at which point the
  // shelf should go off the screen.
  shelf->shelf_layout_manager()->LayoutShelf();
  EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState());
  EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState());
  const gfx::Rect hidden_shelf_bounds = shelf_widget->GetWindowBoundsInScreen();
  EXPECT_NE(shown_shelf_bounds, hidden_shelf_bounds);

  // Go to the second desk.
  ActivateDesk(DesksController::Get()->GetDeskAtIndex(1));
  // The shelf should now want to show itself.
  EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState());

  // Since the layer transform animation is just starting, the transformed
  // bounds should still be hidden. If this fails, the change was not animated.
  gfx::Rect transformed_bounds = shelf_widget->GetLayer()->transform().MapRect(
      shelf_widget->GetWindowBoundsInScreen());
  EXPECT_EQ(transformed_bounds, hidden_shelf_bounds);
  EXPECT_EQ(shelf_widget->GetWindowBoundsInScreen(), shown_shelf_bounds);

  ui::LayerAnimationStoppedWaiter().Wait(shelf_widget->GetLayer());
  EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState());
}

TEST_P(DesksTest, SwitchToDeskWithSnappedActiveWindow) {
  auto* desks_controller = DesksController::Get();
  auto* overview_controller = OverviewController::Get();

  // Two virtual desks: |desk_1| (active) and |desk_2|.
  NewDesk();
  ASSERT_EQ(2u, desks_controller->desks().size());
  Desk* desk_1 = desks_controller->GetDeskAtIndex(0);
  Desk* desk_2 = desks_controller->GetDeskAtIndex(1);

  // Two windows on |desk_1|: |win0| (snapped) and |win1|.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  WindowState* win0_state = WindowState::Get(win0.get());
  WindowSnapWMEvent snap_to_left(WM_EVENT_CYCLE_SNAP_PRIMARY);
  win0_state->OnWMEvent(&snap_to_left);
  EXPECT_EQ(chromeos::WindowStateType::kPrimarySnapped,
            win0_state->GetStateType());

  // Switch to |desk_2| and then back to |desk_1|. Verify that neither split
  // view nor overview arises.
  auto* split_view_controller =
      SplitViewController::Get(Shell::GetPrimaryRootWindow());
  EXPECT_FALSE(split_view_controller->InSplitViewMode());
  EXPECT_FALSE(overview_controller->InOverviewSession());
  ActivateDesk(desk_2);
  EXPECT_FALSE(split_view_controller->InSplitViewMode());
  EXPECT_FALSE(overview_controller->InOverviewSession());
  ActivateDesk(desk_1);
  EXPECT_FALSE(split_view_controller->InSplitViewMode());
  EXPECT_FALSE(overview_controller->InOverviewSession());
}

TEST_P(DesksTest, SuccessfulDragToDeskRemovesSplitViewIndicators) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(window.get());
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());

  auto* overview_session = overview_controller->overview_session();
  auto* overview_item =
      overview_session->GetOverviewItemForWindow(window.get());
  ASSERT_TRUE(overview_item);
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_EQ(2u, desks_bar_view->mini_views().size());

  // Drag it to desk_2's mini_view. The overview grid should now show the
  // "no-windows" widget, and the window should move to desk_2.
  auto* desk_2_mini_view = desks_bar_view->mini_views()[1].get();
  DragItemToPoint(overview_item,
                  desk_2_mini_view->GetBoundsInScreen().CenterPoint(),
                  GetEventGenerator(),
                  /*by_touch_gestures=*/false,
                  /*drop=*/false);
  // Validate that before dropping, the SplitView indicators and the drop target
  // widget are created.
  EXPECT_TRUE(overview_grid->drop_target());
  EXPECT_EQ(SplitViewDragIndicators::WindowDraggingState::kFromOverview,
            overview_session->grid_list()[0]
                ->split_view_drag_indicators()
                ->current_window_dragging_state());
  // Now drop the window, and validate the indicators and the drop target were
  // removed.
  GetEventGenerator()->ReleaseLeftButton();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  EXPECT_TRUE(overview_grid->empty());
  EXPECT_FALSE(DoesActiveDeskContainWindow(window.get()));
  EXPECT_TRUE(overview_grid->no_windows_widget());
  EXPECT_FALSE(overview_grid->drop_target());
  EXPECT_EQ(SplitViewDragIndicators::WindowDraggingState::kNoDrag,
            overview_session->grid_list()[0]
                ->split_view_drag_indicators()
                ->current_window_dragging_state());
}

TEST_P(DesksTest, DragAllOverviewWindowsToOtherDesksNotEndClamshellSplitView) {
  // Two virtual desks.
  NewDesk();
  ASSERT_EQ(2u, DesksController::Get()->desks().size());

  // Two windows: |win0| (in clamshell split view) and |win1| (in overview).
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  auto* overview_controller = OverviewController::Get();
  ASSERT_TRUE(EnterOverview());
  auto* overview_session = overview_controller->overview_session();
  auto* generator = GetEventGenerator();
  DragItemToPoint(overview_session->GetOverviewItemForWindow(win0.get()),
                  gfx::Point(0, 0), generator);
  ASSERT_TRUE(overview_controller->InOverviewSession());
  auto* split_view_controller =
      SplitViewController::Get(Shell::GetPrimaryRootWindow());
  EXPECT_TRUE(split_view_controller->InSplitViewMode());
  EXPECT_TRUE(RootWindowController::ForWindow(win0.get())
                  ->split_view_overview_session());

  // Drag |win1| to the other desk.
  DragItemToPoint(overview_session->GetOverviewItemForWindow(win1.get()),
                  GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())
                      ->desks_bar_view()
                      ->mini_views()[1]
                      ->GetBoundsInScreen()
                      .CenterPoint(),
                  generator);
  EXPECT_FALSE(DoesActiveDeskContainWindow(win1.get()));

  // Overview should now be empty, but split view should still be active.
  ASSERT_TRUE(overview_controller->InOverviewSession());
  EXPECT_TRUE(overview_session->IsEmpty());
  EXPECT_TRUE(split_view_controller->InSplitViewMode());
}

TEST_P(DesksTest, DeskTraversalNonTouchpadMetrics) {
  NewDesk();
  NewDesk();
  NewDesk();
  ASSERT_EQ(4u, DesksController::Get()->desks().size());

  constexpr char kDeskTraversalsHistogramName[] =
      "Ash.Desks.NumberOfDeskTraversals";

  base::HistogramTester histogram_tester;
  auto* controller = DesksController::Get();
  const auto& desks = controller->desks();
  ASSERT_EQ(controller->active_desk(), desks[0].get());

  // Move 5 desks. There is nothing recorded at the end since the timer is still
  // running.
  ActivateDesk(desks[1].get());
  ActivateDesk(desks[0].get());
  ActivateDesk(desks[1].get());
  ActivateDesk(desks[2].get());
  ActivateDesk(desks[3].get());
  histogram_tester.ExpectBucketCount(kDeskTraversalsHistogramName, 5, 0);

  // Simulate advancing the time to end the timer. There should be 5 desks
  // recorded.
  controller->FireMetricsTimerForTesting();
  histogram_tester.ExpectBucketCount(kDeskTraversalsHistogramName, 5, 1);
}

// Tests that clipping is unchanged when removing a desk in overview. Regression
// test for https://crbug.com/1166300.
TEST_P(DesksTest, RemoveDeskPreservesOverviewClipping) {
  // Three virtual desks.
  NewDesk();
  NewDesk();

  auto* controller = DesksController::Get();
  Desk* desk2 = controller->GetDeskAtIndex(1);
  Desk* desk3 = controller->GetDeskAtIndex(2);
  ActivateDesk(desk3);

  // Create a window on |desk3| with a header.
  const int header_height = 32;
  auto win0 = CreateAppWindow(gfx::Rect(200, 200));
  win0->SetProperty(aura::client::kTopViewInset, header_height);
  EXPECT_EQ(desk3->GetDeskContainerForRoot(Shell::GetPrimaryRootWindow()),
            win0->parent());

  ASSERT_TRUE(EnterOverview());
  const gfx::Rect expected_clip = win0->layer()->GetTargetClipRect();

  // Remove |desk3|. |win0| is now a child of |desk2|.
  RemoveDesk(desk3);
  ASSERT_EQ(desk2->GetDeskContainerForRoot(Shell::GetPrimaryRootWindow()),
            win0->parent());

  // Tests that the clip is the same after the desk removal.
  EXPECT_EQ(expected_clip, win0->layer()->GetTargetClipRect());
}

struct PerDeskZOrderTestCase {
  std::string test_name;

  // True when we want to run the test with multiple displays.
  bool multi_display;

  // Numerical identifiers of windows on desk 1 and 2, grouped by root window.
  // Windows will be stacked in the order they appear, with .back() at top.
  std::vector<std::vector<int>> desk_1_windows;
  std::vector<std::vector<int>> desk_2_windows;

  // Numerical identifiers of all-desk windows. Entries must match windows in
  // `desk_1_windows`.
  std::set<int> adw_windows;

  // Windows to activate in order.
  std::vector<int> activate_windows;

  // Once windows have been created and (some) promoted to all-desk, we start
  // the test by switching to desk 2. This is the list of windows that we expect
  // to find on desk 1/2, grouped by root window.
  std::vector<std::vector<int>> expected_desk_1_windows_before;
  std::vector<std::vector<int>> expected_desk_2_windows_before;

  // We can then move some set of windows from desk 2 to desk 1. This must be a
  // subset of `desk_2_windows` and cannot contain entries from `adw_windows`
  // (since those not logically part of a specific desk). Prior to moving, the
  // window will be activated (to simulate the user interacting with it), and
  // this will push it to the front of the MRU list.
  std::vector<int> move_windows;

  // Windows to move from the first display to the second. This can include both
  // normal and adw windows.
  std::vector<int> move_windows_to_other_display;

  // Windows to close while on the second desk. Can include any windows.
  std::vector<int> close_windows;

  // We then switch back to desk 1 and expect to find windows in this order,
  // grouped by root window.
  std::vector<std::vector<int>> expected_desk_1_windows_after;
  std::vector<std::vector<int>> expected_desk_2_windows_after;

  // This is the window we expect to be active after we switch back to desk 1.
  int expected_desk_1_final_active_window;
};

class DesksPerDeskZOrderTest : public AshTestBase {
 public:
  DesksPerDeskZOrderTest() = default;
  ~DesksPerDeskZOrderTest() override = default;

  // AshTestBase:
  void SetUp() override {
    AshTestBase::SetUp();

    // Start the test with two desks.
    NewDesk();
  }

  void RunTests(const std::vector<PerDeskZOrderTestCase>& tests) {
    auto* controller = DesksController::Get();
    auto* desk_1 = controller->GetDeskAtIndex(0);
    auto* desk_2 = controller->GetDeskAtIndex(1);

    for (const auto& test : tests) {
      SCOPED_TRACE(test.test_name);

      if (test.multi_display) {
        UpdateDisplay("700x600,400x500");
      } else {
        UpdateDisplay("700x600");
      }

      // This is only used for multi-displays tests and will in those cases
      // represent the secondary display.
      display::Display secondary_display =
          display::Screen::GetScreen()->GetAllDisplays().back();

      std::map<int, std::unique_ptr<aura::Window>> id_to_window;
      std::map<aura::Window*, int> window_to_id;

      auto populate_desk =
          [&](Desk* desk, const std::vector<std::vector<int>>& desk_windows) {
            SCOPED_TRACE("Create windows for " +
                         base::UTF16ToUTF8(desk->name()));

            // Verify we are on the correct desk.
            ASSERT_TRUE(desk->is_active());

            int offset = 0;
            for (const auto& window_ids : desk_windows) {
              for (int id : window_ids) {
                auto window =
                    CreateAppWindow(gfx::Rect(offset + id, 0 + id, 100, 100));
                window->SetTitle(u"TestWindow" + base::NumberToString16(id));
                window_to_id[window.get()] = id;
                id_to_window[id] = std::move(window);
              }
              // Increment the offset to ensure that the window will be created
              // on the next root window.
              offset += secondary_display.bounds().x();
            }
          };

      // Populate each of the desks with the desired windows.
      populate_desk(desk_1, test.desk_1_windows);
      ActivateDesk(desk_2);
      populate_desk(desk_2, test.desk_2_windows);
      ActivateDesk(desk_1);

      // Mark windows as awd.
      for (int id : test.adw_windows) {
        views::Widget::GetWidgetForNativeWindow(id_to_window.at(id).get())
            ->SetVisibleOnAllWorkspaces(true);
      }

      for (int id : test.activate_windows) {
        wm::ActivateWindow(id_to_window.at(id).get());
      }

      // Verifies that the desk preview for the given root window is consistent
      // with the expected per-desk Z-order. Since the layers are mirrored
      // instead of the same instances, we verify by layer bounds here.
      auto verify_desk_preview_mirrored_layer_tree =
          [&](Desk* desk, aura::Window* root,
              const std::vector<int>& expected_windows,
              const std::string& debug_info) {
            SCOPED_TRACE("Verify " + base::UTF16ToUTF8(desk->name()) + " " +
                         root->GetName() + " " + debug_info);
            ToggleOverview();

            // Retrieves the mirrored layers `mirrored_layers` of application
            // windows for `desk`. The root of `layer_tree_owner` is a layer
            // that has only one child, and the only child acts as the parent of
            // all the mirrored layers of application windows.
            const ui::LayerTreeOwner* layer_tree_owner =
                DesksTestApi::GetMirroredContentsLayerTreeForRootAndDesk(root,
                                                                         desk);
            const std::vector<raw_ptr<ui::Layer, VectorExperimental>>
                mirrored_layers =
                    layer_tree_owner->root()->children().front()->children();

            // Tests that `mirrored_layers` and `expected_windows` are sync'ed.
            ASSERT_EQ(expected_windows.size(), mirrored_layers.size());

            std::vector<gfx::Rect> actual_bounds, expected_bounds;
            for (size_t i = 0; i < expected_windows.size(); i++) {
              expected_bounds.push_back(
                  id_to_window[expected_windows[i]]->layer()->bounds());
              actual_bounds.push_back(mirrored_layers[i]->bounds());
            }
            EXPECT_THAT(actual_bounds, ElementsAreArray(expected_bounds));

            ToggleOverview();
          };

      // Verifies that windows on the given desk and root window are found in
      // the expected order. Any windows that have not been created by the test
      // will be ignored.
      auto verify_windows = [&](Desk* desk, aura::Window* root,
                                const std::vector<int>& expected_windows,
                                const std::string& debug_info) {
        aura::Window* container = desk->GetDeskContainerForRoot(root);

        // Collect any test windows present on the desk.
        std::vector<int> actual_windows;
        for (aura::Window* child : container->children()) {
          auto it = window_to_id.find(child);
          if (it != window_to_id.end()) {
            actual_windows.push_back(it->second);
          }
        }

        ASSERT_EQ(expected_windows, actual_windows)
            << "Window mismatch " << debug_info << " on " << root->GetName()
            << ":" << desk->name();
      };

      auto root_windows = Shell::GetAllRootWindows();
      ASSERT_EQ(test.multi_display ? 2u : 1u, root_windows.size());

      // Now we are ready to actually execute the test.
      ActivateDesk(desk_2);
      for (size_t i = 0; i < root_windows.size(); i++) {
        verify_windows(desk_2, root_windows[i],
                       test.expected_desk_2_windows_before[i], "before moving");
        verify_desk_preview_mirrored_layer_tree(
            desk_1, root_windows[i], test.expected_desk_1_windows_before[i],
            "before");
        verify_desk_preview_mirrored_layer_tree(
            desk_2, root_windows[i], test.expected_desk_2_windows_before[i],
            "before");
      }

      // Move specified windows to desk 1.
      for (int id : test.move_windows) {
        const auto& window = id_to_window.at(id);
        wm::ActivateWindow(window.get());
        ASSERT_TRUE(controller->MoveWindowFromActiveDeskTo(
            window.get(), desk_1, window.get()->GetRootWindow(),
            DesksMoveWindowFromActiveDeskSource::kShortcut));
      }

      // Move specified windows to display 2.
      for (int id : test.move_windows_to_other_display) {
        const auto& window = id_to_window.at(id);
        aura::Window* root_before_moving = window->GetRootWindow();
        auto bounds = window->GetBoundsInScreen();
        bounds.Offset(secondary_display.bounds().origin().x(), 0);
        window->SetBoundsInScreen(bounds, secondary_display);
        ASSERT_NE(root_before_moving, window->GetRootWindow());
      }

      // Close specified windows.
      for (int id : test.close_windows) {
        auto it = id_to_window.find(id);
        ASSERT_NE(it, id_to_window.end()) << "Test setup error";
        window_to_id.erase(it->second.get());
        id_to_window.erase(it);
      }

      ActivateDesk(desk_1);
      for (size_t i = 0; i < root_windows.size(); i++) {
        verify_windows(desk_1, root_windows[i],
                       test.expected_desk_1_windows_after[i], "after moving");
        verify_desk_preview_mirrored_layer_tree(
            desk_1, root_windows[i], test.expected_desk_1_windows_after[i],
            "after");
        verify_desk_preview_mirrored_layer_tree(
            desk_2, root_windows[i], test.expected_desk_2_windows_after[i],
            "after");
      }

      // Verify that the correct window is activated. This is particularly
      // important for when we have all desk windows and multiple displays.
      // Please refer to b/274110274.
      int actual_active_window_id = -1;
      auto active_window_it = window_to_id.find(window_util::GetActiveWindow());
      if (active_window_it != window_to_id.end()) {
        actual_active_window_id = active_window_it->second;
      }
      ASSERT_EQ(test.expected_desk_1_final_active_window,
                actual_active_window_id);
    }
  }
};

TEST_F(DesksPerDeskZOrderTest, SingleDisplay) {
  RunTests(std::vector<PerDeskZOrderTestCase>{
      {.test_name = "Single adw window 1",
       .desk_1_windows = {{1}},
       .desk_2_windows = {{}},
       .adw_windows = {1},
       .expected_desk_1_windows_before = {{1}},
       .expected_desk_2_windows_before = {{1}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}},
       .expected_desk_2_windows_after = {{1}},
       .expected_desk_1_final_active_window = 1},
      {.test_name = "Single adw window 2",
       .desk_1_windows = {{1, 2, 3}},
       .desk_2_windows = {{5, 4}},
       .adw_windows = {1},
       .expected_desk_1_windows_before = {{1, 2, 3}},
       .expected_desk_2_windows_before = {{5, 4, 1}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 2, 3}},
       .expected_desk_2_windows_after = {{5, 4, 1}},
       .expected_desk_1_final_active_window = 3},
      {.test_name = "Single adw window 3",
       .desk_1_windows = {{1, 2, 3}},
       .desk_2_windows = {{5, 4}},
       .adw_windows = {1},
       .expected_desk_1_windows_before = {{1, 2, 3}},
       .expected_desk_2_windows_before = {{5, 4, 1}},
       .move_windows = {5},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 2, 3, 5}},
       .expected_desk_2_windows_after = {{4, 1}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Single adw window 4",
       .desk_1_windows = {{1, 2, 3}},
       .desk_2_windows = {{5, 4}},
       .adw_windows = {2},
       .expected_desk_1_windows_before = {{1, 2, 3}},
       .expected_desk_2_windows_before = {{5, 4, 2}},
       .move_windows = {5},
       .close_windows = {1},
       .expected_desk_1_windows_after = {{2, 3, 5}},
       .expected_desk_2_windows_after = {{4, 2}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Single adw window 5",
       .desk_1_windows = {{1, 2, 3, 4, 5}},
       .desk_2_windows = {{6}},
       .adw_windows = {3},
       .expected_desk_1_windows_before = {{1, 2, 3, 4, 5}},
       .expected_desk_2_windows_before = {{6, 3}},
       .move_windows = {6},
       .close_windows = {1, 2},
       .expected_desk_1_windows_after = {{3, 4, 5, 6}},
       .expected_desk_2_windows_after = {{3}},
       .expected_desk_1_final_active_window = 6},
      {.test_name = "Multiple adw windows 1",
       .desk_1_windows = {{1, 2, 3, 4, 5}},
       .desk_2_windows = {{6, 7}},
       .adw_windows = {2, 4},
       .expected_desk_1_windows_before = {{1, 2, 3, 4, 5}},
       .expected_desk_2_windows_before = {{6, 7, 2, 4}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 2, 3, 4, 5}},
       .expected_desk_2_windows_after = {{6, 7, 2, 4}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Multiple adw windows 2",
       .desk_1_windows = {{1, 2, 3, 4, 5}},
       .desk_2_windows = {{6, 7}},
       .adw_windows = {1, 3, 5},
       .expected_desk_1_windows_before = {{1, 2, 3, 4, 5}},
       .expected_desk_2_windows_before = {{6, 7, 1, 3, 5}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 2, 3, 4, 5}},
       .expected_desk_2_windows_after = {{6, 7, 1, 3, 5}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Multiple adw windows 3",
       .desk_1_windows = {{1, 2}},
       .desk_2_windows = {{}},
       .adw_windows = {1, 2},
       .expected_desk_1_windows_before = {{1, 2}},
       .expected_desk_2_windows_before = {{1, 2}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 2}},
       .expected_desk_2_windows_after = {{1, 2}},
       .expected_desk_1_final_active_window = 2},
      {.test_name = "Multiple adw windows 4",
       .desk_1_windows = {{1, 2, 3, 4}},
       .desk_2_windows = {{}},
       .adw_windows = {1, 4},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{4, 3, 2, 1}},
       .expected_desk_2_windows_before = {{1, 4}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{4, 3, 2, 1}},
       .expected_desk_2_windows_after = {{1, 4}},
       .expected_desk_1_final_active_window = 1},
      {.test_name = "Multiple adw windows 5",
       .desk_1_windows = {{1, 2, 3, 4}},
       .desk_2_windows = {{5}},
       .adw_windows = {1, 3},
       .activate_windows = {1, 2, 3, 4},
       .expected_desk_1_windows_before = {{1, 2, 3, 4}},
       .expected_desk_2_windows_before = {{5, 1, 3}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 2, 3, 4}},
       .expected_desk_2_windows_after = {{5, 1, 3}},
       .expected_desk_1_final_active_window = 4},
  });
}

TEST_F(DesksPerDeskZOrderTest, MultiDisplaySingleADW) {
  RunTests(std::vector<PerDeskZOrderTestCase>{
      {.test_name = "Multiple displays single adw 1",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1},
       .activate_windows = {1, 2, 3, 4},
       .expected_desk_1_windows_before = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_before = {{1}, {5}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_after = {{1}, {5}},
       .expected_desk_1_final_active_window = 4},
      {.test_name = "Multiple displays single adw 2",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1},
       .activate_windows = {1, 2, 3, 4},
       .expected_desk_1_windows_before = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_before = {{1}, {5}},
       .move_windows = {},
       .close_windows = {1},
       .expected_desk_1_windows_after = {{}, {2, 3, 4}},
       .expected_desk_2_windows_after = {{}, {5}},
       .expected_desk_1_final_active_window = 4},
      {.test_name = "Multiple displays single adw 3",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_before = {{1}, {5}},
       .move_windows = {},
       .close_windows = {1},
       .expected_desk_1_windows_after = {{}, {4, 3, 2}},
       .expected_desk_2_windows_after = {{}, {5}},
       .expected_desk_1_final_active_window = 2},
      {.test_name = "Multiple displays single adw 4",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_before = {{1}, {5}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_after = {{1}, {5}},
       .expected_desk_1_final_active_window = 1},
      {.test_name = "Multiple displays single adw 5",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {4},
       .activate_windows = {1, 2, 4, 3},
       .expected_desk_1_windows_before = {{1}, {2, 4, 3}},
       .expected_desk_2_windows_before = {{}, {5, 4}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {2, 4, 3}},
       .expected_desk_2_windows_after = {{}, {5, 4}},
       .expected_desk_1_final_active_window = 3},
      {.test_name = "Multiple displays single adw 6",
       .multi_display = true,
       .desk_1_windows = {{1, 2}, {3, 4}},
       .desk_2_windows = {{5}, {6}},
       .adw_windows = {3},
       .activate_windows = {1, 2, 3, 4},
       .expected_desk_1_windows_before = {{1, 2}, {3, 4}},
       .expected_desk_2_windows_before = {{5}, {6, 3}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 2}, {3, 4}},
       .expected_desk_2_windows_after = {{5}, {6, 3}},
       .expected_desk_1_final_active_window = 4},
      {.test_name = "Multiple displays single adw 7",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_before = {{1}, {5}},
       .move_windows = {5},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {4, 3, 2, 5}},
       .expected_desk_2_windows_after = {{1}, {}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Multiple displays single adw 8",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{5}, {}},
       .adw_windows = {1},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_before = {{5, 1}, {}},
       .move_windows = {5},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 5}, {4, 3, 2}},
       .expected_desk_2_windows_after = {{1}, {}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Multiple displays single adw 9",
       .multi_display = true,
       .desk_1_windows = {{}, {1, 2, 3}},
       .desk_2_windows = {{}, {}},
       .adw_windows = {1},
       .expected_desk_1_windows_before = {{}, {1, 2, 3}},
       .expected_desk_2_windows_before = {{}, {1}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{}, {1, 2, 3}},
       .expected_desk_2_windows_after = {{}, {1}},
       .expected_desk_1_final_active_window = 3},
      {.test_name = "Multiple displays single adw 10",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{5}, {}},
       .adw_windows = {4},
       .activate_windows = {1, 4, 3, 2},
       .expected_desk_1_windows_before = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_before = {{5}, {4}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_after = {{5}, {4}},
       .expected_desk_1_final_active_window = 2},
  });
}

TEST_F(DesksPerDeskZOrderTest, MultiDisplayMultipleADW) {
  RunTests(std::vector<PerDeskZOrderTestCase>{
      {.test_name = "Multiple displays multiple adw 1",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1, 4},
       .activate_windows = {1, 2, 3, 4},
       .expected_desk_1_windows_before = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_before = {{1}, {5, 4}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_after = {{1}, {5, 4}},
       .expected_desk_1_final_active_window = 4},
      {.test_name = "Multiple displays multiple adw 2",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1, 4},
       .activate_windows = {2, 3, 4, 1},
       .expected_desk_1_windows_before = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_before = {{1}, {5, 4}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_after = {{1}, {5, 4}},
       .expected_desk_1_final_active_window = 1},
      {.test_name = "Multiple displays multiple adw 3",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1, 4},
       .activate_windows = {1, 2, 3, 4},
       .expected_desk_1_windows_before = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_before = {{1}, {5, 4}},
       .move_windows = {},
       .close_windows = {1},
       .expected_desk_1_windows_after = {{}, {2, 3, 4}},
       .expected_desk_2_windows_after = {{}, {5, 4}},
       .expected_desk_1_final_active_window = 4},
      {.test_name = "Multiple displays multiple adw 4",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1, 4},
       .activate_windows = {2, 3, 4, 1},
       .expected_desk_1_windows_before = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_before = {{1}, {5, 4}},
       .move_windows = {},
       .close_windows = {1},
       .expected_desk_1_windows_after = {{}, {2, 3, 4}},
       .expected_desk_2_windows_after = {{}, {5, 4}},
       .expected_desk_1_final_active_window = 4},
      {.test_name = "Multiple displays multiple adw 5",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1, 4},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_before = {{1}, {5, 4}},
       .move_windows = {},
       .close_windows = {4},
       .expected_desk_1_windows_after = {{1}, {3, 2}},
       .expected_desk_2_windows_after = {{1}, {5}},
       .expected_desk_1_final_active_window = 1},
      {.test_name = "Multiple displays multiple adw 6",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1, 4},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_before = {{1}, {5, 4}},
       .move_windows = {5},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {4, 3, 2, 5}},
       .expected_desk_2_windows_after = {{1}, {4}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Multiple displays multiple adw 7",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1, 4},
       .activate_windows = {1, 2, 3, 4},
       .expected_desk_1_windows_before = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_before = {{1}, {5, 4}},
       .move_windows = {5},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {2, 3, 4, 5}},
       .expected_desk_2_windows_after = {{1}, {4}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Multiple displays multiple adw 8",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{5}, {}},
       .adw_windows = {1, 4},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{1}, {4, 3, 2}},
       .expected_desk_2_windows_before = {{5, 1}, {4}},
       .move_windows = {5},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 5}, {4, 3, 2}},
       .expected_desk_2_windows_after = {{1}, {4}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Multiple displays multiple adw 9",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{5}, {}},
       .adw_windows = {1, 4},
       .activate_windows = {1, 2, 3, 4},
       .expected_desk_1_windows_before = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_before = {{5, 1}, {4}},
       .move_windows = {5},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1, 5}, {2, 3, 4}},
       .expected_desk_2_windows_after = {{1}, {4}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Multiple displays multiple adw on same root 1",
       .multi_display = true,
       .desk_1_windows = {{1, 2}, {3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1, 2},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{2, 1}, {4, 3}},
       .expected_desk_2_windows_before = {{1, 2}, {5}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{2, 1}, {4, 3}},
       .expected_desk_2_windows_after = {{1, 2}, {5}},
       .expected_desk_1_final_active_window = 1},
      {.test_name = "Multiple displays multiple adw on same root 2",
       .multi_display = true,
       .desk_1_windows = {{1, 2}, {3, 4}},
       .desk_2_windows = {{5}, {}},
       .adw_windows = {1, 2},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{2, 1}, {4, 3}},
       .expected_desk_2_windows_before = {{5, 1, 2}, {}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{2, 1}, {4, 3}},
       .expected_desk_2_windows_after = {{5, 1, 2}, {}},
       .expected_desk_1_final_active_window = 1},
      {.test_name = "Multiple displays multiple adw on same root 3",
       .multi_display = true,
       .desk_1_windows = {{1, 2}, {3, 4}},
       .desk_2_windows = {{}, {5}},
       .adw_windows = {1, 2},
       .activate_windows = {4, 3, 2, 1},
       .expected_desk_1_windows_before = {{2, 1}, {4, 3}},
       .expected_desk_2_windows_before = {{1, 2}, {5}},
       .move_windows = {5},
       .close_windows = {},
       .expected_desk_1_windows_after = {{2, 1}, {4, 3, 5}},
       .expected_desk_2_windows_after = {{1, 2}, {}},
       .expected_desk_1_final_active_window = 5},
      {.test_name = "Multiple displays multiple adw on same root 4",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{5}, {}},
       .adw_windows = {3, 4},
       .activate_windows = {1, 2, 3, 4},
       .expected_desk_1_windows_before = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_before = {{5}, {3, 4}},
       .move_windows = {},
       .close_windows = {},
       .expected_desk_1_windows_after = {{1}, {2, 3, 4}},
       .expected_desk_2_windows_after = {{5}, {3, 4}},
       .expected_desk_1_final_active_window = 4},
  });
}

TEST_F(DesksPerDeskZOrderTest, MultiDisplayMultipleAdwWithMoving) {
  RunTests(std::vector<PerDeskZOrderTestCase>{
      {.test_name = "Multiple displays moving windows 1",
       .multi_display = true,
       .desk_1_windows = {{1}, {}},
       .desk_2_windows = {{}, {}},
       .adw_windows = {1},
       .activate_windows = {1},
       .expected_desk_1_windows_before = {{1}, {}},
       .expected_desk_2_windows_before = {{1}, {}},
       .move_windows = {},
       .move_windows_to_other_display = {1},
       .close_windows = {},
       .expected_desk_1_windows_after = {{}, {1}},
       .expected_desk_2_windows_after = {{}, {1}},
       .expected_desk_1_final_active_window = 1},
      {.test_name = "Multiple displays moving windows 2",
       .multi_display = true,
       .desk_1_windows = {{1, 2}, {}},
       .desk_2_windows = {{}, {}},
       .adw_windows = {1, 2},
       .activate_windows = {1, 2},
       .expected_desk_1_windows_before = {{1, 2}, {}},
       .expected_desk_2_windows_before = {{1, 2}, {}},
       .move_windows = {},
       .move_windows_to_other_display = {1},
       .close_windows = {},
       .expected_desk_1_windows_after = {{2}, {1}},
       .expected_desk_2_windows_after = {{2}, {1}},
       .expected_desk_1_final_active_window = 1},
      {.test_name = "Multiple displays moving windows 3",
       .multi_display = true,
       .desk_1_windows = {{1}, {2, 3, 4}},
       .desk_2_windows = {{}, {}},
       .adw_windows = {1, 4},
       .activate_windows = {1, 2, 3},
       .expected_desk_1_windows_before = {{1}, {4, 2, 3}},
       .expected_desk_2_windows_before = {{1}, {4}},
       .move_windows = {},
       .move_windows_to_other_display = {1},
       .close_windows = {},
       .expected_desk_1_windows_after = {{}, {4, 2, 3, 1}},
       .expected_desk_2_windows_after = {{}, {1, 4}},
       .expected_desk_1_final_active_window = 1},
  });
}

using FloatAllDesksWithZOrderTest = AshTestBase;

// Tests that floating a window that is already visible on all desks removes its
// z-ordering data, and unfloating the window restores the data.
TEST_F(FloatAllDesksWithZOrderTest, TrackOrderAfterUnfloat) {
  // Start the test with two desks.
  NewDesk();

  // Create a window that is visible on both desks.
  auto window = CreateAppWindow();
  views::Widget::GetWidgetForNativeWindow(window.get())
      ->SetVisibleOnAllWorkspaces(true);
  auto* desks_controller = DesksController::Get();
  ASSERT_EQ(1u, desks_controller->visible_on_all_desks_windows().size());
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));
  EXPECT_TRUE(desks_util::BelongsToActiveDesk(window.get()));

  // Each desk should be tracking the window's z-ordering data.
  for (auto& desk : desks_controller->desks()) {
    for (aura::Window* root : Shell::GetAllRootWindows()) {
      auto& adw_data = desk->all_desk_window_stacking().at(root);
      ASSERT_EQ(adw_data.size(), 1u);
      ASSERT_EQ(adw_data.begin()->window, window.get());
    }
  }

  // Float the window.
  PressAndReleaseKey(ui::VKEY_F, ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN);
  EXPECT_TRUE(WindowState::Get(window.get())->IsFloated());

  // The desks are no longer tracking the window's z-ordering data.
  for (auto& desk : desks_controller->desks()) {
    for (aura::Window* root : Shell::GetAllRootWindows()) {
      auto& adw_data = desk->all_desk_window_stacking().at(root);
      ASSERT_EQ(adw_data.size(), 0u);
    }
  }
}

// Tests that sending a floated window to all desks then restoring it to a
// single desk works as intended.
TEST_F(FloatAllDesksWithZOrderTest, FloatThenAllDesks) {
  // Start the test with two desks.
  NewDesk();

  // Create a floated window.
  auto window = CreateAppWindow();
  PressAndReleaseKey(ui::VKEY_F, ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN);
  EXPECT_TRUE(WindowState::Get(window.get())->IsFloated());

  // Send the floated window to all desks.
  views::Widget::GetWidgetForNativeWindow(window.get())
      ->SetVisibleOnAllWorkspaces(true);
  auto* desks_controller = DesksController::Get();
  ASSERT_EQ(1u, desks_controller->visible_on_all_desks_windows().size());

  // The desks are not tracking the window's z-ordering data.
  for (auto& desk : desks_controller->desks()) {
    desk->all_desk_window_stacking().empty();
  }

  // Restore the floated window back to a single desk.
  views::Widget::GetWidgetForNativeWindow(window.get())
      ->SetVisibleOnAllWorkspaces(false);
  ASSERT_EQ(0u, desks_controller->visible_on_all_desks_windows().size());
}

// Regression test for b/345815639.
TEST_F(FloatAllDesksWithZOrderTest, AllDesksThenFloatThenClose) {
  // Start the test with two desks.
  NewDesk();

  auto window = CreateAppWindow();

  // Make the window visible on all desks.
  views::Widget::GetWidgetForNativeWindow(window.get())
      ->SetVisibleOnAllWorkspaces(true);

  // Float the window and then close it.
  PressAndReleaseKey(ui::VKEY_F, ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN);
  EXPECT_TRUE(WindowState::Get(window.get())->IsFloated());
  window.reset();

  // Then switch desks.
  ActivateDesk(DesksController::Get()->GetDeskAtIndex(1));
}

constexpr char kUser1Email[] = "user1@desks";
constexpr char kUser2Email[] = "user2@desks";

class DesksMultiUserTest : public NoSessionAshTestBase,
                           public MultiUserWindowManagerDelegate {
 public:
  DesksMultiUserTest() = default;

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

  ~DesksMultiUserTest() override = default;

  MultiUserWindowManager* multi_user_window_manager() {
    return multi_user_window_manager_.get();
  }
  TestingPrefServiceSimple* user_1_prefs() { return user_1_prefs_; }
  TestingPrefServiceSimple* user_2_prefs() { return user_2_prefs_; }

  // AshTestBase:
  void SetUp() override {
    NoSessionAshTestBase::SetUp();

    TestSessionControllerClient* session_controller =
        GetSessionControllerClient();
    session_controller->Reset();

    // Inject our own PrefServices for each user which enables us to setup the
    // desks restore data before the user signs in.
    auto user_1_prefs = std::make_unique<TestingPrefServiceSimple>();
    user_1_prefs_ = user_1_prefs.get();
    RegisterUserProfilePrefs(user_1_prefs_->registry(), /*country=*/"",
                             /*for_test=*/true);
    auto user_2_prefs = std::make_unique<TestingPrefServiceSimple>();
    user_2_prefs_ = user_2_prefs.get();
    RegisterUserProfilePrefs(user_2_prefs_->registry(), /*country=*/"",
                             /*for_test=*/true);
    session_controller->AddUserSession(kUser1Email,
                                       user_manager::UserType::kRegular,
                                       /*provide_pref_service=*/false);
    session_controller->SetUserPrefService(GetUser1AccountId(),
                                           std::move(user_1_prefs));
    session_controller->AddUserSession(kUser2Email,
                                       user_manager::UserType::kRegular,
                                       /*provide_pref_service=*/false);
    session_controller->SetUserPrefService(GetUser2AccountId(),
                                           std::move(user_2_prefs));
  }

  void TearDown() override {
    multi_user_window_manager_.reset();
    NoSessionAshTestBase::TearDown();
  }

  // MultiUserWindowManagerDelegate:
  void OnWindowOwnerEntryChanged(aura::Window* window,
                                 const AccountId& account_id,
                                 bool was_minimized,
                                 bool teleported) override {}
  void OnTransitionUserShelfToNewAccount() override {}

  AccountId GetUser1AccountId() const {
    return AccountId::FromUserEmail(kUser1Email);
  }

  AccountId GetUser2AccountId() const {
    return AccountId::FromUserEmail(kUser2Email);
  }

  void SwitchActiveUser(const AccountId& account_id) {
    GetSessionControllerClient()->SwitchActiveUser(account_id);
  }

  // Initializes the given |prefs| with a desks restore data of 3 desks, with
  // the third desk named "code", and the rest are default-named.
  void InitPrefsWithDesksRestoreData(PrefService* prefs) {
    InitPrefsWithDesksRestoreData(
        prefs, {std::string(), std::string(), std::string("code")});
  }

  // Initializes the given |prefs| with a desks restore data from the
  // |desk_names| list.
  void InitPrefsWithDesksRestoreData(PrefService* prefs,
                                     std::vector<std::string> desk_names) {
    DCHECK(prefs);
    ScopedListPrefUpdate update(prefs, prefs::kDesksNamesList);
    base::Value::List& pref_data = update.Get();
    ASSERT_TRUE(pref_data.empty());
    for (auto desk_name : desk_names) {
      pref_data.Append(desk_name);
    }
  }

  void SimulateUserLogin(const AccountId& account_id) {
    SwitchActiveUser(account_id);
    multi_user_window_manager_ =
        MultiUserWindowManager::Create(this, account_id);
    MultiUserWindowManagerImpl::Get()->SetAnimationSpeedForTest(
        MultiUserWindowManagerImpl::ANIMATION_SPEED_DISABLED);
    GetSessionControllerClient()->SetSessionState(
        session_manager::SessionState::ACTIVE);
  }

 private:
  std::unique_ptr<MultiUserWindowManager> multi_user_window_manager_;

  raw_ptr<TestingPrefServiceSimple, DanglingUntriaged> user_1_prefs_ = nullptr;
  raw_ptr<TestingPrefServiceSimple, DanglingUntriaged> user_2_prefs_ = nullptr;
};

TEST_F(DesksMultiUserTest, SwitchUsersBackAndForth) {
  SimulateUserLogin(GetUser1AccountId());
  auto* controller = DesksController::Get();
  NewDesk();
  NewDesk();
  ASSERT_EQ(3u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  Desk* desk_3 = controller->GetDeskAtIndex(2);
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  multi_user_window_manager()->SetWindowOwner(win0.get(), GetUser1AccountId());
  EXPECT_TRUE(win0->IsVisible());
  ActivateDesk(desk_2);
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  multi_user_window_manager()->SetWindowOwner(win1.get(), GetUser1AccountId());
  EXPECT_FALSE(win0->IsVisible());
  EXPECT_TRUE(win1->IsVisible());

  // Switch to user_2 and expect no windows from user_1 is visible regardless of
  // the desk.
  SwitchActiveUser(GetUser2AccountId());
  EXPECT_FALSE(win0->IsVisible());
  EXPECT_FALSE(win1->IsVisible());

  // Since this is the first time this user logs in, desk_1 will be activated
  // for this user.
  EXPECT_TRUE(desk_1->is_active());

  auto win2 = CreateAppWindow(gfx::Rect(0, 0, 250, 200));
  multi_user_window_manager()->SetWindowOwner(win2.get(), GetUser2AccountId());
  EXPECT_TRUE(win2->IsVisible());
  ActivateDesk(desk_3);
  auto win3 = CreateAppWindow(gfx::Rect(0, 0, 250, 200));
  multi_user_window_manager()->SetWindowOwner(win3.get(), GetUser2AccountId());
  EXPECT_FALSE(win0->IsVisible());
  EXPECT_FALSE(win1->IsVisible());
  EXPECT_FALSE(win2->IsVisible());
  EXPECT_TRUE(win3->IsVisible());

  // When switching back to user_1, the active desk should be restored to
  // desk_2.
  SwitchActiveUser(GetUser1AccountId());
  EXPECT_TRUE(desk_2->is_active());
  EXPECT_FALSE(win0->IsVisible());
  EXPECT_TRUE(win1->IsVisible());
  EXPECT_FALSE(win2->IsVisible());
  EXPECT_FALSE(win3->IsVisible());

  // When switching to user_2, the active desk should be restored to desk_3.
  SwitchActiveUser(GetUser2AccountId());
  EXPECT_TRUE(desk_3->is_active());
  EXPECT_FALSE(win0->IsVisible());
  EXPECT_FALSE(win1->IsVisible());
  EXPECT_FALSE(win2->IsVisible());
  EXPECT_TRUE(win3->IsVisible());
}

TEST_F(DesksMultiUserTest, RemoveDesks) {
  SimulateUserLogin(GetUser1AccountId());
  // Create two desks with several windows with different app types that
  // belong to different users.
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  multi_user_window_manager()->SetWindowOwner(win0.get(), GetUser1AccountId());
  EXPECT_TRUE(win0->IsVisible());
  ActivateDesk(desk_2);
  auto win1 = CreateAppWindow(gfx::Rect(50, 50, 200, 200));
  auto win2 =
      CreateAppWindow(gfx::Rect(50, 50, 200, 200), chromeos::AppType::ARC_APP);
  // Non-app window.
  auto win3 =
      CreateAppWindow(gfx::Rect(50, 50, 200, 200), chromeos::AppType::NON_APP);
  multi_user_window_manager()->SetWindowOwner(win2.get(), GetUser1AccountId());
  multi_user_window_manager()->SetWindowOwner(win1.get(), GetUser1AccountId());
  multi_user_window_manager()->SetWindowOwner(win3.get(), GetUser1AccountId());
  EXPECT_FALSE(win0->IsVisible());
  EXPECT_TRUE(win1->IsVisible());
  EXPECT_TRUE(win2->IsVisible());
  EXPECT_TRUE(win3->IsVisible());

  // Switch to user_2 and expect no windows from user_1 is visible regardless of
  // the desk.
  SwitchActiveUser(GetUser2AccountId());
  EXPECT_TRUE(desk_1->is_active());
  EXPECT_FALSE(win0->IsVisible());
  EXPECT_FALSE(win1->IsVisible());
  EXPECT_FALSE(win2->IsVisible());
  EXPECT_FALSE(win3->IsVisible());

  auto win4 = CreateAppWindow(gfx::Rect(0, 0, 250, 200));
  multi_user_window_manager()->SetWindowOwner(win4.get(), GetUser2AccountId());
  EXPECT_TRUE(win4->IsVisible());
  ActivateDesk(desk_2);
  auto win5 = CreateAppWindow(gfx::Rect(0, 0, 250, 200));
  multi_user_window_manager()->SetWindowOwner(win5.get(), GetUser2AccountId());
  EXPECT_FALSE(win0->IsVisible());
  EXPECT_FALSE(win1->IsVisible());
  EXPECT_FALSE(win2->IsVisible());
  EXPECT_FALSE(win3->IsVisible());
  EXPECT_FALSE(win4->IsVisible());
  EXPECT_TRUE(win5->IsVisible());

  // Delete desk_2, and expect all app windows move to desk_1.
  RemoveDesk(desk_2);
  EXPECT_TRUE(desk_1->is_active());
  auto* desk_1_container =
      desk_1->GetDeskContainerForRoot(Shell::GetPrimaryRootWindow());
  EXPECT_EQ(desk_1_container, win0->parent());
  EXPECT_EQ(desk_1_container, win1->parent());
  EXPECT_EQ(desk_1_container, win2->parent());
  // The non-app window didn't move.
  EXPECT_NE(desk_1_container, win3->parent());
  EXPECT_EQ(desk_1_container, win4->parent());
  EXPECT_EQ(desk_1_container, win5->parent());

  // Only user_2's window are visible.
  EXPECT_TRUE(win4->IsVisible());
  EXPECT_TRUE(win5->IsVisible());

  // The non-app window will always be hidden.
  EXPECT_FALSE(win3->IsVisible());

  // Switch to user_1 and expect the correct windows' visibility.
  SwitchActiveUser(GetUser1AccountId());
  EXPECT_TRUE(desk_1->is_active());
  EXPECT_TRUE(win0->IsVisible());
  EXPECT_TRUE(win1->IsVisible());
  EXPECT_TRUE(win2->IsVisible());
  EXPECT_FALSE(win3->IsVisible());

  // Create two more desks, switch to user_2, and activate the third desk.
  NewDesk();
  NewDesk();
  ASSERT_EQ(3u, controller->desks().size());
  desk_2 = controller->GetDeskAtIndex(1);
  Desk* desk_3 = controller->GetDeskAtIndex(2);
  SwitchActiveUser(GetUser2AccountId());
  ActivateDesk(desk_3);
  auto win6 = CreateAppWindow(gfx::Rect(0, 0, 250, 200));
  multi_user_window_manager()->SetWindowOwner(win5.get(), GetUser2AccountId());

  // Switch back to user_1, and remove the first desk. When switching back to
  // user_2 after that, we should see that what used to be the third desk is now
  // active.
  SwitchActiveUser(GetUser1AccountId());
  EXPECT_TRUE(desk_1->is_active());
  RemoveDesk(desk_1);
  SwitchActiveUser(GetUser2AccountId());
  EXPECT_TRUE(desk_3->is_active());
  EXPECT_TRUE(win6->IsVisible());
}

TEST_F(DesksMultiUserTest, SwitchingUsersEndsOverview) {
  SimulateUserLogin(GetUser1AccountId());
  OverviewController* overview_controller = OverviewController::Get();
  EXPECT_TRUE(EnterOverview());
  EXPECT_TRUE(overview_controller->InOverviewSession());
  SwitchActiveUser(GetUser2AccountId());
  EXPECT_FALSE(overview_controller->InOverviewSession());
}

using DesksRestoreMultiUserTest = DesksMultiUserTest;

TEST_F(DesksRestoreMultiUserTest, DesksRestoredFromPrimaryUserPrefsOnly) {
  constexpr int kDefaultActiveDesk = 0;
  constexpr int kUser1StoredActiveDesk = 2;
  InitPrefsWithDesksRestoreData(user_1_prefs());

  // Set the primary user1's active desk prefs to kUser1StoredActiveDesk.
  user_1_prefs()->SetInteger(prefs::kDesksActiveDesk, kUser1StoredActiveDesk);

  SimulateUserLogin(GetUser1AccountId());
  // User 1 is the first to login, hence the primary user.
  auto* controller = DesksController::Get();
  const auto& desks = controller->desks();

  auto verify_desks = [&](const std::string& trace_name) {
    SCOPED_TRACE(trace_name);
    EXPECT_EQ(3u, desks.size());
    EXPECT_EQ(u"Desk 1", desks[0]->name());
    EXPECT_EQ(u"Desk 2", desks[1]->name());
    EXPECT_EQ(u"code", desks[2]->name());
    // Restored non-default names should be marked as `set_by_user`.
    EXPECT_FALSE(desks[0]->is_name_set_by_user());
    EXPECT_FALSE(desks[1]->is_name_set_by_user());
    EXPECT_TRUE(desks[2]->is_name_set_by_user());
  };

  verify_desks("Before switching users");
  // The primary user1 should restore the saved active desk from its pref.
  EXPECT_EQ(desks[kUser1StoredActiveDesk]->container_id(),
            desks_util::GetActiveDeskContainerId());

  // Switching users should not change anything as restoring happens only at
  // the time when the first user signs in.
  SwitchActiveUser(GetUser2AccountId());
  verify_desks("After switching users");
  // The secondary user2 should start with a default active desk.
  EXPECT_EQ(desks[kDefaultActiveDesk]->container_id(),
            desks_util::GetActiveDeskContainerId());

  // Activating the second desk in the secondary user session should not
  // affect the primary user1's active desk pref. Moreover, switching back to
  // user1 session should activate the user1's previously active desk
  // correctly.
  ActivateDesk(desks[1].get());
  EXPECT_EQ(user_1_prefs()->GetInteger(prefs::kDesksActiveDesk),
            kUser1StoredActiveDesk);
  SwitchActiveUser(GetUser1AccountId());
  EXPECT_EQ(desks[kUser1StoredActiveDesk]->container_id(),
            desks_util::GetActiveDeskContainerId());
}

TEST_F(DesksRestoreMultiUserTest,
       ChangesMadeBySecondaryUserAffectsOnlyPrimaryUserPrefs) {
  InitPrefsWithDesksRestoreData(user_1_prefs());
  SimulateUserLogin(GetUser1AccountId());

  auto* controller = DesksController::Get();
  const auto& desks = controller->desks();
  ASSERT_EQ(3u, desks.size());

  // Activate the last desk and verify that this is reflected in prefs.
  ActivateDesk(controller->desks().back().get());
  EXPECT_EQ(user_1_prefs()->GetInteger(prefs::kDesksActiveDesk), 2);

  // Switch to user 2 (secondary) and make some desks changes. Those changes
  // should be persisted to user 1's prefs only.
  SwitchActiveUser(GetUser2AccountId());

  // Create a fourth desk.
  NewDesk();
  EXPECT_THAT(GetDeskRestoreNames(user_1_prefs()),
              ElementsAre("", "", "code", ""));

  // User 2's prefs are unaffected (empty list of desks).
  EXPECT_THAT(GetDeskRestoreNames(user_2_prefs()), ElementsAre());

  // Delete the second desk.
  RemoveDesk(desks[1].get());
  EXPECT_THAT(GetDeskRestoreNames(user_1_prefs()), ElementsAre("", "code", ""));
  EXPECT_THAT(GetDeskRestoreNames(user_2_prefs()), ElementsAre());
  // This should adjust the active desk prefs for the primary user.
  EXPECT_EQ(user_1_prefs()->GetInteger(prefs::kDesksActiveDesk), 1);

  // Move the third desk to the second to test desks reordering.
  controller->ReorderDesk(/*old_index=*/2, /*new_index=*/1);
  EXPECT_THAT(GetDeskRestoreNames(user_1_prefs()), ElementsAre("", "", "code"));
  EXPECT_THAT(GetDeskRestoreNames(user_2_prefs()), ElementsAre());
  // This should again adjust the active desk prefs for the primary user.
  EXPECT_EQ(user_1_prefs()->GetInteger(prefs::kDesksActiveDesk), 2);
}

// Tests that desks reordering updates workspaces of all windows in affected
// desks for all simultaneously logged-in users.
TEST_F(DesksRestoreMultiUserTest,
       DeskIndexChangesMadeByActiveUserAffectsAllUsers) {
  // Setup two users and four desks with one window in each desk --------------
  // Create user1 and user2 with four shared desks named numerically by their
  // initial order. Set the user1 active desk to the fourth desk.
  const int n_desks_per_user = 4;
  int user_1_active_desk_index = 3;
  user_1_prefs()->SetInteger(prefs::kDesksActiveDesk, user_1_active_desk_index);
  InitPrefsWithDesksRestoreData(user_1_prefs(),
                                std::vector<std::string>{"0", "1", "2", "3"});
  SimulateUserLogin(GetUser1AccountId());
  auto* controller = DesksController::Get();
  const auto& desks = controller->desks();
  ASSERT_EQ(4u, desks.size());

  // Switch to user2 and activate the third desk. Thus, the desks initial state
  // is [0, 1, 2**, 3*] where * and ** label active desks of user1 and user2.
  EXPECT_EQ(desks[user_1_active_desk_index]->container_id(),
            desks_util::GetActiveDeskContainerId());
  int user_2_active_desk_index = 2;
  SwitchActiveUser(GetUser2AccountId());
  ActivateDesk(desks[user_2_active_desk_index].get());
  EXPECT_EQ(desks[user_2_active_desk_index]->container_id(),
            desks_util::GetActiveDeskContainerId());
  EXPECT_EQ(user_1_active_desk_index,
            user_1_prefs()->GetInteger(prefs::kDesksActiveDesk));

  // For each user's desk, create a window and set window workspace property.
  std::vector<std::unique_ptr<aura::Window>> user1_windows;
  std::vector<std::unique_ptr<aura::Window>> user2_windows;
  for (int i = 0; i < n_desks_per_user; i++) {
    user1_windows.push_back(CreateAppWindow());
    user2_windows.push_back(CreateAppWindow());
    multi_user_window_manager()->SetWindowOwner(user1_windows[i].get(),
                                                GetUser1AccountId());
    multi_user_window_manager()->SetWindowOwner(user2_windows[i].get(),
                                                GetUser2AccountId());
    controller->SendToDeskAtIndex(user1_windows[i].get(), i);
    controller->SendToDeskAtIndex(user2_windows[i].get(), i);
    EXPECT_EQ(i,
              user1_windows[i]->GetProperty(aura::client::kWindowWorkspaceKey));
    EXPECT_EQ(i,
              user2_windows[i]->GetProperty(aura::client::kWindowWorkspaceKey));
  }
  // Done setup four desks with the numerical desk names ----------------------

  // |desk_names_as_ints| represents the numerical desk names in desks order
  // after a series of desks reordering. The initial order is [0, 1, 2, 3].
  auto check_window_workspaces =
      [&](const std::vector<int> desk_names_as_ints) {
        DCHECK(n_desks_per_user == desk_names_as_ints.size());
        for (int desk_index = 0; desk_index < n_desks_per_user; desk_index++) {
          int desk_name_as_int = desk_names_as_ints[desk_index];
          EXPECT_EQ(desk_index, user1_windows[desk_name_as_int]->GetProperty(
                                    aura::client::kWindowWorkspaceKey));
          EXPECT_EQ(desk_index, user2_windows[desk_name_as_int]->GetProperty(
                                    aura::client::kWindowWorkspaceKey));
        }
      };

  // 1. Test that desks reordering from the secondary user updates both users'
  // saved active desks correctly. Move the fourth desk to the second, so the
  // desks state become [0, 3*, 1, 2**].
  controller->ReorderDesk(/*old_index=*/3, /*new_index=*/1);
  user_1_active_desk_index = 1;
  user_2_active_desk_index = 3;
  check_window_workspaces(std::vector<int>{0, 3, 1, 2});
  EXPECT_THAT(GetDeskRestoreNames(user_1_prefs()),
              ElementsAre("0", "3", "1", "2"));
  EXPECT_THAT(GetDeskRestoreNames(user_2_prefs()), ElementsAre());
  EXPECT_EQ(user_1_active_desk_index,
            user_1_prefs()->GetInteger(prefs::kDesksActiveDesk));
  EXPECT_EQ(desks[user_2_active_desk_index]->container_id(),
            desks_util::GetActiveDeskContainerId());

  // Switch to the primary user1.
  SwitchActiveUser(GetUser1AccountId());
  EXPECT_EQ(desks[user_1_active_desk_index]->container_id(),
            desks_util::GetActiveDeskContainerId());

  // 2. Test that desks reordering from the primary user updates both users'
  // saved active desks correctly. Move the first desk to the fourth, so the
  // desks state become [3*, 1, 2**, 0].
  controller->ReorderDesk(/*old_index=*/0, /*new_index=*/3);
  user_1_active_desk_index = 0;
  user_2_active_desk_index = 2;
  check_window_workspaces(std::vector<int>{3, 1, 2, 0});
  EXPECT_THAT(GetDeskRestoreNames(user_1_prefs()),
              ElementsAre("3", "1", "2", "0"));
  EXPECT_THAT(GetDeskRestoreNames(user_2_prefs()), ElementsAre());
  EXPECT_EQ(user_1_active_desk_index,
            user_1_prefs()->GetInteger(prefs::kDesksActiveDesk));
  EXPECT_EQ(desks[user_1_active_desk_index]->container_id(),
            desks_util::GetActiveDeskContainerId());
  SwitchActiveUser(GetUser2AccountId());
  EXPECT_EQ(desks[user_2_active_desk_index]->container_id(),
            desks_util::GetActiveDeskContainerId());
}

}  // namespace

// Simulates the same behavior of event rewriting that key presses go through.
class DesksAcceleratorsTest : public DesksTest {
 public:
  DesksAcceleratorsTest() = default;

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

  ~DesksAcceleratorsTest() override = default;

  // DesksTest:
  void SetUp() override {
    DesksTest::SetUp();

    auto* event_rewriter_controller = EventRewriterController::Get();
    auto event_rewriter = std::make_unique<ui::EventRewriterAsh>(
        &event_rewriter_delegate_, Shell::Get()->keyboard_capability(),
        Shell::Get()->sticky_keys_controller(), false, &fake_ime_keyboard_);
    event_rewriter_controller->AddEventRewriter(std::move(event_rewriter));
  }

  void SendAccelerator(ui::KeyboardCode key_code, int flags) {
    ui::test::EventGenerator* generator = GetEventGenerator();
    generator->PressKey(key_code, flags);
    generator->ReleaseKey(key_code, flags);
  }

  // Moves the overview focus to the next item.
  void MoveOverviewFocusRing(OverviewSession* session) {
    session->Move(/*reverse=*/false);
  }

 private:
  ui::test::FakeEventRewriterAshDelegate event_rewriter_delegate_;
  input_method::FakeImeKeyboard fake_ime_keyboard_;
};

namespace {

TEST_P(DesksAcceleratorsTest, NewDesk) {
  auto* controller = DesksController::Get();
  // It's possible to add up to kMaxNumberOfDesks desks using the
  // shortcut.
  const int flags = ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN;
  for (size_t num_desks = 1; num_desks < desks_util::GetMaxNumberOfDesks();
       ++num_desks) {
    DeskSwitchAnimationWaiter waiter;
    SendAccelerator(ui::VKEY_OEM_PLUS, flags);
    waiter.Wait();
    // The newly created desk should be activated.
    ASSERT_EQ(num_desks + 1, controller->desks().size());
    EXPECT_TRUE(controller->desks().back()->is_active());
  }

  // When we reach the limit, the shortcut does nothing.
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks(), controller->desks().size());
  SendAccelerator(ui::VKEY_OEM_PLUS, flags);
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks(), controller->desks().size());
}

TEST_P(DesksAcceleratorsTest, CannotRemoveLastDesk) {
  auto* controller = DesksController::Get();
  // Removing the last desk is not possible.
  ASSERT_EQ(1u, controller->desks().size());
  const int flags = ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN;
  SendAccelerator(ui::VKEY_OEM_MINUS, flags);
  ASSERT_EQ(1u, controller->desks().size());
}

TEST_P(DesksAcceleratorsTest, RemoveDesk) {
  auto* controller = DesksController::Get();
  // Create a few desks and remove them outside and inside overview using the
  // shortcut.
  NewDesk();
  NewDesk();
  ASSERT_EQ(3u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  Desk* desk_3 = controller->GetDeskAtIndex(2);
  EXPECT_TRUE(desk_1->is_active());
  const int flags = ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN;
  DeskSwitchAnimationWaiter waiter;
  SendAccelerator(ui::VKEY_OEM_MINUS, flags);
  waiter.Wait();
  ASSERT_EQ(2u, controller->desks().size());
  EXPECT_TRUE(desk_2->is_active());

  // Using the accelerator doesn't result in exiting overview.
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  SendAccelerator(ui::VKEY_OEM_MINUS, flags);
  ASSERT_EQ(1u, controller->desks().size());
  EXPECT_TRUE(desk_3->is_active());
  EXPECT_TRUE(overview_controller->InOverviewSession());
}

TEST_P(DesksAcceleratorsTest, RemoveRightmostDesk) {
  auto* controller = DesksController::Get();
  // Create a few desks and remove them outside and inside overview using the
  // shortcut.
  NewDesk();
  NewDesk();
  ASSERT_EQ(3u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  Desk* desk_3 = controller->GetDeskAtIndex(2);
  ActivateDesk(desk_3);
  EXPECT_TRUE(desk_3->is_active());
  const int flags = ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN;
  {
    DeskSwitchAnimationWaiter waiter;
    SendAccelerator(ui::VKEY_OEM_MINUS, flags);
    waiter.Wait();
  }
  ASSERT_EQ(2u, controller->desks().size());
  EXPECT_TRUE(desk_2->is_active());
  {
    DeskSwitchAnimationWaiter waiter;
    SendAccelerator(ui::VKEY_OEM_MINUS, flags);
    waiter.Wait();
  }
  ASSERT_EQ(1u, controller->desks().size());
  EXPECT_TRUE(desk_1->is_active());
}

TEST_P(DesksAcceleratorsTest, LeftRightDeskActivation) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  EXPECT_TRUE(desk_1->is_active());
  // No desk on left, nothing should happen.
  const int flags = ui::EF_COMMAND_DOWN;
  SendAccelerator(ui::VKEY_OEM_4, flags);
  EXPECT_TRUE(desk_1->is_active());

  // Go right until there're no more desks on the right.
  {
    DeskSwitchAnimationWaiter waiter;
    SendAccelerator(ui::VKEY_OEM_6, flags);
    waiter.Wait();
    EXPECT_TRUE(desk_2->is_active());
  }

  // Nothing happens.
  SendAccelerator(ui::VKEY_OEM_6, flags);
  EXPECT_TRUE(desk_2->is_active());

  // Go back left.
  {
    DeskSwitchAnimationWaiter waiter;
    SendAccelerator(ui::VKEY_OEM_4, flags);
    waiter.Wait();
    EXPECT_TRUE(desk_1->is_active());
  }
}

TEST_P(DesksAcceleratorsTest, MoveWindowLeftRightDesk) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  EXPECT_TRUE(desk_1->is_active());

  auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(window.get());
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  // Moving window left when this is the left-most desk. Nothing happens.
  const int flags = ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN;
  SendAccelerator(ui::VKEY_OEM_4, flags);
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());
  EXPECT_TRUE(DoesActiveDeskContainWindow(window.get()));

  // Move window right, it should be deactivated.
  SendAccelerator(ui::VKEY_OEM_6, flags);
  EXPECT_EQ(nullptr, window_util::GetActiveWindow());
  EXPECT_TRUE(desk_1->windows().empty());
  EXPECT_TRUE(base::Contains(desk_2->windows(), window.get()));

  // No more active windows on this desk, nothing happens.
  SendAccelerator(ui::VKEY_OEM_6, flags);
  EXPECT_TRUE(desk_1->windows().empty());
  EXPECT_EQ(nullptr, window_util::GetActiveWindow());

  // Activate desk 2, and do the same set of tests.
  ActivateDesk(desk_2);
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  // Move right does nothing.
  SendAccelerator(ui::VKEY_OEM_6, flags);
  EXPECT_EQ(window.get(), window_util::GetActiveWindow());

  SendAccelerator(ui::VKEY_OEM_4, flags);
  EXPECT_TRUE(desk_2->windows().empty());
  EXPECT_EQ(nullptr, window_util::GetActiveWindow());
  EXPECT_TRUE(base::Contains(desk_1->windows(), window.get()));
}

TEST_P(DesksAcceleratorsTest, MoveWindowLeftRightDeskOverview) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  EXPECT_TRUE(desk_1->is_active());

  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  auto win1 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  wm::ActivateWindow(win0.get());
  EXPECT_EQ(win0.get(), window_util::GetActiveWindow());

  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  const int flags = ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN;
  // In overview, while no window is focused, nothing should happen.
  const size_t num_windows_before = desk_1->windows().size();
  EXPECT_TRUE(desk_2->windows().empty());
  SendAccelerator(ui::VKEY_OEM_6, flags);
  ASSERT_EQ(num_windows_before, desk_1->windows().size());
  EXPECT_TRUE(desk_2->windows().empty());

  auto* overview_session = overview_controller->overview_session();
  ASSERT_TRUE(overview_session);
  // It's possible to move the focused window. `Move()` will cycle through
  // the desk items first, so call it until we are focusing an `OverviewItem`.
  while (!overview_session->GetFocusedWindow()) {
    MoveOverviewFocusRing(overview_session);
  }
  EXPECT_EQ(win0.get(), overview_session->GetFocusedWindow());
  SendAccelerator(ui::VKEY_OEM_6, flags);
  EXPECT_FALSE(DoesActiveDeskContainWindow(win0.get()));
  EXPECT_TRUE(base::Contains(desk_2->windows(), win0.get()));
  EXPECT_TRUE(overview_controller->InOverviewSession());

  // The focus ring should move to the next window if we call
  // `MoveOverviewFocusRing()` again.
  MoveOverviewFocusRing(overview_session);
  EXPECT_EQ(win1.get(), overview_session->GetFocusedWindow());
  SendAccelerator(ui::VKEY_OEM_6, flags);
  EXPECT_FALSE(DoesActiveDeskContainWindow(win1.get()));
  EXPECT_TRUE(base::Contains(desk_2->windows(), win1.get()));
  EXPECT_TRUE(overview_controller->InOverviewSession());

  // Nothing is focused.
  EXPECT_FALSE(overview_session->GetFocusedWindow());
}

TEST_P(DesksAcceleratorsTest, CannotMoveAlwaysOnTopWindows) {
  auto* controller = DesksController::Get();
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  EXPECT_TRUE(desk_1->is_active());

  // An always-on-top window does not belong to any desk and hence cannot be
  // removed.
  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
  win0->SetProperty(aura::client::kZOrderingKey,
                    ui::ZOrderLevel::kFloatingWindow);
  wm::ActivateWindow(win0.get());
  EXPECT_EQ(win0.get(), window_util::GetActiveWindow());
  EXPECT_FALSE(DoesActiveDeskContainWindow(win0.get()));
  EXPECT_FALSE(controller->MoveWindowFromActiveDeskTo(
      win0.get(), desk_2, win0->GetRootWindow(),
      DesksMoveWindowFromActiveDeskSource::kDragAndDrop));
  const int flags = ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN;
  SendAccelerator(ui::VKEY_OEM_4, flags);
  EXPECT_EQ(win0.get(), window_util::GetActiveWindow());
  EXPECT_TRUE(win0->IsVisible());

  // It remains visible even after switching desks.
  ActivateDesk(desk_2);
  EXPECT_TRUE(win0->IsVisible());
}

// Tests that hitting an acclerator to switch desks does not cause a crash if we
// are already at an edge desk. Regression test for https://crbug.com/1159068.
TEST_P(DesksAcceleratorsTest, HitAcceleratorWhenAlreadyAtEdge) {
  NewDesk();

  // Enable animations so that we can make sure that they occur.
  ui::ScopedAnimationDurationScaleMode regular_animations(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  // First go right. Wait until the ending screenshot is taken.
  const int flags = ui::EF_COMMAND_DOWN;
  SendAccelerator(ui::VKEY_OEM_6, flags);

  DeskAnimationBase* animation = DesksController::Get()->animation();
  ASSERT_TRUE(animation);
  base::RunLoop run_loop;
  auto* desk_switch_animator =
      animation->GetDeskSwitchAnimatorAtIndexForTesting(0);
  ASSERT_TRUE(desk_switch_animator);
  RootWindowDeskSwitchAnimatorTestApi(desk_switch_animator)
      .SetOnEndingScreenshotTakenCallback(run_loop.QuitClosure());
  run_loop.Run();

  // Tap the accelerator to go left to desk 1, then tap again. There should be
  // no crash.
  SendAccelerator(ui::VKEY_OEM_4, flags);
  SendAccelerator(ui::VKEY_OEM_4, flags);
}

// Tests that the assign to all desks shortcut works as expected and that its
// metrics are recorded properly.
TEST_P(DesksAcceleratorsTest, AssignToAllDesksShortcut) {
  base::HistogramTester histogram_tester;

  // Create two new desks.
  NewDesk();
  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(3u, controller->desks().size());

  // Create a window and assign it to all desks via
  // chromeos::MoveToDesksMenuDelegate. This simulates assigning it to all desks
  // via the context menu. This should record to the "Assign to desk menu"
  // bucket.
  auto window_1 = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto* widget_1 = views::Widget::GetWidgetForNativeWindow(window_1.get());
  auto menu_delegate =
      std::make_unique<chromeos::MoveToDesksMenuDelegate>(widget_1);
  menu_delegate->ExecuteCommand(
      chromeos::MoveToDesksMenuModel::CommandId::TOGGLE_ASSIGN_TO_ALL_DESKS,
      /*event_flags=*/0);
  histogram_tester.ExpectBucketCount(
      chromeos::kDesksAssignToAllDesksSourceHistogramName,
      chromeos::DesksAssignToAllDesksSource::kMoveToDeskMenu, 1);
  EXPECT_TRUE(widget_1->IsVisibleOnAllWorkspaces());

  // Create another window and assign it to all desks via the keyboard shortcut.
  // This should record to the "Assign to all desks keyboard shortcut menu"
  // bucket.
  auto window_2 = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  ASSERT_EQ(window_2.get(), window_util::GetActiveWindow());
  SendAccelerator(ui::VKEY_A, ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN);
  histogram_tester.ExpectBucketCount(
      chromeos::kDesksAssignToAllDesksSourceHistogramName,
      chromeos::DesksAssignToAllDesksSource::kKeyboardShortcut, 1);
  EXPECT_TRUE(views::Widget::GetWidgetForNativeWindow(window_2.get())
                  ->IsVisibleOnAllWorkspaces());
}

// Tests that the indexed-desk activation keyboard shortcut works properly.
TEST_P(DesksAcceleratorsTest, IndexedDeskActivationShortcut) {
  const int flags = ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN;
  constexpr char kDesksSwitchHistogramName[] = "Ash.Desks.DesksSwitch";
  base::HistogramTester histogram_tester;

  // Create three new desks.
  NewDesk();
  NewDesk();
  NewDesk();
  auto* controller = DesksController::Get();
  auto& desks = controller->desks();
  ASSERT_EQ(4u, desks.size());

  // Switch to the third desk via the keyboard shortcut.
  ASSERT_TRUE(desks[0]->is_active());
  {
    DeskSwitchAnimationWaiter waiter;
    SendAccelerator(ui::VKEY_3, flags);
    waiter.Wait();
  }
  EXPECT_TRUE(desks[2]->is_active());
  histogram_tester.ExpectBucketCount(
      kDesksSwitchHistogramName, DesksSwitchSource::kIndexedDeskSwitchShortcut,
      1);

  // Try to switch to the non-existent fifth desk via the keyboard shortcut.
  SendAccelerator(ui::VKEY_5, flags);
  EXPECT_TRUE(desks[2]->is_active());
  histogram_tester.ExpectBucketCount(
      kDesksSwitchHistogramName, DesksSwitchSource::kIndexedDeskSwitchShortcut,
      1);

  // Switch to the second desk via the keyboard shortcut.
  {
    DeskSwitchAnimationWaiter waiter;
    SendAccelerator(ui::VKEY_2, flags);
    waiter.Wait();
  }
  EXPECT_TRUE(desks[1]->is_active());
  histogram_tester.ExpectBucketCount(
      kDesksSwitchHistogramName, DesksSwitchSource::kIndexedDeskSwitchShortcut,
      2);

  // Open overview and switch to the active desk. This should close overview.
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  SendAccelerator(ui::VKEY_2, flags);
  EXPECT_TRUE(desks[1]->is_active());
  EXPECT_FALSE(OverviewController::Get()->InOverviewSession());
  histogram_tester.ExpectBucketCount(
      kDesksSwitchHistogramName, DesksSwitchSource::kIndexedDeskSwitchShortcut,
      2);
}

class PerDeskShelfTest : public AshTestBase,
                         public ::testing::WithParamInterface<bool> {
 public:
  PerDeskShelfTest() = default;
  PerDeskShelfTest(const PerDeskShelfTest&) = delete;
  PerDeskShelfTest& operator=(const PerDeskShelfTest&) = delete;
  ~PerDeskShelfTest() override = default;

  // AshTestBase:
  void SetUp() override {
    if (GetParam()) {
      scoped_feature_list_.InitAndEnableFeature(features::kPerDeskShelf);
    } else {
      scoped_feature_list_.InitAndDisableFeature(features::kPerDeskShelf);
    }

    AshTestBase::SetUp();
  }

  // Creates and returns an app window that is asscoaited with a shelf item with
  // |type|.
  std::unique_ptr<aura::Window> CreateAppWithShelfItem(ShelfItemType type) {
    auto window = CreateAppWindow(gfx::Rect(0, 0, 250, 100));
    const ash::ShelfID shelf_id(base::StringPrintf("%d", current_shelf_id_++));
    window->SetProperty(ash::kShelfIDKey, shelf_id.Serialize());
    window->SetProperty(ash::kAppIDKey, shelf_id.app_id);
    window->SetProperty<int>(ash::kShelfItemTypeKey, type);
    ShelfItem item;
    item.status = ShelfItemStatus::STATUS_RUNNING;
    item.type = type;
    item.id = shelf_id;
    // Non-empty title for the shelf icon is important to not crash the tooltip.
    // Please see b/293869853.
    item.title = u"Test Window";
    ShelfModel::Get()->Add(item,
                           std::make_unique<TestShelfItemDelegate>(item.id));
    return window;
  }

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

  ShelfView* GetShelfView() const {
    return GetPrimaryShelf()->GetShelfViewForTesting();
  }

  // Returns the index of the shelf item associated with the given |window| or
  // -1 if no such item exists.
  int GetShelfItemIndexForWindow(aura::Window* window) const {
    const auto shelf_id =
        ShelfID::Deserialize(window->GetProperty(kShelfIDKey));
    EXPECT_FALSE(shelf_id.IsNull());
    return ShelfModel::Get()->ItemIndexByID(shelf_id);
  }

  // Verifies that the visibility of the shelf item view associated with the
  // given |window| is equal to the given |expected_visibility|.
  void VerifyViewVisibility(aura::Window* window,
                            bool expected_visibility) const {
    const size_t index = GetShelfItemIndexForWindow(window);
    auto* shelf_view = GetShelfView();
    auto* view_model = shelf_view->view_model();

    views::View* item_view = view_model->view_at(index);
    const bool contained_in_visible_indices =
        base::Contains(shelf_view->visible_views_indices(), index);

    EXPECT_EQ(expected_visibility, item_view->GetVisible());
    EXPECT_EQ(expected_visibility, contained_in_visible_indices);
  }

  void MoveWindowFromActiveDeskTo(aura::Window* window,
                                  Desk* target_desk) const {
    DesksController::Get()->MoveWindowFromActiveDeskTo(
        window, target_desk, window->GetRootWindow(),
        DesksMoveWindowFromActiveDeskSource::kDragAndDrop);
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
  int current_shelf_id_ = 0;
};

TEST_P(PerDeskShelfTest, MoveWindowOutOfActiveDesk) {
  auto* controller = DesksController::Get();
  NewDesk();

  // Create three app windows; a browser window, a pinned app, and a normal app.
  auto win0 = CreateAppWithShelfItem(ShelfItemType::TYPE_BROWSER_SHORTCUT);
  aura::Window* browser = win0.get();
  auto win1 = CreateAppWithShelfItem(ShelfItemType::TYPE_PINNED_APP);
  aura::Window* pinned = win1.get();
  auto win2 = CreateAppWithShelfItem(ShelfItemType::TYPE_APP);
  aura::Window* app = win2.get();

  // All items should be visible.
  VerifyViewVisibility(browser, true);
  VerifyViewVisibility(pinned, true);
  VerifyViewVisibility(app, true);

  // Move the app window, it should be removed from the shelf if the feature is
  // enabled.
  const bool visible_in_per_desk_shelf = IsPerDeskShelfEnabled() ? false : true;
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  MoveWindowFromActiveDeskTo(app, desk_2);
  VerifyViewVisibility(browser, true);
  VerifyViewVisibility(pinned, true);
  VerifyViewVisibility(app, visible_in_per_desk_shelf);

  // Move the pinned app and the browser window, they should remain visible on
  // the shelf even though they're on an inactive desk now.
  MoveWindowFromActiveDeskTo(pinned, desk_2);
  MoveWindowFromActiveDeskTo(browser, desk_2);
  VerifyViewVisibility(browser, true);
  VerifyViewVisibility(pinned, true);
  VerifyViewVisibility(app, visible_in_per_desk_shelf);
}

TEST_P(PerDeskShelfTest, DeskSwitching) {
  // Create two more desks, so total is three.
  auto* controller = DesksController::Get();
  NewDesk();
  NewDesk();

  // On desk_1, create a browser and a normal app.
  auto win0 = CreateAppWithShelfItem(ShelfItemType::TYPE_BROWSER_SHORTCUT);
  aura::Window* browser = win0.get();
  auto win1 = CreateAppWithShelfItem(ShelfItemType::TYPE_APP);
  aura::Window* app1 = win1.get();

  // Switch to desk_2, only the browser app should be visible on the shelf if
  // the feature is enabled.
  const bool visible_in_per_desk_shelf = IsPerDeskShelfEnabled() ? false : true;
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);
  VerifyViewVisibility(browser, true);
  VerifyViewVisibility(app1, visible_in_per_desk_shelf);

  // On desk_2, create a pinned app.
  auto win2 = CreateAppWithShelfItem(ShelfItemType::TYPE_PINNED_APP);
  aura::Window* pinned = win2.get();
  VerifyViewVisibility(pinned, true);

  // Switch to desk_3, only the browser and the pinned app should be visible on
  // the shelf if the feature is enabled.
  Desk* desk_3 = controller->GetDeskAtIndex(2);
  ActivateDesk(desk_3);
  VerifyViewVisibility(browser, true);
  VerifyViewVisibility(app1, visible_in_per_desk_shelf);
  VerifyViewVisibility(pinned, true);

  // On desk_3, create a normal app, then switch back to desk_1. app1 should
  // show again on the shelf.
  auto win3 = CreateAppWithShelfItem(ShelfItemType::TYPE_APP);
  aura::Window* app2 = win3.get();
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  ActivateDesk(desk_1);
  VerifyViewVisibility(browser, true);
  VerifyViewVisibility(app1, true);
  VerifyViewVisibility(pinned, true);
  VerifyViewVisibility(app2, visible_in_per_desk_shelf);
}

TEST_P(PerDeskShelfTest, RemoveInactiveDesk) {
  auto* controller = DesksController::Get();
  NewDesk();

  // On desk_1, create two apps.
  auto win0 = CreateAppWithShelfItem(ShelfItemType::TYPE_APP);
  aura::Window* app1 = win0.get();
  auto win1 = CreateAppWithShelfItem(ShelfItemType::TYPE_APP);
  aura::Window* app2 = win1.get();

  // Switch to desk_2, no apps should show on the shelf if the feature is
  // enabled.
  const bool visible_in_per_desk_shelf = IsPerDeskShelfEnabled() ? false : true;
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);
  VerifyViewVisibility(app1, visible_in_per_desk_shelf);
  VerifyViewVisibility(app2, visible_in_per_desk_shelf);

  // Remove desk_1 (inactive), apps should now show on the shelf.
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  RemoveDesk(desk_1);
  VerifyViewVisibility(app1, true);
  VerifyViewVisibility(app2, true);
}

TEST_P(PerDeskShelfTest, RemoveActiveDesk) {
  auto* controller = DesksController::Get();
  NewDesk();

  // On desk_1, create an app.
  auto win0 = CreateAppWithShelfItem(ShelfItemType::TYPE_APP);
  aura::Window* app1 = win0.get();

  // Switch to desk_2, no apps should show on the shelf if the feature is
  // enabled.
  const bool visible_in_per_desk_shelf = IsPerDeskShelfEnabled() ? false : true;
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  ActivateDesk(desk_2);
  VerifyViewVisibility(app1, visible_in_per_desk_shelf);

  // Create another app on desk_2.
  auto win1 = CreateAppWithShelfItem(ShelfItemType::TYPE_APP);
  aura::Window* app2 = win1.get();

  // Remove desk_2 (active), all apps should now show on the shelf.
  RemoveDesk(desk_2);
  VerifyViewVisibility(app1, true);
  VerifyViewVisibility(app2, true);
}

TEST_P(PerDeskShelfTest, ShelfViewTransformUpdatedForScrollWhenSwitchingDesks) {
  ScrollableShelfView* scrollable_shelf_view = GetPrimaryShelf()
                                                   ->shelf_widget()
                                                   ->hotseat_widget()
                                                   ->scrollable_shelf_view();
  ShelfView* shelf_view = scrollable_shelf_view->shelf_view();
  ShelfViewTestAPI shelf_view_test_api(shelf_view);
  shelf_view_test_api.SetAnimationDuration(base::Milliseconds(1));

  NewDesk();

  // Create apps running on the active desk, and not pinned to the shelf, until
  // the right or bottom scroll arrow appears.
  ScrollArrowView* right_arrow = scrollable_shelf_view->right_arrow();
  std::vector<std::unique_ptr<aura::Window>> windows;
  while (!right_arrow->GetVisible()) {
    windows.push_back(CreateAppWithShelfItem(ShelfItemType::TYPE_APP));
    shelf_view_test_api.RunMessageLoopUntilAnimationsDone();
  }

  // Scroll the shelf.
  LeftClickOn(right_arrow);
  shelf_view_test_api.RunMessageLoopUntilAnimationsDone();
  const gfx::Transform scrolled_transform = shelf_view->GetTransform();
  EXPECT_FALSE(scrolled_transform.IsIdentity());

  // Switch desks.
  ActivateDesk(DesksController::Get()->GetDeskAtIndex(1));
  if (IsPerDeskShelfEnabled()) {
    EXPECT_TRUE(shelf_view->GetTransform().IsIdentity());
  } else {
    EXPECT_EQ(scrolled_transform, shelf_view->GetTransform());
  }
}

// Tests desks name nudges, i.e. when a user creates a new desk, focus + clear
// the new desk's renaming textfield.
TEST_P(DesksTest, NameNudges) {
  UpdateDisplay("1200x800");
  auto* controller = DesksController::Get();

  // Start overview.
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  // Hover over the new desk button.
  const auto* overview_grid =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_TRUE(desks_bar_view->IsZeroState());

  LeftClickOn(desks_bar_view->default_desk_button());
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_EQ(1u, desks_bar_view->mini_views().size());

  auto* new_desk_button = desks_bar_view->new_desk_button();
  EXPECT_TRUE(new_desk_button->GetEnabled());

  // Click on the new desk button until the max number of desks is created. Each
  // time a new desk is created the new desk's name view should have focus, be
  // empty. Also, the previous desk should be left with a default name.
  for (size_t i = 1; i < desks_util::GetMaxNumberOfDesks(); ++i) {
    LeftClickOn(new_desk_button);
    RunScheduledLayoutForAllOverviewDeskBars();
    auto* desk_name_view = desks_bar_view->mini_views()[i]->desk_name_view();
    EXPECT_TRUE(desk_name_view->HasFocus());
    EXPECT_EQ(std::u16string(), controller->GetDeskAtIndex(i)->name());
    EXPECT_EQ(DesksController::GetDeskDefaultName(i - 1),
              controller->GetDeskAtIndex(i - 1)->name());
    // As desks are added, we will scroll the desks bar to keep the "new desk"
    // button in view.
    TryScrollOverviewDeskBar(DeskBarScrollDirection::kRight);
    RunScheduledLayoutForAllOverviewDeskBars();
  }
}

// Tests that name nudges works with multiple displays. When a user
// clicks/touches the new desk button, the newly created DeskNameView that
// resides on the same desk bar view as the clicked button should be focused.
// See crbug.com/1206013.
TEST_P(DesksTest, NameNudgesMultiDisplay) {
  UpdateDisplay("800x700,800x700");

  // Start overview.
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  // Retrieve the desks bar view for each root window.
  auto root_windows = Shell::GetAllRootWindows();
  ASSERT_EQ(2u, root_windows.size());
  const auto* desks_bar_view_1 =
      GetOverviewGridForRoot(root_windows[0])->desks_bar_view();
  const auto* desks_bar_view_2 =
      GetOverviewGridForRoot(root_windows[1])->desks_bar_view();
  ASSERT_TRUE(desks_bar_view_1->IsZeroState());
  ASSERT_TRUE(desks_bar_view_2->IsZeroState());

  // Click on the zero state default desk button for the second root window.
  auto* default_desk_button_2 = desks_bar_view_2->default_desk_button();
  EXPECT_TRUE(default_desk_button_2->GetEnabled());
  LeftClickOn(default_desk_button_2);
  RunScheduledLayoutForAllOverviewDeskBars();

  // The desk bar should not be in the zero state anymore and the existing
  // desk's name view should be focused, but not cleared.
  EXPECT_FALSE(desks_bar_view_2->IsZeroState());
  EXPECT_EQ(1u, desks_bar_view_2->mini_views().size());
  auto* desk_name_view_2 = desks_bar_view_2->mini_views()[0]->desk_name_view();
  EXPECT_TRUE(desk_name_view_2->HasFocus());
  EXPECT_EQ(DesksController::GetDeskDefaultName(/*desk_index=*/0),
            desk_name_view_2->GetText());

  // Restart overview to reset the zero state.
  ExitOverview();
  EnterOverview();
  desks_bar_view_1 = GetOverviewGridForRoot(root_windows[0])->desks_bar_view();
  desks_bar_view_2 = GetOverviewGridForRoot(root_windows[1])->desks_bar_view();
  ASSERT_TRUE(desks_bar_view_1->IsZeroState());
  ASSERT_TRUE(desks_bar_view_2->IsZeroState());

  // Click on the new desk button on the first root window.
  auto* new_desk_button_1 = desks_bar_view_1->new_desk_button();
  EXPECT_TRUE(new_desk_button_1->GetEnabled());
  LeftClickOn(new_desk_button_1);
  RunScheduledLayoutForAllOverviewDeskBars();

  // There should be 2 desks now and the name view on the first root window
  // should be focused. Each new name view on the 2 root windows should be
  // empty.
  EXPECT_EQ(2u, desks_bar_view_1->mini_views().size());
  auto* desk_name_view_1 = desks_bar_view_1->mini_views()[1]->desk_name_view();
  desk_name_view_2 = desks_bar_view_2->mini_views()[1]->desk_name_view();
  EXPECT_TRUE(desk_name_view_1->HasFocus());
  EXPECT_FALSE(desk_name_view_2->HasFocus());
  EXPECT_EQ(std::u16string(), desk_name_view_1->GetText());
  EXPECT_EQ(std::u16string(), desk_name_view_2->GetText());

  // Tap on the new desk button on the second root window.
  auto* new_desk_button_2 = desks_bar_view_2->new_desk_button();
  EXPECT_TRUE(new_desk_button_2->GetEnabled());
  GestureTapOn(new_desk_button_2);
  RunScheduledLayoutForAllOverviewDeskBars();

  // There should be 3 desks now and the name view on the second root window
  // should be focused. Each new name view on the 2 root windows should be
  // empty.
  EXPECT_EQ(3u, desks_bar_view_1->mini_views().size());
  desk_name_view_1 = desks_bar_view_1->mini_views()[2]->desk_name_view();
  desk_name_view_2 = desks_bar_view_2->mini_views()[2]->desk_name_view();
  EXPECT_FALSE(desk_name_view_1->HasFocus());
  EXPECT_TRUE(desk_name_view_2->HasFocus());
  EXPECT_EQ(std::u16string(), desk_name_view_1->GetText());
  EXPECT_EQ(std::u16string(), desk_name_view_2->GetText());
}

// Tests that when a user has a `DeskNameView` focused and clicks within the
// overview grid, the `DeskNameView` loses focus and the overview grid is not
// closed.
TEST_P(DesksTest, ClickingOverviewGridUnfocusesDeskNameView) {
  // Create a second desk so we don't start in zero state.
  NewDesk();

  // Start overview.
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());

  // Focus on a `DeskNameView`.
  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();
  ASSERT_EQ(2u, desks_bar_view->mini_views().size());
  auto* desk_name_view = desks_bar_view->mini_views()[0]->desk_name_view();
  desk_name_view->RequestFocus();
  ASSERT_TRUE(desk_name_view->HasFocus());

  // Click the center of the overview grid. This should not close overview mode
  // and should remove focus from the focused `desk_name_view`.
  auto* event_generator = GetEventGenerator();
  event_generator->MoveMouseTo(
      OverviewGridTestApi(overview_grid).bounds().CenterPoint());
  event_generator->ClickLeftButton();
  EXPECT_FALSE(desk_name_view->HasFocus());
  EXPECT_TRUE(overview_controller->InOverviewSession());
}

TEST_P(DesksTest, ScrollableDesks) {
  UpdateDisplay("201x400");
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  auto* root_window = Shell::GetPrimaryRootWindow();
  const auto* desks_bar_view =
      GetOverviewGridForRoot(root_window)->desks_bar_view();
  ASSERT_TRUE(desks_bar_view->IsZeroState());
  LeftClickOn(desks_bar_view->default_desk_button());
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_EQ(1u, desks_bar_view->mini_views().size());

  auto* new_desk_button = desks_bar_view->new_desk_button();

  // Set the scroll delta large enough to make sure the desks bar can be
  // scrolled to the end each time.
  const int x_scroll_delta = 500;
  gfx::Rect display_bounds =
      screen_util::GetDisplayWorkAreaBoundsInScreenForActiveDeskContainer(
          root_window);
  auto* event_generator = GetEventGenerator();
  for (size_t i = 1; i < desks_util::GetMaxNumberOfDesks(); i++) {
    gfx::Rect new_desk_button_bounds = new_desk_button->GetBoundsInScreen();
    EXPECT_TRUE(display_bounds.Contains(new_desk_button_bounds));
    LeftClickOn(new_desk_button);
    RunScheduledLayoutForAllOverviewDeskBars();
    // Scroll right to make sure the new desk button is always inside the
    // display.
    event_generator->MoveMouseWheel(-x_scroll_delta, 0);
  }

  auto* controller = DesksController::Get();
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks(), controller->desks().size());
  EXPECT_FALSE(controller->CanCreateDesks());

  EXPECT_TRUE(display_bounds.Contains(new_desk_button->GetBoundsInScreen()));
  EXPECT_FALSE(display_bounds.Contains(
      desks_bar_view->mini_views()[0]->GetBoundsInScreen()));
  event_generator->MoveMouseWheel(x_scroll_delta, 0);
  // Tests that scroll to the left will put the first desk inside the display.
  EXPECT_TRUE(display_bounds.Contains(
      desks_bar_view->mini_views()[0]->GetBoundsInScreen()));
  EXPECT_FALSE(display_bounds.Contains(new_desk_button->GetBoundsInScreen()));
}

// Tests the visibility of the scroll buttons and behavior while clicking the
// corresponding scroll button.
TEST_P(DesksTest, ScrollButtonsVisibility) {
  const auto is_scroll_button_visible = [](DeskBarScrollDirection direction) {
    ScrollArrowButton* scroll_arrow = nullptr;
    switch (direction) {
      case DeskBarScrollDirection::kLeft:
        scroll_arrow = DesksTestApi::GetDeskBarLeftScrollButton(
            DeskBarViewBase::Type::kOverview);
        break;
      case DeskBarScrollDirection::kRight:
        scroll_arrow = DesksTestApi::GetDeskBarRightScrollButton(
            DeskBarViewBase::Type::kOverview);
        break;
    }
    return IsLazyInitViewVisible(scroll_arrow);
  };

  UpdateDisplay("600x400");
  for (size_t i = 1; i < desks_util::GetMaxNumberOfDesks(); i++) {
    NewDesk();
  }

  EXPECT_EQ(DesksController::Get()->desks().size(),
            desks_util::GetMaxNumberOfDesks());
  TabletModeControllerTestApi().EnterTabletMode();
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
  auto* desks_bar =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  auto* event_generator = GetEventGenerator();
  event_generator->MoveMouseTo(desks_bar->GetBoundsInScreen().CenterPoint());

  // Set the scroll delta large enough to make sure the desks bar can be
  // scrolled to the end each time.
  const int x_scroll_delta = 1000;
  // Left scroll button should be hidden and right scroll button should be
  // visible while at the start position.
  event_generator->MoveMouseWheel(x_scroll_delta, 0);
  EXPECT_FALSE(is_scroll_button_visible(DeskBarScrollDirection::kLeft));
  EXPECT_TRUE(is_scroll_button_visible(DeskBarScrollDirection::kRight));

  // Click the right scroll button until it reaches to the right most of the
  // scroll view. Then verify the left scroll button is visible.
  TryScrollOverviewDeskBar(DeskBarScrollDirection::kRight);
  EXPECT_TRUE(is_scroll_button_visible(DeskBarScrollDirection::kLeft));

  // Click the left scroll button until it reaches to the right most of the
  // scroll view. In this case, it will scroll back to the start position and
  // left scroll button should be hidden and right scroll button should be
  // visible.
  TryScrollOverviewDeskBar(DeskBarScrollDirection::kLeft);
  EXPECT_TRUE(is_scroll_button_visible(DeskBarScrollDirection::kRight));

  // Left scroll button should be visible and right scroll button should be
  // hidden while at the end position.
  event_generator->MoveMouseTo(desks_bar->GetBoundsInScreen().CenterPoint());
  event_generator->MoveMouseWheel(-x_scroll_delta, 0);
  EXPECT_TRUE(is_scroll_button_visible(DeskBarScrollDirection::kLeft));
  EXPECT_FALSE(is_scroll_button_visible(DeskBarScrollDirection::kRight));
}

TEST_P(DesksTest, GradientsVisibility) {
  // Set a flat display size to make sure there are multiple pages in the desks
  // bar with maximum number of desks.
  UpdateDisplay("800x150");
  const size_t max_desks_size = desks_util::GetMaxNumberOfDesks();
  for (size_t i = 1; i < max_desks_size; i++) {
    NewDesk();
  }

  EnterOverview();
  auto* desks_bar =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();

  auto* left_button = DesksTestApi::GetDeskBarLeftScrollButton(
      DeskBarViewBase::Type::kOverview);
  auto* right_button = DesksTestApi::GetDeskBarRightScrollButton(
      DeskBarViewBase::Type::kOverview);

  // Only right graident is visible while at the first page.
  auto* scroll_view =
      DesksTestApi::GetDeskBarScrollView(DeskBarViewBase::Type::kOverview);
  ASSERT_TRUE(scroll_view);
  EXPECT_EQ(0, scroll_view->GetVisibleRect().x());
  ASSERT_TRUE(left_button);
  EXPECT_FALSE(left_button->GetVisible());
  EXPECT_FALSE(DesksTestApi::IsDeskBarLeftGradientVisible(
      DeskBarViewBase::Type::kOverview));
  ASSERT_TRUE(right_button);
  EXPECT_TRUE(right_button->GetVisible());
  EXPECT_TRUE(DesksTestApi::IsDeskBarRightGradientVisible(
      DeskBarViewBase::Type::kOverview));

  // Both left and right gradients should be visible while during scroll.
  const gfx::Point center_point = desks_bar->bounds().CenterPoint();
  ui::GestureEvent scroll_begin(
      center_point.x(), center_point.y(), ui::EF_NONE, base::TimeTicks::Now(),
      ui::GestureEventDetails(ui::EventType::kGestureScrollBegin, 1, 0));
  scroll_view->OnGestureEvent(&scroll_begin);
  ui::GestureEvent scroll_update(
      center_point.x(), center_point.y(), ui::EF_NONE, base::TimeTicks::Now(),
      ui::GestureEventDetails(ui::EventType::kGestureScrollUpdate, -100, 0));
  scroll_view->OnGestureEvent(&scroll_update);
  EXPECT_TRUE(scroll_view->is_scrolling());
  EXPECT_TRUE(left_button->GetVisible());
  EXPECT_TRUE(DesksTestApi::IsDeskBarLeftGradientVisible(
      DeskBarViewBase::Type::kOverview));
  EXPECT_TRUE(right_button->GetVisible());
  EXPECT_TRUE(DesksTestApi::IsDeskBarRightGradientVisible(
      DeskBarViewBase::Type::kOverview));

  // The gradient should be hidden if the corresponding scroll button is
  // invisible even though it is during scroll.
  ui::GestureEvent second_scroll_update(
      center_point.x() - 100, center_point.y(), ui::EF_NONE,
      base::TimeTicks::Now(),
      ui::GestureEventDetails(ui::EventType::kGestureScrollUpdate, 100, 0));
  scroll_view->OnGestureEvent(&second_scroll_update);
  EXPECT_TRUE(scroll_view->is_scrolling());
  EXPECT_FALSE(left_button->GetVisible());
  EXPECT_FALSE(DesksTestApi::IsDeskBarLeftGradientVisible(
      DeskBarViewBase::Type::kOverview));
  EXPECT_TRUE(right_button->GetVisible());
  EXPECT_TRUE(DesksTestApi::IsDeskBarRightGradientVisible(
      DeskBarViewBase::Type::kOverview));

  ui::GestureEvent scroll_end(
      center_point.x(), center_point.y(), ui::EF_NONE, base::TimeTicks::Now(),
      ui::GestureEventDetails(ui::EventType::kGestureScrollEnd));
  scroll_view->OnGestureEvent(&scroll_end);
  EXPECT_FALSE(scroll_view->is_scrolling());
  EXPECT_FALSE(left_button->GetVisible());
  EXPECT_FALSE(DesksTestApi::IsDeskBarLeftGradientVisible(
      DeskBarViewBase::Type::kOverview));
  EXPECT_TRUE(right_button->GetVisible());
  EXPECT_TRUE(DesksTestApi::IsDeskBarRightGradientVisible(
      DeskBarViewBase::Type::kOverview));

  // Only right gradient should be shown at the middle page when it is not
  // during scroll even though the left scroll button is visible.
  LeftClickOn(right_button);
  EXPECT_TRUE(left_button->GetVisible());
  EXPECT_FALSE(DesksTestApi::IsDeskBarLeftGradientVisible(
      DeskBarViewBase::Type::kOverview));
  EXPECT_TRUE(right_button->GetVisible());
  EXPECT_TRUE(DesksTestApi::IsDeskBarRightGradientVisible(
      DeskBarViewBase::Type::kOverview));

  // Only the left gradient should be shown at the last page.
  while (right_button->GetVisible()) {
    LeftClickOn(right_button);
  }

  EXPECT_EQ(scroll_view->contents()->bounds().width() - scroll_view->width(),
            scroll_view->GetVisibleRect().x());
  EXPECT_TRUE(left_button->GetVisible());
  EXPECT_TRUE(DesksTestApi::IsDeskBarLeftGradientVisible(
      DeskBarViewBase::Type::kOverview));
  EXPECT_FALSE(right_button->GetVisible());
  EXPECT_FALSE(DesksTestApi::IsDeskBarRightGradientVisible(
      DeskBarViewBase::Type::kOverview));
}

// Tests the behavior when long press on the scroll buttons.
TEST_P(DesksTest, ContinueScrollBar) {
  const int scroll_timeout_ms = 20;
  base::AutoReset<base::TimeDelta> auto_reset =
      DesksTestApi::SetScrollTimeInterval(
          base::Milliseconds(scroll_timeout_ms));

  // Make a flat long window to generate multiple pages on desks bar.
  UpdateDisplay("800x150");
  const size_t max_desks_size = desks_util::GetMaxNumberOfDesks();
  for (size_t i = 1; i < max_desks_size; i++) {
    NewDesk();
  }

  auto* desks_controller = DesksController::Get();
  EXPECT_EQ(desks_controller->desks().size(), max_desks_size);
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
  auto* desks_bar =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();

  views::ScrollView* scroll_view =
      DesksTestApi::GetDeskBarScrollView(DeskBarViewBase::Type::kOverview);
  ASSERT_TRUE(scroll_view);
  const int page_size = scroll_view->width();
  const auto mini_views = desks_bar->mini_views();
  const int mini_view_width = mini_views[0]->bounds().width();
  int desks_in_one_page = page_size / mini_view_width;
  float fractional_page = static_cast<float>(page_size % mini_view_width) /
                          static_cast<float>(mini_view_width);
  if (fractional_page > 0.5) {
    desks_in_one_page++;
  }

  int current_index = 0;
  ScrollArrowButton* left_button = DesksTestApi::GetDeskBarLeftScrollButton(
      DeskBarViewBase::Type::kOverview);
  ASSERT_TRUE(left_button);
  ScrollArrowButton* right_button = DesksTestApi::GetDeskBarRightScrollButton(
      DeskBarViewBase::Type::kOverview);
  ASSERT_TRUE(right_button);

  // At first, left scroll button is hidden and right scroll button is visible.
  EXPECT_FALSE(left_button->GetVisible());
  EXPECT_TRUE(right_button->GetVisible());

  const int focus_ring_width_and_padding = 4;

  // Press on the right scroll button by mouse should scroll to the next page.
  // And the final scroll position should be adjusted to make sure the desk
  // preview will not be cropped.
  auto* event_generator = GetEventGenerator();
  event_generator->MoveMouseTo(right_button->GetBoundsInScreen().CenterPoint());
  event_generator->PressLeftButton();
  current_index += desks_in_one_page;
  EXPECT_EQ(scroll_view->GetVisibleRect().x() + focus_ring_width_and_padding,
            mini_views[current_index]->bounds().x());

  // Both scroll buttons should be visible.
  EXPECT_TRUE(left_button->GetVisible());
  EXPECT_TRUE(right_button->GetVisible());

  // Wait for 20ms, there will be another scroll.
  WaitForMilliseconds(scroll_timeout_ms);
  current_index += desks_in_one_page;

  // When the maximum number of desks is 8, the new desk button is smaller, two
  // scrolls will reach the end of the desks bar view, thus we verify the right
  // of the visible scroll view.
  if (!features::Is16DesksEnabled()) {
    EXPECT_EQ(
        scroll_view->GetVisibleRect().right() - focus_ring_width_and_padding,
        desks_bar->new_desk_button()->bounds().right());
  } else {
    EXPECT_EQ(scroll_view->GetVisibleRect().x() + focus_ring_width_and_padding,
              mini_views[current_index]->bounds().x());
  }

  // Release and click a few times to make sure we end up at the maximum offset.
  event_generator->ReleaseLeftButton();
  for (int i = 0; i != 3; ++i) {
    event_generator->ClickLeftButton();
  }

  EXPECT_EQ(scroll_view->GetVisibleRect().x(),
            scroll_view->contents()->width() - page_size);

  // Left scroll button should be visible and right scroll button should be
  // hidden.
  EXPECT_TRUE(left_button->GetVisible());
  EXPECT_FALSE(right_button->GetVisible());

  // Since we're scrolled all the way to the right and the new desk button is
  // visible, this is the index of the leftmost visible mini view.
  current_index = max_desks_size - 1;

  // Press on left scroll button by gesture should scroll to the previous page.
  // And the final scroll position should also be adjusted while scrolling to
  // previous page to make sure the desk preview will not be cropped.
  event_generator->MoveTouch(left_button->GetBoundsInScreen().CenterPoint());
  event_generator->PressTouch();
  // The new desk button and the library button are smaller, thus when scroll to
  // the left from the right mode.
  current_index -= (desks_in_one_page + 1);
  EXPECT_EQ(scroll_view->GetVisibleRect().x() + focus_ring_width_and_padding,
            mini_views[current_index]->bounds().x());

  // Wait for 20ms, there is another scroll.
  WaitForMilliseconds(scroll_timeout_ms);
  current_index -= desks_in_one_page;
  EXPECT_EQ(scroll_view->GetVisibleRect().x() + focus_ring_width_and_padding,
            mini_views[current_index]->bounds().x());

  event_generator->ReleaseTouch();
}

// Tests that change the focused mini view should scroll the desks bar and put
// the focused mini view inside the visible bounds.
TEST_P(DesksTest, FocusedMiniViewIsVisible) {
  UpdateDisplay("600x400");
  for (size_t i = 1; i < desks_util::GetMaxNumberOfDesks(); i++) {
    NewDesk();
  }

  EXPECT_EQ(DesksController::Get()->desks().size(),
            desks_util::GetMaxNumberOfDesks());
  auto window = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  TabletModeControllerTestApi().EnterTabletMode();
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
  auto* desks_bar =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  // Check if scroll view is enabled.
  ASSERT_TRUE(DesksTestApi::GetDeskBarRightScrollButton(
      DeskBarViewBase::Type::kOverview));
  auto mini_views = desks_bar->mini_views();
  ASSERT_EQ(mini_views.size(), desks_util::GetMaxNumberOfDesks());

  auto* generator = GetEventGenerator();
  // Traverse all the desks mini views from left to right.
  for (size_t i = 0; i < desks_util::GetMaxNumberOfDesks(); i++) {
    // Move the focus to the mini view's associated preview view.
    PressAndReleaseKey(ui::VKEY_TAB);
    const views::ScrollView* const scroll_view =
        DesksTestApi::GetDeskBarScrollView(DeskBarViewBase::Type::kOverview);
    ASSERT_TRUE(scroll_view);
    EXPECT_TRUE(
        scroll_view->GetVisibleRect().Contains(mini_views[i]->bounds()));
    // Move the focus to the mini view's associated name view.
    ASSERT_TRUE(TabUntil(
        /*reverse=*/false, ViewFocused(mini_views[i]->desk_name_view()),
        generator));
  }

  // Traverse from all the desk mini views from right to left.
  for (size_t i = desks_util::GetMaxNumberOfDesks() - 1; i > 0; i--) {
    // Move the focus to previous mini view's name view.
    ASSERT_TRUE(TabUntil(
        /*reverse=*/true, ViewFocused(mini_views[i - 1]->desk_name_view()),
        generator));
    const views::ScrollView* const scroll_view =
        DesksTestApi::GetDeskBarScrollView(DeskBarViewBase::Type::kOverview);
    ASSERT_TRUE(scroll_view);
    EXPECT_TRUE(
        scroll_view->GetVisibleRect().Contains(mini_views[i - 1]->bounds()));
  }
}

// Tests that active desk mini view is visible when entering overview especially
// with 16 desks.
TEST_P(DesksTest, ActiveDeskMiniViewIsVisible) {
  for (size_t i = 1; i < desks_util::GetMaxNumberOfDesks(); i++) {
    // Create a new desk and go to that desk.
    NewDesk();
    ActivateDesk(DesksController::Get()->desks().back().get());

    // Enter overview and check the active mini view is fully visible.
    EnterOverview();
    auto* desks_bar =
        GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
    for (ash::DeskMiniView* mini_view : desks_bar->mini_views()) {
      if (mini_view->desk()->is_active()) {
        EXPECT_EQ(mini_view->size(), mini_view->GetVisibleBounds().size());
      }
    }

    ExitOverview();
  }
}

// Tests that change the focused new desk button is fully visible.
TEST_P(DesksTest, FocusedButtonIsVisible) {
  // Create `GetMaxNumberOfDesks() - 1` desks so that the new desk button is
  // still enabled.
  for (size_t i = 1; i < desks_util::GetMaxNumberOfDesks() - 1; i++) {
    NewDesk();
  }

  EnterOverview();

  auto* desk_bar =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  auto* new_desk_button = desk_bar->new_desk_button();
  PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
  EXPECT_TRUE(new_desk_button->GetVisible());
  EXPECT_EQ(new_desk_button->size(),
            new_desk_button->GetVisibleBounds().size());

  ExitOverview();
}

// Tests that the bounds of a window that is visible on all desks is shared
// across desks.
TEST_P(DesksTest, VisibleOnAllDesksGlobalBounds) {
  auto* controller = DesksController::Get();
  NewDesk();
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  auto* root = Shell::GetPrimaryRootWindow();
  const gfx::Rect window_initial_bounds(1, 1, 200, 200);
  const gfx::Rect window_moved_bounds(200, 200, 250, 250);

  auto window = CreateAppWindow(window_initial_bounds);
  auto* widget = views::Widget::GetWidgetForNativeWindow(window.get());
  ASSERT_EQ(window_initial_bounds, window->bounds());

  // Assign |window| to all desks. It shouldn't change bounds.
  widget->SetVisibleOnAllWorkspaces(true);
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));
  EXPECT_EQ(window_initial_bounds, window->bounds());
  EXPECT_EQ(1u, controller->visible_on_all_desks_windows().size());

  // Move to desk 2. The only window on the new desk should be |window|
  // and it should have the same bounds.
  ActivateDesk(desk_2);
  auto desk_2_children = desk_2->GetDeskContainerForRoot(root)->children();
  EXPECT_EQ(1u, desk_2_children.size());
  EXPECT_EQ(window.get(), desk_2_children[0]);
  EXPECT_EQ(window_initial_bounds, window->bounds());

  // Change |window|'s bounds and move to desk 1. It should retain its moved
  // bounds.
  window->SetBounds(window_moved_bounds);
  EXPECT_EQ(window_moved_bounds, window->bounds());
  ActivateDesk(desk_1);
  auto desk_1_children = desk_1->GetDeskContainerForRoot(root)->children();
  EXPECT_EQ(1u, desk_1_children.size());
  EXPECT_EQ(window.get(), desk_1_children[0]);
  EXPECT_EQ(window_moved_bounds, window->bounds());
}

// Tests the behavior of windows that are visible on all desks when the active
// desk is removed.
TEST_P(DesksTest, VisibleOnAllDesksActiveDeskRemoval) {
  auto* controller = DesksController::Get();
  NewDesk();
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  auto* root = Shell::GetPrimaryRootWindow();

  auto win0 = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto win1 = CreateAppWindow(gfx::Rect(1, 1, 150, 150));
  auto* widget0 = views::Widget::GetWidgetForNativeWindow(win0.get());
  auto* widget1 = views::Widget::GetWidgetForNativeWindow(win1.get());

  // Assign |win0| and |win1| to all desks.
  widget0->SetVisibleOnAllWorkspaces(true);
  widget1->SetVisibleOnAllWorkspaces(true);
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(win0.get()));
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(win1.get()));

  // Remove the active desk. The visible on all desks windows should be on
  // |desk_2|.
  RemoveDesk(desk_1);
  auto desk_2_children = desk_2->GetDeskContainerForRoot(root)->children();
  EXPECT_EQ(2u, desk_2_children.size());
  EXPECT_TRUE(window_util::IsStackedBelow(win0.get(), win1.get()));
  EXPECT_EQ(2u, controller->visible_on_all_desks_windows().size());
}

// Tests the behavior of a minimized window that is visible on all desks.
TEST_P(DesksTest, VisibleOnAllDesksMinimizedWindow) {
  auto* controller = DesksController::Get();
  NewDesk();
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  auto* root = Shell::GetPrimaryRootWindow();
  auto window = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto* widget = views::Widget::GetWidgetForNativeWindow(window.get());

  // Minimize |window| and then assign it to all desks. This shouldn't
  // unminimize it.
  auto* window_state = WindowState::Get(window.get());
  window_state->Minimize();
  ASSERT_TRUE(window_state->IsMinimized());
  widget->SetVisibleOnAllWorkspaces(true);
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));
  EXPECT_TRUE(window_state->IsMinimized());

  // Switch desks. |window| should be on the newly active desk and should still
  // be minimized.
  ActivateDesk(desk_2);
  auto desk_2_children = desk_2->GetDeskContainerForRoot(root)->children();
  EXPECT_EQ(1u, desk_2_children.size());
  EXPECT_EQ(window.get(), desk_2_children[0]);
  EXPECT_TRUE(window_state->IsMinimized());
}

// Tests the behavior of a window that is visible on all desks when a user tries
// to move it to another desk using drag and drop (overview mode).
TEST_P(DesksTest, VisibleOnAllDesksMoveWindowToDeskViaDragAndDrop) {
  auto* controller = DesksController::Get();
  auto* root = Shell::GetPrimaryRootWindow();
  NewDesk();
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  const Desk* desk_2 = controller->GetDeskAtIndex(1);

  auto window = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto* widget = views::Widget::GetWidgetForNativeWindow(window.get());

  // Assign |window| to all desks.
  widget->SetVisibleOnAllWorkspaces(true);
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));

  // Try to move |window| to |desk_2| via drag and drop. It should not be moved.
  EXPECT_FALSE(controller->MoveWindowFromActiveDeskTo(
      window.get(), const_cast<Desk*>(desk_2), root,
      DesksMoveWindowFromActiveDeskSource::kDragAndDrop));
  EXPECT_TRUE(desks_util::BelongsToActiveDesk(window.get()));
  EXPECT_EQ(1u, controller->visible_on_all_desks_windows().size());
  EXPECT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));
  EXPECT_TRUE(base::Contains(desk_1->windows(), window.get()));
}

// Tests the behavior of a window that is visible on all desks when a user tries
// to move it to another desk using keyboard shortcuts.
TEST_P(DesksTest, VisibleOnAllDesksMoveWindowToDeskViaShortcuts) {
  auto* controller = DesksController::Get();
  auto* root = Shell::GetPrimaryRootWindow();
  NewDesk();
  const Desk* desk_2 = controller->GetDeskAtIndex(1);

  auto window = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto* widget = views::Widget::GetWidgetForNativeWindow(window.get());

  // Assign |window| to all desks.
  widget->SetVisibleOnAllWorkspaces(true);
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));

  // Move |window| to |desk_2| via keyboard shortcut. It should be on |desk_2|
  // and should no longer be visible on all desks.
  EXPECT_TRUE(controller->MoveWindowFromActiveDeskTo(
      window.get(), const_cast<Desk*>(desk_2), root,
      DesksMoveWindowFromActiveDeskSource::kShortcut));
  EXPECT_FALSE(desks_util::BelongsToActiveDesk(window.get()));
  EXPECT_EQ(0u, controller->visible_on_all_desks_windows().size());
  EXPECT_FALSE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));
  EXPECT_TRUE(base::Contains(desk_2->windows(), window.get()));
}

// Tests the behavior of a window that is visible on all desks when a user tries
// to move it using the context menu.
TEST_P(DesksTest, VisibleOnAllDesksMoveWindowToDeskViaContextMenu) {
  auto* controller = DesksController::Get();
  NewDesk();
  const Desk* desk_2 = controller->GetDeskAtIndex(1);

  auto window = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto* widget = views::Widget::GetWidgetForNativeWindow(window.get());

  // Assign |window| to all desks.
  widget->SetVisibleOnAllWorkspaces(true);
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));

  // Move |window| to |desk_2| via keyboard shortcut. It should be on |desk_2|
  // and should no longer be visible on all desks.
  controller->SendToDeskAtIndex(window.get(), controller->GetDeskIndex(desk_2));
  EXPECT_FALSE(desks_util::BelongsToActiveDesk(window.get()));
  EXPECT_EQ(0u, controller->visible_on_all_desks_windows().size());
  EXPECT_FALSE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));
  EXPECT_TRUE(base::Contains(desk_2->windows(), window.get()));
}

// Tests that when a window that is visible on all desks is destroyed it is
// removed from DesksController.visible_on_all_desks_windows_.
TEST_P(DesksTest, VisibleOnAllDesksWindowDestruction) {
  auto* controller = DesksController::Get();
  NewDesk();
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  auto* root = Shell::GetPrimaryRootWindow();

  auto window = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto* widget = views::Widget::GetWidgetForNativeWindow(window.get());

  // Assign |window| to all desks.
  widget->SetVisibleOnAllWorkspaces(true);
  ASSERT_TRUE(desks_util::IsWindowVisibleOnAllWorkspaces(window.get()));
  EXPECT_EQ(1u, controller->visible_on_all_desks_windows().size());
  EXPECT_EQ(1u, desk_1->GetDeskContainerForRoot(root)->children().size());

  // Destroy |window|. It should be removed from
  // DesksController.visible_on_all_desks_windows_.
  window.reset();
  EXPECT_EQ(0u, controller->visible_on_all_desks_windows().size());
  EXPECT_EQ(0u, desk_1->GetDeskContainerForRoot(root)->children().size());
}

// Tests that when a window that isn't on the currently active desk is made
// visible on all desks, it is also moved to the active desk.
TEST_P(DesksTest, VisibleOnAllDesksInactiveDesk) {
  auto* controller = DesksController::Get();
  auto window = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto* widget = views::Widget::GetWidgetForNativeWindow(window.get());

  NewDesk();
  auto* desk1 = controller->GetDeskAtIndex(0);
  auto* desk2 = controller->GetDeskAtIndex(1);

  ActivateDesk(desk2);
  ASSERT_FALSE(desk1->is_active());
  ASSERT_TRUE(desk2->is_active());

  // The test `window` should exist on the first desk.
  ASSERT_THAT(desk1->windows(), ElementsAre(window.get()));
  ASSERT_THAT(desk2->windows(), ElementsAre());

  // Assign `window` to all desks, this should move it to the active desk.
  widget->SetVisibleOnAllWorkspaces(true);
  EXPECT_THAT(desk1->windows(), ElementsAre());
  EXPECT_THAT(desk2->windows(), ElementsAre(window.get()));
}

// Tests that the desk bar exit animation would not cause any crash or UAF.
// Please refer to b/274497402.
TEST_P(DesksTest, DesksBarExitAnimation) {
  // Create another desk so that the desk bar is not zero state.
  NewDesk();

  // Set to non-zero animation.
  ui::ScopedAnimationDurationScaleMode animation(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  // Enter then exit overview. When shutting down overview grid, the desk bar
  // slide animation will take over the ownership of the desk bar widget. This
  // is to ensure no crash or UAF after the ownership change.
  EnterOverview();
  ExitOverview();
}

TEST_P(DesksTest, EnterOverviewWithCorrectDesksBarState) {
  auto* controller = DesksController::Get();
  ASSERT_EQ(1u, controller->desks().size());
  EnterOverview();

  auto* root_window = Shell::GetPrimaryRootWindow();
  auto* desks_bar_view = GetOverviewGridForRoot(root_window)->desks_bar_view();

  // Desks bar should stay in zero state if there is only one desk and no mini
  // view has been created.
  EXPECT_TRUE(desks_bar_view->IsZeroState());
  EXPECT_TRUE(desks_bar_view->mini_views().empty());

  // Click new desk button in the zero state bar to create a new desk.
  LeftClickOn(desks_bar_view->new_desk_button());
  ExitOverview();

  // Desks bar should not stay in zero state if there are more than one desks.
  EXPECT_EQ(2u, controller->desks().size());
  EnterOverview();
  desks_bar_view = GetOverviewGridForRoot(root_window)->desks_bar_view();
  EXPECT_EQ(2u, desks_bar_view->mini_views().size());
  EXPECT_FALSE(desks_bar_view->IsZeroState());
}

// Tests the behavior of desks bar zero state.
TEST_P(DesksTest, DesksBarZeroState) {
  EnterOverview();

  auto* root_window = Shell::GetPrimaryRootWindow();
  auto* desks_bar_view = GetOverviewGridForRoot(root_window)->desks_bar_view();
  ASSERT_TRUE(desks_bar_view->IsZeroState());
  ASSERT_TRUE(desks_bar_view->mini_views().empty());

  auto* default_desk_button = desks_bar_view->default_desk_button();
  auto* new_desk_button = desks_bar_view->new_desk_button();
  LeftClickOn(default_desk_button);
  // Click the zero state default desk button should switch to expanded desks
  // bar and focus on the default desk's name view. The two buttons in zero
  // state bar should also be hidden.
  EXPECT_FALSE(desks_bar_view->IsZeroState());
  EXPECT_EQ(1u, desks_bar_view->mini_views().size());
  EXPECT_TRUE(desks_bar_view->mini_views()[0]->desk_name_view()->HasFocus());
  EXPECT_FALSE(default_desk_button->GetVisible());
  VerifyZeroStateNewDeskButtonVisibility(desks_bar_view, false);

  ExitOverview();
  EnterOverview();
  desks_bar_view = GetOverviewGridForRoot(root_window)->desks_bar_view();
  ASSERT_TRUE(desks_bar_view->IsZeroState());

  default_desk_button = desks_bar_view->default_desk_button();
  new_desk_button = desks_bar_view->new_desk_button();
  LeftClickOn(new_desk_button);
  // Click the zero state new desk button should switch to expand desks bar,
  // create a new desk and focus on the new created desk's name view. The two
  // buttons in zero state bar should also be hidden.
  EXPECT_FALSE(desks_bar_view->IsZeroState());
  EXPECT_EQ(2u, desks_bar_view->mini_views().size());
  EXPECT_TRUE(desks_bar_view->mini_views()[1]->desk_name_view()->HasFocus());
  EXPECT_FALSE(default_desk_button->GetVisible());
  VerifyZeroStateNewDeskButtonVisibility(desks_bar_view, false);

  CloseDeskFromMiniView(desks_bar_view->mini_views()[0], GetEventGenerator());
  // Desks bar doesn't switch to zero state even if there is only one desk after
  // removing.
  EXPECT_FALSE(desks_bar_view->IsZeroState());
  EXPECT_FALSE(default_desk_button->GetVisible());
  VerifyZeroStateNewDeskButtonVisibility(desks_bar_view, false);
}

// Tests that buttons in the desk bar are shown and hidden correctly when
// transitioning into zero state to ensure ChromeVox navigation works properly.
// Regression test for https://crbug.com/1351501.
TEST_P(DesksTest, DesksBarButtonVisibility) {
  auto* controller = DesksController::Get();

  // Create a new desk so when we enter overview mode the desks bar is in the
  // expanded state.
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());

  // Enter overview mode and check that the desks bar is in the expanded state.
  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());
  const auto* desks_bar_view =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  ASSERT_TRUE(desks_bar_view);
  ASSERT_FALSE(desks_bar_view->IsZeroState());

  // Verify that the expanded state button is visible, while the zero state
  // buttons are not visible.
  auto* default_desk_button = desks_bar_view->default_desk_button();
  VerifyExpandedStateNewDeskButtonVisibility(desks_bar_view, true);
  VerifyZeroStateNewDeskButtonVisibility(desks_bar_view, false);
  EXPECT_FALSE(default_desk_button->GetVisible());

  // Close a desk and check that the desks bar switches into zero state.
  auto* mini_view = desks_bar_view->mini_views().front().get();
  CloseDeskFromMiniView(mini_view, GetEventGenerator());
  ASSERT_EQ(1u, controller->desks().size());
  ASSERT_FALSE(desks_bar_view->IsZeroState());
  EXPECT_EQ(1u, desks_bar_view->mini_views().size());

  // The desk bar doesn't go back to zero state.
  VerifyExpandedStateNewDeskButtonVisibility(desks_bar_view, true);
  VerifyZeroStateNewDeskButtonVisibility(desks_bar_view, false);
  EXPECT_FALSE(default_desk_button->GetVisible());
}

TEST_P(DesksTest, NewDeskButton) {
  auto* controller = DesksController::Get();
  EnterOverview();

  auto* root_window = Shell::GetPrimaryRootWindow();
  auto* desks_bar_view = GetOverviewGridForRoot(root_window)->desks_bar_view();

  // Click the default desk button in the zero state bar to switch to expanded
  // desks bar.
  LeftClickOn(desks_bar_view->default_desk_button());
  RunScheduledLayoutForAllOverviewDeskBars();
  auto* new_desk_button = desks_bar_view->new_desk_button();
  EXPECT_TRUE(new_desk_button->GetVisible());
  EXPECT_TRUE(new_desk_button->GetEnabled());

  for (size_t i = 1; i < desks_util::GetMaxNumberOfDesks(); i++) {
    LeftClickOn(new_desk_button);
    RunScheduledLayoutForAllOverviewDeskBars();

    // When a new desk is created, ensure its desk mini view fully visible.
    auto* mini_view = desks_bar_view->mini_views().back().get();
    EXPECT_EQ(mini_view->size(), mini_view->GetVisibleBounds().size());

    // TODO(b/277081702): When desk order is adjusted for RTL, remove the check
    // below to always make new desk button visible.
    if (!base::i18n::IsRTL()) {
      EXPECT_EQ(new_desk_button->size(),
                new_desk_button->GetVisibleBounds().size());
    }

    TryScrollOverviewDeskBar(DeskBarScrollDirection::kRight);
    RunScheduledLayoutForAllOverviewDeskBars();
  }

  // The new desk button should become disabled after maximum number of desks
  // have been created.
  EXPECT_FALSE(controller->CanCreateDesks());
  EXPECT_FALSE(new_desk_button->GetEnabled());

  ASSERT_EQ(controller->desks().size(), desks_util::GetMaxNumberOfDesks());

  // The new desk button should become enabled again after removing a desk.
  CloseDeskFromMiniView(desks_bar_view->mini_views().back(),
                        GetEventGenerator());
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_TRUE(controller->CanCreateDesks());
  EXPECT_TRUE(new_desk_button->GetEnabled());
}

TEST_P(DesksTest, ZeroStateDeskButtonText) {
  UpdateDisplay("1600x1200");
  EnterOverview();

  auto* root_window = Shell::GetPrimaryRootWindow();
  auto* desks_bar_view = GetOverviewGridForRoot(root_window)->desks_bar_view();
  ASSERT_TRUE(desks_bar_view->IsZeroState());
  // Show the default name "Desk 1" while initializing the desks bar at the
  // first time.
  EXPECT_EQ(u"Desk 1", desks_bar_view->default_desk_button()->GetText());

  LeftClickOn(desks_bar_view->default_desk_button());
  EXPECT_TRUE(desks_bar_view->mini_views()[0]->desk_name_view()->HasFocus());

  // Change the desk name to "test".
  PressAndReleaseKey(ui::VKEY_T);
  PressAndReleaseKey(ui::VKEY_E);
  PressAndReleaseKey(ui::VKEY_S);
  PressAndReleaseKey(ui::VKEY_T);
  PressAndReleaseKey(ui::VKEY_RETURN);
  ExitOverview();
  EnterOverview();

  desks_bar_view = GetOverviewGridForRoot(root_window)->desks_bar_view();
  EXPECT_TRUE(desks_bar_view->IsZeroState());
  // Should show the desk's current name "test" instead of the default name.
  EXPECT_EQ(u"test", desks_bar_view->default_desk_button()->GetText());

  // Create 'Desk 2'.
  LeftClickOn(desks_bar_view->new_desk_button());
  EXPECT_FALSE(desks_bar_view->IsZeroState());
  PressAndReleaseKey(ui::VKEY_RETURN);
  EXPECT_EQ(u"Desk 2", DesksController::Get()->GetDeskAtIndex(1)->name());

  // Close desk 'test' should return to zero state and the zero state default
  // desk button should show current desk's name, which is 'Desk 1'.
  CloseDeskFromMiniView(desks_bar_view->mini_views()[0], GetEventGenerator());

  // Once we leave zero state, we can't go back without exiting overview.
  ExitOverview();
  EnterOverview();
  desks_bar_view = GetOverviewGridForRoot(root_window)->desks_bar_view();
  EXPECT_TRUE(desks_bar_view->IsZeroState());
  EXPECT_EQ(u"Desk 1", desks_bar_view->default_desk_button()->GetText());

  // Set a super long desk name.
  LeftClickOn(desks_bar_view->default_desk_button());
  for (size_t i = 0; i < DeskTextfield::kMaxLength + 5; i++) {
    PressAndReleaseKey(ui::VKEY_A);
  }
  PressAndReleaseKey(ui::VKEY_RETURN);
  ExitOverview();
  EnterOverview();

  desks_bar_view = GetOverviewGridForRoot(root_window)->desks_bar_view();
  auto* default_desk_button = desks_bar_view->default_desk_button();
  std::u16string desk_button_text = default_desk_button->GetText();
  std::u16string expected_desk_name(DeskTextfield::kMaxLength, L'a');
  // Zero state desk button should show the elided name as the DeskNameView.
  EXPECT_EQ(expected_desk_name,
            DesksController::Get()->GetDeskAtIndex(0)->name());
  EXPECT_NE(expected_desk_name, desk_button_text);
  EXPECT_TRUE(base::StartsWith(base::UTF16ToUTF8(desk_button_text), "aaa",
                               base::CompareCase::SENSITIVE));
  EXPECT_FALSE(base::EndsWith(base::UTF16ToUTF8(desk_button_text), "aaa",
                              base::CompareCase::SENSITIVE));
}

TEST_P(DesksTest, ReorderDesksByMouse) {
  auto* desks_controller = DesksController::Get();

  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  auto* root_window = Shell::GetPrimaryRootWindow();
  const auto* desks_bar_view =
      GetOverviewGridForRoot(root_window)->desks_bar_view();

  auto* event_generator = GetEventGenerator();

  // Add two desks (Now we have three desks).
  NewDesk();
  NewDesk();

  // Cache the mini view and corresponding desks.
  std::vector<raw_ptr<DeskMiniView, VectorExperimental>> mini_views =
      desks_bar_view->mini_views();
  DeskMiniView* mini_view_0 = mini_views[0];
  Desk* desk_0 = mini_view_0->desk();
  DeskMiniView* mini_view_1 = mini_views[1];
  Desk* desk_1 = mini_view_1->desk();
  DeskMiniView* mini_view_2 = mini_views[2];
  Desk* desk_2 = mini_view_2->desk();

  // Set desk names. Force update user prefs because `SetName()` does not
  // trigger it but `DeskMiniView::OnViewBlurred`.
  desk_0->SetName(u"0", /*set_by_user=*/true);
  desk_1->SetName(u"1", /*set_by_user=*/true);
  desk_2->SetName(u"2", /*set_by_user=*/true);
  desks_restore_util::UpdatePrimaryUserDeskNamesPrefs();

  auto* prefs = Shell::Get()->session_controller()->GetPrimaryUserPrefService();
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("0", "1", "2"));

  // Dragging the desk preview will trigger drag & drop.
  StartDragDeskPreview(mini_view_1, event_generator);
  EXPECT_TRUE(desks_bar_view->IsDraggingDesk());

  event_generator->ReleaseLeftButton();
  RunScheduledLayoutForAllOverviewDeskBars();

  // Reorder the second desk
  StartDragDeskPreview(mini_view_1, event_generator);
  EXPECT_TRUE(desks_bar_view->IsDraggingDesk());

  // Swap the positions of the second desk and the third desk.
  gfx::Point desk_center_2 =
      mini_view_2->GetPreviewBoundsInScreen().CenterPoint();
  event_generator->MoveMouseTo(desk_center_2);
  RunScheduledLayoutForAllOverviewDeskBars();

  // Now, the desks order should be [0, 2, 1]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_2));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_1));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("0", "2", "1"));

  // Swap the positions of the second desk and the first desk.
  gfx::Point desk_center_0 =
      mini_view_0->GetPreviewBoundsInScreen().CenterPoint();
  event_generator->MoveMouseTo(desk_center_0);
  RunScheduledLayoutForAllOverviewDeskBars();

  // Now, the desks order should be [1, 0, 2]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_1));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_2));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("1", "0", "2"));

  event_generator->ReleaseLeftButton();
  RunScheduledLayoutForAllOverviewDeskBars();
}

TEST_P(DesksTest, ReorderDesksByGesture) {
  auto* desks_controller = DesksController::Get();

  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  auto* root_window = Shell::GetPrimaryRootWindow();
  const auto* desks_bar_view =
      GetOverviewGridForRoot(root_window)->desks_bar_view();

  auto* event_generator = GetEventGenerator();

  // Add two desks (Now we have three desks).
  NewDesk();
  NewDesk();
  RunScheduledLayoutForAllOverviewDeskBars();

  // Cache the mini view and corresponding desks.
  std::vector<raw_ptr<DeskMiniView, VectorExperimental>> mini_views =
      desks_bar_view->mini_views();
  DeskMiniView* mini_view_0 = mini_views[0];
  Desk* desk_0 = mini_view_0->desk();
  DeskMiniView* mini_view_1 = mini_views[1];
  Desk* desk_1 = mini_view_1->desk();
  DeskMiniView* mini_view_2 = mini_views[2];
  Desk* desk_2 = mini_view_2->desk();

  // Set desk names and save to user prefs.
  desk_0->SetName(u"0", /*set_by_user=*/true);
  desk_1->SetName(u"1", /*set_by_user=*/true);
  desk_2->SetName(u"2", /*set_by_user=*/true);
  desks_restore_util::UpdatePrimaryUserDeskNamesPrefs();

  auto* prefs = Shell::Get()->session_controller()->GetPrimaryUserPrefService();
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("0", "1", "2"));

  // If long press on the second desk preview, drag & drop will be triggered.
  // Perform by gesture:
  LongTapOnDeskPreview(mini_view_1, event_generator);
  EXPECT_TRUE(desks_bar_view->IsDraggingDesk());

  event_generator->ReleaseTouch();

  // The context menu appears on a long press on the desk preview. In order to
  // drag the desk again, we first need to get rid of the context menu by
  // tapping and waiting for the menu to disappear.
  event_generator->GestureTapDownAndUp(
      mini_view_1->desk_preview()->GetBoundsInScreen().CenterPoint());
  base::RunLoop().RunUntilIdle();

  // Reorder the second desk
  LongTapOnDeskPreview(mini_view_1, event_generator);
  EXPECT_TRUE(desks_bar_view->IsDraggingDesk());

  // Swap the positions of the second desk and the third desk.
  gfx::Point desk_center_2 =
      mini_view_2->GetPreviewBoundsInScreen().CenterPoint();

  // We need to drag the mouse a bit after long-tapping the desk preview to
  // start the closing of the context menu before rearranging the desk.
  event_generator->MoveTouchBy(10, 0);

  event_generator->MoveTouch(desk_center_2);
  RunScheduledLayoutForAllOverviewDeskBars();

  // Now, the desks order should be [0, 2, 1]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_2));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_1));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("0", "2", "1"));

  // Swap the positions of the second desk and the first desk.
  gfx::Point desk_center_0 =
      mini_view_0->GetPreviewBoundsInScreen().CenterPoint();
  event_generator->MoveTouch(desk_center_0);

  // Now, the desks order should be [1, 0, 2]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_1));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_2));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("1", "0", "2"));

  event_generator->ReleaseTouch();
}

TEST_P(DesksTest, ReorderDesksByKeyboard) {
  auto* desks_controller = DesksController::Get();

  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());

  auto* root_window = Shell::GetPrimaryRootWindow();
  auto* overview_grid = GetOverviewGridForRoot(root_window);
  const auto* desks_bar_view = overview_grid->desks_bar_view();

  auto* event_generator = GetEventGenerator();

  // Add two desks (Now we have three desks).
  NewDesk();
  NewDesk();

  overview_grid->CommitNameChanges();

  // Cache the mini view and corresponding desks.
  std::vector<raw_ptr<DeskMiniView, VectorExperimental>> mini_views =
      desks_bar_view->mini_views();
  DeskMiniView* mini_view_0 = mini_views[0];
  Desk* desk_0 = mini_view_0->desk();
  DeskMiniView* mini_view_1 = mini_views[1];
  Desk* desk_1 = mini_view_1->desk();
  DeskMiniView* mini_view_2 = mini_views[2];
  Desk* desk_2 = mini_view_2->desk();

  // Set desk names and save to user prefs.
  desk_0->SetName(u"0", /*set_by_user=*/true);
  desk_1->SetName(u"1", /*set_by_user=*/true);
  desk_2->SetName(u"2", /*set_by_user=*/true);
  desks_restore_util::UpdatePrimaryUserDeskNamesPrefs();

  auto* prefs = Shell::Get()->session_controller()->GetPrimaryUserPrefService();
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("0", "1", "2"));

  // Focus the second desk.
  mini_view_1->desk_preview()->RequestFocus();

  // Swap the positions of the second desk and the third desk by pressing Ctrl +
  // ->.
  event_generator->PressKey(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN);

  // Now, the desks order should be [0, 2, 1]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_2));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_1));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("0", "2", "1"));

  // Keep pressing -> won't swap desks.
  event_generator->PressKey(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN);

  // Now, the desks order should be [0, 2, 1]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_2));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_1));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("0", "2", "1"));

  // Press Ctrl + <- twice will swap the positions of the second and first desk.
  event_generator->PressKey(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN);
  event_generator->PressKey(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN);

  // Now, the desks order should be [1, 0, 2]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_1));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_2));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("1", "0", "2"));

  // Keep pressing <- won't swap desks.
  event_generator->PressKey(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN);

  // Now, the desks order should be [1, 0, 2]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_1));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_2));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("1", "0", "2"));
}

// Test reordering desks in RTL mode.
TEST_P(DesksTest, ReorderDesksInRTLMode) {
  // Turn on RTL mode.
  const bool default_rtl = base::i18n::IsRTL();
  base::i18n::SetRTLForTesting(true);
  EXPECT_TRUE(base::i18n::IsRTL());

  auto* desks_controller = DesksController::Get();

  auto* overview_controller = OverviewController::Get();
  EnterOverview();
  EXPECT_TRUE(overview_controller->InOverviewSession());

  auto* root_window = Shell::GetPrimaryRootWindow();
  const auto* desks_bar_view =
      GetOverviewGridForRoot(root_window)->desks_bar_view();

  auto* event_generator = GetEventGenerator();

  // Add two desks (Now we have three desks).
  NewDesk();
  NewDesk();

  // Cache the mini view and corresponding desks.
  std::vector<raw_ptr<DeskMiniView, VectorExperimental>> mini_views =
      desks_bar_view->mini_views();
  DeskMiniView* mini_view_0 = mini_views[0];
  Desk* desk_0 = mini_view_0->desk();
  DeskMiniView* mini_view_1 = mini_views[1];
  Desk* desk_1 = mini_view_1->desk();
  DeskMiniView* mini_view_2 = mini_views[2];
  Desk* desk_2 = mini_view_2->desk();

  // Set desk names. Force update user prefs because `SetName()` does not
  // trigger it but `DeskMiniView::OnViewBlurred`.
  desk_0->SetName(u"0", /*set_by_user=*/true);
  desk_1->SetName(u"1", /*set_by_user=*/true);
  desk_2->SetName(u"2", /*set_by_user=*/true);
  desks_restore_util::UpdatePrimaryUserDeskNamesPrefs();

  auto* prefs = Shell::Get()->session_controller()->GetPrimaryUserPrefService();
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("0", "1", "2"));

  // Swap the positions of the |desk_1| and the |desk_2| by mouse.
  StartDragDeskPreview(mini_view_1, event_generator);
  EXPECT_TRUE(desks_bar_view->IsDraggingDesk());

  gfx::Point desk_center_2 =
      mini_view_2->GetPreviewBoundsInScreen().CenterPoint();
  event_generator->MoveMouseTo(desk_center_2);

  // Now, the desks order should be [0, 2, 1]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_2));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_1));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("0", "2", "1"));
  event_generator->ReleaseLeftButton();

  // Swap the positions of the |desk_1| and the |desk_0| by gesture.
  LongTapOnDeskPreview(mini_view_1, event_generator);
  EXPECT_TRUE(desks_bar_view->IsDraggingDesk());

  gfx::Point desk_center_0 =
      mini_view_0->GetPreviewBoundsInScreen().CenterPoint();

  // We need to drag the mouse a bit after long-tapping the desk preview to
  // start the closing of the context menu before rearranging the desk.
  event_generator->MoveTouchBy(-10, 0);

  event_generator->MoveTouch(desk_center_0);

  // Now, the desks order should be [1, 0, 2]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_1));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_0));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_2));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("1", "0", "2"));
  event_generator->ReleaseTouch();

  // Swap the positions of `desk_0` and `desk_2` by keyboard. Focus `desk_0`.
  // Focus the second desk.
  mini_view_0->desk_preview()->RequestFocus();

  // Swap the positions of the |desk_0| and the |desk_2| by pressing Ctrl + ->.
  event_generator->PressKey(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN);

  // Now, the desks order should be [1, 2, 0]:
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_1));
  EXPECT_EQ(1, desks_controller->GetDeskIndex(desk_2));
  EXPECT_EQ(2, desks_controller->GetDeskIndex(desk_0));
  EXPECT_THAT(GetDeskRestoreNames(prefs), ElementsAre("1", "2", "0"));

  // Recover to default RTL mode.
  base::i18n::SetRTLForTesting(default_rtl);
}

// Tests the behavior when dragging a desk on the scroll button.
TEST_P(DesksTest, ScrollBarByDraggedDesk) {
  const int scroll_timeout_ms = 20;
  base::AutoReset<base::TimeDelta> auto_reset =
      DesksTestApi::SetScrollTimeInterval(
          base::Milliseconds(scroll_timeout_ms));

  // Make a flat long window to generate multiple pages on desks bar.
  UpdateDisplay("800x150");
  const size_t max_desks_size = desks_util::GetMaxNumberOfDesks();
  for (size_t i = 1; i < max_desks_size; i++) {
    NewDesk();
  }

  auto* desks_controller = DesksController::Get();
  EXPECT_EQ(desks_controller->desks().size(), max_desks_size);
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
  auto* desks_bar =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();

  views::ScrollView* scroll_view =
      DesksTestApi::GetDeskBarScrollView(DeskBarViewBase::Type::kOverview);
  ASSERT_TRUE(scroll_view);
  const int page_size = scroll_view->width();
  auto mini_views = desks_bar->mini_views();
  const int mini_view_width = mini_views[0]->bounds().width();
  int desks_in_one_page = page_size / mini_view_width;
  float fractional_page = static_cast<float>(page_size % mini_view_width) /
                          static_cast<float>(mini_view_width);
  if (fractional_page > 0.5) {
    desks_in_one_page++;
  }

  int current_index = 0;
  ScrollArrowButton* left_button = DesksTestApi::GetDeskBarLeftScrollButton(
      DeskBarViewBase::Type::kOverview);
  ASSERT_TRUE(left_button);
  ScrollArrowButton* right_button = DesksTestApi::GetDeskBarRightScrollButton(
      DeskBarViewBase::Type::kOverview);
  ASSERT_TRUE(right_button);

  // At first, left scroll button is hidden and right scroll button is visible.
  EXPECT_FALSE(left_button->GetVisible());
  EXPECT_TRUE(right_button->GetVisible());

  // Dragging a desk on the right scroll button should scroll to the next page.
  // And the final scroll position should be adjusted to make sure the desk
  // preview will not be cropped.
  auto* event_generator = GetEventGenerator();
  DeskMiniView* mini_view_0 = mini_views[0];
  Desk* desk_0 = mini_view_0->desk();

  const int focus_ring_width_and_padding = 4;

  StartDragDeskPreview(mini_view_0, event_generator);
  EXPECT_TRUE(desks_bar->IsDraggingDesk());
  event_generator->MoveMouseTo(right_button->GetBoundsInScreen().CenterPoint());
  RunScheduledLayoutForAllOverviewDeskBars();
  current_index += desks_in_one_page;
  EXPECT_EQ(scroll_view->GetVisibleRect().x() + focus_ring_width_and_padding,
            mini_views[current_index]->bounds().x());

  // Both scroll buttons should be visible.
  EXPECT_TRUE(left_button->GetVisible());
  EXPECT_TRUE(right_button->GetVisible());

  // Wait for 20ms, there will be another scroll.
  WaitForMilliseconds(scroll_timeout_ms);
  current_index += desks_in_one_page;

  // When the maximum number of desks is 8, the new desk button is smaller, two
  // scrolls will reach the end of the desks bar view, thus we verify the right
  // of the visible scroll view.
  if (!features::Is16DesksEnabled()) {
    EXPECT_EQ(
        scroll_view->GetVisibleRect().right() - focus_ring_width_and_padding,
        desks_bar->new_desk_button()->bounds().right());
  } else {
    EXPECT_EQ(scroll_view->GetVisibleRect().x() + focus_ring_width_and_padding,
              mini_views[current_index]->bounds().x());
  }

  // While scrolling, the desk cannot be reordered.
  EXPECT_EQ(0, desks_controller->GetDeskIndex(desk_0));

  // Wait longer, it will scroll to the maximum offset. When 16 desks are
  // enabled, we need to allow more time for scrolling.
  WaitForMilliseconds(GetParam().use_16_desks ? 10 * scroll_timeout_ms
                                              : scroll_timeout_ms);
  EXPECT_EQ(scroll_view->GetVisibleRect().x(),
            scroll_view->contents()->width() - page_size);

  // Left scroll button should be visible and right scroll button should be
  // hidden.
  EXPECT_TRUE(left_button->GetVisible());
  EXPECT_FALSE(right_button->GetVisible());

  // Move the dragged desk to the center of the last desk.
  event_generator->MoveMouseTo(
      mini_views[max_desks_size - 1]->GetBoundsInScreen().CenterPoint());
  RunScheduledLayoutForAllOverviewDeskBars();
  // The dragged desk is reordered to the end.
  const int max_index = static_cast<int>(max_desks_size) - 1;
  // Now the desk is reordered to the last position.
  EXPECT_EQ(max_index, desks_controller->GetDeskIndex(desk_0));
  event_generator->ReleaseLeftButton();
  RunScheduledLayoutForAllOverviewDeskBars();

  current_index = max_desks_size - 1;

  // Dragging the desk to left scroll button should scroll to the previous page.
  // And the final scroll position should also be adjusted while scrolling to
  // the previous page to make sure the desk preview will not be cropped.
  mini_views = desks_bar->mini_views();
  StartDragDeskPreview(mini_views[max_desks_size - 1], event_generator);
  event_generator->MoveMouseTo(left_button->GetBoundsInScreen().CenterPoint());
  RunScheduledLayoutForAllOverviewDeskBars();
  // The new desk button and the library button are smaller, thus when scroll to
  // the left from the right most.
  current_index -= (desks_in_one_page + 1);
  EXPECT_EQ(scroll_view->GetVisibleRect().x() + focus_ring_width_and_padding,
            mini_views[current_index]->bounds().x());

  // Wait for 20ms, there is another scroll.
  WaitForMilliseconds(scroll_timeout_ms);
  current_index -= desks_in_one_page;
  EXPECT_EQ(scroll_view->GetVisibleRect().x() + focus_ring_width_and_padding,
            mini_views[current_index]->bounds().x());

  // The desk is still not reordered while scrolling backward.
  EXPECT_EQ(max_index, desks_controller->GetDeskIndex(desk_0));

  // Drop the desk. Desks bar will scroll to show the desk's target position.
  event_generator->ReleaseLeftButton();
  RunScheduledLayoutForAllOverviewDeskBars();
  // Wait 100 milliseconds for the animation of the scrollable bar to end.
  // Otherwise, the test could be flaky, i.e, the visible bounds of the scroll
  // bar is not updated yet if we get its bounds immediately after the desk is
  // dropped.
  WaitForMilliseconds(100);
  gfx::Rect bounds_0 = mini_view_0->bounds();
  gfx::Rect bounds_visible = scroll_view->GetVisibleRect();
  EXPECT_LE(bounds_visible.x(), bounds_0.x());
  EXPECT_GE(bounds_visible.right(), bounds_0.right());
}

// Tests that while reordering desks by drag & drop, when a desk is snapping
// back, click its target location won't cause any crashes.
// Regression test of https://crbug.com/1171880.
TEST_P(DesksTest, ClickTargetLocationOfDroppedDesk) {
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  DeskBarViewBase* desk_bar_view = overview_grid->desks_bar_view();

  // Add a desk.
  NewDesk();

  // Cache the second desk's mini view.
  DeskMiniView* mini_view = desk_bar_view->mini_views()[1];

  auto* event_generator = GetEventGenerator();

  // Drag the second desk away from the desk bar.
  StartDragDeskPreview(mini_view, event_generator);
  EXPECT_TRUE(desk_bar_view->IsDraggingDesk());

  event_generator->MoveMouseBy(0, desk_bar_view->height());

  ui::ScopedAnimationDurationScaleMode normal_anim(
      ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION);
  // Drop the desk and click on the mini view.
  event_generator->ReleaseLeftButton();
  EXPECT_TRUE(desk_bar_view->IsDraggingDesk());
  DeskSwitchAnimationWaiter waiter;
  LeftClickOn(mini_view);
  DesksTestApi::WaitForDeskBarUiUpdate(desk_bar_view);
  waiter.Wait();
}

// Tests that while reordering desks by drag & drop, when a desk is snapping
// back, dragging a desk preview on the shelf will start a new drag.
TEST_P(DesksTest, DragNewDeskWhileSnappingBack) {
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();

  // Add a desk.
  NewDesk();

  // Cache the desks' mini views.
  DeskMiniView* mini_view_1 = desks_bar_view->mini_views()[0];
  DeskMiniView* mini_view_2 = desks_bar_view->mini_views()[1];

  auto* event_generator = GetEventGenerator();

  // Drag the second desk away from the desk bar.
  StartDragDeskPreview(mini_view_2, event_generator);
  EXPECT_EQ(DesksTestApi::GetDeskBarDragView(DeskBarViewBase::Type::kOverview),
            mini_view_2);

  event_generator->MoveMouseBy(0, desks_bar_view->height());

  ui::ScopedAnimationDurationScaleMode normal_anim(
      ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION);

  // Drop the desk and drag first desk.
  event_generator->ReleaseLeftButton();
  EXPECT_EQ(DesksTestApi::GetDeskBarDragView(DeskBarViewBase::Type::kOverview),
            mini_view_2);
  StartDragDeskPreview(mini_view_1, event_generator);
  EXPECT_EQ(DesksTestApi::GetDeskBarDragView(DeskBarViewBase::Type::kOverview),
            mini_view_1);
}

// Tests that dragging desk is ended in two cases: (1) removing a dragged desk.
// (2) removing a desk makes the dragged desk the only one left. Then, releasing
// mouse or exiting overview will not have UAF issues
// (https://crbug.com/1222120).
TEST_P(DesksTest, RemoveDeskWhileDragging) {
  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  const auto* desks_bar_view =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();

  auto* event_generator = GetEventGenerator();

  // Add two desks (Now we have three desks).
  NewDesk();
  NewDesk();

  // Cache the mini views.
  const std::vector<raw_ptr<DeskMiniView, VectorExperimental>>& mini_views =
      desks_bar_view->mini_views();
  DeskMiniView* mini_view_0 = mini_views[0];
  DeskMiniView* mini_view_1 = mini_views[1];
  DeskMiniView* mini_view_2 = mini_views[2];

  // Dragging the first desk preview will trigger drag & drop.
  StartDragDeskPreview(mini_view_0, event_generator);
  EXPECT_TRUE(desks_bar_view->IsDraggingDesk());

  // Removing the first desk will end dragging.
  RemoveDesk(mini_view_0->desk());
  EXPECT_FALSE(desks_bar_view->IsDraggingDesk());

  // Releasing mouse will not have any issue.
  event_generator->ReleaseLeftButton();

  // There are only two desks left.
  EXPECT_EQ(2u, mini_views.size());

  // Dragging the second desk preview.
  StartDragDeskPreview(mini_view_1, event_generator);
  EXPECT_TRUE(desks_bar_view->IsDraggingDesk());

  RemoveDesk(mini_view_2->desk());
  // Removing the third desk won't end dragging, since the desk bar doesn't
  // switch to zero state.
  EXPECT_TRUE(desks_bar_view->IsDraggingDesk());

  // Exiting overview will not have any issue.
  ExitOverview();
}

// Used to wait for all animations to complete in a `LayerAnimator`.
class LayerAnimationWaiter : public ui::LayerAnimationObserver {
 public:
  explicit LayerAnimationWaiter(ui::LayerAnimator* animator)
      : animator_(animator) {
    animator_->AddObserver(this);
  }

  void OnLayerAnimationEnded(ui::LayerAnimationSequence* sequence) override {
    OnAnimationCompleted();
  }

  void OnLayerAnimationAborted(ui::LayerAnimationSequence* sequence) override {
    OnAnimationCompleted();
  }

  void OnLayerAnimationScheduled(
      ui::LayerAnimationSequence* sequence) override {}

  void Wait() { run_loop_.Run(); }

 private:
  void OnAnimationCompleted() {
    if (animator_->is_animating() == false) {
      animator_->RemoveObserver(this);
      run_loop_.Quit();
    }
  }

  raw_ptr<ui::LayerAnimator> animator_;
  base::RunLoop run_loop_;
};

// Regression test for the asan failure at https://crbug.com/1274641.
TEST_P(DesksTest, DragMiniViewWhileRemoving) {
  NewDesk();
  NewDesk();

  EnterOverview();
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

  const auto* desks_bar_view =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();

  auto* event_generator = GetEventGenerator();

  // Cache the center point of the desk preview that is about to be removed.
  auto* mini_view = desks_bar_view->mini_views().back().get();
  const gfx::Point desk_preview_center =
      mini_view->GetPreviewBoundsInScreen().CenterPoint();

  LayerAnimationWaiter animation_waiter(mini_view->layer()->GetAnimator());
  {
    // This test requires animation to repro the asan failure.
    ui::ScopedAnimationDurationScaleMode animation_scale(
        ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION);

    // This will trigger the mini view removal animation, and the miniview won't
    // be removed immediately.
    CloseDeskFromMiniView(mini_view, event_generator);

    // Drag the mini view that is being animated to be removed, and expect drag
    // not to start, nor trigger a crash or an asan failure.
    event_generator->set_current_screen_location(desk_preview_center);
    event_generator->PressLeftButton();
    event_generator->MoveMouseBy(0, 50);
    EXPECT_FALSE(desks_bar_view->IsDraggingDesk());
  }

  animation_waiter.Wait();
}

// Tests that the right desk containers are visible when switching between desks
// really fast. Regression test for https://crbug.com/1194757.
TEST_P(DesksTest, FastDeskSwitches) {
  // Add 3 more desks and add a couple windows on each one.
  CreateTestWindow();
  CreateTestWindow();

  for (int i = 0; i < 3; ++i) {
    NewDesk();
    CreateTestWindow();
    CreateTestWindow();
  }

  // Start at the rightmost, 4th desk.
  auto* desks_controller = DesksController::Get();
  ASSERT_EQ(4u, desks_controller->desks().size());
  desks_controller->ActivateDesk(desks_controller->GetDeskAtIndex(3),
                                 DesksSwitchSource::kUserSwitch);

  ui::ScopedAnimationDurationScaleMode normal_anim(
      ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION);

  // Activate the first 2 desks very quickly, without waiting for screenshots to
  // be taken.
  desks_controller->ActivateAdjacentDesk(
      /*going_left=*/true, DesksSwitchSource::kDeskSwitchShortcut);
  desks_controller->ActivateAdjacentDesk(
      /*going_left=*/true, DesksSwitchSource::kDeskSwitchShortcut);

  // Let the last desk animation to complete.
  desks_controller->ActivateAdjacentDesk(
      /*going_left=*/true, DesksSwitchSource::kDeskSwitchShortcut);
  // Note that `DeskController::ActivateAdjacentDesk()` will trigger two
  // `OnDeskSwitchAnimationFinished()` calls. The first is from the previous
  // animation which we destroy since its screenshots have not been taken yet.
  // The second is the animation to the first desk that we want to wait to take
  // the screenshots and animate.
  DeskSwitchAnimationWaiter waiter;
  waiter.Wait();

  // Check the desk containers. Test that only the first desk container is
  // visible, but they should all be opaque.
  std::vector<aura::Window*> desk_containers =
      desks_util::GetDesksContainers(Shell::GetPrimaryRootWindow());
  ASSERT_EQ(desks_util::GetMaxNumberOfDesks(), desk_containers.size());
  EXPECT_TRUE(desk_containers[0]->IsVisible());
  EXPECT_EQ(1.f, desk_containers[0]->layer()->opacity());

  for (size_t i = 1; i < desk_containers.size(); ++i) {
    SCOPED_TRACE(base::StringPrintf("Desk #%lu", i + 1));
    EXPECT_FALSE(desk_containers[i]->IsVisible());
    EXPECT_EQ(1.f, desk_containers[i]->layer()->opacity());
  }
}

// Tests that when the user is in tablet mode, the virtual keyboard is opened
// during name nudges.
TEST_P(DesksTest, NameNudgesTabletMode) {
  TabletModeControllerTestApi().EnterTabletMode();

  // Tablet mode requires at least two desks so create one.
  NewDesk();
  ASSERT_EQ(2u, DesksController::Get()->desks().size());

  // Start overview.
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // Setup an internal keyboard and an external keyboard.
  ui::DeviceDataManagerTestApi().SetKeyboardDevices(
      std::vector<ui::KeyboardDevice>{
          {1, ui::INPUT_DEVICE_INTERNAL, "internal keyboard"},
          {2, ui::INPUT_DEVICE_USB, "external keyboard"}});
  auto* device_data_manager = ui::DeviceDataManager::GetInstance();
  auto keyboard_devices = device_data_manager->GetKeyboardDevices();
  ASSERT_EQ(2u, keyboard_devices.size());

  // Tap the new desk button. There should be a new DeskNameView that is created
  // and the virtual keyboard should not be shown because there is at least one
  // external keyboard attached.
  const auto* desks_bar_view =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  GestureTapOn(desks_bar_view->new_desk_button());
  RunScheduledLayoutForAllOverviewDeskBars();
  EXPECT_FALSE(keyboard::KeyboardUIController::Get()->IsKeyboardVisible());
  EXPECT_EQ(3u, desks_bar_view->mini_views().size());
  auto* desk_name_view = desks_bar_view->mini_views()[2]->desk_name_view();
  EXPECT_TRUE(desk_name_view->HasFocus());
  EXPECT_EQ(std::u16string(), desk_name_view->GetText());

  // Reset the devices and make it so there's only an internal keyboard.
  ui::DeviceDataManagerTestApi().SetKeyboardDevices(
      std::vector<ui::KeyboardDevice>{
          {1, ui::INPUT_DEVICE_INTERNAL, "internal keyboard"},
      });
  keyboard_devices = device_data_manager->GetKeyboardDevices();
  ASSERT_EQ(1u, keyboard_devices.size());

  // Tap the new desk button again. There should be a new DeskNameView that is
  // created and the virtual keyboard should be shown.
  ui::DeviceDataManagerTestApi().SetKeyboardDevices({});
  GestureTapOn(desks_bar_view->new_desk_button());
  RunScheduledLayoutForAllOverviewDeskBars();
  ASSERT_TRUE(keyboard::test::WaitUntilShown());
  EXPECT_TRUE(keyboard::KeyboardUIController::Get()->IsKeyboardVisible());
  EXPECT_EQ(4u, desks_bar_view->mini_views().size());
  desk_name_view = desks_bar_view->mini_views()[3]->desk_name_view();
  EXPECT_TRUE(desk_name_view->HasFocus());
  EXPECT_EQ(std::u16string(), desk_name_view->GetText());
}

// Tests that metrics are being recorded when a desk is renamed, when new desks
// are added, and when a desk is being removed.
TEST_P(DesksTest, TestCustomDeskNameMetricsRecording) {
  // Actions that should cause the histogram to update.
  enum class UpdateSource {
    kDeskRenamed,
    kDeskAdded,
    kDeskRemoved,
  };

  struct {
    const std::string scope_trace;
    const UpdateSource update_source;
    const int expected_number_of_custom_desks;
    const int expected_percentage_of_custom_desks;
    const int expected_custom_name_change_true_hits;
    const int expected_custom_name_change_false_hits;
  } kTestCases[] = {
      {"Rename a desk", UpdateSource::kDeskRenamed, 1, 50, 1, 1},
      {"Add a desk", UpdateSource::kDeskAdded, 1, 33, 1, 2},
      {"Remove a desk", UpdateSource::kDeskRemoved, 1, 50, 1, 2},
  };

  base::HistogramTester histogram_tester;

  // Create a new desk. At this point we should have had one update for the new
  // desk addition because adding a new desk requires confirming the new desk's
  // name.
  NewDesk();
  int number_of_updates = 1;
  histogram_tester.ExpectTotalCount(kNumberOfCustomNamesHistogramName,
                                    number_of_updates);
  histogram_tester.ExpectTotalCount(kPercentageOfCustomNamesHistogramName,
                                    number_of_updates);
  histogram_tester.ExpectTotalCount(kCustomNameCreatedHistogramName,
                                    number_of_updates);
  const auto& desks = DesksController::Get()->desks();

  for (const auto& test_case : kTestCases) {
    SCOPED_TRACE(test_case.scope_trace);

    switch (test_case.update_source) {
      case UpdateSource::kDeskRenamed:
        desks[0]->SetName(u"Hello", /*set_by_user=*/true);
        break;
      case UpdateSource::kDeskAdded:
        NewDesk();
        break;
      case UpdateSource::kDeskRemoved:
        RemoveDesk(desks.back().get());
        break;
    }

    ++number_of_updates;
    histogram_tester.ExpectTotalCount(kNumberOfCustomNamesHistogramName,
                                      number_of_updates);
    histogram_tester.ExpectTotalCount(kPercentageOfCustomNamesHistogramName,
                                      number_of_updates);

    // There should be at least one recording of the expected custom desk count
    // and percentage.
    EXPECT_NE(0, histogram_tester.GetBucketCount(
                     kNumberOfCustomNamesHistogramName,
                     test_case.expected_number_of_custom_desks));
    EXPECT_NE(0, histogram_tester.GetBucketCount(
                     kPercentageOfCustomNamesHistogramName,
                     test_case.expected_percentage_of_custom_desks));
    EXPECT_EQ(
        test_case.expected_custom_name_change_true_hits,
        histogram_tester.GetBucketCount(kCustomNameCreatedHistogramName, true));
    EXPECT_EQ(test_case.expected_custom_name_change_false_hits,
              histogram_tester.GetBucketCount(kCustomNameCreatedHistogramName,
                                              false));
  }
}

// Tests that no crash when entering overview  and clicking on the new desk
// button in guest mode. This is a regression test for b/287376870 and
// b/291718574.
TEST_P(DesksTest, EnterOverviewAndAddDeskInGuestMode) {
  // Simulate a guest user logging in, where the session is ephemeral.
  SimulateGuestLogin();

  // Verify no crash while entering overview mode.
  EnterOverview();

  auto* overview_controller = OverviewController::Get();
  ASSERT_TRUE(overview_controller->InOverviewSession());
  auto* overview_grid = GetOverviewGridForRoot(Shell::GetPrimaryRootWindow());
  const auto* desks_bar_view = overview_grid->desks_bar_view();

  auto* new_desk_button = desks_bar_view->new_desk_button();
  // Verify no crash while clicking on the new desk button.
  LeftClickOn(new_desk_button);

  // Verify that desk bar is transformed to the expanded state from zero state.
  ASSERT_FALSE(desks_bar_view->IsZeroState());
  new_desk_button = desks_bar_view->new_desk_button();
  // Click on the expanded new desk button to add one more desk, verify no
  // crash.
  LeftClickOn(new_desk_button);

  // Verify that there're 3 desks in total now.
  EXPECT_EQ(3u, DesksController::Get()->desks().size());
}

// A test class that uses a mock time test environment.
class DesksMockTimeTest : public DesksTest {
 public:
  DesksMockTimeTest()
      : DesksTest(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}
  DesksMockTimeTest(const DesksMockTimeTest&) = delete;
  DesksMockTimeTest& operator=(const DesksMockTimeTest&) = delete;
  ~DesksMockTimeTest() override = default;

  // DesksTest:
  void SetUp() override {
    // The `g_weekly_active_desks` global counter may be non-zero at the
    // beginning of tests so reset it. See https://crbug.com/1200684.
    Desk::SetWeeklyActiveDesks(0);
    DesksTest::SetUp();
  }
};

// Tests that the weekly active desks metric is properly recorded.
TEST_P(DesksMockTimeTest, WeeklyActiveDesks) {
  constexpr char kWeeklyActiveDesksHistogram[] = "Ash.Desks.WeeklyActiveDesks";
  base::HistogramTester histogram_tester;

  // Create three new desks.
  NewDesk();
  NewDesk();
  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(4u, controller->desks().size());
  const Desk* desk_1 = controller->GetDeskAtIndex(0);
  const Desk* desk_2 = controller->GetDeskAtIndex(1);
  Desk* desk_3 = controller->GetDeskAtIndex(2);
  Desk* desk_4 = controller->GetDeskAtIndex(3);

  // Let a week elapse. There should be a new entry for four since there were
  // three created desks and the initial active desk.
  task_environment()->AdvanceClock(base::Days(7));
  task_environment()->RunUntilIdle();
  histogram_tester.ExpectBucketCount(kWeeklyActiveDesksHistogram, 4, 1);
  EXPECT_EQ(1u,
            histogram_tester.GetAllSamples(kWeeklyActiveDesksHistogram).size());

  // Activate the second desk and quickly activate the first desk. Let a week
  // elapse. There should be a new entry for one since we shouldn't count a desk
  // that was briefly visited.
  EXPECT_EQ(1, Desk::GetWeeklyActiveDesks());
  ActivateDesk(desk_2);
  ActivateDesk(desk_1);
  task_environment()->AdvanceClock(base::Days(7));
  task_environment()->RunUntilIdle();
  histogram_tester.ExpectBucketCount(kWeeklyActiveDesksHistogram, 1, 1);
  EXPECT_EQ(2u,
            histogram_tester.GetAllSamples(kWeeklyActiveDesksHistogram).size());

  // Activate the second desk and wait on it. Activate the first desk and wait
  // on it. Activate the second desk again. Let a week elapse. There should be a
  // new entry for two since we shouldn't count activating the second desk
  // twice.
  EXPECT_EQ(1, Desk::GetWeeklyActiveDesks());
  ActivateDesk(desk_2);
  task_environment()->FastForwardBy(base::Seconds(5));
  ActivateDesk(desk_1);
  task_environment()->FastForwardBy(base::Seconds(5));
  ActivateDesk(desk_2);
  task_environment()->AdvanceClock(base::Days(7));
  task_environment()->RunUntilIdle();
  histogram_tester.ExpectBucketCount(kWeeklyActiveDesksHistogram, 2, 1);
  EXPECT_EQ(3u,
            histogram_tester.GetAllSamples(kWeeklyActiveDesksHistogram).size());

  // Rename the third desk twice and move two windows to the fourth desk. Let a
  // week elapse. There should be a new entry for three.
  EXPECT_EQ(1, Desk::GetWeeklyActiveDesks());
  desk_3->SetName(u"foo", /*set_by_user=*/true);
  desk_3->SetName(u"bar", /*set_by_user=*/true);

  auto win1 = CreateAppWindow();
  auto win2 = CreateAppWindow();
  controller->MoveWindowFromActiveDeskTo(
      win1.get(), desk_4, win1->GetRootWindow(),
      DesksMoveWindowFromActiveDeskSource::kSendToDesk);
  controller->MoveWindowFromActiveDeskTo(
      win2.get(), desk_4, win2->GetRootWindow(),
      DesksMoveWindowFromActiveDeskSource::kSendToDesk);

  task_environment()->AdvanceClock(base::Days(7));
  task_environment()->RunUntilIdle();
  histogram_tester.ExpectBucketCount(kWeeklyActiveDesksHistogram, 3, 1);
  EXPECT_EQ(4u,
            histogram_tester.GetAllSamples(kWeeklyActiveDesksHistogram).size());

  // Wait six days on the current desk. Since a week hasn't elapsed relative to
  // the previous report, this should not report anything. Currently the weekly
  // active desks count should be one, so check the "one-count" bucket to make
  // sure it matches its previous number of entries.
  EXPECT_EQ(1, Desk::GetWeeklyActiveDesks());
  const int number_of_one_bucket_entries =
      histogram_tester.GetBucketCount(kWeeklyActiveDesksHistogram, 1);
  task_environment()->AdvanceClock(base::Days(6));
  task_environment()->RunUntilIdle();
  histogram_tester.ExpectBucketCount(kWeeklyActiveDesksHistogram, 1,
                                     number_of_one_bucket_entries);

  // Wait one more day and it should now report an entry for one, accounting for
  // the current active desk.
  task_environment()->AdvanceClock(base::Days(1));
  task_environment()->RunUntilIdle();
  histogram_tester.ExpectBucketCount(kWeeklyActiveDesksHistogram, 1,
                                     number_of_one_bucket_entries + 1);
}

// A class that maintains a window created inside of a test. If the window is
// destroyed from outside of the class, it releases the window's unique pointer
// to prevent use-after-free issues.
class WindowHolder : public aura::WindowObserver {
 public:
  explicit WindowHolder(std::unique_ptr<aura::Window> window)
      : window_(std::move(window)) {
    DCHECK(window_);
    window_->AddObserver(this);
  }

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

  ~WindowHolder() override {
    if (window_) {
      window_->RemoveObserver(this);
    }
    // `window_` is destroyed automatically here through the unique pointer.
  }

  aura::Window* window() { return window_.get(); }

  bool is_valid() const { return !!window_; }

  // aura::WindowObserver:
  void OnWindowDestroying(aura::Window* window) override {
    // The window was destroyed from outside of this WindowHolder (such as
    // through the `Desk::CloseAllAppWindows` function). In this case, we do not
    // want the unique pointer `window_` to try to destroy the already-destroyed
    // window, so we need to remove this observer and release the unique
    // pointer.
    DCHECK_EQ(window, window_.get());
    window_->RemoveObserver(this);
    window_.release();
  }

 private:
  std::unique_ptr<aura::Window> window_;
};

class DesksCloseAllTest : public DesksTest {
 public:
  DesksCloseAllTest()
      : test_close_all_window_close_timeout_(
            DesksTestApi::SetCloseAllWindowCloseTimeout(
                base::Milliseconds(close_all_window_close_timeout_ms_))) {}
  DesksCloseAllTest(const DesksCloseAllTest&) = delete;
  DesksCloseAllTest& operator=(const DesksCloseAllTest&) = delete;
  ~DesksCloseAllTest() override = default;

  // Clicks on the close-all button for the desk at index `index`.
  void ClickOnCloseAllButtonForDesk(size_t index) {
    ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
    const auto* desks_bar_view = GetPrimaryRootDesksBarView();
    ASSERT_LT(index, desks_bar_view->mini_views().size());

    LeftClickOn(desks_bar_view->mini_views()[index]
                    ->desk_action_view()
                    ->close_all_button());
    RunScheduledLayoutForAllOverviewDeskBars();
  }

  // Executes the close-all context menu command for the desk at index `index`.
  void ExecuteContextMenuCloseAllForDesk(size_t index) {
    ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
    const auto* desks_bar_view = GetPrimaryRootDesksBarView();
    ASSERT_LT(index, desks_bar_view->mini_views().size());

    // Run the context menu command for closing a desk with all of its windows.
    auto* menu_controller = DesksTestApi::GetContextMenuForDesk(
        DeskBarViewBase::Type::kOverview, index);
    menu_controller->ExecuteCommand(
        static_cast<int>(DeskActionContextMenu::CommandId::kCloseAll),
        /*event_flags=*/0);
  }

  // Opens the context menu for the mini view at `index`.
  void OpenContextMenuForMiniView(int index) {
    ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
    const DeskPreviewView* desk_preview_view =
        GetPrimaryRootDesksBarView()->mini_views()[index]->desk_preview();
    const gfx::Point desk_preview_view_center =
        desk_preview_view->GetBoundsInScreen().CenterPoint();
    auto* event_generator = GetEventGenerator();
    event_generator->MoveMouseTo(desk_preview_view_center);
    event_generator->ClickRightButton();
    ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  }

  void ClickOnUndoDeskRemovalButton() {
    views::LabelButton* dismiss_button =
        DesksTestApi::GetCloseAllUndoToastDismissButton();
    const gfx::Point button_center =
        dismiss_button->GetBoundsInScreen().CenterPoint();
    auto* event_generator = GetEventGenerator();
    event_generator->MoveMouseTo(button_center);
    event_generator->ClickLeftButton();
  }

 protected:
  const int close_all_window_close_timeout_ms_ = 20;
  base::AutoReset<base::TimeDelta> test_close_all_window_close_timeout_;
};

// Runs through test cases for closing active and inactive desks with windows in
// overview.
TEST_P(DesksCloseAllTest, CloseDesksWithWindowsInOverview) {
  // Possible sources for "close all" actions. `kCloseAllButton` means that we
  // will be trying to close the desk through the designated button on the
  // desk's `DeskActionView`, while `kContextMenu` means we will be trying to
  // close the desk by executing the desk's "close all" context menu option. As
  // we add more ways to perform a "close all" action (such as through an
  // accelerator) we can add more cases to this enum.
  enum class CloseAllSource {
    kCloseAllButton,
    kContextMenu,
  };

  struct {
    const std::string scope_trace;
    const CloseAllSource source;
  } kTestCases[] = {
      {"Remove desks using close all button", CloseAllSource::kCloseAllButton},
      {"Remove desks using close all context menu option",
       CloseAllSource::kContextMenu},
  };

  auto* controller = DesksController::Get();

  for (const auto& test_case : kTestCases) {
    SCOPED_TRACE(test_case.scope_trace);

    // Create three desks so that we can close one inactive desk and one active
    // desk.
    NewDesk();
    NewDesk();
    ASSERT_EQ(3u, controller->desks().size());
    Desk* desk_1 = controller->GetDeskAtIndex(0);
    Desk* desk_2 = controller->GetDeskAtIndex(1);
    Desk* desk_3 = controller->GetDeskAtIndex(2);
    ASSERT_TRUE(desk_1->is_active());

    // Create two `WindowHolder`s and assign one window to each desk.
    WindowHolder win1(CreateAppWindow());
    WindowHolder win2(CreateAppWindow());
    controller->SendToDeskAtIndex(win1.window(), 0);
    controller->SendToDeskAtIndex(win2.window(), 1);
    ASSERT_EQ(1u, desk_1->windows().size());
    ASSERT_EQ(1u, desk_2->windows().size());

    EnterOverview();
    ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

    // Execute and evaluate a test case for an inactive desk and an active desk.
    // We do it in this order so that we do not switch the active desk.
    if (test_case.source == CloseAllSource::kCloseAllButton) {
      ClickOnCloseAllButtonForDesk(1);
      SimulateWaitForCloseAll();
      EXPECT_FALSE(DesksTestApi::DesksControllerHasDesk(desk_2));
      EXPECT_TRUE(win1.is_valid());
      // `win2` is closed along with `desk_2` and should become invalid.
      EXPECT_FALSE(win2.is_valid());

      ClickOnCloseAllButtonForDesk(0);
      SimulateWaitForCloseAll();
      EXPECT_FALSE(DesksTestApi::DesksControllerHasDesk(desk_1));
      // `win1` is closed along with `desk_1` and should become invalid.
      EXPECT_FALSE(win1.is_valid());
    } else if (test_case.source == CloseAllSource::kContextMenu) {
      ExecuteContextMenuCloseAllForDesk(1);
      SimulateWaitForCloseAll();
      EXPECT_FALSE(DesksTestApi::DesksControllerHasDesk(desk_2));
      // `win1` and `win2` should both be valid at this point because `desk_2`
      // is being preserved.
      EXPECT_TRUE(win1.is_valid());
      // `win2` is closed along with `desk_2` and should become invalid.
      EXPECT_FALSE(win2.is_valid());

      ExecuteContextMenuCloseAllForDesk(0);
      SimulateWaitForCloseAll();
      EXPECT_FALSE(DesksTestApi::DesksControllerHasDesk(desk_1));
      // `win1` is closed along with `desk_1` and should become invalid.
      EXPECT_FALSE(win1.is_valid());
    }

    // Desk activation should have changed to `desk_3` and we should still be in
    // overview.
    EXPECT_TRUE(desk_3->is_active());
    EXPECT_TRUE(OverviewController::Get()->InOverviewSession());

    // We should have one desk remaining.
    EXPECT_EQ(1u, GetPrimaryRootDesksBarView()->mini_views().size());
  }
}

// Test that a stored desk is cleared when we add a desk.
TEST_P(DesksCloseAllTest, ClearStoredDeskWhenDeskAdded) {
  // Create two desks with one app window each.
  WindowHolder win1(CreateAppWindow());
  WindowHolder win2(CreateAppWindow());
  NewDesk();
  auto* controller = DesksController::Get();
  controller->SendToDeskAtIndex(win1.window(), 0);
  controller->SendToDeskAtIndex(win2.window(), 1);
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  ASSERT_EQ(1u, desk_1->windows().size());
  ASSERT_EQ(1u, desk_2->windows().size());
  ASSERT_TRUE(desk_1->is_active());

  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // Remove `desk_2` to store it in the `controller`.
  RemoveDesk(desk_2, DeskCloseType::kCloseAllWindowsAndWait);
  ASSERT_TRUE(desk_2->is_desk_being_removed());
  ASSERT_EQ(1u, controller->desks().size());
  ASSERT_TRUE(DesksTestApi::DesksControllerCanUndoDeskRemoval());

  // Creating a new desk should clear the stored desk.
  NewDesk();
  EXPECT_EQ(2u, controller->desks().size());
  EXPECT_FALSE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
}

// Test that a stored desk is cleared when closing another desk. If the second
// desk is being removed by a close-all-and-wait operation, then the second desk
// should replace the first desk in storage. If the second desk is being removed
// by a combine desks operation or an immediate close-all operation, then the
// stored desk should be cleared.
TEST_P(DesksCloseAllTest, ClearStoredDeskWhenClosingAnotherDesk) {
  // These test cases are differentiated on whether they use the
  // close-all-and-wait operation to remove the second desk (where
  // `desk_close_type` is `DeskCloseType::kCloseAllWindowsAndWait`), if they
  // use the combine desks operation to remove the second desk (where
  // `desk_close_type` is `DeskCloseType::kCombineDesks), or if they use the
  // immediate close-all operation to remove the second desk (where
  // `desk_close_type` is `DeskCloseType::kCloseAllWindows`).
  struct {
    const std::string scope_trace;
    const DeskCloseType desk_close_type;
  } kTestCases[] = {
      {"Remove second desk with close-all-and-wait",
       DeskCloseType::kCloseAllWindowsAndWait},
      {"Remove second desk with combine desks", DeskCloseType::kCombineDesks},
      {"Remove second desk with close-all", DeskCloseType::kCloseAllWindows},
  };

  for (const auto& test_case : kTestCases) {
    base::HistogramTester histogram_tester;
    SCOPED_TRACE(test_case.scope_trace);
    // Create two desks with one app window each.
    WindowHolder win1(CreateAppWindow());
    WindowHolder win2(CreateAppWindow());

    // Create one additional desk (so that we can remove the first two).
    NewDesk();
    NewDesk();
    auto* controller = DesksController::Get();
    controller->SendToDeskAtIndex(win1.window(), 0);
    controller->SendToDeskAtIndex(win2.window(), 1);
    Desk* desk_1 = controller->GetDeskAtIndex(0);
    Desk* desk_2 = controller->GetDeskAtIndex(1);
    Desk* desk_3 = controller->GetDeskAtIndex(2);
    ASSERT_EQ(1u, desk_1->windows().size());
    ASSERT_EQ(1u, desk_2->windows().size());
    ASSERT_EQ(0u, desk_3->windows().size());
    ASSERT_TRUE(desk_1->is_active());

    EnterOverview();
    ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

    // Remove `desk_1` by a close-all-and-wait operation to store it in the
    // `controller`.
    RemoveDesk(desk_1, DeskCloseType::kCloseAllWindowsAndWait);
    ASSERT_TRUE(desk_1->is_desk_being_removed());
    ASSERT_EQ(2u, controller->desks().size());
    ASSERT_TRUE(desk_2->is_active());
    ASSERT_TRUE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
    EXPECT_EQ(GetPrimaryUserPrefService()->GetInteger(prefs::kDesksActiveDesk),
              0);

    RemoveDesk(desk_2, test_case.desk_close_type);
    EXPECT_EQ(1u, controller->desks().size());
    EXPECT_NE(desk_1, controller->GetDeskAtIndex(0));
    EXPECT_NE(desk_2, controller->GetDeskAtIndex(0));

    switch (test_case.desk_close_type) {
      case DeskCloseType::kCloseAllWindowsAndWait:
        // If we are waiting after using close-all to remove the second desk,
        // then desk_2 should still be preserved, and will maintain
        // `desk_2->is_desk_being_removed()` to be true.
        EXPECT_TRUE(desk_2->is_desk_being_removed());
        EXPECT_TRUE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
        break;
      case DeskCloseType::kCombineDesks:
      case DeskCloseType::kCloseAllWindows:
        // `kCombineDesks` and `kCloseAllWindows` should both clear the removed
        // desk immediately.
        EXPECT_FALSE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
        break;
    }
  }
}

// Tests that a desk that is closed with all of its windows is restored to its
// original position and its original active state when the undo callback is
// run. Also tests that a desk is destroyed when we allow for the undo toast to
// expire.
TEST_P(DesksCloseAllTest, RestoreOrDestroyDeskWithToast) {
  // These test cases are differentiated by whether they run the undo toast's
  // callback to restore the desk (when `restore_desk` is true) or if they let
  // the undo toast expire and destroy the removed desk (when `restore_desk` is
  // false).
  struct {
    const std::string scope_trace;
    const bool restore_desk;
  } kTestCases[] = {
      {"Restore removed desk by undo", true},
      {"Allow undo toast to expire", false},
  };

  WindowHolder window(CreateAppWindow());
  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(2u, controller->desks().size());
  controller->SendToDeskAtIndex(window.window(), 0);
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  ASSERT_EQ(1u, desk_1->windows().size());
  ASSERT_EQ(0u, desk_2->windows().size());
  ASSERT_TRUE(desk_1->is_active());

  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  for (const auto& test_case : kTestCases) {
    SCOPED_TRACE(test_case.scope_trace);
    RemoveDesk(desk_1, DeskCloseType::kCloseAllWindowsAndWait);
    ASSERT_TRUE(desk_1->is_desk_being_removed());
    ASSERT_EQ(1u, controller->desks().size());
    ASSERT_TRUE(desk_2->is_active());
    ASSERT_TRUE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
    ASSERT_TRUE(window.is_valid());
    EXPECT_EQ(GetPrimaryUserPrefService()->GetInteger(prefs::kDesksActiveDesk),
              0);

    if (test_case.restore_desk) {
      // When `desk_1` is restored it should be back in its original position
      // and should be active again.
      ClickOnUndoDeskRemovalButton();
      EXPECT_FALSE(desk_1->is_desk_being_removed());
      EXPECT_EQ(2u, controller->desks().size());
      EXPECT_TRUE(desk_1->is_active());
      EXPECT_EQ(desk_1, controller->GetDeskAtIndex(0));
      EXPECT_FALSE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
      EXPECT_TRUE(window.is_valid());
      EXPECT_EQ(
          GetPrimaryUserPrefService()->GetInteger(prefs::kDesksActiveDesk), 0);
    } else {
      // Because undo toasts persist on hover, we need to move the cursor
      // outside of the undo toast to start the countdown for its expiration.
      GetEventGenerator()->MoveMouseTo(gfx::Point(0, 0));

      // When we wait for the undo toast to expire, `desk_1` should be
      // destroyed.
      SimulateWaitForCloseAll();
      EXPECT_EQ(1u, controller->desks().size());
      EXPECT_FALSE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
      EXPECT_FALSE(window.is_valid());
    }
  }
}

// Checks that the combine desks button and context menu option are not visible
// when there are no windows on a desk, and that they are visible on desks with
// windows.
TEST_P(DesksCloseAllTest, HideCombineDesksOptionWhenNoWindowsOnDesk) {
  // Create a new desk with no windows to have an expanded desks bar view with
  // mini views.
  NewDesk();
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  DeskMiniView* mini_view = GetPrimaryRootDesksBarView()->mini_views()[0];
  auto* event_generator = GetEventGenerator();
  if (!features::IsSavedDeskUiRevampEnabled()) {
    // We need to hover over the desk preview to properly check the combine
    // desks button's visibility.
    event_generator->MoveMouseTo(
        mini_view->desk_preview()->GetBoundsInScreen().CenterPoint());
    EXPECT_FALSE(
        mini_view->desk_action_view()->combine_desks_button()->GetVisible());
  }

  // We need to open the context menu to trigger its creation.
  OpenContextMenuForMiniView(0);
  // If there are no windows, there should only be 1 option in the context menu.
  EXPECT_EQ(1u, DesksTestApi::GetContextMenuModelForDesk(
                    DeskBarViewBase::Type::kOverview, 0)
                    .GetItemCount());
  event_generator->ClickLeftButton();

  // Add a window and check to see if that causes the creation of the context
  // option for combining desks. Closing and reopening overview will invalidate
  // the `mini_view` object, so we need to get another one.
  auto window = CreateAppWindow();
  DesksController::Get()->SendToDeskAtIndex(window.get(), 0);
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  mini_view = GetPrimaryRootDesksBarView()->mini_views()[0];

  if (!features::IsSavedDeskUiRevampEnabled()) {
    event_generator->MoveMouseTo(
        mini_view->desk_preview()->GetBoundsInScreen().CenterPoint());
    EXPECT_TRUE(
        mini_view->desk_action_view()->combine_desks_button()->GetVisible());
  }
  OpenContextMenuForMiniView(0);

  if (features::IsSavedDeskUiRevampEnabled()) {
    // The saved desk is part of the context menu with this feature on, although
    // it may be disabled.
    EXPECT_EQ(3u, DesksTestApi::GetContextMenuModelForDesk(
                      DeskBarViewBase::Type::kOverview, 0)
                      .GetItemCount());
  } else {
    EXPECT_EQ(2u, DesksTestApi::GetContextMenuModelForDesk(
                      DeskBarViewBase::Type::kOverview, 0)
                      .GetItemCount());
  }
}

TEST_P(DesksCloseAllTest, AccessibleName) {
  // Create a new desk with no windows to have an expanded desks bar view with
  // mini views.
  NewDesk();
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  DeskMiniView* mini_view = GetPrimaryRootDesksBarView()->mini_views()[0];

  ui::AXNodeData data;
  mini_view->GetViewAccessibility().GetAccessibleNodeData(&data);
  EXPECT_EQ(data.role,
            mini_view->desk_preview()->GetViewAccessibility().GetCachedRole());
  EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
            l10n_util::GetStringFUTF16(IDS_ASH_DESKS_DESK_ACCESSIBLE_NAME,
                                       mini_view->desk()->name()));

  mini_view->desk()->SetName(u"Sample Desk Name", /*set_by_user=*/true);

  data = ui::AXNodeData();
  mini_view->GetViewAccessibility().GetAccessibleNodeData(&data);
  EXPECT_EQ(data.GetString16Attribute(ax::mojom::StringAttribute::kName),
            l10n_util::GetStringFUTF16(IDS_ASH_DESKS_DESK_ACCESSIBLE_NAME,
                                       mini_view->desk()->name()));
}

// Tests that the shortcut to close all (Ctrl + Shift + W) on a desk mini view
// works as expected.
TEST_P(DesksCloseAllTest, ShortcutCloseAll) {
  WindowHolder window1(CreateAppWindow());
  WindowHolder window2(CreateAppWindow());
  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  ASSERT_TRUE(desk_1->is_active());
  ASSERT_TRUE(base::Contains(desk_1->windows(), window1.window()));
  ASSERT_TRUE(base::Contains(desk_1->windows(), window2.window()));

  EnterOverview();
  auto* overview_session = OverviewController::Get()->overview_session();
  ASSERT_TRUE(overview_session);

  auto* desks_bar =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  auto* mini_view = desks_bar->mini_views()[0].get();

  PressAndReleaseKey(ui::VKEY_TAB);
  PressAndReleaseKey(ui::VKEY_TAB);
  PressAndReleaseKey(ui::VKEY_TAB);
  ASSERT_TRUE(mini_view->desk_preview()->HasFocus());

  // Tests that after hitting Ctrl + Shift + W, the desk is destroyed along with
  // all it's app windows.
  PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
  SimulateWaitForCloseAll();
  EXPECT_EQ(1u, controller->desks().size());
  EXPECT_FALSE(window1.is_valid());
  EXPECT_FALSE(window2.is_valid());
}

TEST_P(DesksCloseAllTest, ShortcutUndoCloseAll) {
  WindowHolder window1(CreateAppWindow());
  WindowHolder window2(CreateAppWindow());
  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  ASSERT_TRUE(desk_1->is_active());
  ASSERT_TRUE(base::Contains(desk_1->windows(), window1.window()));
  ASSERT_TRUE(base::Contains(desk_1->windows(), window2.window()));

  EnterOverview();
  auto* overview_session = OverviewController::Get()->overview_session();
  ASSERT_TRUE(overview_session);

  // Closes the active desk.
  ClickOnCloseAllButtonForDesk(0);
  ASSERT_TRUE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
  ASSERT_EQ(1u, controller->desks().size());

  // Tests that after hitting Ctrl + Z, the desk deleting is undone.
  PressAndReleaseKey(ui::VKEY_Z, ui::EF_CONTROL_DOWN);
  EXPECT_EQ(2u, controller->desks().size());
  EXPECT_TRUE(window1.is_valid());
  EXPECT_TRUE(window2.is_valid());
}

// Tests CloseAll on active desk will close app windows on it.
TEST_P(DesksCloseAllTest, CloseActiveDeskCloseWindows) {
  WindowHolder window1(CreateAppWindow());
  WindowHolder window2(CreateAppWindow());

  NewDesk();

  auto* controller = DesksController::Get();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  ASSERT_TRUE(desk_1->is_active());
  ASSERT_TRUE(base::Contains(desk_1->windows(), window1.window()));
  ASSERT_TRUE(base::Contains(desk_1->windows(), window2.window()));

  // Closes the active desk.
  RemoveDesk(desk_1, DeskCloseType::kCloseAllWindowsAndWait);

  // Waits for the toast to disappear.
  SimulateWaitForCloseAll();
  EXPECT_EQ(1u, controller->desks().size());
  EXPECT_FALSE(window1.is_valid());
  EXPECT_FALSE(window2.is_valid());
}

// Tests CloseAll will forcefully close window that is not closed in time.
TEST_P(DesksCloseAllTest, ForceCloseWindows) {
  WindowHolder window1(CreateAppWindow());

  WindowHolder window2(CreateAppWindow(
      gfx::Rect(), chromeos::AppType::SYSTEM_APP,
      ShellWindowId::kShellWindowId_Invalid, new StuckWidgetDelegate()));

  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  ASSERT_TRUE(desk_1->is_active());
  ASSERT_TRUE(base::Contains(desk_1->windows(), window1.window()));
  ASSERT_TRUE(base::Contains(desk_1->windows(), window2.window()));

  RemoveDesk(desk_1, DeskCloseType::kCloseAllWindowsAndWait);

  // Wait, but not long enough for slow window (`window2`) to forcefully be
  // closed.
  DesksController::Get()->MaybeCommitPendingDeskRemoval();
  WaitForMilliseconds(close_all_window_close_timeout_ms_ / 2);
  EXPECT_EQ(1u, controller->desks().size());
  EXPECT_FALSE(window1.is_valid());
  EXPECT_TRUE(window2.is_valid());

  // Waits for long enough for `DesksController` to forcefully close the window.
  WaitForMilliseconds(close_all_window_close_timeout_ms_);
  EXPECT_FALSE(window2.is_valid());
}

// Checks that the desk preview highlight overlay is visible on a desk preview
// view only when its corresponding desk mini view's `DeskActionContextMenu` is
// active.
TEST_P(DesksCloseAllTest, DeskPreviewHighlightShowsWhenContextMenuIsOpen) {
  // We need to make the display this large so that the preview view is
  // right-clickable.
  UpdateDisplay("1366x768");
  NewDesk();

  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // The highlight overlay should start out invisible.
  views::View* highlight_overlay =
      DesksTestApi::GetHighlightOverlayForDeskPreview(
          DeskBarViewBase::Type::kOverview, 0);
  ASSERT_FALSE(highlight_overlay->GetVisible());

  // Open the context menu for the first desk and check that highlight overlay
  // is now visible.
  DeskPreviewView* desk_preview_view =
      GetPrimaryRootDesksBarView()->mini_views()[0]->desk_preview();
  gfx::Point desk_preview_view_center =
      desk_preview_view->GetBoundsInScreen().CenterPoint();
  auto* event_generator = GetEventGenerator();
  event_generator->MoveMouseTo(desk_preview_view_center);
  event_generator->ClickRightButton();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  ASSERT_TRUE(highlight_overlay->GetVisible());

  // Close the context menu and check that the highlight overlay is no longer
  // visible.
  event_generator->ClickLeftButton();

  // We need to wait for the `DeskActionContextMenu` to close, because
  // `SimpleMenuModel::MenuWillClose()` runs post tasks asynchronously.
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(highlight_overlay->GetVisible());
}

// Checks that the combine desks tooltip's validity is maintained whenever the
// user adds a desk, closes a desk, moves a desk, or changes the name of a desk.
TEST_P(DesksCloseAllTest, CombineDesksTooltipIsUpdatedOnUserActions) {
  if (features::IsSavedDeskUiRevampEnabled()) {
    GTEST_SKIP()
        << "Save desk buttons have been moved to the desk context menu. The "
           "associated context menu item has text so it doesn't need a tooltip";
  }
  // Possible sources for tooltip updates.
  enum class UpdateSource {
    kAddDesk,
    kCloseDesk,
    kMoveActiveDesk,
    kMoveNonActiveDesk,
    kChangeActiveDeskName,
    kChangeNonActiveDeskName,
  };

  struct {
    const std::string scope_trace;
    const UpdateSource source;

    // The desk name that we expect `desk_1` in the test case to point to as the
    // target for its combine desks operation after the test is performed.
    const std::u16string expected_target_1;

    // The desk name that we expect `desk_2` in the test case to point to as the
    // target for its combine desks operation after the test is performed.
    const std::u16string expected_target_2;
  } kTestCases[] = {
      {"Adding desk", UpdateSource::kAddDesk, u"Desk 2", u"Desk 1"},
      {"Closing desk", UpdateSource::kCloseDesk, u"Desk 2", u"Desk 1"},
      {"Moving active desk", UpdateSource::kMoveActiveDesk, u"Desk 1",
       u"Desk 2"},
      {"Moving non-active desk", UpdateSource::kMoveNonActiveDesk, u"Desk 2",
       u"Desk 1"},
      {"Changing active desk name", UpdateSource::kChangeActiveDeskName,
       u"Desk 2", u"goo"},
      {"Changing non-active desk name", UpdateSource::kChangeNonActiveDeskName,
       u"gle", u"goo"},
  };

  // We need to make the display this large so that the mini views are
  // draggable.
  UpdateDisplay("1366x768");
  auto* controller = DesksController::Get();

  // Create two initial desks with one window each.
  NewDesk();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);

  WindowHolder win1(CreateAppWindow());
  WindowHolder win2(CreateAppWindow());
  controller->SendToDeskAtIndex(win1.window(), 0);
  controller->SendToDeskAtIndex(win2.window(), 1);
  ASSERT_EQ(1u, desk_1->windows().size());
  ASSERT_EQ(1u, desk_2->windows().size());

  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  const DeskBarViewBase* desks_bar_view = GetPrimaryRootDesksBarView();

  // Cache the mini views and their name views and combine desks buttons.
  DeskMiniView* mini_view_1 = desks_bar_view->mini_views()[0];
  DeskMiniView* mini_view_2 = desks_bar_view->mini_views()[1];
  DeskNameView* desk_name_view_1 = mini_view_1->desk_name_view();
  DeskNameView* desk_name_view_2 = mini_view_2->desk_name_view();
  const CloseButton* combine_desks_button_1 =
      mini_view_1->desk_action_view()->combine_desks_button();
  const CloseButton* combine_desks_button_2 =
      mini_view_2->desk_action_view()->combine_desks_button();

  const std::u16string tooltip_prefix = u"Combine with ";
  auto* event_generator = GetEventGenerator();
  for (const auto& test_case : kTestCases) {
    SCOPED_TRACE(test_case.scope_trace);

    ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
    ASSERT_EQ(tooltip_prefix + controller->GetCombineDesksTargetName(desk_1),
              combine_desks_button_1->GetTooltipText());
    ASSERT_EQ(tooltip_prefix + controller->GetCombineDesksTargetName(desk_2),
              combine_desks_button_2->GetTooltipText());

    switch (test_case.source) {
      case UpdateSource::kAddDesk:
        NewDesk();
        break;
      case UpdateSource::kCloseDesk:
        ASSERT_EQ(3u, controller->desks().size());
        RemoveDesk(controller->GetDeskAtIndex(2));
        break;
      case UpdateSource::kMoveActiveDesk:
        ASSERT_TRUE(controller->GetDeskAtIndex(0)->is_active());
        StartDragDeskPreview(mini_view_1, event_generator);
        ASSERT_TRUE(desks_bar_view->IsDraggingDesk());
        event_generator->MoveMouseTo(
            mini_view_2->GetPreviewBoundsInScreen().CenterPoint());
        event_generator->ReleaseLeftButton();
        RunScheduledLayoutForAllOverviewDeskBars();
        break;
      case UpdateSource::kMoveNonActiveDesk:
        ASSERT_FALSE(controller->GetDeskAtIndex(0)->is_active());
        StartDragDeskPreview(mini_view_2, event_generator);
        EXPECT_TRUE(desks_bar_view->IsDraggingDesk());
        event_generator->MoveMouseTo(
            mini_view_1->GetPreviewBoundsInScreen().CenterPoint());
        event_generator->ReleaseLeftButton();
        RunScheduledLayoutForAllOverviewDeskBars();
        break;
      case UpdateSource::kChangeActiveDeskName:
        ASSERT_TRUE(controller->GetDeskAtIndex(0)->is_active());
        event_generator->MoveMouseTo(
            desk_name_view_1->GetBoundsInScreen().CenterPoint());
        event_generator->ClickLeftButton();
        PressAndReleaseKey(ui::VKEY_G);
        PressAndReleaseKey(ui::VKEY_O);
        PressAndReleaseKey(ui::VKEY_O);
        PressAndReleaseKey(ui::VKEY_RETURN);
        RunScheduledLayoutForAllOverviewDeskBars();
        break;
      case UpdateSource::kChangeNonActiveDeskName:
        ASSERT_EQ(u"goo", mini_view_1->desk()->name());
        ASSERT_FALSE(controller->GetDeskAtIndex(1)->is_active());
        LeftClickOn(desk_name_view_2);
        PressAndReleaseKey(ui::VKEY_G);
        PressAndReleaseKey(ui::VKEY_L);
        PressAndReleaseKey(ui::VKEY_E);
        PressAndReleaseKey(ui::VKEY_RETURN);
        RunScheduledLayoutForAllOverviewDeskBars();
        break;
    }

    EXPECT_EQ(tooltip_prefix + test_case.expected_target_1,
              combine_desks_button_1->GetTooltipText());
    EXPECT_EQ(tooltip_prefix + test_case.expected_target_2,
              combine_desks_button_2->GetTooltipText());
  }
}

// Test metrics are being recorded in close all case.
TEST_P(DesksCloseAllTest, TestMetricsRecordingWhenCloseAllWindows) {
  struct {
    const std::string scope_trace;
    const bool restore_desk;
  } kTestCases[] = {
      {"Restore removed desk by undo", true},
      {"Allow undo toast to expire", false},
  };
  base::HistogramTester histogram_tester;

  // Set up a new desk with two windows
  WindowHolder window(CreateAppWindow());
  WindowHolder window1(CreateAppWindow());
  NewDesk();
  auto* controller = DesksController::Get();
  controller->SendToDeskAtIndex(window.window(), 0);
  controller->SendToDeskAtIndex(window1.window(), 0);
  EnterOverview();

  int remove_desk_type_count = 0;
  int undo_toast_expired_count = 0;
  for (const auto& test_case : kTestCases) {
    SCOPED_TRACE(test_case.scope_trace);
    auto* menu_controller = DesksTestApi::GetContextMenuForDesk(
        DeskBarViewBase::Type::kOverview, 0);
    menu_controller->ExecuteCommand(
        static_cast<int>(DeskActionContextMenu::CommandId::kCloseAll),
        /*event_flags=*/0);
    RunScheduledLayoutForAllOverviewDeskBars();
    // Record RemoveDeskType: closeAll, combine and closeAllAndWait
    histogram_tester.ExpectBucketCount("Ash.Desks.RemoveDeskType",
                                       DeskCloseType::kCloseAllWindowsAndWait,
                                       ++remove_desk_type_count);

    if (test_case.restore_desk) {
      // When `desk_1` is restored it should be back in its original position
      // and should be active again.
      views::LabelButton* dismiss_button =
          DesksTestApi::GetCloseAllUndoToastDismissButton();
      const gfx::Point button_center =
          dismiss_button->GetBoundsInScreen().CenterPoint();
      auto* event_generator = GetEventGenerator();
      event_generator->MoveMouseTo(button_center);
      event_generator->ClickLeftButton();
      RunScheduledLayoutForAllOverviewDeskBars();
      // Record click undo button in toast after remove all
      histogram_tester.ExpectTotalCount("Ash.Desks.CloseAllUndo", 1);
      // Record undo toast expired
      histogram_tester.ExpectTotalCount("Ash.Desks.CloseAllTotal",
                                        ++undo_toast_expired_count);
      // Record number of windows being closed.
      histogram_tester.ExpectTotalCount("Ash.Desks.NumberOfWindowsClosed2", 0);
      // Record number of windows being closed per source.
      histogram_tester.ExpectTotalCount(
          "Ash.Desks.NumberOfWindowsClosed2.Button", 0);

    } else {
      // Because undo toasts persist on hover, we need to move the cursor
      // outside of the undo toast to start the countdown for its expiration.
      GetEventGenerator()->MoveMouseTo(gfx::Point(0, 0));
      RunScheduledLayoutForAllOverviewDeskBars();

      // Simulate the toast timing out.
      DesksController::Get()->MaybeCommitPendingDeskRemoval();

      // Record undo toast expired.
      histogram_tester.ExpectTotalCount("Ash.Desks.CloseAllTotal",
                                        ++undo_toast_expired_count);
      // Record number of windows being closed.
      histogram_tester.ExpectUniqueSample("Ash.Desks.NumberOfWindowsClosed2", 2,
                                          1);
      // Record number of windows being closed per source.
      histogram_tester.ExpectUniqueSample(
          "Ash.Desks.NumberOfWindowsClosed2.Button", 2, 1);
    }
  }
}

TEST_P(DesksCloseAllTest, DeskPreviewAccessibleProperties) {
  NewDesk();
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // Long press on the first desk preview view.
  DeskPreviewView* desk_preview_view =
      GetPrimaryRootDesksBarView()->mini_views()[0]->desk_preview();

  ui::AXNodeData data;
  desk_preview_view->GetViewAccessibility().GetAccessibleNodeData(&data);
  EXPECT_EQ(
      data.GetString16Attribute(ax::mojom::StringAttribute::kRoleDescription),
      l10n_util::GetStringUTF16(IDS_ASH_DESKS_DESK_PREVIEW_ROLE_DESCRIPTION));
}

// Checks that a `DeskActionContextMenu` opens when the user long-presses a
// desk's mini view.
TEST_P(DesksCloseAllTest, ContextMenuOpensOnLongPress) {
  NewDesk();
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // Long press on the first desk preview view.
  const DeskPreviewView* desk_preview_view =
      GetPrimaryRootDesksBarView()->mini_views()[0]->desk_preview();
  const gfx::Point desk_preview_view_center =
      desk_preview_view->GetBoundsInScreen().CenterPoint();
  auto* event_generator = GetEventGenerator();
  LongGestureTap(desk_preview_view_center, event_generator);

  EXPECT_TRUE(DesksTestApi::IsContextMenuRunningForDesk(
      DeskBarViewBase::Type::kOverview, 0));
}

// Tests that desks can be closed in quick succession while still saving the
// removed desk.
TEST_P(DesksCloseAllTest, CanCloseMultipleDesksInSuccessionAndUndo) {
  NewDesk();
  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(3u, controller->desks().size());

  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  ClickOnCloseAllButtonForDesk(0);
  ASSERT_TRUE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
  ClickOnCloseAllButtonForDesk(0);
  ASSERT_TRUE(DesksTestApi::DesksControllerCanUndoDeskRemoval());
  ClickOnUndoDeskRemovalButton();
  EXPECT_EQ(2u, controller->desks().size());
}

// Tests that an active desk's windows are restored with an identity transform
// when it's removal is undone outside of overview mode.
TEST_P(DesksCloseAllTest,
       ActiveDeskWindowsAreRestoredProperlyOutsideOfOverview) {
  WindowHolder window(CreateAppWindow());
  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(2u, controller->desks().size());
  controller->SendToDeskAtIndex(window.window(), 0);
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  Desk* desk_2 = controller->GetDeskAtIndex(1);
  ASSERT_EQ(1u, desk_1->windows().size());
  ASSERT_EQ(0u, desk_2->windows().size());
  ASSERT_TRUE(desk_1->is_active());

  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  EXPECT_FALSE(window.window()->transform().IsIdentity());

  ClickOnCloseAllButtonForDesk(0);
  ExitOverview();
  ASSERT_FALSE(OverviewController::Get()->InOverviewSession());

  // Overview is destroyed asynchronously so we have to wait for it to finish.
  base::RunLoop().RunUntilIdle();

  // Clicking the undo button outside of overview triggers a desk switch
  // animation, so we have to wait for that.
  DeskSwitchAnimationWaiter waiter;
  ClickOnUndoDeskRemovalButton();
  waiter.Wait();
  EXPECT_TRUE(window.is_valid());

  // At this point, the transformation applied to the window by overview mode
  // should have been removed by the desk removal operation.
  EXPECT_TRUE(window.window()->transform().IsIdentity());
}

// Tests that we can create the maximum number of desks, remove one, and add one
// before the toast asking if the user would like to undo goes away.
TEST_P(DesksCloseAllTest, CanAddLastDeskWhileUndoToastIsBeingDisplayed) {
  auto* controller = DesksController::Get();
  while (controller->desks().size() < desks_util::GetMaxNumberOfDesks()) {
    NewDesk();
  }
  ASSERT_EQ(desks_util::GetMaxNumberOfDesks(), controller->desks().size());

  // Create a window to ensure that closing windows after removing the last desk
  // still occurs correctly.
  WindowHolder window(CreateAppWindow());
  const int last_desk_index = desks_util::GetMaxNumberOfDesks() - 1;
  controller->SendToDeskAtIndex(window.window(), last_desk_index);

  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());

  // Remove the last desk with close-all. This should show the undo toast.
  RemoveDesk(controller->GetDeskAtIndex(last_desk_index),
             DeskCloseType::kCloseAllWindowsAndWait);
  ASSERT_EQ(desks_util::GetMaxNumberOfDesks() - 1, controller->desks().size());
  ASSERT_TRUE(DesksTestApi::DesksControllerCanUndoDeskRemoval());

  // The new desk button should be enabled at this point.
  auto* new_desk_button = GetPrimaryRootDesksBarView()->new_desk_button();
  ASSERT_TRUE(new_desk_button->GetEnabled());

  // Scroll all the way to the right to ensure that the new button is visible.
  for (int i = 0; i != 3; ++i) {
    TryScrollOverviewDeskBar(DeskBarScrollDirection::kRight);
  }

  // If we click on the `new_desk_button`, we should create a new desk and
  // destroy the previously removed desk and the window inside of it.
  LeftClickOn(new_desk_button);
  EXPECT_EQ(desks_util::GetMaxNumberOfDesks(), controller->desks().size());
  EXPECT_FALSE(DesksTestApi::DesksControllerCanUndoDeskRemoval());

  // Ensure that the window is still closed properly.
  WaitForMilliseconds(close_all_window_close_timeout_ms_);
  EXPECT_FALSE(window.is_valid());
}

// Tests that windows in CloseAll will not be unparented while they are closing
// asynchronously.
TEST_P(DesksCloseAllTest, ClosingWindowsHaveParent) {
  WindowHolder window(CreateAppWindow(
      gfx::Rect(), chromeos::AppType::SYSTEM_APP,
      ShellWindowId::kShellWindowId_Invalid, new StuckWidgetDelegate()));

  NewDesk();
  auto* controller = DesksController::Get();
  ASSERT_EQ(2u, controller->desks().size());
  Desk* desk_1 = controller->GetDeskAtIndex(0);
  ASSERT_TRUE(desk_1->is_active());
  EXPECT_TRUE(base::Contains(desk_1->windows(), window.window()));

  RemoveDesk(desk_1, DeskCloseType::kCloseAllWindowsAndWait);

  // Window will still be open because it has not yet been force-closed.
  DesksController::Get()->MaybeCommitPendingDeskRemoval();
  WaitForMilliseconds(close_all_window_close_timeout_ms_ / 2);
  ASSERT_EQ(1u, controller->desks().size());
  ASSERT_TRUE(window.is_valid());

  // Closing windows should be reparented to the
  // `kShellWindowId_UnparentedContainer` window.
  EXPECT_TRUE(window.window()->GetRootWindow());
  EXPECT_EQ(kShellWindowId_UnparentedContainer,
            window.window()->parent()->GetId());
}

TEST_P(DesksCloseAllTest, TestRecordingNumerOfClosedWindowsMetrics) {
  struct {
    const std::string scope_trace;
    const DeskCloseType desk_close_type;
  } kTestCases[] = {
      {"Remove second desk with combine desks", DeskCloseType::kCombineDesks},
      {"Remove second desk with close-all-and-wait",
       DeskCloseType::kCloseAllWindowsAndWait},
      {"Remove second desk with close-all", DeskCloseType::kCloseAllWindows},
  };

  for (const auto& test_case : kTestCases) {
    base::HistogramTester histogram_tester;

    SCOPED_TRACE(test_case.scope_trace);
    WindowHolder win1(CreateAppWindow());

    NewDesk();
    auto* controller = DesksController::Get();
    controller->SendToDeskAtIndex(win1.window(), 1);
    Desk* desk = controller->GetDeskAtIndex(1);

    EnterOverview();

    RemoveDesk(desk, test_case.desk_close_type);

    switch (test_case.desk_close_type) {
      case DeskCloseType::kCombineDesks:
        histogram_tester.ExpectTotalCount("Ash.Desks.NumberOfWindowsClosed2",
                                          0);
        histogram_tester.ExpectTotalCount(
            "Ash.Desks.NumberOfWindowsClosed2.Button", 0);
        break;
      // Wait and toast expired.
      case DeskCloseType::kCloseAllWindowsAndWait:
        // Because undo toasts persist on hover, we need to move the cursor
        // outside of the undo toast to start the countdown for its expiration.
        GetEventGenerator()->MoveMouseTo(gfx::Point(0, 0));
        DesksController::Get()->MaybeCommitPendingDeskRemoval();
        WaitForMilliseconds(200);
        histogram_tester.ExpectTotalCount("Ash.Desks.NumberOfWindowsClosed2",
                                          1);
        histogram_tester.ExpectUniqueSample(
            "Ash.Desks.NumberOfWindowsClosed2.Button", 1, 1);
        break;

      case DeskCloseType::kCloseAllWindows:
        // `kCombineDesks` and `kCloseAllWindows` should both clear the removed
        // desk immediately.
        histogram_tester.ExpectTotalCount("Ash.Desks.NumberOfWindowsClosed2",
                                          1);
        histogram_tester.ExpectUniqueSample(
            "Ash.Desks.NumberOfWindowsClosed2.Button", 1, 1);
        break;
    }
  }
}

// Tests that when a desk is created its GUID is saved in the desks restore
// data, and when a desk is removed its GUID is removed.
TEST_P(DesksTest, DeskGuidsSaved) {
  // We don't need to save the desk GUID for restore if there is only one desk.
  NewDesk();
  auto* controller = DesksController::Get();
  base::Uuid desk1_guid = controller->GetDeskAtIndex(0)->uuid();
  base::Uuid desk2_guid = controller->GetDeskAtIndex(1)->uuid();
  EXPECT_THAT(GetDeskRestoreGuids(GetPrimaryUserPrefService()),
              testing::ElementsAre(desk1_guid, desk2_guid));

  // Add a third desk, close the second desk, and check the GUIDs.
  NewDesk();
  base::Uuid desk3_guid = controller->GetDeskAtIndex(2)->uuid();
  EnterOverview();
  CloseDeskFromMiniView(GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())
                            ->desks_bar_view()
                            ->mini_views()[1],
                        GetEventGenerator());
  EXPECT_THAT(GetDeskRestoreGuids(GetPrimaryUserPrefService()),
              testing::ElementsAre(desk1_guid, desk3_guid));
}

// Tests that when desks are reordered their GUIDs are reordered in the desk
// restore data correspondingly.
TEST_P(DesksTest, DeskGuidsReorder) {
  NewDesk();
  NewDesk();
  auto* controller = DesksController::Get();
  base::Uuid desk1_guid = controller->GetDeskAtIndex(0)->uuid();
  base::Uuid desk2_guid = controller->GetDeskAtIndex(1)->uuid();
  base::Uuid desk3_guid = controller->GetDeskAtIndex(2)->uuid();
  EXPECT_THAT(GetDeskRestoreGuids(GetPrimaryUserPrefService()),
              testing::ElementsAre(desk1_guid, desk2_guid, desk3_guid));

  // Swap the 2nd and 3rd desks with the mouse.
  EnterOverview();
  const auto* desks_bar_view =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  std::vector<raw_ptr<DeskMiniView, VectorExperimental>> mini_views =
      desks_bar_view->mini_views();
  auto* event_generator = GetEventGenerator();

  StartDragDeskPreview(mini_views[1], event_generator);
  gfx::Point desk_center_2 =
      mini_views[2]->GetPreviewBoundsInScreen().CenterPoint();
  event_generator->MoveMouseTo(desk_center_2);
  event_generator->ReleaseLeftButton();

  EXPECT_THAT(GetDeskRestoreGuids(GetPrimaryUserPrefService()),
              testing::ElementsAre(desk1_guid, desk3_guid, desk2_guid));
}

TEST_P(DesksTest, DeskLacrosIdPrefs) {
  NewDesk();
  NewDesk();

  auto* controller = DesksController::Get();
  // Set some lacros profile IDs for the three desks.
  controller->GetDeskAtIndex(0)->SetLacrosProfileId(1001);
  controller->GetDeskAtIndex(1)->SetLacrosProfileId(2001);
  controller->GetDeskAtIndex(2)->SetLacrosProfileId(3001);
  EXPECT_THAT(GetDeskRestoreLacrosProfileIds(GetPrimaryUserPrefService()),
              testing::ElementsAre(1001, 2001, 3001));

  // Reorder the last two desks. We expect the prefs to update to match.
  controller->ReorderDesk(1, 2);
  EXPECT_THAT(GetDeskRestoreLacrosProfileIds(GetPrimaryUserPrefService()),
              testing::ElementsAre(1001, 3001, 2001));

  // Remove the first desk.
  RemoveDesk(controller->GetDeskAtIndex(0));
  EXPECT_THAT(GetDeskRestoreLacrosProfileIds(GetPrimaryUserPrefService()),
              testing::ElementsAre(3001, 2001));

  // Create a new desk, its lacros profile ID should default to 0.
  NewDesk();
  EXPECT_THAT(GetDeskRestoreLacrosProfileIds(GetPrimaryUserPrefService()),
              testing::ElementsAre(3001, 2001, 0));
}

// Tests that windows are closed when the user interacts with the shelf.
TEST_P(DesksCloseAllTest, InteractingWithShelfClosesToast) {
  auto* shelf_model = ShelfModel::Get();
  NewDesk();

  // Create a window and a shelf item for the window.
  WindowHolder window(CreateAppWindow());
  const ash::ShelfID shelf_id("cool_app");
  window.window()->SetProperty(ash::kShelfIDKey, shelf_id.Serialize());
  window.window()->SetProperty(ash::kAppIDKey, shelf_id.app_id);
  window.window()->SetProperty<int>(ash::kShelfItemTypeKey,
                                    ShelfItemType::TYPE_PINNED_APP);
  ShelfItem item;
  item.status = ShelfItemStatus::STATUS_RUNNING;
  item.type = ShelfItemType::TYPE_PINNED_APP;
  item.id = shelf_id;
  shelf_model->Add(item, std::make_unique<TestShelfItemDelegate>(item.id));

  // Enter overview and close the desk.
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  ClickOnCloseAllButtonForDesk(0);

  // Get the view for the shelf item.
  int item_index = shelf_model->ItemIndexByID(shelf_id);
  auto* view_model = GetPrimaryShelf()->GetShelfViewForTesting()->view_model();
  views::View* item_view = view_model->view_at(item_index);

  // Try opening the context menu for the shelf item with a right click.
  gfx::Point item_view_center = item_view->GetBoundsInScreen().CenterPoint();
  auto* event_generator = GetEventGenerator();
  event_generator->MoveMouseTo(item_view_center);
  event_generator->ClickRightButton();

  // The right click should destroy the desk and the window.
  EXPECT_FALSE(DesksTestApi::DesksControllerCanUndoDeskRemoval());

  // The window will destroy asynchronously.
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(window.is_valid());
}

// Regression test for http://b/356460723.
TEST_P(DesksCloseAllTest, UndoToastWorksWithChromevox) {
  NewDesk();
  Shell::Get()->accessibility_controller()->spoken_feedback().SetEnabled(true);

  // Enter overview and close the desk.
  EnterOverview();
  ASSERT_TRUE(OverviewController::Get()->InOverviewSession());
  ClickOnCloseAllButtonForDesk(/*index=*/0);
  ASSERT_EQ(1, DesksController::Get()->GetNumberOfDesks());

  views::LabelButton* button =
      DesksTestApi::GetCloseAllUndoToastDismissButton();
  ASSERT_TRUE(button);
  LeftClickOn(button);
  EXPECT_EQ(2, DesksController::Get()->GetNumberOfDesks());
  EXPECT_TRUE(OverviewController::Get()->InOverviewSession());
}

class DeskBarTest
    : public AshTestBase,
      public ::testing::WithParamInterface<
          testing::tuple<bool, bool, bool, DeskBarViewBase::Type>> {
 public:
  DeskBarTest()
      : test_close_all_window_close_timeout_(
            DesksTestApi::SetCloseAllWindowCloseTimeout(
                base::Milliseconds(20))) {}
  DeskBarTest(const DeskBarTest&) = delete;
  DeskBarTest& operator=(const DeskBarTest&) = delete;
  ~DeskBarTest() override = default;

  void SetUp() override {
    std::tie(use_touch_gestures_, use_16_desks_, use_desk_profiles_,
             bar_type_) = GetParam();

    scoped_feature_list_.InitWithFeatureStates(
        {{features::kFeatureManagement16Desks, use_16_desks_},
         {chromeos::features::kDeskProfiles, use_desk_profiles_}});

    AshTestBase::SetUp();

    // Wait for the desk model to have completed its initialization. Not doing
    // this would lead to flaky tests.
    ash_test_helper()->saved_desk_test_helper()->WaitForDeskModels();

    SetShowDeskButtonInShelfPref(GetPrimaryUserPrefService(), true);

    if (use_desk_profiles_) {
      // Add two lacros profiles so that the desk profile avatar shows up in
      // desk mini views.
      AddDummyLacrosDeskProfiles(2);
    }
  }

  void TearDown() override {
    AshTestBase::TearDown();
    scoped_feature_list_.Reset();
  }

  desks_storage::DeskModel* desk_model() {
    return ash_test_helper()->saved_desk_test_helper()->desk_model();
  }

  void DeleteAllSavedDesks() {
    base::RunLoop loop;
    desk_model()->DeleteAllEntries(base::BindLambdaForTesting(
        [&](desks_storage::DeskModel::DeleteEntryStatus status) {
          loop.Quit();
        }));
    loop.Run();
  }

  void ClickOrPressOnPoint(const gfx::Point& p) {
    auto* event_generator = GetEventGenerator();
    if (use_touch_gestures_) {
      event_generator->PressTouch(p);
      event_generator->ReleaseTouch();
    } else {
      event_generator->MoveMouseTo(p);
      event_generator->ClickLeftButton();
    }
  }

  void ClickOrPressOnView(const views::View* view) {
    const gfx::Point view_center = view->GetBoundsInScreen().CenterPoint();
    ClickOrPressOnPoint(view_center);
  }

  void OpenDeskBar(aura::Window* root = Shell::Get()->GetPrimaryRootWindow()) {
    OpenDeskBar(root, bar_type_);
  }

  void OpenDeskBar(aura::Window* root, DeskBarViewBase::Type bar_type) {
    switch (bar_type) {
      case DeskBarViewBase::Type::kOverview:
        EnterOverview();
        break;
      case DeskBarViewBase::Type::kDeskButton:
        DesksController::Get()->desk_bar_controller()->OpenDeskBar(root);
        break;
    }
    DeskBarViewBase* const desk_bar_view = GetDeskBarView(root, bar_type);
    if (desk_bar_view) {
      views::test::RunScheduledLayout(desk_bar_view);
    }
  }

  void CloseDeskBar(aura::Window* root = Shell::Get()->GetPrimaryRootWindow()) {
    CloseDeskBar(root, bar_type_);
  }

  void CloseDeskBar(aura::Window* root, DeskBarViewBase::Type bar_type) {
    switch (bar_type) {
      case DeskBarViewBase::Type::kOverview:
        ExitOverview();
        break;
      case DeskBarViewBase::Type::kDeskButton:
        DesksController::Get()->desk_bar_controller()->CloseDeskBar(root);
        break;
    }
  }

  DeskBarViewBase* GetDeskBarView(
      aura::Window* root = Shell::Get()->GetPrimaryRootWindow()) {
    return GetDeskBarView(root, bar_type_);
  }

  DeskBarViewBase* GetDeskBarView(aura::Window* root,
                                  DeskBarViewBase::Type bar_type) {
    DeskBarViewBase* desk_bar_view = nullptr;
    switch (bar_type) {
      case DeskBarViewBase::Type::kOverview:
        if (OverviewController::Get()->InOverviewSession()) {
          desk_bar_view = GetOverviewGridForRoot(root)->desks_bar_view();
        }
        break;
      case DeskBarViewBase::Type::kDeskButton:
        desk_bar_view =
            DesksController::Get()->desk_bar_controller()->GetDeskBarView(root);
        break;
    }
    return desk_bar_view;
  }

  void EnterLibrary(aura::Window* root = Shell::Get()->GetPrimaryRootWindow()) {
    EnterLibrary(root, bar_type_);
  }

  void EnterLibrary(aura::Window* root, DeskBarViewBase::Type bar_type) {
    auto* desk_bar_view = GetDeskBarView(root, bar_type);
    ASSERT_TRUE(desk_bar_view);

    // Clicking the library button on the desk button desk bar.
    ASSERT_TRUE(desk_bar_view->library_button());
    ASSERT_TRUE(desk_bar_view->library_button()->GetVisible());
    ClickOrPressOnView(desk_bar_view->library_button());

    // It should enter overview mode and the saved desk library should be
    // visible. Desk button desk bar should be gone, and the overview desk bar
    // should show up.
    auto* overview_controller = OverviewController::Get();
    ASSERT_TRUE(overview_controller->InOverviewSession());
    RunScheduledLayoutForAllOverviewDeskBars();
    auto* overview_session = overview_controller->overview_session();
    EXPECT_TRUE(overview_session &&
                overview_session->IsShowingSavedDeskLibrary());
    EXPECT_FALSE(GetDeskBarView(root, DeskBarViewBase::Type::kDeskButton));
    EXPECT_TRUE(GetDeskBarView(root, DeskBarViewBase::Type::kOverview));
  }

  // Executes a context menu command for the desk at index `index`. `close_all`
  // indicates whether we want to close a desk with windows or combine desks.
  void ExecuteContextMenuDeskActionForDesk(size_t index,
                                           bool close_all,
                                           aura::Window* root,
                                           DeskBarViewBase::Type bar_type) {
    const auto* desks_bar_view = GetDeskBarView(root, bar_type);
    ASSERT_LT(index, desks_bar_view->mini_views().size());

    // Run the context menu command for closing a desk with all of its windows.
    auto* menu_controller =
        DesksTestApi::GetContextMenuForDesk(bar_type, index);

    const int command_id = static_cast<int>(
        close_all ? DeskActionContextMenu::CommandId::kCloseAll
                  : DeskActionContextMenu::CommandId::kCombineDesks);
    if (bar_type == DeskBarViewBase::Type::kDeskButton &&
        desks_bar_view->mini_views()[index]->desk()->is_active()) {
      DeskSwitchAnimationWaiter waiter;
      menu_controller->ExecuteCommand(command_id,
                                      /*event_flags=*/0);
      waiter.Wait();
    } else {
      menu_controller->ExecuteCommand(command_id,
                                      /*event_flags=*/0);
    }
  }

  // Closes the desk at `index` with the selected method, using the context menu
  // if we are using touch gestures.
  void CloseDeskWithButton(size_t index,
                           bool close_all,
                           aura::Window* root,
                           DeskBarViewBase::Type bar_type) {
    if (use_touch_gestures_) {
      ExecuteContextMenuDeskActionForDesk(index, close_all, root, bar_type);
    } else {
      const auto* desk_bar_view = GetDeskBarView(root, bar_type);
      ASSERT_LT(index, desk_bar_view->mini_views().size());
      auto* target_mini_view = desk_bar_view->mini_views()[index].get();
      GetEventGenerator()->MoveMouseTo(
          target_mini_view->desk_preview()->GetBoundsInScreen().CenterPoint());
      auto* target_button =
          close_all
              ? target_mini_view->desk_action_view()->close_all_button()
              : target_mini_view->desk_action_view()->combine_desks_button();
      ASSERT_TRUE(target_button->GetVisible());

      if (bar_type == DeskBarViewBase::Type::kDeskButton &&
          target_mini_view->desk()->is_active()) {
        DeskSwitchAnimationWaiter waiter;
        LeftClickOn(target_button);
        waiter.Wait();
      } else {
        LeftClickOn(target_button);
      }
    }
  }

  // TODO(http://b/350771229): Fully replace `CloseDeskWithButton` with this
  // function once Forest is enabled by default (including touch gestures).
  // Closes the desk at `index` using the "Combine desk" option in the desk
  // context menu, accessed using the context menu button. Only available if the
  // Forest feature is enabled.
  void CombineDeskWithMenu(size_t index,
                           aura::Window* root,
                           DeskBarViewBase::Type bar_type) {
    CHECK(features::IsSavedDeskUiRevampEnabled());

    // Get the menu option to save the desk as a template and click it.
    views::MenuItemView* menu_item =
        DesksTestApi::OpenDeskContextMenuAndGetMenuItem(
            root, bar_type, index,
            DeskActionContextMenu::CommandId::kCombineDesks);
    ASSERT_TRUE(menu_item);

    if (bar_type == DeskBarViewBase::Type::kDeskButton &&
        DesksController::Get()->GetActiveDeskIndex() ==
            static_cast<int>(index)) {
      DeskSwitchAnimationWaiter waiter;
      LeftClickOn(menu_item);
      waiter.Wait();
    } else {
      LeftClickOn(menu_item);
    }
  }

  bool use_touch_gestures_;
  bool use_16_desks_;
  bool use_desk_profiles_;
  DeskBarViewBase::Type bar_type_;

 private:
  base::AutoReset<base::TimeDelta> test_close_all_window_close_timeout_;
  base::test::ScopedFeatureList scoped_feature_list_;
};

// Tests that `DeskTextfield` can be used outside overview.
TEST_P(DeskBarTest, DeskTextfieldOutsideOverview) {
  auto widget =
      TestWidgetBuilder()
          .SetDelegate(nullptr)
          .SetBounds(gfx::Rect(0, 0, 300, 300))
          .SetParent(Shell::GetPrimaryRootWindow())
          .SetShow(true)
          .SetWidgetType(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS)
          .BuildOwnsNativeWidget();
  auto* desk_text_view = widget->SetContentsView(
      std::make_unique<DeskTextfield>(SystemTextfield::Type::kSmall));

  // There is no crash for committing name changes for `DeskTextfield` outside
  // overview.
  desk_text_view->CommitChanges(widget.get());
}

// Tests that shutting down when desk bar is alive does not crash without
// animation.
TEST_P(DeskBarTest, ShutdownNoAnimation) {
  OpenDeskBar();
}

// Tests that shutting down when desk bar is alive does not crash with
// animation.
TEST_P(DeskBarTest, ShutdownWithAnimation) {
  ui::ScopedAnimationDurationScaleMode animation_scale(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  OpenDeskBar();
}

struct DeskBarTestBasicCase {
  std::string test_name;

  // IDs of all desks.
  std::vector<int> desks;

  // ID of active desk.
  int active_desk;

  // Shelf alignment.
  ShelfAlignment shelf_alignment;

  // Indicates if there are any saved desks.
  bool has_saved_desks;

  // The expected bar widget bounds for desk button desk bar.
  gfx::Rect desk_button_bar_widget_bounds;

  // The expected bar view bounds for desk button desk bar.
  gfx::Rect desk_button_bar_view_bounds;

  // The expected bar widget bounds for overview desk bar.
  gfx::Rect overview_bar_widget_bounds;

  // The expected bar view bounds for overview desk bar.
  gfx::Rect overview_bar_view_bounds;
};

// Tests that desk button desk bar can show outside of overview with expected
// bounds for different shelf alignments.
TEST_P(DeskBarTest, Basic) {
  UpdateDisplay("800x600");

  const int expected_expanded_overview_height =
      features::IsForestFeatureEnabled() ? 114 : 98;

  const DeskBarTestBasicCase tests[] = {
      {.test_name = "single desk + bottom shelf + saved desks",
       .desks = {0},
       .active_desk = 0,
       .shelf_alignment = ShelfAlignment::kBottom,
       .has_saved_desks = true,
       .desk_button_bar_widget_bounds = {299, 446, 202, 98},
       .desk_button_bar_view_bounds = {0, 0, 202, 98},
       .overview_bar_widget_bounds = {0, 0, 800, 40},
       .overview_bar_view_bounds = {0, 0, 800, 40}},
      {.test_name = "single desk + bottom shelf",
       .desks = {0},
       .active_desk = 0,
       .shelf_alignment = ShelfAlignment::kBottom,
       .has_saved_desks = false,
       .desk_button_bar_widget_bounds = {323, 446, 154, 98},
       .desk_button_bar_view_bounds = {0, 0, 154, 98},
       .overview_bar_widget_bounds = {0, 0, 800, 40},
       .overview_bar_view_bounds = {0, 0, 800, 40}},
      {.test_name = "single desk + left shelf + saved desks",
       .desks = {0},
       .active_desk = 0,
       .shelf_alignment = ShelfAlignment::kLeft,
       .has_saved_desks = true,
       .desk_button_bar_widget_bounds = {56, 247, 202, 98},
       .desk_button_bar_view_bounds = {0, 0, 202, 98},
       .overview_bar_widget_bounds = {48, 0, 752, 40},
       .overview_bar_view_bounds = {0, 0, 752, 40}},
      {.test_name = "single desk + right shelf + saved desks",
       .desks = {0},
       .active_desk = 0,
       .shelf_alignment = ShelfAlignment::kRight,
       .has_saved_desks = true,
       .desk_button_bar_widget_bounds = {542, 247, 202, 98},
       .desk_button_bar_view_bounds = {0, 0, 202, 98},
       .overview_bar_widget_bounds = {0, 0, 752, 40},
       .overview_bar_view_bounds = {0, 0, 752, 40}},
      {.test_name = "multiple desks + bottom shelf + saved desks",
       .desks = {0, 1, 2},
       .active_desk = 0,
       .shelf_alignment = ShelfAlignment::kBottom,
       .has_saved_desks = true,
       .desk_button_bar_widget_bounds = {221, 446, 358, 98},
       .desk_button_bar_view_bounds = {0, 0, 358, 98},
       .overview_bar_widget_bounds = {0, 0, 800,
                                      expected_expanded_overview_height},
       .overview_bar_view_bounds = {0, 0, 800,
                                    expected_expanded_overview_height}},
  };

  auto* desks_controller = DesksController::Get();
  Shelf* shelf = GetPrimaryShelf();

  for (const auto& test : tests) {
    SCOPED_TRACE(test.test_name);

    // Set up desks.
    while (desks_controller->GetNumberOfDesks() < (int)test.desks.size()) {
      NewDesk();
    }
    if (!desks_controller->GetDeskAtIndex(test.active_desk)->is_active()) {
      ActivateDesk(desks_controller->GetDeskAtIndex(test.active_desk));
    }

    // Set up shelf.
    shelf->SetAlignment(test.shelf_alignment);

    // Set up saved desk.
    if (test.has_saved_desks) {
      AddSavedDeskEntry(desk_model(), base::Uuid::GenerateRandomV4(),
                        "saved_desk_1", base::Time::Now(),
                        DeskTemplateType::kSaveAndRecall);
    }

    // Create the desk bar then verify the bar and its child UI have expected
    // appearance.
    OpenDeskBar();
    auto* desk_bar_view = GetDeskBarView();
    ASSERT_TRUE(desk_bar_view);
    ASSERT_TRUE(desk_bar_view->GetVisible());
    auto* desk_bar_widget = desk_bar_view->GetWidget();
    ASSERT_TRUE(desk_bar_widget);
    if (bar_type_ == DeskBarViewBase::Type::kOverview) {
      EXPECT_THAT(desk_bar_widget->GetWindowBoundsInScreen(),
                  test.overview_bar_widget_bounds);
      EXPECT_THAT(desk_bar_view->bounds(), test.overview_bar_view_bounds);
      EXPECT_THAT(desk_bar_view->IsZeroState(), test.desks.size() == 1);
    } else {
      EXPECT_THAT(desk_bar_widget->GetWindowBoundsInScreen(),
                  test.desk_button_bar_widget_bounds);
      EXPECT_THAT(desk_bar_view->bounds(), test.desk_button_bar_view_bounds);
      EXPECT_FALSE(desk_bar_view->IsZeroState());
    }
    auto* new_desk_button = desk_bar_view->new_desk_button();
    const auto expected_button_state =
        bar_type_ == DeskBarViewBase::Type::kOverview && test.desks.size() == 1
            ? DeskIconButton::State::kZero
            : DeskIconButton::State::kExpanded;
    EXPECT_THAT(new_desk_button->state(), expected_button_state);
    EXPECT_TRUE(new_desk_button->GetVisible());
    EXPECT_THAT(new_desk_button->GetEnabled(),
                desks_controller->CanCreateDesks());
    auto* library_button = desk_bar_view->library_button();
    EXPECT_THAT(IsLazyInitViewVisible(library_button), test.has_saved_desks);
    if (library_button) {
      EXPECT_THAT(library_button->state(), expected_button_state);
      EXPECT_TRUE(library_button->GetEnabled());
    }

    CloseDeskBar();

    // Reset to clean state, i.e. only 1 desk and no saved desks.
    while (desks_controller->CanRemoveDesks()) {
      RemoveDesk(desks_controller->desks().back().get());
    }
    DeleteAllSavedDesks();
  }
}

// Tests that desk button desk bar shows with the correct bounds in secondary
// display.
TEST_P(DeskBarTest, BasicSecondaryDisplay) {
  UpdateDisplay("800x600,800x600");

  NewDesk();

  aura::Window* root = Shell::Get()->GetAllRootWindows().back();
  OpenDeskBar(root);

  auto* desk_bar_view = GetDeskBarView(root);
  ASSERT_TRUE(desk_bar_view);
  ASSERT_TRUE(desk_bar_view->GetVisible());
  auto* desk_bar_widget = desk_bar_view->GetWidget();
  ASSERT_TRUE(desk_bar_widget);

  const int expected_expanded_overview_height =
      features::IsForestFeatureEnabled() ? 114 : 98;

  if (bar_type_ == DeskBarViewBase::Type::kOverview) {
    EXPECT_THAT(desk_bar_widget->GetWindowBoundsInScreen(),
                gfx::Rect(800, 0, 800, expected_expanded_overview_height));
    EXPECT_THAT(desk_bar_view->bounds(),
                gfx::Rect(0, 0, 800, expected_expanded_overview_height));
    EXPECT_FALSE(desk_bar_view->IsZeroState());
  } else {
    EXPECT_THAT(desk_bar_widget->GetWindowBoundsInScreen(),
                gfx::Rect(1084, 446, 232, 98));
    EXPECT_THAT(desk_bar_view->bounds(), gfx::Rect(0, 0, 232, 98));
    EXPECT_FALSE(desk_bar_view->IsZeroState());
  }

  CloseDeskBar(root);
}

// Tests that desk button desk bar shows the scroll arrow buttons when overflow
// happens.
TEST_P(DeskBarTest, ScrollLayout) {
  UpdateDisplay("600x400");

  auto* desks_controller = DesksController::Get();
  while (desks_controller->CanCreateDesks()) {
    NewDesk();
  }

  OpenDeskBar();

  auto* left_scroll_button =
      DesksTestApi::GetDeskBarLeftScrollButton(bar_type_);
  ASSERT_TRUE(left_scroll_button);
  auto* right_scroll_button =
      DesksTestApi::GetDeskBarRightScrollButton(bar_type_);
  ASSERT_TRUE(right_scroll_button);
  EXPECT_FALSE(left_scroll_button->GetVisible());
  EXPECT_TRUE(right_scroll_button->GetVisible());

  while (right_scroll_button->GetVisible()) {
    ClickOrPressOnView(right_scroll_button);
    EXPECT_TRUE(left_scroll_button->GetVisible());
  }

  while (left_scroll_button->GetVisible()) {
    ClickOrPressOnView(left_scroll_button);
    EXPECT_TRUE(right_scroll_button->GetVisible());
  }

  CloseDeskBar();
}

TEST_P(DeskBarTest, HoverBasic) {
  auto window_1 = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto window_2 = CreateAppWindow(gfx::Rect(0, 0, 100, 100));

  NewDesk();

  auto* desks_controller = DesksController::Get();
  desks_controller->SendToDeskAtIndex(window_1.get(), 0);
  desks_controller->SendToDeskAtIndex(window_2.get(), 1);

  OpenDeskBar();

  for (int i = 0; i < desks_controller->GetNumberOfDesks(); i++) {
    auto* event_generator = GetEventGenerator();
    auto* mini_view = GetDeskBarView()->mini_views()[i].get();

    EXPECT_FALSE(DesksTestApi::IsDeskShortcutViewVisible(mini_view));
    event_generator->MoveMouseTo(
        mini_view->desk_preview()->GetBoundsInScreen().CenterPoint());

    if (features::IsSavedDeskUiRevampEnabled()) {
      EXPECT_TRUE(mini_view->desk_action_view()->context_menu_button());
      EXPECT_TRUE(
          mini_view->desk_action_view()->context_menu_button()->GetVisible());
    } else {
      EXPECT_TRUE(mini_view->desk_action_view()->combine_desks_button());
      EXPECT_TRUE(
          mini_view->desk_action_view()->combine_desks_button()->GetVisible());
    }

    EXPECT_TRUE(
        mini_view->desk_action_view()->close_all_button()->GetVisible());

    // The shortcut view only appears on the first 8 desks in the desk button
    // desk bar.
    const bool expected_visibility =
        i <= 7 && bar_type_ == DeskBarViewBase::Type::kDeskButton;
    EXPECT_EQ(DesksTestApi::IsDeskShortcutViewVisible(mini_view),
              expected_visibility);
  }

  CloseDeskBar();
}

// Tests that clicking on new desk button does the expected thing.
TEST_P(DeskBarTest, NewDeskButton) {
  OpenDeskBar();

  auto* desks_controller = DesksController::Get();
  auto* desk_bar_view = GetDeskBarView();
  auto* new_desk_button = desk_bar_view->new_desk_button();

  auto verify_disabled_new_desk_button = [&]() {
    EXPECT_THAT(desks_controller->GetNumberOfDesks(),
                desks_util::GetMaxNumberOfDesks());
    EXPECT_FALSE(desks_controller->CanCreateDesks());
    EXPECT_FALSE(new_desk_button->GetEnabled());
    EXPECT_THAT(new_desk_button->GetState(), views::Button::STATE_DISABLED);
    EXPECT_THAT(desk_bar_view->mini_views().size(),
                desks_controller->GetNumberOfDesks());
  };
  auto verify_enabled_new_desk_button = [&](bool zero_state_bar) {
    EXPECT_LE(desks_controller->GetNumberOfDesks(),
              (int)desks_util::GetMaxNumberOfDesks());
    EXPECT_TRUE(desks_controller->CanCreateDesks());
    EXPECT_THAT(desk_bar_view->IsZeroState(), zero_state_bar);
    EXPECT_TRUE(new_desk_button->GetEnabled());
    EXPECT_NE(new_desk_button->GetState(), views::Button::STATE_DISABLED);
    EXPECT_THAT(desk_bar_view->mini_views().size(),
                zero_state_bar ? 0 : desks_controller->GetNumberOfDesks());
  };

  // Create max number of desks.
  for (int i = 2; i <= (int)desks_util::GetMaxNumberOfDesks(); i++) {
    const bool zero_state_bar =
        bar_type_ == DeskBarViewBase::Type::kOverview && i == 2;
    verify_enabled_new_desk_button(zero_state_bar);
    ClickOrPressOnView(new_desk_button);

    EXPECT_TRUE(desks_controller->CanRemoveDesks());
    EXPECT_THAT(desks_controller->GetNumberOfDesks(), i);
  }

  // The new desk button should be disabled.
  verify_disabled_new_desk_button();

  // Clicking on the new desk button again does nothing now.
  ClickOrPressOnView(new_desk_button);
  verify_disabled_new_desk_button();

  CloseDeskBar();
}

// Tests that we can go to saved desk library directly via desk button desk bar.
TEST_P(DeskBarTest, LibraryButton) {
  ui::ScopedAnimationDurationScaleMode animation_scale(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  // Add a saved desk, so that the library button can show up.
  AddSavedDeskEntry(desk_model(), base::Uuid::GenerateRandomV4(),
                    "saved_desk_1", base::Time::Now(),
                    DeskTemplateType::kSaveAndRecall);

  auto test_library_button = [&](const std::string& trace_message) {
    SCOPED_TRACE(trace_message);

    OpenDeskBar();
    if (bar_type_ == DeskBarViewBase::Type::kOverview) {
      WaitForOverviewEnterAnimation();
    }

    EnterLibrary();
    auto* root = Shell::GetPrimaryRootWindow();
    if (bar_type_ == DeskBarViewBase::Type::kOverview) {
      // Clicking on library button in zero state overview desk bar would
      // trigger a bar bounds animation.
      DesksTestApi::WaitForDeskBarUiUpdate(
          GetDeskBarView(root, DeskBarViewBase::Type::kOverview));
    }
    const views::FocusRing* library_button_focus_ring =
        views::FocusRing::Get(GetPrimaryRootDesksBarView()->library_button());
    ASSERT_TRUE(library_button_focus_ring);
    ASSERT_TRUE(library_button_focus_ring->GetVisible());
    EXPECT_FALSE(library_button_focus_ring->GetVisibleBounds().IsEmpty());

    CloseDeskBar(root, DeskBarViewBase::Type::kOverview);
  };

  test_library_button("no app window");

  auto window = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  test_library_button("one app window");
}

// Tests that the desk button desk bar support dragging to reorder desks.
TEST_P(DeskBarTest, ReorderDesk) {
  OpenDeskBar();

  auto* desks_controller = DesksController::Get();
  auto* desk_bar_view = GetDeskBarView();
  auto* event_generator = GetEventGenerator();

  // Create two more desks.
  std::vector<std::string> desk_names = {"1", "2", "3"};
  for (auto i = 0; auto desk_name : desk_names) {
    if (desks_controller->GetNumberOfDesks() - 1 < i) {
      NewDesk();
    }
    desks_controller->GetDeskAtIndex(i)->SetName(base::UTF8ToUTF16(desk_name),
                                                 /*set_by_user=*/true);
    EXPECT_THAT(desk_bar_view->mini_views().size(),
                GetDeskBarView()->IsZeroState()
                    ? 0
                    : desks_controller->GetNumberOfDesks());
    i++;
  }
  views::test::RunScheduledLayout(desk_bar_view);
  desks_restore_util::UpdatePrimaryUserDeskNamesPrefs();

  auto verify_desks = [&]() {
    for (int i = 0; i < desks_controller->GetNumberOfDesks(); i++) {
      EXPECT_THAT(desks_controller->GetDeskAtIndex(i)->name(),
                  base::UTF8ToUTF16(desk_names[i]));
    }
    auto* prefs =
        Shell::Get()->session_controller()->GetPrimaryUserPrefService();
    EXPECT_THAT(GetDeskRestoreNames(prefs),
                ::testing::ElementsAreArray(desk_names));
  };

  auto drag_desk = [&](int from, int to) {
    SCOPED_TRACE("Swap desk " + base::NumberToString(from) + " with desk " +
                 base::NumberToString(to));

    // Drag the desk from `from` to `to`.
    StartDragDeskPreview(desk_bar_view->mini_views()[from], event_generator);
    EXPECT_TRUE(desk_bar_view->IsDraggingDesk());
    event_generator->MoveMouseTo(desk_bar_view->mini_views()[to]
                                     ->GetPreviewBoundsInScreen()
                                     .CenterPoint());
    event_generator->ReleaseLeftButton();
    EXPECT_FALSE(desk_bar_view->IsDraggingDesk());

    // Update `desk_names` with the expected order.
    std::string dragged_desk = desk_names[from];
    if (from <= to) {
      for (int i = from + 1; i <= to; i++) {
        desk_names[i - 1] = desk_names[i];
      }
    } else {
      for (int i = from - 1; i >= to; i--) {
        desk_names[i + 1] = desk_names[i];
      }
    }
    desk_names[to] = dragged_desk;

    // Verify desks are with expected order.
    verify_desks();
  };

  verify_desks();
  drag_desk(/*from=*/0, /*to=*/1);
  drag_desk(/*from=*/1, /*to=*/2);
  drag_desk(/*from=*/0, /*to=*/1);
  drag_desk(/*from=*/2, /*to=*/0);

  CloseDeskBar();
}

// Tests that the desk button desk bar supports keyboard reordering desks.
TEST_P(DeskBarTest, KeyboardReorderDesk) {
  OpenDeskBar();
  auto* desks_controller = DesksController::Get();
  auto* desk_bar_view = GetDeskBarView();

  // Create two more desks and store uuids to verify swaps.
  NewDesk();
  NewDesk();

  std::vector<base::Uuid> desk_uuids;
  for (auto& desk : desks_controller->desks()) {
    desk_uuids.push_back(desk->uuid());
  }

  auto verify_desk_uuids = [&]() {
    for (int i = 0; i < desks_controller->GetNumberOfDesks(); i++) {
      EXPECT_THAT(desks_controller->GetDeskAtIndex(i)->uuid(), desk_uuids[i]);
    }
  };

  auto verify_shortcut_label = [&](auto* mini_view, int desk_index) {
    const bool expected_shortcut_visibility =
        bar_type_ == DeskBarViewBase::Type::kDeskButton;

    ASSERT_EQ(DesksTestApi::IsDeskShortcutViewVisible(mini_view),
              expected_shortcut_visibility);
    if (expected_shortcut_visibility) {
      views::Label* label = DesksTestApi::GetDeskShortcutLabel(mini_view);
      ASSERT_TRUE(label);
      EXPECT_EQ(base::NumberToString16(desk_index + 1), label->GetText());
    }
  };

  auto swap_desk = [&](int desk_index, bool left) {
    SCOPED_TRACE("Swap desk " + base::NumberToString(desk_index) + " to the " +
                 (left ? "left" : "right"));

    // Ensure swap is possible.
    ASSERT_FALSE(desk_index == 0 && left);
    ASSERT_FALSE(desk_index == 2 && !left);

    // Perform the swap.
    auto* mini_view = desk_bar_view->mini_views()[desk_index].get();
    mini_view->desk_preview()->RequestFocus();
    verify_shortcut_label(mini_view, desk_index);
    PressAndReleaseKey(left ? ui::VKEY_LEFT : ui::VKEY_RIGHT,
                       ui::EF_CONTROL_DOWN);

    // Verify the swap.
    const int new_index = desk_index + (left ? -1 : 1);
    EXPECT_EQ(mini_view, desk_bar_view->mini_views()[new_index]);
    verify_shortcut_label(mini_view, new_index);

    // Update `desk_uuids` with the expected order and verify desks.
    std::swap(desk_uuids[desk_index], desk_uuids[new_index]);
    verify_desk_uuids();
  };

  verify_desk_uuids();
  swap_desk(/*desk_index=*/0, /*left=*/false);
  swap_desk(/*desk_index=*/1, /*left=*/false);
  swap_desk(/*desk_index=*/0, /*left=*/false);
  swap_desk(/*desk_index=*/1, /*left=*/false);
  swap_desk(/*desk_index=*/1, /*left=*/true);
  swap_desk(/*desk_index=*/2, /*left=*/true);
  swap_desk(/*desk_index=*/1, /*left=*/true);
  swap_desk(/*desk_index=*/0, /*left=*/false);
  swap_desk(/*desk_index=*/2, /*left=*/true);
  swap_desk(/*desk_index=*/1, /*left=*/false);
  swap_desk(/*desk_index=*/1, /*left=*/true);

  CloseDeskBar();
}

TEST_P(DeskBarTest, ActivateDesk) {
  auto* desks_controller = DesksController::Get();

  NewDesk();
  EXPECT_THAT(desks_controller->GetActiveDeskIndex(), 0);

  // Clicking on active desk would *not* switch desk but just hide the bar.
  OpenDeskBar();
  ClickOrPressOnView(GetDeskBarView()->mini_views()[0]);
  EXPECT_THAT(desks_controller->GetActiveDeskIndex(), 0);
  EXPECT_FALSE(GetDeskBarView());

  // Clicking on non-active desk would switch desk and hide the bar.
  OpenDeskBar();
  DeskSwitchAnimationWaiter waiter;
  ClickOrPressOnView(GetDeskBarView()->mini_views()[1]);
  waiter.Wait();
  EXPECT_THAT(desks_controller->GetActiveDeskIndex(), 1);
  EXPECT_FALSE(GetDeskBarView());
}

TEST_P(DeskBarTest, CombineOrCloseDesk) {
  // Setup 3 desks, e.g. "Desk 1", "Desk 2", and "Desk 3". Only "Desk 3" has a
  // window.
  NewDesk();
  NewDesk();
  auto window = CreateAppWindow(gfx::Rect(0, 0, 100, 100));
  auto* desks_controller = DesksController::Get();
  desks_controller->SendToDeskAtIndex(window.get(), 2);

  OpenDeskBar();

  for (int desk_index = desks_controller->GetNumberOfDesks() - 1;
       desk_index > 0; desk_index--) {
    CloseDeskFromMiniView(GetDeskBarView()->mini_views()[desk_index],
                          GetEventGenerator());
    EXPECT_THAT(GetDeskBarView()->mini_views().size(),
                GetDeskBarView()->IsZeroState() ? 0 : desk_index);
  }

  CloseDeskBar();
}

TEST_P(DeskBarTest, DeskRenameKeyEsc) {
  NewDesk();
  OpenDeskBar();

  auto* desk_bar_view = GetDeskBarView();
  Desk* desk = DesksController::Get()->GetDeskAtIndex(0);
  auto* mini_view = desk_bar_view->FindMiniViewForDesk(desk);
  auto* desk_name_view = mini_view->desk_name_view();

  ClickOrPressOnView(desk_name_view);
  ASSERT_TRUE(desk_name_view->HasFocus());

  // Undo by pressing esc on keyboard.
  PressAndReleaseKey(ui::VKEY_D, ui::EF_SHIFT_DOWN);
  PressAndReleaseKey(ui::VKEY_1);
  PressAndReleaseKey(ui::VKEY_ESCAPE);
  EXPECT_FALSE(desk_name_view->HasFocus());
  EXPECT_FALSE(desk->is_name_set_by_user());
  EXPECT_THAT(desk_name_view->GetText(), u"Desk 1");

  CloseDeskBar();
}

TEST_P(DeskBarTest, DeskRenameKeyReturn) {
  NewDesk();
  OpenDeskBar();

  auto* desk_bar_view = GetDeskBarView();
  Desk* desk = DesksController::Get()->GetDeskAtIndex(0);
  auto* mini_view = desk_bar_view->FindMiniViewForDesk(desk);
  auto* desk_name_view = mini_view->desk_name_view();

  ClickOrPressOnView(desk_name_view);
  ASSERT_TRUE(desk_name_view->HasFocus());

  // Commit by pressing return on keyboard.
  PressAndReleaseKey(ui::VKEY_D, ui::EF_SHIFT_DOWN);
  PressAndReleaseKey(ui::VKEY_1);
  PressAndReleaseKey(ui::VKEY_RETURN);
  EXPECT_FALSE(desk_name_view->HasFocus());
  EXPECT_TRUE(desk->is_name_set_by_user());
  EXPECT_THAT(desk_name_view->GetText(), u"D1");

  CloseDeskBar();
}

TEST_P(DeskBarTest, DeskRenameKeyTab) {
  NewDesk();
  OpenDeskBar();

  auto* desk_bar_view = GetDeskBarView();
  Desk* desk = DesksController::Get()->desks().front().get();
  auto* mini_view = desk_bar_view->FindMiniViewForDesk(desk);
  auto* desk_name_view = mini_view->desk_name_view();

  ClickOrPressOnView(desk_name_view);
  ASSERT_TRUE(desk_name_view->HasFocus());

  // Commit by pressing tab on keyboard.
  PressAndReleaseKey(ui::VKEY_D, ui::EF_SHIFT_DOWN);
  PressAndReleaseKey(ui::VKEY_1);
  PressAndReleaseKey(ui::VKEY_TAB);
  EXPECT_FALSE(desk_name_view->HasFocus());
  EXPECT_TRUE(desk->is_name_set_by_user());
  EXPECT_THAT(desk_name_view->GetText(), u"D1");
  ASSERT_TRUE(desk_bar_view->mini_views()[1]->desk_preview()->HasFocus());

  CloseDeskBar();
}

TEST_P(DeskBarTest, DeskRenameKeyShiftTab) {
  NewDesk();
  OpenDeskBar();

  auto* desk_bar_view = GetDeskBarView();
  Desk* desk = DesksController::Get()->desks().front().get();
  auto* mini_view = desk_bar_view->FindMiniViewForDesk(desk);
  auto* desk_name_view = mini_view->desk_name_view();

  ClickOrPressOnView(desk_name_view);
  ASSERT_TRUE(desk_name_view->HasFocus());

  // Commit by pressing shift+tab on keyboard.
  PressAndReleaseKey(ui::VKEY_D, ui::EF_SHIFT_DOWN);
  PressAndReleaseKey(ui::VKEY_1);
  PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
  EXPECT_FALSE(desk_name_view->HasFocus());
  EXPECT_TRUE(desk->is_name_set_by_user());
  EXPECT_THAT(desk_name_view->GetText(), u"D1");
  ASSERT_TRUE(mini_view->desk_action_view()->close_all_button()->HasFocus());

  CloseDeskBar();
}

TEST_P(DeskBarTest, DeskRenameClickOnBar) {
  NewDesk();
  OpenDeskBar();

  auto* desk_bar_view = GetDeskBarView();
  Desk* desk = DesksController::Get()->GetDeskAtIndex(0);
  auto* mini_view = desk_bar_view->FindMiniViewForDesk(desk);
  auto* desk_name_view = mini_view->desk_name_view();

  ClickOrPressOnView(desk_name_view);
  ASSERT_TRUE(desk_name_view->HasFocus());

  // Commit by clicking or pressing empty area on the bar.
  PressAndReleaseKey(ui::VKEY_D, ui::EF_SHIFT_DOWN);
  PressAndReleaseKey(ui::VKEY_1);
  gfx::Point empty_point = desk_bar_view->GetBoundsInScreen().top_center();
  empty_point.Offset(0, 2);
  ClickOrPressOnPoint(empty_point);

  EXPECT_FALSE(desk_name_view->HasFocus());
  EXPECT_TRUE(desk->is_name_set_by_user());
  EXPECT_THAT(desk_name_view->GetText(), u"D1");

  CloseDeskBar();
}

TEST_P(DeskBarTest, DeskRenameClickOffBar) {
  NewDesk();
  OpenDeskBar();

  auto* desk_bar_view = GetDeskBarView();
  Desk* desk = DesksController::Get()->GetDeskAtIndex(0);
  auto* mini_view = desk_bar_view->FindMiniViewForDesk(desk);
  auto* desk_name_view = mini_view->desk_name_view();

  ClickOrPressOnView(desk_name_view);
  ASSERT_TRUE(desk_name_view->HasFocus());
  PressAndReleaseKey(ui::VKEY_D, ui::EF_SHIFT_DOWN);
  PressAndReleaseKey(ui::VKEY_1);

  // Commit by clicking or pressing empty area off the bar.
  gfx::Point empty_point = desk_bar_view->GetBoundsInScreen().bottom_center();
  empty_point.Offset(0, 2);
  ClickOrPressOnPoint(empty_point);
  EXPECT_FALSE(desk_name_view->HasFocus());
  EXPECT_TRUE(desk->is_name_set_by_user());
  EXPECT_THAT(desk_name_view->GetText(), u"D1");
  EXPECT_TRUE(GetDeskBarView());

  CloseDeskBar();
}

TEST_P(DeskBarTest, AutoHideClickOrPress) {
  OpenDeskBar();
  auto* desk_bar_view = GetDeskBarView();

  // Clicking on wallpaper hides the bar.
  gfx::Point empty_point = desk_bar_view->GetBoundsInScreen().bottom_center();
  empty_point.Offset(0, 2);
  ClickOrPressOnPoint(empty_point);
  EXPECT_FALSE(GetDeskBarView());
}

TEST_P(DeskBarTest, AutoHideKeyEsc) {
  OpenDeskBar();
  ASSERT_TRUE(GetDeskBarView());

  // Pressing `Esc` hides the bar.
  PressAndReleaseKey(ui::VKEY_ESCAPE);
  EXPECT_FALSE(GetDeskBarView());
}

TEST_P(DeskBarTest, AutoHideKeyBack) {
  OpenDeskBar();
  ASSERT_TRUE(GetDeskBarView());

  // Pressing `Back` hides the bar.
  PressAndReleaseKey(ui::VKEY_BROWSER_BACK);
  EXPECT_FALSE(GetDeskBarView());
}

TEST_P(DeskBarTest, ForwardTabbing) {
  // Add a saved desk, so that the library button can show up.
  AddSavedDeskEntry(desk_model(), base::Uuid::GenerateRandomV4(),
                    "saved_desk_1", base::Time::Now(),
                    DeskTemplateType::kSaveAndRecall);

  // Create `max - 1` number of desks.
  for (size_t i = 2; i <= desks_util::GetMaxNumberOfDesks() - 1; i++) {
    NewDesk();
  }
  auto* desk_controller = DesksController::Get();
  ASSERT_EQ(desk_controller->GetNumberOfDesks(),
            static_cast<int>(desks_util::GetMaxNumberOfDesks()) - 1);
  const auto& window = CreateAppWindow();
  desk_controller->SendToDeskAtIndex(window.get(), 0);

  OpenDeskBar();
  auto* desk_bar_view = GetDeskBarView();
  ASSERT_TRUE(desk_bar_view);

  // Tab through the first window if we are in overview.
  if (bar_type_ == DeskBarViewBase::Type::kOverview) {
    PressAndReleaseKey(ui::VKEY_TAB);
  }

  // Tab through all desks.
  for (int i = 0; i < desk_controller->GetNumberOfDesks(); i++) {
    auto* mini_view = desk_bar_view->mini_views()[i].get();

    PressAndReleaseKey(ui::VKEY_TAB);
    ASSERT_TRUE(mini_view->desk_preview()->HasFocus());
    // The shortcut view only appears on the first 8 desks in the desk button
    // desk bar.
    const bool expected_visibility =
        i <= 7 && bar_type_ == DeskBarViewBase::Type::kDeskButton;
    EXPECT_EQ(DesksTestApi::IsDeskShortcutViewVisible(mini_view),
              expected_visibility);

    if (use_desk_profiles_) {
      PressAndReleaseKey(ui::VKEY_TAB);
      ASSERT_TRUE(mini_view->desk_profiles_button()->HasFocus());
    }

    if (i == 0) {
      PressAndReleaseKey(ui::VKEY_TAB);

      if (features::IsSavedDeskUiRevampEnabled()) {
        ASSERT_TRUE(mini_view->desk_action_view()->context_menu_button());
        ASSERT_TRUE(
            mini_view->desk_action_view()->context_menu_button()->HasFocus());
      } else {
        ASSERT_TRUE(mini_view->desk_action_view()->combine_desks_button());
        ASSERT_TRUE(
            mini_view->desk_action_view()->combine_desks_button()->HasFocus());
      }
    }

    PressAndReleaseKey(ui::VKEY_TAB);
    ASSERT_TRUE(mini_view->desk_action_view()->close_all_button()->HasFocus());
    // The shortcut view only appears on the first 8 desks in the desk button
    // desk bar.
    EXPECT_EQ(DesksTestApi::IsDeskShortcutViewVisible(mini_view),
              expected_visibility);

    PressAndReleaseKey(ui::VKEY_TAB);
    ASSERT_TRUE(mini_view->desk_name_view()->HasFocus());
    EXPECT_FALSE(DesksTestApi::IsDeskShortcutViewVisible(
        desk_bar_view->mini_views()[i]));
  }

  // Tab through new desk button.
  PressAndReleaseKey(ui::VKEY_TAB);
  ASSERT_TRUE(desk_bar_view->new_desk_button()->HasFocus());

  // Tab through library button.
  PressAndReleaseKey(ui::VKEY_TAB);
  ASSERT_TRUE(desk_bar_view->library_button());
  ASSERT_TRUE(desk_bar_view->library_button()->HasFocus());

  CloseDeskBar();
}

TEST_P(DeskBarTest, ReverseTabbing) {
  // Add a saved desk, so that the library button can show up.
  AddSavedDeskEntry(desk_model(), base::Uuid::GenerateRandomV4(),
                    "saved_desk_1", base::Time::Now(),
                    DeskTemplateType::kSaveAndRecall);

  // Create `max - 1` number of desks.
  for (size_t i = 2; i <= desks_util::GetMaxNumberOfDesks() - 1; i++) {
    NewDesk();
  }
  auto* desk_controller = DesksController::Get();
  ASSERT_EQ(desk_controller->GetNumberOfDesks(),
            static_cast<int>(desks_util::GetMaxNumberOfDesks()) - 1);
  const auto& window = CreateAppWindow();
  desk_controller->SendToDeskAtIndex(window.get(), 0);

  OpenDeskBar();
  auto* desk_bar_view = GetDeskBarView();
  ASSERT_TRUE(desk_bar_view);

  // If it is the bento button desk bar, tab one more time since it starts at
  // the active desk.
  if (bar_type_ == DeskBarViewBase::Type::kDeskButton) {
    PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
  }

  // Tab through library button.
  PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
  ASSERT_TRUE(desk_bar_view->library_button());
  ASSERT_TRUE(desk_bar_view->library_button()->HasFocus());

  // Tab through new desk button.
  PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
  ASSERT_TRUE(desk_bar_view->new_desk_button()->HasFocus());

  // Tab through all desks.
  for (int i = desk_controller->GetNumberOfDesks() - 1; i >= 0; i--) {
    auto* mini_view = desk_bar_view->mini_views()[i].get();

    PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
    ASSERT_TRUE(mini_view->desk_name_view()->HasFocus());
    EXPECT_FALSE(DesksTestApi::IsDeskShortcutViewVisible(
        desk_bar_view->mini_views()[i]));

    PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
    ASSERT_TRUE(mini_view->desk_action_view()->close_all_button()->HasFocus());

    if (i == 0) {
      PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);

      if (features::IsSavedDeskUiRevampEnabled()) {
        ASSERT_TRUE(mini_view->desk_action_view()->context_menu_button());
        ASSERT_TRUE(
            mini_view->desk_action_view()->context_menu_button()->HasFocus());
      } else {
        ASSERT_TRUE(mini_view->desk_action_view()->combine_desks_button());
        ASSERT_TRUE(
            mini_view->desk_action_view()->combine_desks_button()->HasFocus());
      }
    }

    if (use_desk_profiles_) {
      PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
      ASSERT_TRUE(mini_view->desk_profiles_button()->HasFocus());
    }

    // The shortcut view only appears on the first 8 desks in the desk button
    // desk bar.
    const bool expected_visibility =
        i <= 7 && bar_type_ == DeskBarViewBase::Type::kDeskButton;
    EXPECT_EQ(DesksTestApi::IsDeskShortcutViewVisible(mini_view),
              expected_visibility);
    PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
    ASSERT_TRUE(mini_view->desk_preview()->HasFocus());
    EXPECT_EQ(DesksTestApi::IsDeskShortcutViewVisible(mini_view),
              expected_visibility);
  }

  CloseDeskBar();
}

TEST_P(DeskBarTest, CloseActiveDesk) {
  // Create one app window and two more desks.
  WindowHolder window_holder(CreateAppWindow());
  NewDesk();
  NewDesk();

  // Move window to desk #1 and active the desk.
  auto* desks_controller = DesksController::Get();
  desks_controller->desks()[0]->MoveWindowToDesk(
      window_holder.window(), desks_controller->desks()[1].get(),
      window_holder.window()->GetRootWindow(), /*unminimize=*/true);
  ActivateDesk(desks_controller->desks()[1].get());

  OpenDeskBar();
  auto* desk_bar_view = GetDeskBarView();
  ASSERT_TRUE(desk_bar_view);

  // Focus desk #1.
  ASSERT_TRUE(TabUntil(
      /*reverse=*/false,
      ViewFocused(desk_bar_view->mini_views()[1]->desk_preview()),
      GetEventGenerator()));

  // Close active desk.
  if (bar_type_ == DeskBarViewBase::Type::kOverview) {
    // Closing the active desk in overview should remain in the current overview
    // session.
    PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
    EXPECT_TRUE(GetDeskBarView());
    CloseDeskBar();
  } else {
    // Closing the active desk in desk button desk bar should trigger a desk
    // switch and hide the bar.
    DeskSwitchAnimationWaiter waiter;
    PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
    waiter.Wait();
    EXPECT_FALSE(GetDeskBarView());
  }
  EXPECT_THAT(desks_controller->GetActiveDeskIndex(), 0);
  EXPECT_THAT(desks_controller->desks().size(), 2);
  SimulateWaitForCloseAll();
  EXPECT_FALSE(window_holder.is_valid());
}

TEST_P(DeskBarTest, MergeActiveDesk) {
  // Create one app window and two more desks.
  WindowHolder window_holder(CreateAppWindow());
  NewDesk();
  NewDesk();

  // Move window to desk #1 and active the desk.
  auto* desks_controller = DesksController::Get();
  desks_controller->desks()[0]->MoveWindowToDesk(
      window_holder.window(), desks_controller->desks()[1].get(),
      window_holder.window()->GetRootWindow(), /*unminimize=*/true);
  ActivateDesk(desks_controller->desks()[1].get());

  OpenDeskBar();
  auto* desk_bar_view = GetDeskBarView();
  ASSERT_TRUE(desk_bar_view);

  // Focus desk #1
  ASSERT_TRUE(TabUntil(
      /*reverse=*/false,
      ViewFocused(desk_bar_view->mini_views()[1]->desk_preview()),
      GetEventGenerator()));

  // Merge active desk.
  if (bar_type_ == DeskBarViewBase::Type::kOverview) {
    // Merging the active desk in overview should remain in the current overview
    // session.
    PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN);
    EXPECT_TRUE(GetDeskBarView());
    CloseDeskBar();
  } else {
    // Merging the active desk in desk button desk bar should trigger a desk
    // switch and hide the bar.
    DeskSwitchAnimationWaiter waiter;
    PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN);
    waiter.Wait();
    EXPECT_FALSE(GetDeskBarView());
  }
  EXPECT_THAT(desks_controller->GetActiveDeskIndex(), 0);
  EXPECT_THAT(desks_controller->desks().size(), 2);
  EXPECT_TRUE(window_holder.is_valid());
  EXPECT_TRUE(desks_controller->desks()[0]
                  ->GetDeskContainerForRoot(Shell::GetPrimaryRootWindow())
                  ->Contains(window_holder.window()));
}

TEST_P(DeskBarTest, CloseNonActiveDesk) {
  // Create one app window and two more desks.
  WindowHolder window_holder(CreateAppWindow());
  NewDesk();
  NewDesk();

  // Move window to desk #1.
  auto* desks_controller = DesksController::Get();
  desks_controller->desks()[0]->MoveWindowToDesk(
      window_holder.window(), desks_controller->desks()[1].get(),
      window_holder.window()->GetRootWindow(), /*unminimize=*/true);

  OpenDeskBar();
  auto* desk_bar_view = GetDeskBarView();
  ASSERT_TRUE(desk_bar_view);

  // Highlight desk #1.
  ASSERT_TRUE(TabUntil(
      /*reverse=*/false,
      ViewFocused(desk_bar_view->mini_views()[1]->desk_preview()),
      GetEventGenerator()));

  // Close non-active desk.
  PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
  EXPECT_TRUE(GetDeskBarView());
  EXPECT_THAT(desks_controller->GetActiveDeskIndex(), 0);
  EXPECT_THAT(desks_controller->desks().size(), 2);
  SimulateWaitForCloseAll();
  EXPECT_FALSE(window_holder.is_valid());
  CloseDeskBar();
}

TEST_P(DeskBarTest, MergeNonActiveDesk) {
  // Create one app window and two more desks.
  WindowHolder window_holder(CreateAppWindow());
  NewDesk();
  NewDesk();

  // Move window to desk #1.
  auto* desks_controller = DesksController::Get();
  desks_controller->desks()[0]->MoveWindowToDesk(
      window_holder.window(), desks_controller->desks()[1].get(),
      window_holder.window()->GetRootWindow(), /*unminimize=*/true);

  OpenDeskBar();
  auto* desk_bar_view = GetDeskBarView();
  ASSERT_TRUE(desk_bar_view);

  // Highlight desk #1.
  ASSERT_TRUE(TabUntil(
      /*reverse=*/false,
      ViewFocused(desk_bar_view->mini_views()[1]->desk_preview()),
      GetEventGenerator()));

  // Close non-active desk.
  PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN);
  EXPECT_TRUE(GetDeskBarView());
  EXPECT_THAT(desks_controller->GetActiveDeskIndex(), 0);
  EXPECT_THAT(desks_controller->desks().size(), 2);
  EXPECT_TRUE(window_holder.is_valid());
  EXPECT_TRUE(desks_controller->desks()[0]
                  ->GetDeskContainerForRoot(Shell::GetPrimaryRootWindow())
                  ->Contains(window_holder.window()));

  CloseDeskBar();
}

// Tests that the actions in the desk button and overview desk bars are being
// correctly recorded in their histograms.
TEST_P(DeskBarTest, DeskBarActionMetrics) {
  NewDesk();

  // Add a saved desk so that the library button can show up.
  AddSavedDeskEntry(desk_model(), base::Uuid::GenerateRandomV4(),
                    "saved_desk_1", base::Time::Now(),
                    DeskTemplateType::kSaveAndRecall);

  base::HistogramTester histogram_tester;

  // Windows can only be added to desks when the desk bar is closed. Otherwise
  // the combine desks button will not show.
  WindowHolder window(CreateAppWindow());
  auto* desks_controller = DesksController::Get();
  desks_controller->SendToDeskAtIndex(window.window(), 1);

  OpenDeskBar();
  auto* desk_bar_view = GetDeskBarView();

  // Add new desk.
  ClickOrPressOnView(desk_bar_view->new_desk_button());
  views::test::RunScheduledLayout(desk_bar_view);
  histogram_tester.ExpectTotalCount(
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? kDeskButtonDeskBarNewDeskHistogramName
          : kOverviewDeskBarNewDeskHistogramName,
      1);

  // Set desk name.
  PressAndReleaseKey(ui::VKEY_A, ui::EF_NONE);
  PressAndReleaseKey(ui::VKEY_B, ui::EF_NONE);
  PressAndReleaseKey(ui::VKEY_C, ui::EF_NONE);
  PressAndReleaseKey(ui::VKEY_RETURN, ui::EF_NONE);
  views::test::RunScheduledLayout(desk_bar_view);
  histogram_tester.ExpectTotalCount(
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? kDeskButtonDeskBarRenameDeskHistogramName
          : kOverviewDeskBarRenameDeskHistogramName,
      1);

  // Activate the third desk.
  DeskSwitchAnimationWaiter waiter;
  ClickOrPressOnView(desk_bar_view->mini_views()[2]->desk_preview());
  waiter.Wait();
  histogram_tester.ExpectTotalCount(
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? kDeskButtonDeskBarActivateDeskHistogramName
          : kOverviewDeskBarActivateDeskHistogramName,
      1);

  // Activating the desk should take us out of our desk bar, so we need a new
  // one.
  OpenDeskBar();
  desk_bar_view = GetDeskBarView();

  // Drag desk to reorder.
  const auto& mini_views = desk_bar_view->mini_views();
  auto* event_generator = GetEventGenerator();
  StartDragDeskPreview(mini_views[0], event_generator);
  EXPECT_TRUE(desk_bar_view->IsDraggingDesk());
  event_generator->MoveMouseTo(
      mini_views[2]->GetPreviewBoundsInScreen().CenterPoint());
  event_generator->ReleaseLeftButton();
  views::test::RunScheduledLayout(desk_bar_view);
  EXPECT_FALSE(desk_bar_view->IsDraggingDesk());
  histogram_tester.ExpectTotalCount(
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? kDeskButtonDeskBarReorderDeskHistogramName
          : kOverviewDeskBarReorderDeskHistogramName,
      1);

  // Combine desks.
  auto* root_window = Shell::Get()->GetPrimaryRootWindow();
  if (features::IsSavedDeskUiRevampEnabled()) {
    CombineDeskWithMenu(/*index=*/0, root_window, bar_type_);
  } else {
    CloseDeskWithButton(/*index=*/0, /*close_all=*/false, root_window,
                        bar_type_);
  }

  histogram_tester.ExpectTotalCount(
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? kDeskButtonDeskBarCombineDesksHistogramName
          : kOverviewDeskBarCombineDesksHistogramName,
      1);

  // Close desk with windows.
  CloseDeskWithButton(/*index=*/1, /*close_all=*/true, root_window, bar_type_);
  histogram_tester.ExpectTotalCount(
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? kDeskButtonDeskBarCloseDeskHistogramName
          : kOverviewDeskBarCloseDeskHistogramName,
      1);

  // Open library.
  EnterLibrary();
  histogram_tester.ExpectTotalCount(
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? kDeskButtonDeskBarOpenLibraryHistogramName
          : kOverviewDeskBarOpenLibraryHistogramName,
      1);
}

// Tests that metrics are correctly separated for desk switches between the
// overview desk bar and the desk button desk bar.
TEST_P(DeskBarTest, DeskBarSwitchMetrics) {
  NewDesk();
  NewDesk();

  base::HistogramTester histogram_tester;

  // Create an app window on the first desk.
  WindowHolder window(CreateAppWindow());
  auto* desks_controller = DesksController::Get();
  desks_controller->SendToDeskAtIndex(window.window(), 0);

  OpenDeskBar();

  DeskSwitchAnimationWaiter waiter;
  ClickOrPressOnView(GetDeskBarView()->mini_views()[1]->desk_preview());
  waiter.Wait();
  ASSERT_TRUE(desks_controller->desks()[1]->is_active());
  histogram_tester.ExpectBucketCount(
      kDeskSwitchHistogramName,
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? DesksSwitchSource::kDeskButtonMiniViewButton
          : DesksSwitchSource::kMiniViewButton,
      1);

  OpenDeskBar();

  auto* root_window = Shell::Get()->GetPrimaryRootWindow();
  CloseDeskWithButton(/*index=*/1, /*close_all=*/true, root_window, bar_type_);
  histogram_tester.ExpectBucketCount(
      kDeskSwitchHistogramName,
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? DesksSwitchSource::kDeskButtonDeskRemoved
          : DesksSwitchSource::kDeskRemoved,
      1);

  OpenDeskBar();

  // Combine desks.
  if (features::IsSavedDeskUiRevampEnabled()) {
    CombineDeskWithMenu(/*index=*/0, root_window, bar_type_);
  } else {
    CloseDeskWithButton(/*index=*/0, /*close_all=*/false, root_window,
                        bar_type_);
  }

  histogram_tester.ExpectBucketCount(
      kDeskSwitchHistogramName,
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? DesksSwitchSource::kDeskButtonDeskRemoved
          : DesksSwitchSource::kDeskRemoved,
      2);
}

// Tests that metrics are correctly separated for desk creation and removal
// between the overview desk bar and the desk button desk bar.
TEST_P(DeskBarTest, DeskCreationRemovalMetrics) {
  NewDesk();

  base::HistogramTester histogram_tester;

  WindowHolder window(CreateAppWindow());
  auto* desks_controller = DesksController::Get();
  desks_controller->SendToDeskAtIndex(window.window(), 0);

  OpenDeskBar();
  auto* desk_bar = GetDeskBarView();

  ClickOrPressOnView(desk_bar->new_desk_button());
  histogram_tester.ExpectBucketCount(
      kNewDeskHistogramName,
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? DesksCreationRemovalSource::kDeskButtonDeskBarButton
          : DesksCreationRemovalSource::kButton,
      1);

  auto* root_window = Shell::Get()->GetPrimaryRootWindow();
  CloseDeskWithButton(/*index=*/1, /*close_all=*/true, root_window, bar_type_);
  histogram_tester.ExpectBucketCount(
      kRemoveDeskHistogramName,
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? DesksCreationRemovalSource::kDeskButtonDeskBarButton
          : DesksCreationRemovalSource::kButton,
      1);

  // Long press doesn't register if there have been touch events on the desk bar
  // prior to trying to long press. Close and reopen the desk bar.
  if (features::IsSavedDeskUiRevampEnabled()) {
    CloseDeskBar();
  }
  OpenDeskBar();

  // Combine desks.
  if (features::IsSavedDeskUiRevampEnabled()) {
    CombineDeskWithMenu(/*index=*/0, root_window, bar_type_);
  } else {
    CloseDeskWithButton(/*index=*/0, /*close_all=*/false, root_window,
                        bar_type_);
  }

  histogram_tester.ExpectBucketCount(
      kRemoveDeskHistogramName,
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? DesksCreationRemovalSource::kDeskButtonDeskBarButton
          : DesksCreationRemovalSource::kButton,
      2);
}

// Tests that metrics are correctly separated for open desk context menu
// between the overview desk bar and the desk button desk bar.
TEST_P(DeskBarTest, DeskOpenContextMenuMetrics) {
  NewDesk();

  base::HistogramTester histogram_tester;

  WindowHolder window(CreateAppWindow());
  auto* desks_controller = DesksController::Get();
  desks_controller->SendToDeskAtIndex(window.window(), 0);

  OpenDeskBar();
  auto* desk_bar = GetDeskBarView();
  RightClickOn(desk_bar->mini_views()[0]);

  EnterOverview();
  auto* overview_desks_bar =
      GetOverviewGridForRoot(Shell::GetPrimaryRootWindow())->desks_bar_view();
  RightClickOn(overview_desks_bar->mini_views()[0]);
  histogram_tester.ExpectTotalCount(
      bar_type_ == DeskBarViewBase::Type::kDeskButton
          ? kDeskButtonDeskBarOpenContextMenuHistogramName
          : kOverviewDeskBarOpenContextMenuHistogramName,
      1);
}

// Tests that setting to bottom locked shelf should not crash. Please refer to
// b/293625099.
TEST_P(DeskBarTest, BottomLockedShelf) {
  OpenDeskBar();
  GetPrimaryShelf()->SetAlignment(ShelfAlignment::kBottomLocked);
}

// Tests that we can undo close-all solely via keyboard navigation (tabbing to
// the undo toast and pressing enter).
TEST_P(DeskBarTest, CanUndoDeskClosureThroughKeyboardNavigation) {
  // Scenarios in which we can try to undo desk closure. If the active desk is
  // removed, we close the desk bar and immediately focus the undo button.
  enum class DeskRemovalMethod {
    kInactiveDeskRemovedForwardTab,
    kInactiveDeskRemovedReverseTab,
    kActiveDeskRemoved,
  };

  struct {
    const std::string scope_trace;
    const DeskRemovalMethod desk_removal_method;
  } kTestCases[] = {
      {"Forward tabbing to the undo button after removing an inactive desk",
       DeskRemovalMethod::kInactiveDeskRemovedForwardTab},
      {"Reverse tabbing to the undo button after removing an inactive desk",
       DeskRemovalMethod::kInactiveDeskRemovedReverseTab},
      {"Activating the undo button after removing the active desk",
       DeskRemovalMethod::kActiveDeskRemoved},
  };

  NewDesk();
  NewDesk();
  Shell::Get()->accessibility_controller()->spoken_feedback().SetEnabled(true);

  OpenDeskBar();
  auto* desk_bar = GetDeskBarView();
  const auto& mini_views = desk_bar->mini_views();

  DesksController* desks_controller = DesksController::Get();

  for (const auto& test_case : kTestCases) {
    SCOPED_TRACE(test_case.scope_trace);

    // Tab to the first mini view.
    PressAndReleaseKey(ui::VKEY_TAB);

    // If we are not closing the active desk, close the next desk instead.
    if (test_case.desk_removal_method !=
        DeskRemovalMethod::kActiveDeskRemoved) {
      PressAndReleaseKey(ui::VKEY_TAB);
      PressAndReleaseKey(ui::VKEY_TAB);

      // If desk profiles are enabled then we need to tab past the profile
      // avatar button.
      if (use_desk_profiles_) {
        PressAndReleaseKey(ui::VKEY_TAB);
      }

      PressAndReleaseKey(ui::VKEY_TAB);
      ASSERT_TRUE(mini_views[1]->desk_preview()->HasFocus());

      PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
    } else if (bar_type_ == DeskBarViewBase::Type::kDeskButton) {
      ASSERT_EQ(mini_views[0]->desk_preview(),
                desk_bar->GetWidget()->GetFocusManager()->GetFocusedView());

      // In the desk button desk bar, we run the desk switch animation when
      // removing the active desk.
      DeskSwitchAnimationWaiter waiter;
      PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
      waiter.Wait();
    } else {
      ASSERT_EQ(DeskBarViewBase::Type::kOverview, bar_type_);
      ASSERT_TRUE(mini_views[0]->desk_preview()->HasFocus());
      PressAndReleaseKey(ui::VKEY_W, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
    }

    ASSERT_EQ(2u, desks_controller->desks().size());

    ASSERT_TRUE(TabUntil(
        /*reverse=*/
        test_case.desk_removal_method ==
            DeskRemovalMethod::kInactiveDeskRemovedReverseTab,
        [desks_controller] { return desks_controller->IsUndoToastFocused(); },
        GetEventGenerator()));

    // Pressing undo in the desk button desk bar after closing the active desk
    // will switch us back to the removed desk.
    if (test_case.desk_removal_method ==
            DeskRemovalMethod::kActiveDeskRemoved &&
        bar_type_ == DeskBarViewBase::Type::kDeskButton) {
      DeskSwitchAnimationWaiter waiter;
      PressAndReleaseKey(ui::VKEY_RETURN);
      waiter.Wait();
    } else {
      PressAndReleaseKey(ui::VKEY_RETURN);
    }

    ASSERT_EQ(3u, desks_controller->desks().size());
  }
}

TEST_P(DeskBarTest, DeskActionButtonTooltipForNewDesk) {
  OpenDeskBar();

  // Click the new desk button and verify the desk action buttons' tooltip.
  auto* desk_bar_view = GetDeskBarView();
  ClickOrPressOnView(desk_bar_view->new_desk_button());
  views::test::RunScheduledLayout(desk_bar_view);
  auto* desk_action_view = desk_bar_view->mini_views()[1]->desk_action_view();

  if (features::IsSavedDeskUiRevampEnabled()) {
    EXPECT_TRUE(desk_action_view->context_menu_button());
    EXPECT_THAT(desk_action_view->context_menu_button()->GetTooltipText(),
                u"Open context menu");
  } else {
    EXPECT_TRUE(desk_action_view->combine_desks_button());
    EXPECT_THAT(desk_action_view->combine_desks_button()->GetTooltipText(),
                u"Combine with Desk 1");
  }

  EXPECT_THAT(desk_action_view->close_all_button()->GetTooltipText(),
              u"Close Desk 2 and windows");

  // Rename desk 2 to `D2` and verify the desk action buttons' tooltip.
  PressAndReleaseKey(ui::VKEY_D, ui::EF_SHIFT_DOWN);
  PressAndReleaseKey(ui::VKEY_2);
  PressAndReleaseKey(ui::VKEY_RETURN);
  views::test::RunScheduledLayout(desk_bar_view);

  if (features::IsSavedDeskUiRevampEnabled()) {
    EXPECT_TRUE(desk_action_view->context_menu_button());
    EXPECT_THAT(desk_action_view->context_menu_button()->GetTooltipText(),
                u"Open context menu");
  } else {
    EXPECT_TRUE(desk_action_view->combine_desks_button());
    EXPECT_THAT(desk_action_view->combine_desks_button()->GetTooltipText(),
                u"Combine with Desk 1");
  }

  EXPECT_THAT(desk_action_view->close_all_button()->GetTooltipText(),
              u"Close D2 and windows");

  CloseDeskBar();
}

struct DeskButtonTestParams {
  ShelfAlignment alignment = ShelfAlignment::kBottom;
};

class DeskButtonTest
    : public AshTestBase,
      public ::testing::WithParamInterface<DeskButtonTestParams> {
 public:
  DeskButtonTest() = default;
  DeskButtonTest(const DeskButtonTest&) = delete;
  DeskButtonTest& operator=(const DeskButtonTest&) = delete;
  ~DeskButtonTest() override = default;

  // AshTestBase:
  void SetUp() override {
    AshTestBase::SetUp();
    shelf_test_api_ = std::make_unique<ShelfViewTestAPI>(
        GetPrimaryShelf()->GetShelfViewForTesting());
    GetPrimaryShelf()->SetAlignment(GetParam().alignment);
    SetShowDeskButtonInShelfPref(GetPrimaryUserPrefService(), true);
    // Set the shelf alignment pref to the desired alignment because if a test
    // updates the display size the shelf alignment will be reset from the pref.
    SetShelfAlignmentPref(GetPrimaryUserPrefService(), GetPrimaryDisplay().id(),
                          GetParam().alignment);
  }

  DeskButtonWidget* GetDeskButtonWidget() {
    return GetPrimaryShelf()->shelf_widget()->desk_button_widget();
  }

  DeskButton* GetDeskButton() {
    return GetDeskButtonWidget()->GetDeskButtonContainer()->desk_button();
  }

  DeskSwitchButton* GetPrevDeskButton() {
    return GetDeskButtonWidget()->GetDeskButtonContainer()->prev_desk_button();
  }

  DeskSwitchButton* GetNextDeskButton() {
    return GetDeskButtonWidget()->GetDeskButtonContainer()->next_desk_button();
  }

  // Switches to adjacent desk by clicking one of the desk switch buttons when
  // it's bottom shelf, or by pressing desk switch shortcut when it's side
  // shelf. When `next` is true, we go to the next desk, otherwise we go to the
  // previous desk.
  void SwitchToAdjacentDesk(bool next) {
    if (GetParam().alignment == ShelfAlignment::kBottom) {
      // The buttons will show if we hover the desk button, so we need to do
      // that first.
      auto* event_generator = GetEventGenerator();
      auto* desk_button = GetDeskButton();
      ASSERT_TRUE(desk_button);
      event_generator->MoveMouseTo(
          desk_button->GetBoundsInScreen().CenterPoint());
      views::ImageButton* target_button =
          next ? GetNextDeskButton() : GetPrevDeskButton();
      ASSERT_TRUE(target_button);
      EXPECT_TRUE(target_button->GetVisible());
      EXPECT_TRUE(target_button->GetEnabled());
      event_generator->MoveMouseTo(
          target_button->GetBoundsInScreen().CenterPoint());
      DeskSwitchAnimationWaiter waiter;
      event_generator->ClickLeftButton();
      waiter.Wait();
    } else {
      // Desk button does not expand for side shelf, thus use shortcut to switch
      // desks.
      DeskSwitchAnimationWaiter waiter;
      PressAndReleaseKey(next ? ui::VKEY_OEM_6 : ui::VKEY_OEM_4,
                         ui::EF_COMMAND_DOWN);
      waiter.Wait();
    }
  }

  // Clicks on the desk button.
  void ClickDeskButton() {
    // In the case of left and right shelf alignments, the button must be
    // hovered before it can be clicked if it is not already activated.
    HoverDeskButton();
    auto* event_generator = GetEventGenerator();
    auto* desk_button = GetDeskButton();
    ASSERT_TRUE(desk_button);
    event_generator->MoveMouseTo(
        desk_button->GetBoundsInScreen().CenterPoint());
    event_generator->ClickLeftButton();
  }

  // Hovers on the desk button.
  void HoverDeskButton() {
    auto* event_generator = GetEventGenerator();
    auto* desk_button = GetDeskButton();
    ASSERT_TRUE(desk_button);
    event_generator->MoveMouseTo(
        desk_button->GetBoundsInScreen().CenterPoint());
    if (!desk_button->zero_state()) {
      ASSERT_EQ(GetParam().alignment, ShelfAlignment::kBottom);
    }
  }

  // Unhovers away from the desk button.
  void UnhoverDeskButton() {
    auto* event_generator = GetEventGenerator();
    event_generator->MoveMouseTo(0, 0);
  }

  void OpenDeskBar() {
    DesksController::Get()->desk_bar_controller()->OpenDeskBar(
        Shell::Get()->GetPrimaryRootWindow());
  }

  void CloseDeskBar() {
    DesksController::Get()->desk_bar_controller()->CloseDeskBar(
        Shell::Get()->GetPrimaryRootWindow());
  }

  DeskBarViewBase* GetDeskBarView() {
    return DesksController::Get()->desk_bar_controller()->GetDeskBarView(
        Shell::Get()->GetPrimaryRootWindow());
  }

 private:
  std::unique_ptr<ShelfViewTestAPI> shelf_test_api_;
};

TEST_P(DeskButtonTest, AccessiblePrevAndNextFocusWindow) {
  NewDesk();
  views::test::RunScheduledLayout(GetDeskButtonWidget());

  auto* desk_button = GetDeskButton();
  auto* shelf_widget =
      Shelf::ForWindow(desk_button->GetWidget()->GetNativeWindow())
          ->shelf_widget();

  EXPECT_EQ(desk_button->GetViewAccessibility().GetPreviousWindowFocus(),
            shelf_widget->navigation_widget());
  EXPECT_EQ(desk_button->GetViewAccessibility().GetNextWindowFocus(),
            shelf_widget);
}

// Tests functionalities for `DeskSwitchButton`s.
TEST_P(DeskButtonTest, DeskSwitchButtons) {
  // With only one desk, both switch buttons are hidden.
  views::ImageButton* prev_desk_button = GetPrevDeskButton();
  views::ImageButton* next_desk_button = GetNextDeskButton();
  ASSERT_TRUE(prev_desk_button);
  ASSERT_TRUE(next_desk_button);
  EXPECT_FALSE(prev_desk_button->GetVisible());
  EXPECT_FALSE(next_desk_button->GetVisible());

  // Create a new desk. The previous desk button should be hidden and
  // the next desk button should be enabled.
  NewDesk();
  views::test::RunScheduledLayout(GetDeskButtonWidget());
  if (GetParam().alignment == ShelfAlignment::kBottom) {
    EXPECT_FALSE(prev_desk_button->GetVisible());
    EXPECT_TRUE(next_desk_button->GetVisible());
    EXPECT_TRUE(next_desk_button->GetEnabled());
  } else {
    EXPECT_FALSE(prev_desk_button->GetVisible());
    EXPECT_FALSE(next_desk_button->GetVisible());
  }

  // Switch to desk 2. The previous desk button should be visible and enabled.
  // The next desk button should be visible but disabled.
  SwitchToAdjacentDesk(/*next=*/true);
  if (GetParam().alignment == ShelfAlignment::kBottom) {
    EXPECT_TRUE(prev_desk_button->GetVisible());
    EXPECT_TRUE(prev_desk_button->GetEnabled());
    EXPECT_TRUE(next_desk_button->GetVisible());
    EXPECT_FALSE(next_desk_button->GetEnabled());
  } else {
    EXPECT_FALSE(prev_desk_button->GetVisible());
    EXPECT_FALSE(next_desk_button->GetVisible());
  }

  // Create a new desk. Both buttons should be visible and enabled.
  NewDesk();
  views::test::RunScheduledLayout(GetDeskButtonWidget());
  if (GetParam().alignment == ShelfAlignment::kBottom) {
    EXPECT_TRUE(prev_desk_button->GetVisible());
    EXPECT_TRUE(prev_desk_button->GetEnabled());
    EXPECT_TRUE(next_desk_button->GetVisible());
    EXPECT_TRUE(next_desk_button->GetEnabled());
  } else {
    EXPECT_FALSE(prev_desk_button->GetVisible());
    EXPECT_FALSE(next_desk_button->GetVisible());
  }

  // Switch to desk 3. The previous desk button should be visible and enabled.
  // The next desk button should be visible but disabled.
  SwitchToAdjacentDesk(/*next=*/true);
  if (GetParam().alignment == ShelfAlignment::kBottom) {
    EXPECT_TRUE(prev_desk_button->GetVisible());
    EXPECT_TRUE(prev_desk_button->GetEnabled());
    EXPECT_TRUE(next_desk_button->GetVisible());
    EXPECT_FALSE(next_desk_button->GetEnabled());
  } else {
    EXPECT_FALSE(prev_desk_button->GetVisible());
    EXPECT_FALSE(next_desk_button->GetVisible());
  }

  // Switch back to desk 2. Both buttons should be visible and enabled.
  SwitchToAdjacentDesk(/*next=*/false);
  if (GetParam().alignment == ShelfAlignment::kBottom) {
    EXPECT_TRUE(prev_desk_button->GetVisible());
    EXPECT_TRUE(prev_desk_button->GetEnabled());
    EXPECT_TRUE(next_desk_button->GetVisible());
    EXPECT_TRUE(next_desk_button->GetEnabled());
  } else {
    EXPECT_FALSE(prev_desk_button->GetVisible());
    EXPECT_FALSE(next_desk_button->GetVisible());
  }
}

// Tests that button text updates when desk is changed.
TEST_P(DeskButtonTest, DeskButtonTextReflectsDeskChange) {
  // Desk button will be forced to be zero state for display that is narrower
  // than 1280.
  UpdateDisplay("1280x720");

  NewDesk();

  auto* controller = DesksController::Get();
  auto* desk_1 = controller->GetDeskAtIndex(0);
  auto* desk_2 = controller->GetDeskAtIndex(1);

  // Check that renaming the active desk changes the text in the button.
  ASSERT_TRUE(desk_1->is_active());

  desk_1->SetName(u"Work", /*set_by_user=*/true);
  auto* desk_button = GetDeskButton();
  ASSERT_TRUE(desk_button);
  EXPECT_EQ(GetParam().alignment == ShelfAlignment::kBottom ? u"Work" : u"W",
            desk_button->desk_name_label()->GetText());
  views::test::RunScheduledLayout(desk_button);

  desk_2->SetName(u"Fun", /*set_by_user=*/true);
  EXPECT_EQ(GetParam().alignment == ShelfAlignment::kBottom ? u"Work" : u"W",
            desk_button->desk_name_label()->GetText());

  SwitchToAdjacentDesk(/*next=*/true);
  EXPECT_EQ(GetParam().alignment == ShelfAlignment::kBottom ? u"Fun" : u"F",
            desk_button->desk_name_label()->GetText());

  // Add a third desk and don't name it to check how default desk names are
  // handled.
  NewDesk();
  SwitchToAdjacentDesk(/*next=*/true);
  EXPECT_EQ(GetParam().alignment == ShelfAlignment::kBottom ? u"Desk 3" : u"#3",
            desk_button->desk_name_label()->GetText());
}

// Tests that emojis show up correctly for desk names.
TEST_P(DeskButtonTest, DeskButtonTextWorksWithEmojis) {
  // Desk button will be forced to be zero state for display that is narrower
  // than 1280.
  UpdateDisplay("1280x720");

  NewDesk();

  auto* controller = DesksController::Get();
  controller->GetDeskAtIndex(0)->SetName(u"😃emoji", /*set_by_user=*/true);

  auto* desk_button = GetDeskButton();
  ASSERT_TRUE(desk_button);
  EXPECT_EQ(
      GetParam().alignment == ShelfAlignment::kBottom ? u"😃emoji" : u"😃",
      desk_button->desk_name_label()->GetText());
}

// Tests that the desk button is visible after changing desks from overview.
TEST_P(DeskButtonTest, OverviewDeskSwitch) {
  NewDesk();
  EXPECT_TRUE(GetDeskButtonWidget()->GetLayer()->GetTargetVisibility());

  EnterOverview();
  EXPECT_FALSE(GetDeskButtonWidget()->GetLayer()->GetTargetVisibility());
  auto* desks_controller = DesksController::Get();
  ActivateDesk(desks_controller->GetDeskAtIndex(1));
  EXPECT_TRUE(GetDeskButtonWidget()->GetLayer()->GetTargetVisibility());
}

// Tests that switching the shelf alignment correctly repositions the desk
// button and updates their colors.
TEST_P(DeskButtonTest, UpdateShelfAlignmentDuringTest) {
  // Desk button will be forced to be zero state for display that is narrower
  // than 1280.
  UpdateDisplay("1280x720");

  NewDesk();
  DesksController::Get()->GetDeskAtIndex(0)->SetName(u"school",
                                                     /*set_by_user=*/true);

  const bool bottom_at_start = GetParam().alignment == ShelfAlignment::kBottom;
  auto* desk_button = GetDeskButton();
  ASSERT_TRUE(desk_button);
  // Verify desk names and color changes.
  ASSERT_EQ(bottom_at_start ? u"school" : u"s",
            desk_button->desk_name_label()->GetText());
  auto* color_provider = desk_button->GetColorProvider();
  ASSERT_EQ(color_provider->GetColor(bottom_at_start
                                         ? cros_tokens::kCrosSysSystemOnBase1
                                         : cros_tokens::kCrosSysSystemOnBase),
            desk_button->GetBackground()->get_color());

  // Activate/Deactivate the desk button and verify color changes.
  ClickDeskButton();
  ASSERT_EQ(
      color_provider->GetColor(cros_tokens::kCrosSysSystemPrimaryContainer),
      desk_button->GetBackground()->get_color());
  ClickDeskButton();
  ASSERT_EQ(color_provider->GetColor(bottom_at_start
                                         ? cros_tokens::kCrosSysSystemOnBase1
                                         : cros_tokens::kCrosSysSystemOnBase),
            desk_button->GetBackground()->get_color());

  // Update shelf alignment and verify desk names and color changes.
  GetPrimaryShelf()->SetAlignment(bottom_at_start ? ShelfAlignment::kLeft
                                                  : ShelfAlignment::kBottom);
  ASSERT_EQ(color_provider->GetColor(bottom_at_start
                                         ? cros_tokens::kCrosSysSystemOnBase
                                         : cros_tokens::kCrosSysSystemOnBase1),
            desk_button->GetBackground()->get_color());
  EXPECT_EQ(bottom_at_start ? u"s" : u"school",
            desk_button->desk_name_label()->GetText());
}

// Tests that when the desk button is activated, shelf auto-hide should be
// suspended.
TEST_P(DeskButtonTest, SuspendShelfAutoHideWhenActivated) {
  auto* shelf = GetPrimaryShelf();
  shelf->SetAutoHideBehavior(ShelfAutoHideBehavior::kAlways);
  ASSERT_FALSE(shelf->disable_auto_hide());

  auto* desk_button = GetDeskButton();
  ASSERT_TRUE(desk_button);

  ClickDeskButton();
  UnhoverDeskButton();
  EXPECT_TRUE(desk_button->is_activated());
  EXPECT_NE(desk_button->GetState(), views::Button::ButtonState::STATE_HOVERED);
  EXPECT_TRUE(shelf->disable_auto_hide());

  ClickDeskButton();
  UnhoverDeskButton();
  EXPECT_FALSE(desk_button->is_activated());
  EXPECT_NE(desk_button->GetState(), views::Button::ButtonState::STATE_HOVERED);
  ASSERT_FALSE(shelf->disable_auto_hide());
}

// Tests that the desk button and its child components are correctly positioned
// in each phase of the desk button's desk switch process.
TEST_P(DeskButtonTest, ValidateDeskButtonPosition) {
  // Desk button will be forced to be zero state for display that is narrower
  // than 1280.
  UpdateDisplay("1280x720");

  NewDesk();
  NewDesk();

  auto* desk_button = GetDeskButton();
  auto* prev_desk_button = GetPrevDeskButton();
  auto* next_desk_button = GetNextDeskButton();
  auto* desk_name_label = desk_button->desk_name_label();
  auto* desk_controller = DesksController::Get();
  const int desk_count = desk_controller->GetNumberOfDesks();

  for (int i = desk_count - 1; i >= 0; i--) {
    ActivateDesk(desk_controller->desks()[i].get());

    const bool should_show_prev_desk_button =
        GetParam().alignment == ShelfAlignment::kBottom && i > 0;
    const bool should_show_next_desk_button =
        GetParam().alignment == ShelfAlignment::kBottom;
    const bool should_enable_next_desk_button =
        GetParam().alignment == ShelfAlignment::kBottom && i < desk_count - 1;

    // Check the desk button and both desk switch buttons.
    if (GetParam().alignment == ShelfAlignment::kBottom) {
      EXPECT_TRUE(gfx::Rect(4, 4, 128, 28).Contains(desk_button->bounds()));
      EXPECT_TRUE(
          gfx::Rect(10, 0, 102, 28).Contains(desk_name_label->bounds()));
    } else {
      EXPECT_EQ(desk_button->bounds(), gfx::Rect(0, 0, 36, 36));
      EXPECT_EQ(desk_name_label->bounds(), gfx::Rect(4, 4, 28, 28));
    }
    EXPECT_EQ(prev_desk_button->GetVisible(), should_show_prev_desk_button);
    if (prev_desk_button->GetVisible()) {
      EXPECT_TRUE(prev_desk_button->GetEnabled());
    }
    EXPECT_EQ(next_desk_button->GetVisible(), should_show_next_desk_button);
    if (next_desk_button->GetVisible()) {
      EXPECT_EQ(next_desk_button->GetEnabled(), should_enable_next_desk_button);
    }
  }
}

// Tests that desk button press metrics are correctly recorded.
TEST_P(DeskButtonTest, DeskButtonPressMetrics) {
  NewDesk();
  base::HistogramTester histogram_tester;
  ClickDeskButton();
  histogram_tester.ExpectTotalCount(kDeskButtonPressesHistogramName, 1);
  ClickDeskButton();
  histogram_tester.ExpectTotalCount(kDeskButtonPressesHistogramName, 2);
}

// Tests that the desk button shows up in the correct position and layout
// in RTL. The desk bar is laid out LTR in RTL mode so the desk button should be
// too, ensuring that pressing the left chevron button moves activation to the
// desk to the left in the desk bar.
TEST_P(DeskButtonTest, LayoutInRTL) {
  // Turn on RTL mode.
  const bool default_rtl = base::i18n::IsRTL();
  base::i18n::SetRTLForTesting(true);
  EXPECT_TRUE(base::i18n::IsRTL());

  // The test doesn't start in RTL so we need to tell the widget to swap the
  // desk switch buttons because RTL was disabled in the constructor.
  GetDeskButtonWidget()->HandleLocaleChange();
  GetPrimaryShelf()->shelf_layout_manager()->LayoutShelf();

  // Desk button will be forced to be zero state for display that is narrower
  // than 1280.
  UpdateDisplay("1280x720");

  // Add an app icon to the shelf.
  SkBitmap app_bitmap;
  app_bitmap.allocN32Pixels(1, 1);
  app_bitmap.eraseColor(SK_ColorRED);
  ShelfTestUtil::AddAppShortcutWithIcon(
      "0", TYPE_PINNED_APP, gfx::ImageSkia::CreateFrom1xBitmap(app_bitmap));

  // Navigate to the 2nd of 3 desks so both buttons should be visible.
  NewDesk();
  NewDesk();
  views::test::RunScheduledLayout(GetDeskButtonWidget());
  SwitchToAdjacentDesk(/*next=*/true);

  // The desk button should show up to the right of the shelf apps in horizontal
  // and on top in vertical.
  const gfx::Rect desk_button_bounds = GetDeskButton()->GetBoundsInScreen();
  const gfx::Rect app_icon_bounds = GetPrimaryShelf()
                                        ->hotseat_widget()
                                        ->GetShelfView()
                                        ->first_visible_button_for_testing()
                                        ->GetBoundsInScreen();

  switch (GetParam().alignment) {
    case ShelfAlignment::kBottom:
    case ShelfAlignment::kBottomLocked:
      EXPECT_TRUE(gfx::Rect(684, 682, 128, 28).Contains(desk_button_bounds));
      EXPECT_LT(app_icon_bounds.x(), desk_button_bounds.x());
      break;
    case ShelfAlignment::kLeft:
      EXPECT_EQ(gfx::Rect(6, 286, 36, 36), desk_button_bounds);
      EXPECT_LT(desk_button_bounds.y(), app_icon_bounds.y());
      break;
    case ShelfAlignment::kRight:
      EXPECT_EQ(gfx::Rect(1238, 286, 36, 36), desk_button_bounds);
      EXPECT_LT(desk_button_bounds.y(), app_icon_bounds.y());
      break;
  }

  // Hover over the button to show the desk switch buttons.
  auto* prev_desk_button = GetPrevDeskButton();
  auto* next_desk_button = GetNextDeskButton();
  if (GetParam().alignment == ShelfAlignment::kBottom) {
    ASSERT_TRUE(prev_desk_button->GetVisible());
    ASSERT_TRUE(prev_desk_button->GetEnabled());
    ASSERT_TRUE(next_desk_button->GetVisible());
    ASSERT_TRUE(next_desk_button->GetEnabled());

    // The previous desk button should be to the right of the desk button, and
    // the next desk button should be to the right of the previous desk button.
    EXPECT_GT(prev_desk_button->GetBoundsInScreen().x(),
              desk_button_bounds.right());
    EXPECT_GT(next_desk_button->GetBoundsInScreen().x(),
              prev_desk_button->GetBoundsInScreen().right());
  } else {
    ASSERT_FALSE(prev_desk_button->GetVisible());
    ASSERT_FALSE(next_desk_button->GetVisible());
  }

  // Clicking the previous desk button should take us to desk 1, and clicking
  // the next desk button twice should take us to desk 3.
  auto* desks_controller = DesksController::Get();
  SwitchToAdjacentDesk(/*next=*/false);
  EXPECT_EQ(0, desks_controller->GetActiveDeskIndex());
  SwitchToAdjacentDesk(/*next=*/true);
  SwitchToAdjacentDesk(/*next=*/true);
  EXPECT_EQ(2, desks_controller->GetActiveDeskIndex());

  // Recover to default RTL mode.
  base::i18n::SetRTLForTesting(default_rtl);
}

TEST_P(DeskButtonTest, BarBoundsWithDeviceSacleFactorChange) {
  // Test both upscaling and downscaling.
  for (auto key : {ui::VKEY_OEM_MINUS, ui::VKEY_OEM_PLUS}) {
    OpenDeskBar();
    PressAndReleaseKey(key, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN);
    ASSERT_TRUE(GetDeskBarView());
    gfx::Rect bounds = GetDeskBarView()->GetWidget()->GetWindowBoundsInScreen();
    CloseDeskBar();
    OpenDeskBar();
    gfx::Rect expected_bounds =
        GetDeskBarView()->GetWidget()->GetWindowBoundsInScreen();
    CloseDeskBar();
    EXPECT_EQ(bounds, expected_bounds);
  }
}

TEST_P(DeskButtonTest, BarBoundsWithScreenRotationChange) {
  const int control_and_shift = ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN;

  // Accept the dialog once so later on it does not pop up.
  auto* accessibility_controller = Shell::Get()->accessibility_controller();
  PressAndReleaseKey(ui::VKEY_BROWSER_REFRESH, control_and_shift);
  if (auto* confirm_dialog =
          accessibility_controller->GetConfirmationDialogForTest()) {
    confirm_dialog->AcceptDialog();
    base::RunLoop().RunUntilIdle();
  }

  // Test with all four screen rotations.
  for (int i = 0; i < 4; i++) {
    OpenDeskBar();
    PressAndReleaseKey(ui::VKEY_BROWSER_REFRESH, control_and_shift);
    ASSERT_TRUE(GetDeskBarView());
    gfx::Rect bounds = GetDeskBarView()->GetWidget()->GetWindowBoundsInScreen();
    CloseDeskBar();
    OpenDeskBar();
    gfx::Rect expected_bounds =
        GetDeskBarView()->GetWidget()->GetWindowBoundsInScreen();
    CloseDeskBar();
    EXPECT_EQ(bounds, expected_bounds);
  }
}

TEST_P(DeskButtonTest, BarBoundsWithWorkAreaChangeChromevox) {
  const int control_and_alt = ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN;

  // Test with chromevox on and off.
  OpenDeskBar();
  PressAndReleaseKey(ui::VKEY_Z, control_and_alt);
  ASSERT_TRUE(GetDeskBarView());
  gfx::Rect bounds = GetDeskBarView()->GetWidget()->GetWindowBoundsInScreen();
  CloseDeskBar();
  OpenDeskBar();
  gfx::Rect expected_bounds =
      GetDeskBarView()->GetWidget()->GetWindowBoundsInScreen();
  CloseDeskBar();
  PressAndReleaseKey(ui::VKEY_Z, control_and_alt);
  EXPECT_EQ(bounds, expected_bounds);
}

TEST_P(DeskButtonTest, BarBoundsWithWorkAreaChangeDockedMagnifier) {
  // Set the display large enough for the docked magnifier and the desk bar.
  UpdateDisplay("1024x768");

  const int control_and_search = ui::EF_CONTROL_DOWN | ui::EF_COMMAND_DOWN;

  // Accept the dialog once so later on it does not pop up.
  auto* accessibility_controller = Shell::Get()->accessibility_controller();
  PressAndReleaseKey(ui::VKEY_D, control_and_search);
  if (auto* confirm_dialog =
          accessibility_controller->GetConfirmationDialogForTest()) {
    confirm_dialog->AcceptDialog();
    base::RunLoop().RunUntilIdle();
  }
  PressAndReleaseKey(ui::VKEY_D, control_and_search);

  // Test with docked magnifier on and off.
  OpenDeskBar();
  PressAndReleaseKey(ui::VKEY_D, control_and_search);
  ASSERT_TRUE(GetDeskBarView());
  gfx::Rect bounds = GetDeskBarView()->GetWidget()->GetWindowBoundsInScreen();
  CloseDeskBar();
  OpenDeskBar();
  gfx::Rect expected_bounds =
      GetDeskBarView()->GetWidget()->GetWindowBoundsInScreen();
  CloseDeskBar();
  PressAndReleaseKey(ui::VKEY_D, control_and_search);
  EXPECT_EQ(bounds, expected_bounds);
}

TEST_P(DeskButtonTest, BarBoundsWithRTL) {
  UpdateDisplay("800x600");

  // Turn on RTL mode.
  const bool default_rtl = base::i18n::IsRTL();
  base::i18n::SetRTLForTesting(true);
  ASSERT_TRUE(base::i18n::IsRTL());

  OpenDeskBar();
  EXPECT_EQ(GetDeskBarView()->bounds(), gfx::Rect(0, 0, 154, 98));

  CloseDeskBar();

  // Recover to default RTL mode.
  base::i18n::SetRTLForTesting(default_rtl);
}

// Tests that desk button tab order is correct in the shelf.
TEST_P(DeskButtonTest, TabOrder) {
  NewDesk();
  NewDesk();
  auto* desks_controller = DesksController::Get();
  ASSERT_THAT(desks_controller->desks().size(), 3);
  ASSERT_THAT(desks_controller->GetActiveDeskIndex(), 0);

  // Tabbing once should focus the shelf navigation widget.
  PressAndReleaseKey(ui::VKEY_TAB);

  if (GetParam().alignment == ShelfAlignment::kBottom) {
    // One more tab should focus the desk button, then the next desk button.
    // There should be no previous desk button since we're on the first desk.
    PressAndReleaseKey(ui::VKEY_TAB);
    ASSERT_TRUE(GetDeskButton()->HasFocus());
    PressAndReleaseKey(ui::VKEY_TAB);
    ASSERT_TRUE(GetNextDeskButton()->HasFocus());

    // Tabbing in the other direction should work too.
    PressAndReleaseKey(ui::VKEY_TAB, ui::EF_SHIFT_DOWN);
    ASSERT_TRUE(GetDeskButton()->HasFocus());
    PressAndReleaseKey(ui::VKEY_TAB);
    ASSERT_TRUE(GetNextDeskButton()->HasFocus());

    // Pressing the next desk button should take us to the next desk, and
    // immediately pressing enter again should take us to the last desk.
    DeskSwitchAnimationWaiter waiter;
    PressAndReleaseKey(ui::VKEY_RETURN);
    waiter.Wait();
    ASSERT_THAT(desks_controller->GetActiveDeskIndex(), 1);
    ASSERT_TRUE(GetPrevDeskButton()->GetEnabled());
    ASSERT_TRUE(GetNextDeskButton()->GetEnabled());
    DeskSwitchAnimationWaiter waiter2;
    PressAndReleaseKey(ui::VKEY_RETURN);
    waiter2.Wait();
    ASSERT_THAT(desks_controller->GetActiveDeskIndex(), 2);

    // Focus should have been passed to the hotseat widget now that the next
    // desk button isn't visible.
    ASSERT_FALSE(GetNextDeskButton()->GetEnabled());
  } else {
    // Desk button does not expand for side shelf.
    PressAndReleaseKey(ui::VKEY_TAB);
    ASSERT_TRUE(GetDeskButton()->HasFocus());
    ASSERT_TRUE(GetDeskButton()->zero_state());
    PressAndReleaseKey(ui::VKEY_TAB);
    ASSERT_FALSE(GetDeskButton()->HasFocus());
    ASSERT_TRUE(GetDeskButton()->zero_state());
  }
}

// Tests that desk bar is on top of floated window.
TEST_P(DeskButtonTest, BarAboveFloatWindow) {
  // Create a floated window.
  std::unique_ptr<aura::Window> floated_window = CreateAppWindow();
  PressAndReleaseKey(ui::VKEY_F, ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN);
  ASSERT_TRUE(WindowState::Get(floated_window.get())->IsFloated());

  // Open desk bar, set the floated window to be the same bounds, then check if
  // the bar is above the floated window.
  OpenDeskBar();
  auto* desk_bar_view = GetDeskBarView();
  floated_window->SetBounds(desk_bar_view->GetBoundsInScreen());
  EXPECT_EQ(
      GetTopmostWindowAtPoint(desk_bar_view->GetBoundsInScreen().CenterPoint(),
                              /*ignore=*/{}),
      desk_bar_view->GetWidget()->GetNativeWindow());
}

// Tests that desk bar sends back focus to desk button when hitting esc.
TEST_P(DeskButtonTest, SendFocusBackToDeskButton) {
  // Focus the desk button.
  PressAndReleaseKey(ui::VKEY_TAB);
  PressAndReleaseKey(ui::VKEY_TAB);
  ASSERT_TRUE(GetDeskButton()->HasFocus());

  // Open desk bar.
  PressAndReleaseKey(ui::VKEY_RETURN);
  ASSERT_TRUE(GetDeskBarView());

  // Hit esc and verify focus is sent back to the desk button.
  PressAndReleaseKey(ui::VKEY_ESCAPE);
  ASSERT_TRUE(GetDeskButton()->HasFocus());
}

// Tests that desk button shows context menu when right clicked and long tapped,
// and does not show the menu when the desk bar is active.
TEST_P(DeskButtonTest, DeskButtonContextMenu) {
  for (bool use_touch_gestures : {false, true}) {
    auto* event_generator = GetEventGenerator();
    auto* desk_button = GetDeskButton();

    // The context menu should show when the desk bar is *not* active.
    if (use_touch_gestures) {
      LongGestureTap(desk_button->GetBoundsInScreen().CenterPoint(),
                     event_generator);
    } else {
      RightClickOn(desk_button);
    }
    EXPECT_NE(desk_button->GetState(),
              views::Button::ButtonState::STATE_HOVERED);
    EXPECT_TRUE(GetPrimaryShelf()->GetShelfViewForTesting()->IsShowingMenu());
    PressAndReleaseKey(ui::VKEY_ESCAPE);
    EXPECT_FALSE(GetPrimaryShelf()->GetShelfViewForTesting()->IsShowingMenu());

    // The context menu should *not* show when the desk bar is active.
    ClickDeskButton();
    if (use_touch_gestures) {
      LongGestureTap(desk_button->GetBoundsInScreen().CenterPoint(),
                     event_generator);
    } else {
      RightClickOn(desk_button);
    }
    EXPECT_FALSE(GetPrimaryShelf()->GetShelfViewForTesting()->IsShowingMenu());
    CloseDeskBar();
  }
}

// Tests that desk switch buttons show context menu when right clicked and long
// tapped, and do not show the menu when the desk bar is active.
TEST_P(DeskButtonTest, DeskSwitchButtonContextMenu) {
  if (GetParam().alignment != ShelfAlignment::kBottom) {
    SUCCEED();
    return;
  }

  NewDesk();
  NewDesk();

  struct DeskSwitchButtonTestCase {
    bool visible;
    bool enabled;
    bool show_context_menu;
  };
  const DeskSwitchButtonTestCase prev_test_cases[] = {
      {.visible = false, .enabled = false, .show_context_menu = false},
      {.visible = true, .enabled = true, .show_context_menu = true},
      {.visible = true, .enabled = true, .show_context_menu = true},
  };
  const DeskSwitchButtonTestCase next_test_cases[] = {
      {.visible = true, .enabled = true, .show_context_menu = true},
      {.visible = true, .enabled = true, .show_context_menu = true},
      {.visible = true, .enabled = false, .show_context_menu = false},
  };

  auto* event_generator = GetEventGenerator();
  auto* shelf_view = GetPrimaryShelf()->GetShelfViewForTesting();
  auto verify_button = [&](DeskSwitchButton* button, bool button_visible,
                           bool button_enabled, bool button_show_context_menu,
                           bool use_touch_gestures, bool desk_bar_active) {
    SCOPED_TRACE(
        "Testing " +
        (button->type() == DeskSwitchButton::Type::kPrev
             ? std::string("previous desk button")
             : std::string("next desk button")) +
        " in " +
        base::UTF16ToUTF8(DesksController::Get()->active_desk()->name()) +
        " using " +
        (use_touch_gestures ? std::string("gestures") : std::string("mouse")) +
        " when desk bar " +
        (desk_bar_active ? std::string("active") : std::string("not active")));

    ASSERT_EQ(button->GetVisible(), button_visible);
    if (!button->GetVisible()) {
      return;
    }
    EXPECT_EQ(button->GetEnabled(), button_enabled);
    if (use_touch_gestures) {
      LongGestureTap(button->GetBoundsInScreen().CenterPoint(),
                     event_generator);
    } else {
      RightClickOn(button);
    }
    views::test::RunScheduledLayout(button);
    EXPECT_EQ(shelf_view->IsShowingMenu(), button_show_context_menu);
    if (!desk_bar_active) {
      EXPECT_NE(button->GetState(), views::Button::ButtonState::STATE_HOVERED);
    }
    if (shelf_view->IsShowingMenu()) {
      PressAndReleaseKey(ui::VKEY_ESCAPE);
      EXPECT_FALSE(shelf_view->IsShowingMenu());
    }
  };

  for (bool use_touch_gestures : {false, true}) {
    auto* desk_controller = DesksController::Get();
    for (int index = 0; index < desk_controller->GetNumberOfDesks(); index++) {
      // Switch to the desired desk if needed.
      if (desk_controller->GetActiveDeskIndex() != index) {
        ActivateDesk(desk_controller->GetDeskAtIndex(index));
      }

      // The context menu could show when the desk bar is *not* active.
      verify_button(GetPrevDeskButton(), prev_test_cases[index].visible,
                    prev_test_cases[index].enabled,
                    prev_test_cases[index].show_context_menu,
                    use_touch_gestures, false);
      verify_button(GetNextDeskButton(), next_test_cases[index].visible,
                    next_test_cases[index].enabled,
                    next_test_cases[index].show_context_menu,
                    use_touch_gestures, false);

      // The context menu could *not* show when the desk bar is active.
      ClickDeskButton();
      verify_button(GetPrevDeskButton(), prev_test_cases[index].visible,
                    prev_test_cases[index].enabled, false, use_touch_gestures,
                    true);
      verify_button(GetNextDeskButton(), next_test_cases[index].visible,
                    next_test_cases[index].enabled, false, use_touch_gestures,
                    true);
      CloseDeskBar();
    }
  }
}

// Tests that metrics are being recorded when a desk animation screenshot is
// taken.
TEST_P(DesksAcceleratorsTest, DeskSwitchScreenshotMetricsRecording) {
  NewDesk();
  base::HistogramTester histogram_tester;
  histogram_tester.ExpectTotalCount(kDeskSwitchScreenshotResultHistogramName,
                                    0);

  // Switching desks should result in 2 successful screenshots: one for the
  // starting desk and one for the ending desk.
  DeskSwitchAnimationWaiter waiter;
  SendAccelerator(ui::VKEY_OEM_6, ui::EF_COMMAND_DOWN);
  waiter.Wait();
  histogram_tester.ExpectTotalCount(kDeskSwitchScreenshotResultHistogramName,
                                    2);
  histogram_tester.ExpectBucketCount(kDeskSwitchScreenshotResultHistogramName,
                                     true, 2);
}

class DeskProfilesTest : public AshTestBase {
 public:
  DeskProfilesTest() = default;
  ~DeskProfilesTest() override = default;

 private:
  base::test::ScopedFeatureList scoped_feature_list_{
      chromeos::features::kDeskProfiles};
};

TEST_F(DeskProfilesTest, RemoveProfile) {
  // This test creates three dummy lacros profiles and sets up three desks with
  // each associated with a different user. The last user is then removed and we
  // verify that the desk has reverted to the default lacros profile.
  AddDummyLacrosDeskProfiles(3);

  const uint64_t lacros_profile_id1 = GetDummyLacrosDeskProfileId(0);
  const uint64_t lacros_profile_id2 = GetDummyLacrosDeskProfileId(1);
  const uint64_t lacros_profile_id3 = GetDummyLacrosDeskProfileId(2);

  GetDeskProfilesTestDelegate().SetPrimaryProfileByProfileId(
      lacros_profile_id1);

  NewDesk();
  NewDesk();

  // Assign different lacros profiles to all three desks.
  auto* controller = DesksController::Get();
  auto* desk1 = controller->GetDeskAtIndex(0);
  auto* desk2 = controller->GetDeskAtIndex(1);
  auto* desk3 = controller->GetDeskAtIndex(2);
  desk1->SetLacrosProfileId(lacros_profile_id1);
  desk2->SetLacrosProfileId(lacros_profile_id2);
  desk3->SetLacrosProfileId(lacros_profile_id3);

  EXPECT_EQ(desk1->lacros_profile_id(), lacros_profile_id1);
  EXPECT_EQ(desk2->lacros_profile_id(), lacros_profile_id2);
  EXPECT_EQ(desk3->lacros_profile_id(), lacros_profile_id3);

  // Remove the last profile. We now expect the desk to be updated to the
  // default profile (lacros_profile_id1).
  GetDeskProfilesTestDelegate().RemoveTestProfile(lacros_profile_id3);

  EXPECT_EQ(desk1->lacros_profile_id(), lacros_profile_id1);
  EXPECT_EQ(desk2->lacros_profile_id(), lacros_profile_id2);
  EXPECT_EQ(desk3->lacros_profile_id(), lacros_profile_id1);
}

TEST_F(DeskProfilesTest, SelectProfile) {
  AddDummyLacrosDeskProfiles(2);

  base::HistogramTester histogram_tester;
  auto* desk_bar_controller = DesksController::Get()->desk_bar_controller();

  NewDesk();
  auto* desk1 = DesksController::Get()->GetDeskAtIndex(0);
  auto* desk2 = DesksController::Get()->GetDeskAtIndex(1);

  // By default, neither desk has a lacros profile ID assigned.
  EXPECT_EQ(0u, desk1->lacros_profile_id());
  EXPECT_EQ(0u, desk2->lacros_profile_id());

  desk_bar_controller->OpenDeskBar(Shell::Get()->GetPrimaryRootWindow());
  auto* desk_bar_view =
      desk_bar_controller->GetDeskBarView(Shell::Get()->GetPrimaryRootWindow());
  views::test::RunScheduledLayout(desk_bar_view);
  ASSERT_EQ(2u, desk_bar_view->mini_views().size());

  // Assign a profile to the second desk using the desk profile button.
  {
    DeskProfilesButton* desk_profile_button =
        DesksTestApi::GetDeskProfileButton(desk_bar_view->mini_views()[1]);
    ASSERT_TRUE(desk_profile_button);

    LeftClickOn(desk_profile_button);
    DeskActionContextMenu* menu = desk_profile_button->menu();
    ASSERT_TRUE(menu);

    // Get the menu item for the seecond profile and click it.
    views::MenuItemView* menu_item = DesksTestApi::GetDeskActionContextMenuItem(
        menu, DeskActionContextMenu::kDynamicProfileStart + 1);
    ASSERT_TRUE(menu_item);
    LeftClickOn(menu_item);

    // Verify that the profile has indeed been set on desk 2.
    EXPECT_EQ(desk2->lacros_profile_id(), GetDummyLacrosDeskProfileId(1));
  }

  // Assign a profile to the second desk using the desk action context menu.
  {
    DeskActionContextMenu* menu = DesksTestApi::GetContextMenuForDesk(
        DeskBarViewBase::Type::kDeskButton, 1);
    ASSERT_TRUE(menu);

    // Get the menu item for the first profile and click it.
    views::MenuItemView* menu_item = DesksTestApi::GetDeskActionContextMenuItem(
        menu, DeskActionContextMenu::kDynamicProfileStart);
    ASSERT_TRUE(menu_item);
    LeftClickOn(menu_item);

    // Verify that the profile has been updated on desk 2.
    EXPECT_EQ(desk2->lacros_profile_id(), GetDummyLacrosDeskProfileId(0));
  }
}

// TODO(afakhry): Add more tests:
// - Always on top windows are not tracked by any desk.
// - Reusing containers when desks are removed and created.

// Instantiate the parametrized tests.

// This is used for tests that test all combinations of 8/16 desks, and
// clicks/touch. Additionally, some combinations are tested with per-desk-shelf
// enabled.
constexpr DesksTestParams kTestCombinations[] = {
    {.use_touch_gestures = false, .use_16_desks = false},
    {.use_touch_gestures = false, .use_16_desks = true},
    {.use_touch_gestures = true, .use_16_desks = false},
    {.use_touch_gestures = true, .use_16_desks = true},
    // Per-desk shelf enabled combinations.
    {.per_desk_shelf = true},
};

// This is used for tests that only want to test 8/16 desks.
constexpr DesksTestParams kDeskCountOnly[] = {
    {.use_16_desks = false},
    {.use_16_desks = true},
};

std::string GetDeskCountSuffix(bool use_16_desks) {
  return use_16_desks ? "16Desks" : "8Desks";
}

std::string GetTestSuffix(const DesksTestParams& params) {
  std::string use_touch = params.use_touch_gestures ? "Touch" : "Mouse";
  std::string use_16 = GetDeskCountSuffix(params.use_16_desks);
  std::string use_per_desk_shelf =
      params.per_desk_shelf ? "PerDeskShelf" : "NoPerDeskShelf";
  return base::StringPrintf("%s_%s_%s", use_touch.c_str(), use_16.c_str(),
                            use_per_desk_shelf.c_str());
}

std::string GetDeskCountOnlyTestSuffix(
    const testing::TestParamInfo<DesksTestParams>& info) {
  return GetDeskCountSuffix(info.param.use_16_desks);
}

constexpr DeskButtonTestParams kDeskButtonTestParamCombinations[] = {
    {.alignment = ShelfAlignment::kBottom},
    {.alignment = ShelfAlignment::kLeft},
    {.alignment = ShelfAlignment::kRight}};

INSTANTIATE_TEST_SUITE_P(
    All,
    DesksTest,
    ValuesIn(kTestCombinations),
    [](const testing::TestParamInfo<DesksTestParams>& info) {
      return GetTestSuffix(info.param);
    });

INSTANTIATE_TEST_SUITE_P(All,
                         DesksEditableNamesTest,
                         ValuesIn(kDeskCountOnly),
                         GetDeskCountOnlyTestSuffix);
INSTANTIATE_TEST_SUITE_P(All,
                         TabletModeDesksTest,
                         ValuesIn(kDeskCountOnly),
                         GetDeskCountOnlyTestSuffix);
INSTANTIATE_TEST_SUITE_P(All,
                         DesksAcceleratorsTest,
                         ValuesIn(kDeskCountOnly),
                         GetDeskCountOnlyTestSuffix);
INSTANTIATE_TEST_SUITE_P(All,
                         DesksMockTimeTest,
                         ValuesIn(kDeskCountOnly),
                         GetDeskCountOnlyTestSuffix);
INSTANTIATE_TEST_SUITE_P(All,
                         DesksCloseAllTest,
                         ValuesIn(kDeskCountOnly),
                         GetDeskCountOnlyTestSuffix);
INSTANTIATE_TEST_SUITE_P(All,
                         PerDeskShelfTest,
                         testing::Bool(),
                         [](const testing::TestParamInfo<bool>& info) {
                           return info.param ? "PerDeskShelfOn"
                                             : "PerDeskShelfOff";
                         });
INSTANTIATE_TEST_SUITE_P(
    All,
    DeskBarTest,
    testing::Combine(testing::Bool(),  // use touch gestures
                     testing::Bool(),  // use 16 desks
                     testing::Bool(),  // use desk profiles
                     testing::Values(DeskBarViewBase::Type::kDeskButton,
                                     DeskBarViewBase::Type::kOverview)),
    [](const testing::TestParamInfo<DeskBarTest::ParamType>& info) {
      DesksTestParams params;
      bool use_desk_profiles;
      DeskBarViewBase::Type bar_type;
      std::tie(params.use_touch_gestures, params.use_16_desks,
               use_desk_profiles, bar_type) = info.param;
      std::string result = GetTestSuffix(params);
      std::string bar_type_str;
      switch (bar_type) {
        case DeskBarViewBase::Type::kDeskButton:
          bar_type_str = "DeskButtonBar";
          break;
        case DeskBarViewBase::Type::kOverview:
          bar_type_str = "OverviewBar";
          break;
      }

      std::string desk_profiles_str =
          use_desk_profiles ? "DeskProfiles" : "NoDeskProfiles";
      return base::StringPrintf("%s_%s_%s", result.c_str(),
                                bar_type_str.c_str(),
                                desk_profiles_str.c_str());
    });

INSTANTIATE_TEST_SUITE_P(
    All,
    DeskButtonTest,
    ValuesIn(kDeskButtonTestParamCombinations),
    [](const testing::TestParamInfo<DeskButtonTestParams>& info) {
      std::stringstream sstream;
      sstream << "Shelf" << info.param.alignment;
      return sstream.str();
    });

}  // namespace

}  // namespace ash