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

pdf / pdf_ink_module_unittest.cc [blame]

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

#include "pdf/pdf_ink_module.h"

#include <array>
#include <set>
#include <string>
#include <string_view>
#include <vector>

#include "base/check_op.h"
#include "base/containers/contains.h"
#include "base/containers/span.h"
#include "base/containers/to_vector.h"
#include "base/files/file_path.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/values_test_util.h"
#include "base/values.h"
#include "pdf/pdf_features.h"
#include "pdf/pdf_ink_brush.h"
#include "pdf/pdf_ink_conversions.h"
#include "pdf/pdf_ink_metrics_handler.h"
#include "pdf/pdf_ink_module_client.h"
#include "pdf/pdf_ink_transform.h"
#include "pdf/pdfium/pdfium_ink_reader.h"
#include "pdf/test/mouse_event_builder.h"
#include "pdf/test/pdf_ink_test_helpers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/input/web_mouse_event.h"
#include "third_party/blink/public/common/input/web_touch_event.h"
#include "third_party/ink/src/ink/brush/brush.h"
#include "third_party/ink/src/ink/brush/type_matchers.h"
#include "third_party/ink/src/ink/geometry/affine_transform.h"
#include "third_party/ink/src/ink/strokes/input/type_matchers.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/vector2d_f.h"

using testing::_;
using testing::ElementsAre;
using testing::ElementsAreArray;
using testing::Field;
using testing::InSequence;
using testing::NiceMock;
using testing::Pair;
using testing::Pointwise;
using testing::Return;
using testing::SizeIs;

namespace chrome_pdf {

namespace {

// Some commonly used points with InitializeSimpleSinglePageBasicLayout().
constexpr gfx::PointF kLeftVerticalStrokePoint1(10.0f, 15.0f);
constexpr gfx::PointF kLeftVerticalStrokePoint2(10.0f, 35.0f);
constexpr gfx::PointF kMiddleVerticalStrokePoint1(25.0f, 15.0f);
constexpr gfx::PointF kMiddleVerticalStrokePoint2(25.0f, 35.0f);
constexpr gfx::PointF kRightVerticalStrokePoint1(40.0f, 15.0f);
constexpr gfx::PointF kRightVerticalStrokePoint2(40.0f, 35.0f);

// Constants to support a layout of 2 pages, arranged vertically with a small
// gap between them.
constexpr gfx::RectF kVerticalLayout2Pages[] = {
    gfx::RectF(/*x=*/5.0f,
               /*y=*/5.0f,
               /*width=*/50.0f,
               /*height=*/60.0f),
    gfx::RectF(/*x=*/5.0f,
               /*y=*/70.0f,
               /*width=*/50.0f,
               /*height=*/60.0f),
};

// Some commonly used points in relation to `kVerticalLayout2Pages`.
constexpr gfx::PointF kTwoPageVerticalLayoutPointOutsidePages(10.0f, 0.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutPoint1InsidePage0(10.0f, 10.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutPoint2InsidePage0(15.0f, 15.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutPoint3InsidePage0(20.0f, 15.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutPoint4InsidePage0(10.0f, 20.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutPoint1InsidePage1(10.0f, 75.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutPoint2InsidePage1(15.0f, 80.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutPoint3InsidePage1(20.0f, 80.0f);

// Canonical points after stroking horizontal & vertical lines with some
// commonly used points.
// Horizontal line uses: kTwoPageVerticalLayoutPoint2InsidePage0 to
//                       kTwoPageVerticalLayoutPoint3InsidePage0
//                   or: kTwoPageVerticalLayoutPoint2InsidePage1 to
//                       kTwoPageVerticalLayoutPoint3InsidePage1
// Vertical line uses:   kTwoPageVerticalLayoutPoint1InsidePage0 to
//                       kTwoPageVerticalLayoutPoint4InsidePage0
constexpr gfx::PointF kTwoPageVerticalLayoutHorzLinePoint0Canonical(10.0f,
                                                                    10.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutHorzLinePoint1Canonical(15.0f,
                                                                    10.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutVertLinePoint0Canonical(5.0f, 5.0f);
constexpr gfx::PointF kTwoPageVerticalLayoutVertLinePoint1Canonical(5.0f,
                                                                    15.0f);

// The inputs for a stroke that starts in first page, leaves the bounds of that
// page, but then moves back into the page results in one stroke with two
// segments.
constexpr gfx::PointF kTwoPageVerticalLayoutPageExitAndReentryPoints[] = {
    gfx::PointF(10.0f, 5.0f), gfx::PointF(10.0f, 0.0f),
    gfx::PointF(15.0f, 0.0f), gfx::PointF(15.0f, 5.0f),
    gfx::PointF(15.0f, 10.0f)};
// The two segments created by the inputs above.
constexpr gfx::PointF kTwoPageVerticalLayoutPageExitAndReentrySegment1[] = {
    gfx::PointF(5.0f, 5.0f), gfx::PointF(5.0f, 0.0f)};
constexpr gfx::PointF kTwoPageVerticalLayoutPageExitAndReentrySegment2[] = {
    gfx::PointF(10.0f, 0.0f), gfx::PointF(10.0f, 5.0f),
    gfx::PointF(15.0f, 10.0f)};

// The stroke inputs for vertical and horizontal lines in the pages.  The
// `.time` fields intentionally get a common value, to match the behavior of
// `MouseEventBuilder`.
constexpr auto kTwoPageVerticalLayoutHorzLinePage0Inputs =
    std::to_array<PdfInkInputData>({
        {kTwoPageVerticalLayoutHorzLinePoint0Canonical, base::Seconds(0)},
        {kTwoPageVerticalLayoutHorzLinePoint1Canonical, base::Seconds(0)},
    });
constexpr auto kTwoPageVerticalLayoutVertLinePage0Inputs =
    std::to_array<PdfInkInputData>({
        {kTwoPageVerticalLayoutVertLinePoint0Canonical, base::Seconds(0)},
        {kTwoPageVerticalLayoutVertLinePoint1Canonical, base::Seconds(0)},
    });
constexpr auto kTwoPageVerticalLayoutHorzLinePage1Inputs =
    std::to_array<PdfInkInputData>({
        {kTwoPageVerticalLayoutHorzLinePoint0Canonical, base::Seconds(0)},
        {kTwoPageVerticalLayoutHorzLinePoint1Canonical, base::Seconds(0)},
    });

// Matcher for ink::Stroke objects against their expected brush and inputs.
MATCHER_P(InkStrokeEq, expected_brush, "") {
  const auto& [actual_stroke, expected_inputs] = arg;
  const auto brush_matcher = ink::BrushEq(expected_brush);
  const auto input_matcher = ink::StrokeInputBatchEq(expected_inputs);
  return testing::Matches(brush_matcher)(actual_stroke->GetBrush()) &&
         testing::Matches(input_matcher)(actual_stroke->GetInputs());
}

// Matcher for ink::Stroke objects against an expected brush color.
MATCHER_P(InkStrokeBrushColorEq, expected_color, "") {
  return chrome_pdf::GetSkColorFromInkBrush(arg.GetBrush()) == expected_color;
}

// Matcher for ink::Stroke objects against an expected brush size.
MATCHER_P(InkStrokeBrushSizeEq, expected_size, "") {
  return arg.GetBrush().GetSize() == expected_size;
}

// Matcher for ink::Stroke objects against an expected drawing brush type.
// A pen is opaque while a highlighter has transparency, so a drawing
// brush type can be deduced from the ink::Stroke's brush coat.
MATCHER_P(InkStrokeDrawingBrushTypeEq, expected_type, "") {
  const ink::Brush& ink_brush = arg.GetBrush();
  const ink::BrushCoat& coat = ink_brush.GetCoats()[0];
  float opacity = coat.tips[0].opacity_multiplier;
  if (expected_type == PdfInkBrush::Type::kPen) {
    return opacity == 1.0f;
  }

  CHECK(expected_type == PdfInkBrush::Type::kHighlighter);
  return opacity == 0.4f;
}

// Matcher for bitmap against expected dimensions.
MATCHER_P(BitmapImageSizeEq, dimensions, "") {
  return arg.dimensions() == dimensions;
}

std::map<int, std::vector<raw_ref<const ink::Stroke>>> CollectVisibleStrokes(
    PdfInkModule::PageInkStrokeIterator strokes_iter) {
  std::map<int, std::vector<raw_ref<const ink::Stroke>>> visible_stroke_shapes;
  for (auto page_stroke = strokes_iter.GetNextStrokeAndAdvance();
       page_stroke.has_value();
       page_stroke = strokes_iter.GetNextStrokeAndAdvance()) {
    visible_stroke_shapes[page_stroke.value().page_index].push_back(
        page_stroke.value().stroke);
  }

  return visible_stroke_shapes;
}

base::Value::Dict CreateGetAnnotationBrushMessageForTesting(
    const std::string& brush_type) {
  base::Value::Dict message;
  message.Set("type", "getAnnotationBrush");
  message.Set("messageId", "foo");
  if (!brush_type.empty()) {
    message.Set("brushType", brush_type);
  }
  return message;
}

blink::WebTouchEvent CreateTouchEvent(blink::WebInputEvent::Type type,
                                      base::span<const gfx::PointF> points) {
  CHECK_LE(points.size(), blink::WebTouchEvent::kTouchesLengthCap);

  constexpr int kNoModifiers = 0;
  blink::WebTouchEvent touch_event(
      type, kNoModifiers, blink::WebInputEvent::GetStaticTimeStampForTests());
  for (size_t i = 0; i < points.size(); ++i) {
    touch_event.touches[i].SetPositionInWidget(points[i]);
  }
  touch_event.touches_length = points.size();
  return touch_event;
}

class FakeClient : public PdfInkModuleClient {
 public:
  FakeClient() = default;
  FakeClient(const FakeClient&) = delete;
  FakeClient& operator=(const FakeClient&) = delete;
  ~FakeClient() override = default;

  // PdfInkModuleClient:
  PageOrientation GetOrientation() const override { return orientation_; }

  gfx::Vector2dF GetViewportOriginOffset() override {
    return viewport_origin_offset_;
  }

  gfx::Rect GetPageContentsRect(int index) override {
    CHECK_GE(index, 0);
    CHECK_LT(static_cast<size_t>(index), page_layouts_.size());
    return gfx::ToEnclosedRect(page_layouts_[index]);
  }

  float GetZoom() const override { return zoom_; }

  void Invalidate(const gfx::Rect& rect) override {
    invalidations_.push_back(rect);
  }

  bool IsPageVisible(int page_index) override {
    return base::Contains(visible_page_indices_, page_index);
  }

  MOCK_METHOD(PdfInkModuleClient::DocumentV2InkPathShapesMap,
              LoadV2InkPathsFromPdf,
              (),
              (override));

  MOCK_METHOD(void, PostMessage, (base::Value::Dict message), (override));

  MOCK_METHOD(void,
              StrokeAdded,
              (int page_index, InkStrokeId id, const ink::Stroke& stroke),
              (override));

  void StrokeFinished() override { ++stroke_finished_count_; }

  MOCK_METHOD(void, UpdateInkCursorImage, (SkBitmap bitmap), (override));

  MOCK_METHOD(void,
              UpdateShapeActive,
              (int page_index, InkModeledShapeId id, bool active),
              (override));

  MOCK_METHOD(void,
              UpdateStrokeActive,
              (int page_index, InkStrokeId id, bool active),
              (override));

  MOCK_METHOD(void,
              DiscardStroke,
              (int page_index, InkStrokeId id),
              (override));

  void UpdateThumbnail(int page_index) override {
    updated_thumbnail_page_indices_.push_back(page_index);
  }

  int VisiblePageIndexFromPoint(const gfx::PointF& point) override {
    for (size_t i = 0; i < page_layouts_.size(); ++i) {
      if (IsPageVisible(i) && page_layouts_[i].Contains(point)) {
        return i;
      }
    }

    // Point is not over a visible page in the viewer plane.
    return -1;
  }

  int stroke_finished_count() const { return stroke_finished_count_; }

  const std::vector<int>& updated_thumbnail_page_indices() const {
    return updated_thumbnail_page_indices_;
  }

  const std::vector<gfx::Rect>& invalidations() const { return invalidations_; }

  // Provide the sequence of pages and the coordinates and dimensions for how
  // they are laid out in a viewer plane.  It is upon the caller to ensure the
  // positioning makes sense (e.g., pages do not overlap).
  void set_page_layouts(base::span<const gfx::RectF> page_layouts) {
    page_layouts_ = base::ToVector(page_layouts);
  }

  // Marks pages as visible or not. The caller is responsible for making sure
  // the values makes sense.
  void set_page_visibility(int index, bool visible) {
    if (visible) {
      visible_page_indices_.insert(index);
    } else {
      visible_page_indices_.erase(index);
    }
  }

  void set_orientation(PageOrientation orientation) {
    orientation_ = orientation;
  }

  void set_viewport_origin_offset(const gfx::Vector2dF& offset) {
    viewport_origin_offset_ = offset;
  }

  void set_zoom(float zoom) { zoom_ = zoom; }

 private:
  int stroke_finished_count_ = 0;
  std::vector<int> updated_thumbnail_page_indices_;
  std::vector<gfx::RectF> page_layouts_;
  std::set<int> visible_page_indices_;
  PageOrientation orientation_ = PageOrientation::kOriginal;
  gfx::Vector2dF viewport_origin_offset_;
  float zoom_ = 1.0f;
  std::vector<gfx::Rect> invalidations_;
};

class PdfInkModuleTest : public testing::Test {
 protected:
  void EnableAnnotationMode() {
    EXPECT_TRUE(
        ink_module().OnMessage(CreateSetAnnotationModeMessageForTesting(true)));
  }

  FakeClient& client() { return client_; }
  PdfInkModule& ink_module() { return ink_module_; }
  const PdfInkModule& ink_module() const { return ink_module_; }

 private:
  base::test::ScopedFeatureList feature_list_{features::kPdfInk2};

  NiceMock<FakeClient> client_;
  PdfInkModule ink_module_{client_};
};

}  // namespace

TEST_F(PdfInkModuleTest, UnknownMessage) {
  base::Value::Dict message;
  message.Set("type", "nonInkMessage");
  EXPECT_FALSE(ink_module().OnMessage(message));
}

// Verify that a get eraser message gets the eraser parameters.
TEST_F(PdfInkModuleTest, HandleGetAnnotationBrushMessageEraser) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  EXPECT_CALL(client(), PostMessage)
      .WillOnce([](const base::Value::Dict& dict) {
        auto expected = base::test::ParseJsonDict(R"({
            "type": "getAnnotationBrushReply",
            "messageId": "foo",
            "data": {
              "type": "eraser",
              "size": 3.0,
            },
        })");
        EXPECT_THAT(dict, base::test::DictionaryHasValues(expected));
      });

  EXPECT_TRUE(ink_module().OnMessage(
      CreateGetAnnotationBrushMessageForTesting("eraser")));
}

// Verify that a get pen message gets the pen brush parameters.
TEST_F(PdfInkModuleTest, HandleGetAnnotationBrushMessagePen) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  EXPECT_CALL(client(), PostMessage)
      .WillOnce([](const base::Value::Dict& dict) {
        auto expected = base::test::ParseJsonDict(R"({
            "type": "getAnnotationBrushReply",
            "messageId": "foo",
            "data": {
              "type": "pen",
              "size": 3.0,
              "color": {
                "r": 0,
                "g": 0,
                "b": 0,
              },
            },
        })");
        EXPECT_THAT(dict, base::test::DictionaryHasValues(expected));
      });

  EXPECT_TRUE(
      ink_module().OnMessage(CreateGetAnnotationBrushMessageForTesting("pen")));
}

// Verify that a get highlighter message gets the highlighter brush parameters.
TEST_F(PdfInkModuleTest, HandleGetAnnotationBrushMessageHighlighter) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  EXPECT_CALL(client(), PostMessage)
      .WillOnce([](const base::Value::Dict& dict) {
        auto expected = base::test::ParseJsonDict(R"({
            "type": "getAnnotationBrushReply",
            "messageId": "foo",
            "data": {
              "type": "highlighter",
              "size": 8.0,
              "color": {
                "r": 242,
                "g": 139,
                "b": 130,
              },
            },
        })");
        EXPECT_THAT(dict, base::test::DictionaryHasValues(expected));
      });

  EXPECT_TRUE(ink_module().OnMessage(
      CreateGetAnnotationBrushMessageForTesting("highlighter")));
}

// Verify that a get brush message without a parameter gets the default brush
// parameters.
TEST_F(PdfInkModuleTest, HandleGetAnnotationBrushMessageDefault) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  EXPECT_CALL(client(), PostMessage)
      .WillOnce([](const base::Value::Dict& dict) {
        auto expected = base::test::ParseJsonDict(R"({
            "type": "getAnnotationBrushReply",
            "messageId": "foo",
            "data": {
              "type": "pen",
              "size": 3.0,
              "color": {
                "r": 0,
                "g": 0,
                "b": 0,
              },
            },
        })");
        EXPECT_THAT(dict, base::test::DictionaryHasValues(expected));
      });

  EXPECT_TRUE(
      ink_module().OnMessage(CreateGetAnnotationBrushMessageForTesting("")));
}

// Verify that a get brush message without a parameter gets the current brush
// parameters if the brush has changed from the default brush.
TEST_F(PdfInkModuleTest, HandleGetAnnotationBrushMessageCurrent) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  // Set the brush to eraser.
  EXPECT_TRUE(ink_module().OnMessage(CreateSetAnnotationBrushMessageForTesting(
      "eraser", /*size=*/4.5, nullptr)));

  EXPECT_CALL(client(), PostMessage)
      .WillOnce([](const base::Value::Dict& dict) {
        auto expected = base::test::ParseJsonDict(R"({
            "type": "getAnnotationBrushReply",
            "messageId": "foo",
            "data": {
              "type": "eraser",
              "size": 4.5,
            },
        })");
        EXPECT_THAT(dict, base::test::DictionaryHasValues(expected));
      });

  EXPECT_TRUE(
      ink_module().OnMessage(CreateGetAnnotationBrushMessageForTesting("")));
}

// Verify that a set eraser message sets the annotation brush to an eraser.
TEST_F(PdfInkModuleTest, HandleSetAnnotationBrushMessageEraser) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  base::Value::Dict message = CreateSetAnnotationBrushMessageForTesting(
      "eraser", /*size=*/2.5, nullptr);
  EXPECT_TRUE(ink_module().OnMessage(message));

  const PdfInkBrush* brush = ink_module().GetPdfInkBrushForTesting();
  EXPECT_FALSE(brush);
  std::optional<float> eraser = ink_module().GetEraserSizeForTesting();
  EXPECT_THAT(eraser, testing::Optional(2.5f));
}

// Verify that a set pen message sets the annotation brush to a pen, with the
// given params.
TEST_F(PdfInkModuleTest, HandleSetAnnotationBrushMessagePen) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  TestAnnotationBrushMessageParams message_params{/*color_r=*/10,
                                                  /*color_g=*/255,
                                                  /*color_b=*/50};
  base::Value::Dict message = CreateSetAnnotationBrushMessageForTesting(
      "pen", /*size=*/8.0, &message_params);
  EXPECT_TRUE(ink_module().OnMessage(message));

  const PdfInkBrush* brush = ink_module().GetPdfInkBrushForTesting();
  ASSERT_TRUE(brush);

  const ink::Brush& ink_brush = brush->ink_brush();
  EXPECT_EQ(SkColorSetRGB(10, 255, 50), GetSkColorFromInkBrush(ink_brush));
  EXPECT_EQ(8.0f, ink_brush.GetSize());
  ASSERT_EQ(1u, ink_brush.CoatCount());
  const ink::BrushCoat& coat = ink_brush.GetCoats()[0];
  ASSERT_EQ(1u, coat.tips.size());
  EXPECT_EQ(1.0f, coat.tips[0].corner_rounding);
  EXPECT_EQ(1.0f, coat.tips[0].opacity_multiplier);
}

// Verify that a set highlighter message sets the annotation brush to a
// highlighter, with the given params.
TEST_F(PdfInkModuleTest, HandleSetAnnotationBrushMessageHighlighter) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  TestAnnotationBrushMessageParams message_params{/*color_r=*/240,
                                                  /*color_g=*/133,
                                                  /*color_b=*/0};
  base::Value::Dict message = CreateSetAnnotationBrushMessageForTesting(
      "highlighter", /*size=*/4.5, &message_params);
  EXPECT_TRUE(ink_module().OnMessage(message));

  const PdfInkBrush* brush = ink_module().GetPdfInkBrushForTesting();
  ASSERT_TRUE(brush);

  const ink::Brush& ink_brush = brush->ink_brush();
  EXPECT_EQ(SkColorSetRGB(240, 133, 0), GetSkColorFromInkBrush(ink_brush));
  EXPECT_EQ(4.5f, ink_brush.GetSize());
  ASSERT_EQ(1u, ink_brush.CoatCount());
  const ink::BrushCoat& coat = ink_brush.GetCoats()[0];
  ASSERT_EQ(1u, coat.tips.size());
  EXPECT_EQ(0.0f, coat.tips[0].corner_rounding);
  EXPECT_EQ(0.4f, coat.tips[0].opacity_multiplier);
}

// Verify that brushes with zero color values can be set as the annotation
// brush.
TEST_F(PdfInkModuleTest, HandleSetAnnotationBrushMessageColorZero) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  TestAnnotationBrushMessageParams message_params{/*color_r=*/0, /*color_g=*/0,
                                                  /*color_b=*/0};
  base::Value::Dict message = CreateSetAnnotationBrushMessageForTesting(
      "pen", /*size=*/4.5, &message_params);
  EXPECT_TRUE(ink_module().OnMessage(message));

  const PdfInkBrush* brush = ink_module().GetPdfInkBrushForTesting();
  ASSERT_TRUE(brush);

  const ink::Brush& ink_brush = brush->ink_brush();
  EXPECT_EQ(SK_ColorBLACK, GetSkColorFromInkBrush(ink_brush));
  EXPECT_EQ(4.5f, ink_brush.GetSize());
  ASSERT_EQ(1u, ink_brush.CoatCount());
  const ink::BrushCoat& coat = ink_brush.GetCoats()[0];
  ASSERT_EQ(1u, coat.tips.size());
  EXPECT_EQ(1.0f, coat.tips[0].corner_rounding);
  EXPECT_EQ(1.0f, coat.tips[0].opacity_multiplier);
}

TEST_F(PdfInkModuleTest, HandleSetAnnotationModeMessage) {
  EXPECT_CALL(client(), LoadV2InkPathsFromPdf())
      .WillOnce(Return(PdfInkModuleClient::DocumentV2InkPathShapesMap{
          {0,
           PdfInkModuleClient::PageV2InkPathShapesMap{
               {InkModeledShapeId(0), ink::PartitionedMesh()},
               {InkModeledShapeId(1), ink::PartitionedMesh()}}},
          {3,
           PdfInkModuleClient::PageV2InkPathShapesMap{
               {InkModeledShapeId(2), ink::PartitionedMesh()}}},
      }));

  const auto kShapeMapMatcher = ElementsAre(
      Pair(0, ElementsAre(Field(&PdfInkModule::LoadedV2ShapeState::id,
                                InkModeledShapeId(0)),
                          Field(&PdfInkModule::LoadedV2ShapeState::id,
                                InkModeledShapeId(1)))),
      Pair(3, ElementsAre(Field(&PdfInkModule::LoadedV2ShapeState::id,
                                InkModeledShapeId(2)))));

  EXPECT_FALSE(ink_module().enabled());

  base::Value::Dict message =
      CreateSetAnnotationModeMessageForTesting(/*enable=*/false);

  EXPECT_TRUE(ink_module().OnMessage(message));
  EXPECT_FALSE(ink_module().enabled());
  EXPECT_TRUE(ink_module().loaded_v2_shapes_.empty());

  message.Set("enable", true);
  EXPECT_TRUE(ink_module().OnMessage(message));
  EXPECT_TRUE(ink_module().enabled());
  EXPECT_THAT(ink_module().loaded_v2_shapes_, kShapeMapMatcher);

  message.Set("enable", false);
  EXPECT_TRUE(ink_module().OnMessage(message));
  EXPECT_FALSE(ink_module().enabled());
  EXPECT_THAT(ink_module().loaded_v2_shapes_, kShapeMapMatcher);
}

TEST_F(PdfInkModuleTest, MaybeSetCursorWhenTogglingAnnotationMode) {
  EXPECT_FALSE(ink_module().enabled());

  EXPECT_CALL(client(), UpdateInkCursorImage(_))
      .WillOnce(
          [this](SkBitmap bitmap) { EXPECT_TRUE(ink_module().enabled()); });

  base::Value::Dict message =
      CreateSetAnnotationModeMessageForTesting(/*enable=*/true);
  EXPECT_TRUE(ink_module().OnMessage(message));
  EXPECT_TRUE(ink_module().enabled());

  message.Set("enable", false);
  EXPECT_TRUE(ink_module().OnMessage(message));
  EXPECT_FALSE(ink_module().enabled());
}

TEST_F(PdfInkModuleTest, MaybeSetCursorWhenChangingBrushes) {
  {
    InSequence seq;
    EXPECT_CALL(client(), UpdateInkCursorImage(_))
        .WillOnce([](SkBitmap bitmap) {
          EXPECT_EQ(6, bitmap.width());
          EXPECT_EQ(6, bitmap.height());
        });
    EXPECT_CALL(client(), UpdateInkCursorImage(_))
        .WillOnce([](SkBitmap bitmap) {
          EXPECT_EQ(20, bitmap.width());
          EXPECT_EQ(20, bitmap.height());
        });
    EXPECT_CALL(client(), UpdateInkCursorImage(_))
        .WillOnce([](SkBitmap bitmap) {
          EXPECT_EQ(10, bitmap.width());
          EXPECT_EQ(10, bitmap.height());
        });
  }

  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  TestAnnotationBrushMessageParams message_params{/*color_r=*/0,
                                                  /*color_g=*/255,
                                                  /*color_b=*/0};
  base::Value::Dict message = CreateSetAnnotationBrushMessageForTesting(
      "pen", /*size=*/16.0, &message_params);
  EXPECT_TRUE(ink_module().OnMessage(message));

  message = CreateSetAnnotationBrushMessageForTesting("eraser", /*size=*/8.0,
                                                      nullptr);
  EXPECT_TRUE(ink_module().OnMessage(message));
}

TEST_F(PdfInkModuleTest, MaybeSetCursorWhenChangingZoom) {
  {
    InSequence seq;
    EXPECT_CALL(client(), UpdateInkCursorImage(_))
        .WillOnce([](SkBitmap bitmap) {
          EXPECT_EQ(6, bitmap.width());
          EXPECT_EQ(6, bitmap.height());
        });
    EXPECT_CALL(client(), UpdateInkCursorImage(_))
        .WillOnce([](SkBitmap bitmap) {
          EXPECT_EQ(20, bitmap.width());
          EXPECT_EQ(20, bitmap.height());
        });
    EXPECT_CALL(client(), UpdateInkCursorImage(_))
        .WillOnce([](SkBitmap bitmap) {
          EXPECT_EQ(10, bitmap.width());
          EXPECT_EQ(10, bitmap.height());
        });
  }

  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  TestAnnotationBrushMessageParams message_params{/*color_r=*/0,
                                                  /*color_g=*/255,
                                                  /*color_b=*/0};
  base::Value::Dict message = CreateSetAnnotationBrushMessageForTesting(
      "pen", /*size=*/16.0, &message_params);
  EXPECT_TRUE(ink_module().OnMessage(message));

  client().set_zoom(0.5f);
  ink_module().OnGeometryChanged();
}

TEST_F(PdfInkModuleTest, ContentFocusedPostMessage) {
  EnableAnnotationMode();
  EXPECT_TRUE(ink_module().enabled());

  blink::WebMouseEvent mouse_down_event =
      MouseEventBuilder().CreateLeftClickAtPosition(gfx::PointF()).Build();

  EXPECT_CALL(client(), PostMessage)
      .WillOnce([](const base::Value::Dict& dict) {
        auto expected = base::test::ParseJsonDict(R"({
            "type": "contentFocused",
        })");
        EXPECT_THAT(dict, base::test::DictionaryHasValues(expected));
      });

  ink_module().HandleInputEvent(mouse_down_event);
}

class PdfInkModuleStrokeTest : public PdfInkModuleTest {
 protected:
  // Mouse locations used for `RunStrokeCheckTest()`.
  // Touch events may use the same coordinates.
  static constexpr gfx::PointF kMouseDownPoint = gfx::PointF(10.0f, 15.0f);
  static constexpr gfx::PointF kMouseMovePoint = gfx::PointF(20.0f, 25.0f);
  static constexpr gfx::PointF kMouseUpPoint = gfx::PointF(30.0f, 17.0f);
  static constexpr gfx::PointF kMousePoints[] = {
      kMouseDownPoint, kMouseMovePoint, kMouseUpPoint};

  void InitializeSimpleSinglePageBasicLayout() {
    // Single page layout that matches visible area.
    constexpr gfx::RectF kPage(0.0f, 0.0f, 50.0f, 60.0f);
    client().set_page_layouts(base::span_from_ref(kPage));
    client().set_page_visibility(0, true);
  }

  void InitializeScaledLandscapeSinglePageBasicLayout() {
    // Single page layout that matches visible area.
    constexpr gfx::RectF kPage(0.0f, 0.0f, 120.0f, 100.0f);
    client().set_page_layouts(base::span_from_ref(kPage));
    client().set_page_visibility(0, true);
  }

  void InitializeVerticalTwoPageLayout() {
    // Page 2 is below page 1. Not side-by-side.
    client().set_page_layouts(kVerticalLayout2Pages);
    client().set_page_visibility(0, true);
    client().set_page_visibility(1, true);
  }

  void ApplyStrokeWithMouseAtPoints(
      const gfx::PointF& mouse_down_point,
      base::span<const gfx::PointF> mouse_move_points,
      const gfx::PointF& mouse_up_point) {
    ApplyStrokeWithMouseAtPointsMaybeHandled(
        mouse_down_point, mouse_move_points, mouse_up_point,
        /*expect_mouse_events_handled=*/true);
  }
  void ApplyStrokeWithMouseAtPointsNotHandled(
      const gfx::PointF& mouse_down_point,
      base::span<const gfx::PointF> mouse_move_points,
      const gfx::PointF& mouse_up_point) {
    ApplyStrokeWithMouseAtPointsMaybeHandled(
        mouse_down_point, mouse_move_points, mouse_up_point,
        /*expect_mouse_events_handled=*/false);
  }

  void RunStrokeCheckTest(bool annotation_mode_enabled) {
    EXPECT_TRUE(ink_module().OnMessage(
        CreateSetAnnotationModeMessageForTesting(annotation_mode_enabled)));
    EXPECT_EQ(annotation_mode_enabled, ink_module().enabled());

    ApplyStrokeWithMouseAtPointsMaybeHandled(
        kMouseDownPoint, base::span_from_ref(kMouseMovePoint), kMouseUpPoint,
        /*expect_mouse_events_handled=*/annotation_mode_enabled);

    const int expected_count = annotation_mode_enabled ? 1 : 0;
    EXPECT_EQ(expected_count, client().stroke_finished_count());
    const std::vector<int>& updated_thumbnail_page_indices =
        client().updated_thumbnail_page_indices();
    if (annotation_mode_enabled) {
      EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));
    } else {
      EXPECT_TRUE(updated_thumbnail_page_indices.empty());
    }
  }

  void ApplyStrokeWithMouseAtMouseDownPoint() {
    ApplyStrokeWithMouseAtPoints(
        kMouseDownPoint, base::span_from_ref(kMouseDownPoint), kMouseDownPoint);
  }

  void ApplyStrokeWithTouchAtPoints(
      base::span<const gfx::PointF> touch_start_points,
      std::vector<base::span<const gfx::PointF>> all_touch_move_points,
      base::span<const gfx::PointF> touch_end_points) {
    ApplyStrokeWithTouchAtPointsMaybeHandled(
        touch_start_points, all_touch_move_points, touch_end_points,
        /*expect_touch_events_handled=*/true);
  }

  // TODO(crbug.com/377733396): Consider refactoring to combine with
  // RunStrokeCheckTest().
  void RunStrokeTouchCheckTest(bool annotation_mode_enabled) {
    EXPECT_TRUE(ink_module().OnMessage(
        CreateSetAnnotationModeMessageForTesting(annotation_mode_enabled)));
    EXPECT_EQ(annotation_mode_enabled, ink_module().enabled());

    const std::vector<base::span<const gfx::PointF>> all_touch_move_points{
        base::span_from_ref(kMouseMovePoint),
    };
    ApplyStrokeWithTouchAtPointsMaybeHandled(
        base::span_from_ref(kMouseDownPoint), all_touch_move_points,
        base::span_from_ref(kMouseUpPoint),
        /*expect_touch_events_handled=*/annotation_mode_enabled);

    const int expected_count = annotation_mode_enabled ? 1 : 0;
    EXPECT_EQ(expected_count, client().stroke_finished_count());
    const std::vector<int>& updated_thumbnail_page_indices =
        client().updated_thumbnail_page_indices();
    if (annotation_mode_enabled) {
      EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));
    } else {
      EXPECT_TRUE(updated_thumbnail_page_indices.empty());
    }
  }

  // TODO(crbug.com/377733396): Consider refactoring to combine with
  // RunStrokeCheckTest().
  //
  // Note that currently multi-touch is not handled, so the test expectations
  // are different from the ones in RunStrokeTouchCheckTest().
  void RunStrokeMultiTouchCheckTest(bool annotation_mode_enabled) {
    EXPECT_TRUE(ink_module().OnMessage(
        CreateSetAnnotationModeMessageForTesting(annotation_mode_enabled)));
    EXPECT_EQ(annotation_mode_enabled, ink_module().enabled());

    const std::vector<gfx::PointF> touch_start_points{kMouseDownPoint,
                                                      kMouseDownPoint};
    const std::vector<gfx::PointF> touch_move_points{kMouseMovePoint,
                                                     kMouseMovePoint};
    const std::vector<base::span<const gfx::PointF>> all_touch_move_points{
        touch_move_points,
    };
    const std::vector<gfx::PointF> touch_end_points{kMouseUpPoint,
                                                    kMouseUpPoint};
    ApplyStrokeWithTouchAtPointsMaybeHandled(
        touch_start_points, all_touch_move_points, touch_end_points,
        /*expect_touch_events_handled=*/false);

    EXPECT_EQ(0, client().stroke_finished_count());
    const std::vector<int>& updated_thumbnail_page_indices =
        client().updated_thumbnail_page_indices();
    EXPECT_TRUE(updated_thumbnail_page_indices.empty());
  }

  void RunStrokeMissedEndEventCheckTest() {
    {
      // Start a drawing or erase action.
      blink::WebMouseEvent mouse_down_event =
          MouseEventBuilder()
              .CreateLeftClickAtPosition(kMouseDownPoint)
              .Build();
      EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));

      // Simulate scenario where another view has taken the focus and consumed
      // the mouse up event, such that subsequent mouse moves don't show the
      // left mouse button being pressed.  This should be handled, as it treats
      // it as a signal to terminate the prior stroke.
      blink::WebMouseEvent mouse_move_event =
          MouseEventBuilder()
              .SetType(blink::WebInputEvent::Type::kMouseMove)
              .SetPosition(kMouseMovePoint)
              .SetButton(blink::WebPointerProperties::Button::kNoButton)
              .Build();
      EXPECT_TRUE(ink_module().HandleInputEvent(mouse_move_event));
    }

    {
      // Another mouse move event without the button down is no longer handled
      // since there is no longer any active drawing or erasing.
      constexpr gfx::PointF kMouseMovePoint2 = gfx::PointF(21.0f, 26.0f);
      blink::WebMouseEvent mouse_move_event =
          MouseEventBuilder()
              .SetType(blink::WebInputEvent::Type::kMouseMove)
              .SetPosition(kMouseMovePoint2)
              .SetButton(blink::WebPointerProperties::Button::kNoButton)
              .Build();
      EXPECT_FALSE(ink_module().HandleInputEvent(mouse_move_event));
    }

    {
      // Start another stroke with a new mouse down event, which is handled.
      blink::WebMouseEvent mouse_down_event =
          MouseEventBuilder()
              .CreateLeftClickAtPosition(kMouseDownPoint)
              .Build();
      EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));

      blink::WebMouseEvent mouse_up_event =
          MouseEventBuilder()
              .CreateLeftMouseUpAtPosition(kMouseUpPoint)
              .Build();
      EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));
    }
  }

  void SelectBrushTool(PdfInkBrush::Type type,
                       float size,
                       const TestAnnotationBrushMessageParams& params) {
    EXPECT_TRUE(
        ink_module().OnMessage(CreateSetAnnotationBrushMessageForTesting(
            PdfInkBrush::TypeToString(type), size, ¶ms)));
  }

  void SelectEraserToolOfSize(float size) {
    EXPECT_TRUE(ink_module().OnMessage(
        CreateSetAnnotationBrushMessageForTesting("eraser", size, nullptr)));
  }

  PdfInkModule::DocumentStrokeInputPointsMap StrokeInputPositions() const {
    return ink_module().GetStrokesInputPositionsForTesting();
  }
  PdfInkModule::DocumentStrokeInputPointsMap VisibleStrokeInputPositions()
      const {
    return ink_module().GetVisibleStrokesInputPositionsForTesting();
  }

  void ExpectStrokesAdded(int strokes_affected) {
    CHECK_GT(strokes_affected, 0);
    EXPECT_CALL(client(), StrokeAdded(_, _, _)).Times(strokes_affected);
  }

  void ExpectNoStrokeAdded() {
    EXPECT_CALL(client(), StrokeAdded(_, _, _)).Times(0);
  }

  void ExpectUpdateStrokesActive(int strokes_affected, bool expected_active) {
    CHECK_GT(strokes_affected, 0);
    EXPECT_CALL(client(), UpdateStrokeActive(_, _, expected_active))
        .Times(strokes_affected);
  }

  void ExpectNoUpdateStrokeActive() {
    EXPECT_CALL(client(), UpdateStrokeActive(_, _, _)).Times(0);
  }

  void VerifyAndClearExpectations() {
    testing::Mock::VerifyAndClearExpectations(this);
  }

 private:
  void ApplyStrokeWithMouseAtPointsMaybeHandled(
      const gfx::PointF& mouse_down_point,
      base::span<const gfx::PointF> mouse_move_points,
      const gfx::PointF& mouse_up_point,
      bool expect_mouse_events_handled) {
    blink::WebMouseEvent mouse_down_event =
        MouseEventBuilder().CreateLeftClickAtPosition(mouse_down_point).Build();
    EXPECT_EQ(expect_mouse_events_handled,
              ink_module().HandleInputEvent(mouse_down_event));

    for (const gfx::PointF& mouse_move_point : mouse_move_points) {
      blink::WebMouseEvent mouse_move_event =
          MouseEventBuilder()
              .SetType(blink::WebInputEvent::Type::kMouseMove)
              .SetPosition(mouse_move_point)
              .SetButton(blink::WebPointerProperties::Button::kLeft)
              .Build();
      EXPECT_EQ(expect_mouse_events_handled,
                ink_module().HandleInputEvent(mouse_move_event));
    }

    blink::WebMouseEvent mouse_up_event =
        MouseEventBuilder().CreateLeftMouseUpAtPosition(mouse_up_point).Build();
    EXPECT_EQ(expect_mouse_events_handled,
              ink_module().HandleInputEvent(mouse_up_event));
  }

  void ApplyStrokeWithTouchAtPointsMaybeHandled(
      base::span<const gfx::PointF> touch_start_points,
      std::vector<base::span<const gfx::PointF>> all_touch_move_points,
      base::span<const gfx::PointF> touch_end_points,
      bool expect_touch_events_handled) {
    blink::WebTouchEvent touch_start_event = CreateTouchEvent(
        blink::WebInputEvent::Type::kTouchStart, touch_start_points);
    EXPECT_EQ(expect_touch_events_handled,
              ink_module().HandleInputEvent(touch_start_event));
    for (const auto& touch_move_points : all_touch_move_points) {
      blink::WebTouchEvent touch_move_event = CreateTouchEvent(
          blink::WebInputEvent::Type::kTouchMove, touch_move_points);
      EXPECT_EQ(expect_touch_events_handled,
                ink_module().HandleInputEvent(touch_move_event));
    }

    blink::WebTouchEvent touch_end_event = CreateTouchEvent(
        blink::WebInputEvent::Type::kTouchEnd, touch_end_points);
    EXPECT_EQ(expect_touch_events_handled,
              ink_module().HandleInputEvent(touch_end_event));
  }
};

TEST_F(PdfInkModuleStrokeTest, NoAnnotationWithMouseIfNotEnabled) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeCheckTest(/*annotation_mode_enabled=*/false);
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kMouse));
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kTouch));
}

TEST_F(PdfInkModuleStrokeTest, AnnotationWithMouseIfEnabled) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);
  EXPECT_EQ(3, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kMouse));
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kTouch));
}

TEST_F(PdfInkModuleStrokeTest, NoAnnotationWithTouchIfNotEnabled) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeTouchCheckTest(/*annotation_mode_enabled=*/false);
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kMouse));
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kTouch));
}

TEST_F(PdfInkModuleStrokeTest, AnnotationWithTouchIfEnabled) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeTouchCheckTest(/*annotation_mode_enabled=*/true);
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kMouse));
  EXPECT_EQ(3, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kTouch));
}

TEST_F(PdfInkModuleStrokeTest, NoAnnotationWithMultiTouchIfNotEnabled) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeMultiTouchCheckTest(/*annotation_mode_enabled=*/false);
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kMouse));
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kTouch));
}

TEST_F(PdfInkModuleStrokeTest, NoAnnotationWithMultiTouchIfEnabled) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeMultiTouchCheckTest(/*annotation_mode_enabled=*/true);
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kMouse));
  EXPECT_EQ(0, ink_module().GetInputOfTypeCountForPageForTesting(
                   /*page_index=*/0, ink::StrokeInput::ToolType::kTouch));
}

TEST_F(PdfInkModuleStrokeTest, CanonicalAnnotationPoints) {
  // Setup to support examining the page stroke points for a layout that is
  // more complicated than what is provide by
  // `InitializeSimpleSinglePageBasicLayout()`.  Include viewport offset,
  // scroll, rotation, and zoom.
  constexpr gfx::SizeF kPageSize(100.0f, 120.0f);
  constexpr gfx::PointF kPageOrigin(5.0f, -15.0f);
  constexpr gfx::RectF kPageLayout(kPageOrigin, kPageSize);
  client().set_page_layouts(base::span_from_ref(kPageLayout));
  client().set_page_visibility(0, true);
  client().set_orientation(PageOrientation::kClockwise180);
  client().set_zoom(2.0f);

  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // There should be 3 points collected, for the mouse down, move, and up
  // events. Verify that the collected points match a canonical position for
  // the PdfInkModuleClient setup.
  constexpr gfx::PointF kCanonicalMouseDownPosition(47.0f, 44.5f);
  constexpr gfx::PointF kCanonicalMouseMovePosition(42.0f, 39.5f);
  constexpr gfx::PointF kCanonicalMouseUpPosition(37.0f, 43.5f);
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(Pair(0, PdfInkModule::PageStrokeInputPoints{
                                      {kCanonicalMouseDownPosition,
                                       kCanonicalMouseMovePosition,
                                       kCanonicalMouseUpPosition}})));
}

TEST_F(PdfInkModuleStrokeTest, BasicLayoutInvalidationsFromStroke) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // The default brush param size is 3.0.
  const gfx::Rect kInvalidationAreaMouseDown(gfx::Point(8.0f, 13.0f),
                                             gfx::Size(4.0f, 4.0f));
  const gfx::Rect kInvalidationAreaMouseMove(gfx::Point(8.0f, 13.0f),
                                             gfx::Size(14.0f, 14.0f));
  const gfx::Rect kInvalidationAreaMouseUp(gfx::Point(18.0f, 15.0f),
                                           gfx::Size(14.0f, 12.0f));
  const gfx::Rect kInvalidationAreaFinishedStroke(8.0f, 13.0f, 25.0f, 7.0f);
  EXPECT_THAT(
      client().invalidations(),
      ElementsAre(kInvalidationAreaMouseDown, kInvalidationAreaMouseMove,
                  kInvalidationAreaMouseUp, kInvalidationAreaFinishedStroke));
}

TEST_F(PdfInkModuleStrokeTest, TransformedLayoutInvalidationsFromStroke) {
  // Setup to support examining the invalidation areas from page stroke points
  // for a layout that is more complicated than what is provide by
  // `InitializeSimpleSinglePageBasicLayout()`.  Include viewport offset,
  // scroll, rotation, and zoom.
  constexpr gfx::SizeF kPageSize(100.0f, 120.0f);
  constexpr gfx::PointF kPageOrigin(5.0f, -15.0f);
  constexpr gfx::RectF kPageLayout(kPageOrigin, kPageSize);
  client().set_page_layouts(base::span_from_ref(kPageLayout));
  client().set_page_visibility(0, true);
  client().set_orientation(PageOrientation::kClockwise180);
  client().set_zoom(2.0f);

  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // The default brush param size is 3.0.
  const gfx::Rect kInvalidationAreaMouseDown(gfx::Point(8.0f, 13.0f),
                                             gfx::Size(4.0f, 4.0f));
  const gfx::Rect kInvalidationAreaMouseMove(gfx::Point(8.0f, 13.0f),
                                             gfx::Size(14.0f, 14.0f));
  const gfx::Rect kInvalidationAreaMouseUp(gfx::Point(18.0f, 15.0f),
                                           gfx::Size(14.0f, 12.0f));
  const gfx::Rect kInvalidationAreaFinishedStroke(7.0f, 12.0f, 27.0f, 9.0f);
  EXPECT_THAT(
      client().invalidations(),
      ElementsAre(kInvalidationAreaMouseDown, kInvalidationAreaMouseMove,
                  kInvalidationAreaMouseUp, kInvalidationAreaFinishedStroke));
}

TEST_F(PdfInkModuleStrokeTest, StrokeOutsidePage) {
  EnableAnnotationMode();
  InitializeVerticalTwoPageLayout();

  // Start out without any strokes.
  EXPECT_TRUE(StrokeInputPositions().empty());

  // A stroke that starts outside of any page does not generate a stroke, even
  // if it crosses into a page.
  ApplyStrokeWithMouseAtPointsNotHandled(
      kTwoPageVerticalLayoutPointOutsidePages,
      base::span_from_ref(kTwoPageVerticalLayoutPoint2InsidePage0),
      kTwoPageVerticalLayoutPoint3InsidePage0);

  EXPECT_TRUE(StrokeInputPositions().empty());
}

TEST_F(PdfInkModuleStrokeTest, StrokeInsidePages) {
  EnableAnnotationMode();
  InitializeVerticalTwoPageLayout();

  // Start out without any strokes.
  EXPECT_TRUE(StrokeInputPositions().empty());

  // A stroke in the first page generates a stroke only for that page.
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint1InsidePage0,
      base::span_from_ref(kTwoPageVerticalLayoutPoint2InsidePage0),
      kTwoPageVerticalLayoutPoint3InsidePage0);

  EXPECT_THAT(StrokeInputPositions(), ElementsAre(Pair(0, SizeIs(1))));

  // A stroke in the second page generates a stroke only for that page.
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint1InsidePage1,
      base::span_from_ref(kTwoPageVerticalLayoutPoint2InsidePage1),
      kTwoPageVerticalLayoutPoint3InsidePage1);

  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(Pair(0, SizeIs(1)), Pair(1, SizeIs(1))));
}

TEST_F(PdfInkModuleStrokeTest, StrokeAcrossPages) {
  EnableAnnotationMode();
  InitializeVerticalTwoPageLayout();

  // Start out without any strokes.
  EXPECT_TRUE(StrokeInputPositions().empty());

  // A stroke that starts in first page and ends in the second page only
  // generates one stroke in the first page.
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint1InsidePage0,
      base::span_from_ref(kTwoPageVerticalLayoutPoint2InsidePage1),
      kTwoPageVerticalLayoutPoint3InsidePage1);

  EXPECT_THAT(StrokeInputPositions(), ElementsAre(Pair(0, SizeIs(1))));
}

TEST_F(PdfInkModuleStrokeTest, StrokePageExitAndReentry) {
  EnableAnnotationMode();
  InitializeVerticalTwoPageLayout();

  // Start out without any strokes.
  EXPECT_TRUE(StrokeInputPositions().empty());

  ApplyStrokeWithMouseAtPoints(kTwoPageVerticalLayoutPoint1InsidePage0,
                               kTwoPageVerticalLayoutPageExitAndReentryPoints,
                               kTwoPageVerticalLayoutPoint3InsidePage0);

  EXPECT_THAT(
      StrokeInputPositions(),
      ElementsAre(Pair(
          0,
          ElementsAre(ElementsAreArray(
                          kTwoPageVerticalLayoutPageExitAndReentrySegment1),
                      ElementsAreArray(
                          kTwoPageVerticalLayoutPageExitAndReentrySegment2)))));
}

TEST_F(PdfInkModuleStrokeTest, StrokePageExitAndReentryWithQuickMoves) {
  EnableAnnotationMode();
  InitializeVerticalTwoPageLayout();

  // Start out without any strokes.
  EXPECT_TRUE(StrokeInputPositions().empty());

  // When the mouse cursor moves quickly, PdfInkModule gets fewer input events.
  // Simulate that here with fewer movement inputs compared to
  // `kTwoPageVerticalLayoutPageExitAndReentryPoints`.
  constexpr gfx::PointF kQuickPageExitAndReentryPoints[] = {
      kTwoPageVerticalLayoutPointOutsidePages,
      kTwoPageVerticalLayoutPoint2InsidePage0};
  ApplyStrokeWithMouseAtPoints(kTwoPageVerticalLayoutPoint1InsidePage0,
                               kQuickPageExitAndReentryPoints,
                               kTwoPageVerticalLayoutPoint2InsidePage0);

  EXPECT_THAT(
      StrokeInputPositions(),
      ElementsAre(Pair(
          0, ElementsAre(ElementsAreArray(
                             kTwoPageVerticalLayoutPageExitAndReentrySegment1),
                         ElementsAreArray({gfx::PointF(6.666667f, 0.0f),
                                           gfx::PointF(10.0f, 10.0f)})))));
}

TEST_F(PdfInkModuleStrokeTest, EraseStroke) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // Check that there are now some visible strokes.
  EXPECT_THAT(
      VisibleStrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAre(ElementsAreArray(kMousePoints)))));
  EXPECT_EQ(1, client().stroke_finished_count());
  const std::vector<int>& updated_thumbnail_page_indices =
      client().updated_thumbnail_page_indices();
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));

  // Stroke with the eraser tool.
  SelectEraserToolOfSize(3.0f);
  ApplyStrokeWithMouseAtMouseDownPoint();

  // Now there are no visible strokes left.
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  // Erasing counts as another stroke action.
  EXPECT_EQ(2, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));

  // Stroke again. The stroke that have already been erased should stay erased.
  ApplyStrokeWithMouseAtMouseDownPoint();

  // Still no visible strokes.
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  // Nothing got erased, so the count stays at 2.
  EXPECT_EQ(2, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));
}

TEST_F(PdfInkModuleStrokeTest, EraseOnPageWithoutStrokes) {
  EnableAnnotationMode();
  InitializeSimpleSinglePageBasicLayout();

  // Verify there are no visible strokes to start with.
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());

  // Stroke with the eraser tool when there are no strokes on the page.
  SelectEraserToolOfSize(3.0f);
  ApplyStrokeWithMouseAtMouseDownPoint();

  // Verify there are still no visible strokes and StrokeFinished() never got
  // called.
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  EXPECT_EQ(0, client().stroke_finished_count());
  EXPECT_TRUE(client().updated_thumbnail_page_indices().empty());
}

TEST_F(PdfInkModuleStrokeTest, EraseStrokeEntirelyOffPage) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // Check that there are now some visible strokes.
  EXPECT_THAT(
      VisibleStrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAre(ElementsAreArray(kMousePoints)))));
  EXPECT_EQ(1, client().stroke_finished_count());
  const std::vector<int>& updated_thumbnail_page_indices =
      client().updated_thumbnail_page_indices();
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));

  // Stroke with the eraser tool outside of the page.
  SelectEraserToolOfSize(3.0f);
  constexpr gfx::PointF kOffPagePoint(99.0f, 99.0f);
  ApplyStrokeWithMouseAtPointsNotHandled(
      kOffPagePoint, base::span_from_ref(kOffPagePoint), kOffPagePoint);

  // Check that the visible strokes remain, and StrokeFinished() did not get
  // called again.
  EXPECT_THAT(
      VisibleStrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAre(ElementsAreArray(kMousePoints)))));
  EXPECT_EQ(1, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));
}

TEST_F(PdfInkModuleStrokeTest, EraseStrokeErasesTwoStrokes) {
  InitializeSimpleSinglePageBasicLayout();
  ExpectStrokesAdded(/*strokes_affected=*/2);
  ExpectNoUpdateStrokeActive();
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // Draw a second stroke.
  constexpr gfx::PointF kMouseDownPoint2 = gfx::PointF(10.0f, 30.0f);
  constexpr gfx::PointF kMouseUpPoint2 = gfx::PointF(30.0f, 30.0f);
  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint2, base::span_from_ref(kMouseMovePoint), kMouseUpPoint2);

  // Check that there are now some visible strokes.
  const auto kStroke2Matcher =
      ElementsAre(kMouseDownPoint2, kMouseMovePoint, kMouseUpPoint2);
  const auto kVisibleStrokesMatcher = ElementsAre(
      Pair(0, ElementsAre(ElementsAreArray(kMousePoints), kStroke2Matcher)));
  EXPECT_THAT(VisibleStrokeInputPositions(), kVisibleStrokesMatcher);
  EXPECT_EQ(2, client().stroke_finished_count());
  const std::vector<int>& updated_thumbnail_page_indices =
      client().updated_thumbnail_page_indices();
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));

  // Stroke with the eraser tool at `kMouseMovePoint`, where it should
  // intersect with both strokes, but does not because InkStrokeModeler modeled
  // the "V" shaped input into an input with a much gentler line slope.
  SelectEraserToolOfSize(3.0f);
  ApplyStrokeWithMouseAtPoints(
      kMouseMovePoint, base::span_from_ref(kMouseMovePoint), kMouseMovePoint);

  // Check that the visible strokes are still there since the eraser tool missed
  // the strokes.
  EXPECT_THAT(VisibleStrokeInputPositions(), kVisibleStrokesMatcher);
  EXPECT_EQ(2, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));

  // Stroke with the eraser tool again at `kMousePoints`, but now with a much
  // bigger eraser size. This will actually intersect with both strokes.
  SelectEraserToolOfSize(8.0f);
  VerifyAndClearExpectations();
  ExpectNoStrokeAdded();
  ExpectUpdateStrokesActive(/*strokes_affected=*/2, /*expected_active=*/false);
  ApplyStrokeWithMouseAtPoints(
      kMouseMovePoint, base::span_from_ref(kMouseMovePoint), kMouseMovePoint);

  // Check that there are now no visible strokes.
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  EXPECT_EQ(3, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0, 0));
}

TEST_F(PdfInkModuleStrokeTest, EraseStrokesAcrossTwoPages) {
  EnableAnnotationMode();
  InitializeVerticalTwoPageLayout();

  // Start out without any strokes.
  EXPECT_TRUE(StrokeInputPositions().empty());
  EXPECT_EQ(0, client().stroke_finished_count());
  const std::vector<int>& updated_thumbnail_page_indices =
      client().updated_thumbnail_page_indices();
  EXPECT_TRUE(updated_thumbnail_page_indices.empty());

  ExpectStrokesAdded(/*strokes_affected=*/2);
  ExpectNoUpdateStrokeActive();

  // A stroke in the first page generates a stroke only for that page.
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint1InsidePage0,
      base::span_from_ref(kTwoPageVerticalLayoutPoint2InsidePage0),
      kTwoPageVerticalLayoutPoint3InsidePage0);
  EXPECT_THAT(StrokeInputPositions(), ElementsAre(Pair(0, SizeIs(1))));
  EXPECT_EQ(1, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));

  // A stroke in the second page generates a stroke only for that page.
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint1InsidePage1,
      base::span_from_ref(kTwoPageVerticalLayoutPoint2InsidePage1),
      kTwoPageVerticalLayoutPoint3InsidePage1);
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(Pair(0, SizeIs(1)), Pair(1, SizeIs(1))));
  EXPECT_EQ(2, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 1));

  // Erasing across the two pages should erase everything.
  SelectEraserToolOfSize(3.0f);
  VerifyAndClearExpectations();
  ExpectNoStrokeAdded();
  ExpectUpdateStrokesActive(/*strokes_affected=*/2, /*expected_active=*/false);
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint1InsidePage0,
      std::vector<gfx::PointF>{kTwoPageVerticalLayoutPoint2InsidePage0,
                               kTwoPageVerticalLayoutPoint1InsidePage1},
      kTwoPageVerticalLayoutPoint3InsidePage1);
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  EXPECT_EQ(3, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 1, 0, 1));
}

TEST_F(PdfInkModuleStrokeTest, EraseStrokePageExitAndReentry) {
  EnableAnnotationMode();
  InitializeVerticalTwoPageLayout();

  // Start out without any strokes.
  EXPECT_TRUE(StrokeInputPositions().empty());

  ApplyStrokeWithMouseAtPoints(kTwoPageVerticalLayoutPoint1InsidePage0,
                               kTwoPageVerticalLayoutPageExitAndReentryPoints,
                               kTwoPageVerticalLayoutPoint3InsidePage0);

  EXPECT_THAT(
      StrokeInputPositions(),
      ElementsAre(Pair(
          0,
          ElementsAre(ElementsAreArray(
                          kTwoPageVerticalLayoutPageExitAndReentrySegment1),
                      ElementsAreArray(
                          kTwoPageVerticalLayoutPageExitAndReentrySegment2)))));
  EXPECT_EQ(1, client().stroke_finished_count());
  const std::vector<int>& updated_thumbnail_page_indices =
      client().updated_thumbnail_page_indices();
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));

  // Select the eraser tool and call ApplyStrokeWithMouseAtPoints() again with
  // the same arguments.
  SelectEraserToolOfSize(3.0f);
  ApplyStrokeWithMouseAtPoints(kTwoPageVerticalLayoutPoint1InsidePage0,
                               kTwoPageVerticalLayoutPageExitAndReentryPoints,
                               kTwoPageVerticalLayoutPoint3InsidePage0);

  // The strokes are all still there, but none of them are visible.
  EXPECT_THAT(
      StrokeInputPositions(),
      ElementsAre(Pair(
          0,
          ElementsAre(ElementsAreArray(
                          kTwoPageVerticalLayoutPageExitAndReentrySegment1),
                      ElementsAreArray(
                          kTwoPageVerticalLayoutPageExitAndReentrySegment2)))));
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  // Erasing counts as another stroke action.
  EXPECT_EQ(2, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));
}

TEST_F(PdfInkModuleStrokeTest, EraseStrokeWithTouch) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeTouchCheckTest(/*annotation_mode_enabled=*/true);

  // Check that there are now some visible strokes.
  EXPECT_THAT(
      VisibleStrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAre(ElementsAreArray(kMousePoints)))));
  EXPECT_EQ(1, client().stroke_finished_count());
  const std::vector<int>& updated_thumbnail_page_indices =
      client().updated_thumbnail_page_indices();
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));

  // Stroke with the eraser tool.
  SelectEraserToolOfSize(3.0f);
  const std::vector<base::span<const gfx::PointF>> touch_move_points{
      base::span_from_ref(kMouseMovePoint),
  };
  ApplyStrokeWithTouchAtPoints(base::span_from_ref(kMouseDownPoint),
                               touch_move_points,
                               base::span_from_ref(kMouseDownPoint));

  // Now there are no visible strokes left.
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  // Erasing counts as another stroke action.
  EXPECT_EQ(2, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));

  // Stroke again. The stroke that have already been erased should stay erased.
  ApplyStrokeWithTouchAtPoints(base::span_from_ref(kMouseDownPoint),
                               touch_move_points,
                               base::span_from_ref(kMouseDownPoint));

  // Still no visible strokes.
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  // Nothing got erased, so the count stays at 2.
  EXPECT_EQ(2, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));

  // Stroke again with the mouse gets the same results.
  ApplyStrokeWithMouseAtMouseDownPoint();

  // Still no visible strokes.
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  // Nothing got erased, so the count stays at 2.
  EXPECT_EQ(2, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));
}

TEST_F(PdfInkModuleStrokeTest, RunStrokeMissedEndEventDuringDrawing) {
  InitializeSimpleSinglePageBasicLayout();
  EXPECT_TRUE(ink_module().OnMessage(
      CreateSetAnnotationModeMessageForTesting(/*enable=*/true)));
  EXPECT_TRUE(ink_module().enabled());

  // No need to distinguish between pen or highlighter here.
  EXPECT_TRUE(
      ink_module().OnMessage(CreateGetAnnotationBrushMessageForTesting("pen")));

  RunStrokeMissedEndEventCheckTest();
}

TEST_F(PdfInkModuleStrokeTest, RunStrokeMissedEndEventDuringErasing) {
  InitializeSimpleSinglePageBasicLayout();
  EXPECT_TRUE(ink_module().OnMessage(
      CreateSetAnnotationModeMessageForTesting(/*enable=*/true)));
  EXPECT_TRUE(ink_module().enabled());

  SelectEraserToolOfSize(3.0f);

  RunStrokeMissedEndEventCheckTest();
}

TEST_F(PdfInkModuleStrokeTest, ChangeBrushColorDuringDrawing) {
  EnableAnnotationMode();
  InitializeSimpleSinglePageBasicLayout();

  // Start drawing a stroke with a black pen.  The stroke will not finish
  // until the mouse-up event.
  EXPECT_CALL(client(), StrokeAdded(_, _, _)).Times(0);
  TestAnnotationBrushMessageParams black_pen_message_params{/*color_r=*/0,
                                                            /*color_g=*/0,
                                                            /*color_b=*/0};
  static constexpr float kPenSize = 3.0f;
  SelectBrushTool(PdfInkBrush::Type::kPen, kPenSize, black_pen_message_params);

  blink::WebMouseEvent mouse_down_event =
      MouseEventBuilder()
          .CreateLeftClickAtPosition(kLeftVerticalStrokePoint1)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));

  // While the stroke is still in progress, change the pen color.
  TestAnnotationBrushMessageParams red_pen_message_params{/*color_r=*/242,
                                                          /*color_g=*/139,
                                                          /*color_b=*/130};
  SelectBrushTool(PdfInkBrush::Type::kPen, kPenSize, red_pen_message_params);
  VerifyAndClearExpectations();

  // Continue with mouse movement and then mouse up at a new location.  Notice
  // that the events are handled and the new stroke is added.
  // TODO(crbug.com/381908888): The in-progress stroke is affected by the
  // color change.  Update the expectation to show the in-progress stroke is
  // still black once the brush management in PdfInkModule protects against
  // such changes.
  static constexpr int kPageIndex = 0;
  EXPECT_CALL(client(),
              StrokeAdded(kPageIndex, InkStrokeId(0),
                          InkStrokeBrushColorEq(SkColorSetRGB(242, 139, 130))));
  blink::WebMouseEvent mouse_move_event =
      MouseEventBuilder()
          .SetType(blink::WebInputEvent::Type::kMouseMove)
          .SetPosition(kLeftVerticalStrokePoint2)
          .SetButton(blink::WebPointerProperties::Button::kLeft)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_move_event));
  blink::WebMouseEvent mouse_up_event =
      MouseEventBuilder()
          .CreateLeftMouseUpAtPosition(kLeftVerticalStrokePoint2)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));
  VerifyAndClearExpectations();

  // Do another stroke.  Notice that the changed pen color is in effect for
  // the new stroke that is added.
  EXPECT_CALL(client(),
              StrokeAdded(kPageIndex, InkStrokeId(1),
                          InkStrokeBrushColorEq(SkColorSetRGB(242, 139, 130))));
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));
}

TEST_F(PdfInkModuleStrokeTest, ChangeBrushSizeDuringDrawing) {
  EnableAnnotationMode();
  InitializeSimpleSinglePageBasicLayout();

  // Start drawing a stroke with a black pen.  The stroke will not finish
  // until the mouse-up event.  The cursor image will be updated immediately
  // each time the brush tool is changed, regardless of whether a stroke is
  // in progress.
  EXPECT_CALL(client(), StrokeAdded(_, _, _)).Times(0);
  {
    InSequence seq;
    EXPECT_CALL(client(),
                UpdateInkCursorImage(BitmapImageSizeEq(SkISize(6, 6))));
    EXPECT_CALL(client(),
                UpdateInkCursorImage(BitmapImageSizeEq(SkISize(8, 8))));
  }
  TestAnnotationBrushMessageParams message_params{/*color_r=*/0,
                                                  /*color_g=*/0,
                                                  /*color_b=*/0};
  SelectBrushTool(PdfInkBrush::Type::kPen, 2.0f, message_params);

  blink::WebMouseEvent mouse_down_event =
      MouseEventBuilder()
          .CreateLeftClickAtPosition(kLeftVerticalStrokePoint1)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));

  // While the stroke is still in progress, change the pen size.
  SelectBrushTool(PdfInkBrush::Type::kPen, 6.0f, message_params);
  VerifyAndClearExpectations();

  // Continue with mouse movement and then mouse up at a new location.  Notice
  // that the events are handled and the new stroke is added.
  // TODO(crbug.com/381908888): The in-progress stroke and cursor image are
  // affected by the size change.  Update the expectation to show the
  // in-progress stroke is still thin once the brush management in
  // PdfInkModule protects against such changes.
  static constexpr int kPageIndex = 0;
  EXPECT_CALL(client(), StrokeAdded(kPageIndex, InkStrokeId(0),
                                    InkStrokeBrushSizeEq(6.0f)));
  blink::WebMouseEvent mouse_move_event =
      MouseEventBuilder()
          .SetType(blink::WebInputEvent::Type::kMouseMove)
          .SetPosition(kLeftVerticalStrokePoint2)
          .SetButton(blink::WebPointerProperties::Button::kLeft)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_move_event));
  blink::WebMouseEvent mouse_up_event =
      MouseEventBuilder()
          .CreateLeftMouseUpAtPosition(kLeftVerticalStrokePoint2)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));
  VerifyAndClearExpectations();

  // Do another stroke.  Notice that the changed pen color has now taken
  // effect for the new stroke that is added.
  EXPECT_CALL(client(), StrokeAdded(kPageIndex, InkStrokeId(1),
                                    InkStrokeBrushSizeEq(6.0f)));
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));
}

TEST_F(PdfInkModuleStrokeTest, ChangeSizeDuringErasing) {
  EnableAnnotationMode();
  InitializeSimpleSinglePageBasicLayout();

  // Initialize to have three strokes, so there is something to erase.
  static constexpr int kPageIndex = 0;
  EXPECT_CALL(client(), StrokeAdded(kPageIndex, _, _)).Times(3);
  EXPECT_CALL(client(), UpdateStrokeActive(_, _, _)).Times(0);

  ApplyStrokeWithMouseAtPoints(kLeftVerticalStrokePoint1,
                               base::span_from_ref(kLeftVerticalStrokePoint2),
                               kLeftVerticalStrokePoint2);

  ApplyStrokeWithMouseAtPoints(kMiddleVerticalStrokePoint1,
                               base::span_from_ref(kMiddleVerticalStrokePoint2),
                               kMiddleVerticalStrokePoint2);

  ApplyStrokeWithMouseAtPoints(kRightVerticalStrokePoint1,
                               base::span_from_ref(kRightVerticalStrokePoint2),
                               kRightVerticalStrokePoint2);

  // Set up for erasing.
  SelectEraserToolOfSize(2.0f);
  VerifyAndClearExpectations();

  // Apply erase strokes at positions nearby the second and third strokes.
  // They are not close enough for an eraser with a thin size to erase them.
  EXPECT_CALL(client(), UpdateStrokeActive(_, _, _)).Times(0);

  static constexpr gfx::PointF kNearbyPointAboveMiddleVerticalStroke(25.0f,
                                                                     10.0f);
  ApplyStrokeWithMouseAtPoints(
      kNearbyPointAboveMiddleVerticalStroke,
      base::span_from_ref(kNearbyPointAboveMiddleVerticalStroke),
      kNearbyPointAboveMiddleVerticalStroke);

  static constexpr gfx::PointF kNearbyPointAboveRightVerticalStroke(40.0f,
                                                                    10.0f);
  ApplyStrokeWithMouseAtPoints(
      kNearbyPointAboveRightVerticalStroke,
      base::span_from_ref(kNearbyPointAboveRightVerticalStroke),
      kNearbyPointAboveRightVerticalStroke);

  VerifyAndClearExpectations();

  // Start erasing from where the first stroke was added.
  EXPECT_CALL(client(),
              UpdateStrokeActive(kPageIndex, InkStrokeId(0), /*active=*/false));

  blink::WebMouseEvent mouse_down_event =
      MouseEventBuilder()
          .CreateLeftClickAtPosition(kLeftVerticalStrokePoint1)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));

  // While the stroke is still in progress, change the eraser size.
  SelectEraserToolOfSize(6.0f);
  VerifyAndClearExpectations();

  // Continue the stroke, moving to the nearby-point above the second stroke.
  // Since the eraser has immediately updated to the thick eraser size, it is
  // now close enough that the stroke gets erased.
  //
  // Eraser stroke movement is like below, from the mouse down position D
  // moving through position M before finishing at mouse up position U:
  //
  //           M............U
  //           .
  //           .
  //    left   D            |  middle
  //  stroke   |            |  stroke
  //           |            |
  //
  // TODO(crbug.com/381908888): The in-progress stroke is affected by the
  // size change.  Update the expectation to show the in-progress stroke is
  // unchanged once the brush management in PdfInkModule protects against
  // such changes.
  EXPECT_CALL(client(),
              UpdateStrokeActive(kPageIndex, InkStrokeId(1), /*active=*/false));

  static constexpr gfx::PointF kNearbyPointAboveLeftVerticalStroke(10.0f,
                                                                   10.0f);
  blink::WebMouseEvent mouse_move_event =
      MouseEventBuilder()
          .SetType(blink::WebInputEvent::Type::kMouseMove)
          .SetPosition(kNearbyPointAboveLeftVerticalStroke)
          .SetButton(blink::WebPointerProperties::Button::kLeft)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_move_event));

  blink::WebMouseEvent mouse_up_event =
      MouseEventBuilder()
          .CreateLeftMouseUpAtPosition(kNearbyPointAboveMiddleVerticalStroke)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));

  VerifyAndClearExpectations();

  // Do another eraser stroke at the nearby-point above the third stroke.
  // This point is close enough to be deleted with the thick eraser size
  // that is now in effect.
  EXPECT_CALL(client(),
              UpdateStrokeActive(kPageIndex, InkStrokeId(2), /*active=*/false));

  ApplyStrokeWithMouseAtPoints(
      kNearbyPointAboveRightVerticalStroke,
      base::span_from_ref(kNearbyPointAboveRightVerticalStroke),
      kNearbyPointAboveRightVerticalStroke);
}

TEST_F(PdfInkModuleStrokeTest, ChangeToEraserDuringDrawing) {
  InitializeSimpleSinglePageBasicLayout();

  // Draw an initial stroke.
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // Start drawing another stroke.
  static constexpr int kPageIndex = 0;
  EXPECT_CALL(client(), StrokeAdded(kPageIndex, InkStrokeId(1), _));
  EXPECT_CALL(client(), UpdateStrokeActive(_, _, _)).Times(0);
  blink::WebMouseEvent mouse_down_event =
      MouseEventBuilder()
          .CreateLeftClickAtPosition(kRightVerticalStrokePoint1)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));

  // While the stroke is still in progress, change to the eraser tool.  This
  // causes the in-progress stroke to finish even before the mouse-up event.
  SelectEraserToolOfSize(2.0f);
  VerifyAndClearExpectations();

  // Continue with mouse movement and then mouse up at a new location.  Notice
  // that the events are not handled and there is no further effect for adding
  // or erasing strokes, since the prior stroke was already finished.
  EXPECT_CALL(client(), StrokeAdded(_, _, _)).Times(0);
  EXPECT_CALL(client(), UpdateStrokeActive(_, _, _)).Times(0);
  blink::WebMouseEvent mouse_move_event =
      MouseEventBuilder()
          .SetType(blink::WebInputEvent::Type::kMouseMove)
          .SetPosition(kRightVerticalStrokePoint2)
          .SetButton(blink::WebPointerProperties::Button::kLeft)
          .Build();
  EXPECT_FALSE(ink_module().HandleInputEvent(mouse_move_event));
  blink::WebMouseEvent mouse_up_event =
      MouseEventBuilder()
          .CreateLeftMouseUpAtPosition(kRightVerticalStrokePoint2)
          .Build();
  EXPECT_FALSE(ink_module().HandleInputEvent(mouse_up_event));
  VerifyAndClearExpectations();

  // Do a simple stroke in the same place where the last stroke was added.
  // Notice that the changed tool type has taken effect and the recently added
  // stroke is erased.
  EXPECT_CALL(client(), StrokeAdded(_, _, _)).Times(0);
  EXPECT_CALL(client(),
              UpdateStrokeActive(kPageIndex, InkStrokeId(1), /*active=*/false));
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));
}

TEST_F(PdfInkModuleStrokeTest, ChangeToDrawingDuringErasing) {
  EnableAnnotationMode();
  InitializeSimpleSinglePageBasicLayout();

  // Initialize to have two strokes, so there is something to erase.
  static constexpr int kPageIndex = 0;
  EXPECT_CALL(client(), StrokeAdded(kPageIndex, InkStrokeId(0), _));
  EXPECT_CALL(client(), StrokeAdded(kPageIndex, InkStrokeId(1), _));
  EXPECT_CALL(client(), UpdateStrokeActive(_, _, _)).Times(0);

  ApplyStrokeWithMouseAtPoints(kLeftVerticalStrokePoint1,
                               base::span_from_ref(kLeftVerticalStrokePoint2),
                               kLeftVerticalStrokePoint2);

  ApplyStrokeWithMouseAtPoints(kRightVerticalStrokePoint1,
                               base::span_from_ref(kRightVerticalStrokePoint2),
                               kRightVerticalStrokePoint2);

  // Set up for erasing.
  SelectEraserToolOfSize(2.0f);
  VerifyAndClearExpectations();

  // Start erasing from where the first stroke was added.
  EXPECT_CALL(client(), StrokeAdded(_, _, _)).Times(0);
  EXPECT_CALL(client(), UpdateStrokeActive(kPageIndex, InkStrokeId(0), _));
  blink::WebMouseEvent mouse_down_event =
      MouseEventBuilder()
          .CreateLeftClickAtPosition(kLeftVerticalStrokePoint1)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));

  // While the stroke is still in progress, change the input tool type to a
  // pen.  Note that this causes the in-progress erase stroke to finish even
  // before the mouse-up event.
  TestAnnotationBrushMessageParams message_params{/*color_r=*/0,
                                                  /*color_g=*/0,
                                                  /*color_b=*/0};
  SelectBrushTool(PdfInkBrush::Type::kPen, 8.0f, message_params);
  VerifyAndClearExpectations();

  // Continue with mouse movement and then mouse up at a new location.  Notice
  // that the events are not handled and there is no further effect for adding
  // or erasing strokes, since the prior stroke was already finished.
  EXPECT_CALL(client(), StrokeAdded(_, _, _)).Times(0);
  EXPECT_CALL(client(), UpdateStrokeActive(_, _, _)).Times(0);
  blink::WebMouseEvent mouse_move_event =
      MouseEventBuilder()
          .SetType(blink::WebInputEvent::Type::kMouseMove)
          .SetPosition(kRightVerticalStrokePoint2)
          .SetButton(blink::WebPointerProperties::Button::kLeft)
          .Build();
  EXPECT_FALSE(ink_module().HandleInputEvent(mouse_move_event));
  blink::WebMouseEvent mouse_up_event =
      MouseEventBuilder()
          .CreateLeftMouseUpAtPosition(kRightVerticalStrokePoint1)
          .Build();
  EXPECT_FALSE(ink_module().HandleInputEvent(mouse_up_event));
  VerifyAndClearExpectations();

  // Do another stroke.  Notice that the changed tool type has taken effect
  // and a new stroke is added.
  EXPECT_CALL(client(), StrokeAdded(kPageIndex, InkStrokeId(2), _));
  EXPECT_CALL(client(), UpdateStrokeActive(_, _, _)).Times(0);
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));
}

TEST_F(PdfInkModuleStrokeTest, ChangeDrawingBrushTypeDuringDrawing) {
  EnableAnnotationMode();
  InitializeSimpleSinglePageBasicLayout();

  // Start drawing a stroke with a black pen.  The stroke will not finish
  // until the mouse-up event.  The cursor image will be updated immediately
  // each time the brush tool is changed, regardless of whether a stroke is
  // in progress.
  EXPECT_CALL(client(), StrokeAdded(_, _, _)).Times(0);
  {
    InSequence seq;
    EXPECT_CALL(client(),
                UpdateInkCursorImage(BitmapImageSizeEq(SkISize(6, 6))));
    EXPECT_CALL(client(),
                UpdateInkCursorImage(BitmapImageSizeEq(SkISize(10, 10))));
  }
  TestAnnotationBrushMessageParams pen_message_params{/*color_r=*/0,
                                                      /*color_g=*/0,
                                                      /*color_b=*/0};
  SelectBrushTool(PdfInkBrush::Type::kPen, 2.0f, pen_message_params);

  blink::WebMouseEvent mouse_down_event =
      MouseEventBuilder()
          .CreateLeftClickAtPosition(kLeftVerticalStrokePoint1)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));

  // While the stroke is still in progress, change the input tool type to a
  // highlighter.  The entire stroke changes to this new type.
  TestAnnotationBrushMessageParams highlighter_message_params{/*color_r=*/221,
                                                              /*color_g=*/243,
                                                              /*color_b=*/0};
  SelectBrushTool(PdfInkBrush::Type::kHighlighter, 8.0f,
                  highlighter_message_params);
  VerifyAndClearExpectations();

  // Continue with mouse movement and then mouse up at a new location.  Notice
  // that the events are handled and the new stroke is added.
  // TODO(crbug.com/381908888): The in-progress stroke and cursor image are
  // affected by the brush type change.  Update the expectation to show the
  // in-progress stroke is still a pen once the brush management in
  // PdfInkModule protects against such changes.
  static constexpr int kPageIndex = 0;
  EXPECT_CALL(client(), StrokeAdded(kPageIndex, InkStrokeId(0),
                                    InkStrokeDrawingBrushTypeEq(
                                        PdfInkBrush::Type::kHighlighter)));
  blink::WebMouseEvent mouse_move_event =
      MouseEventBuilder()
          .SetType(blink::WebInputEvent::Type::kMouseMove)
          .SetPosition(kLeftVerticalStrokePoint2)
          .SetButton(blink::WebPointerProperties::Button::kLeft)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_move_event));
  blink::WebMouseEvent mouse_up_event =
      MouseEventBuilder()
          .CreateLeftMouseUpAtPosition(kLeftVerticalStrokePoint2)
          .Build();
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));
  VerifyAndClearExpectations();

  // Do another stroke.  Notice that the changed input tool type has taken
  // effect for the new stroke that is added.
  EXPECT_CALL(client(), StrokeAdded(kPageIndex, InkStrokeId(1),
                                    InkStrokeDrawingBrushTypeEq(
                                        PdfInkBrush::Type::kHighlighter)));
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_down_event));
  EXPECT_TRUE(ink_module().HandleInputEvent(mouse_up_event));
}

class PdfInkModuleUndoRedoTest : public PdfInkModuleStrokeTest {
 protected:
  void PerformUndo() {
    EXPECT_TRUE(
        ink_module().OnMessage(CreateSetAnnotationUndoRedoMessageForTesting(
            TestAnnotationUndoRedoMessageType::kUndo)));
  }
  void PerformRedo() {
    EXPECT_TRUE(
        ink_module().OnMessage(CreateSetAnnotationUndoRedoMessageForTesting(
            TestAnnotationUndoRedoMessageType::kRedo)));
  }
};

TEST_F(PdfInkModuleUndoRedoTest, UndoRedoEmpty) {
  InitializeSimpleSinglePageBasicLayout();
  EnableAnnotationMode();

  EXPECT_TRUE(StrokeInputPositions().empty());
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());

  // Spurious undo message is a no-op.
  PerformUndo();
  EXPECT_TRUE(StrokeInputPositions().empty());
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());

  // Spurious redo message is a no-op.
  PerformRedo();
  EXPECT_TRUE(StrokeInputPositions().empty());
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
}

TEST_F(PdfInkModuleUndoRedoTest, UndoRedoBasic) {
  InitializeSimpleSinglePageBasicLayout();
  ExpectStrokesAdded(/*strokes_affected=*/1);
  ExpectUpdateStrokesActive(/*strokes_affected=*/1, /*expect_active=*/false);
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  const auto kMatcher =
      ElementsAre(Pair(0, ElementsAre(ElementsAreArray(kMousePoints))));
  EXPECT_THAT(StrokeInputPositions(), kMatcher);
  EXPECT_THAT(VisibleStrokeInputPositions(), kMatcher);
  // RunStrokeCheckTest() performed the only stroke.
  EXPECT_EQ(1, client().stroke_finished_count());
  const std::vector<int>& updated_thumbnail_page_indices =
      client().updated_thumbnail_page_indices();
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));

  PerformUndo();
  EXPECT_THAT(StrokeInputPositions(), kMatcher);
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  // Undo/redo here and below do not trigger StrokeFinished().
  EXPECT_EQ(1, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));

  // Spurious undo message is a no-op.
  VerifyAndClearExpectations();
  ExpectNoStrokeAdded();
  ExpectNoUpdateStrokeActive();
  PerformUndo();
  EXPECT_THAT(StrokeInputPositions(), kMatcher);
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  EXPECT_EQ(1, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));

  VerifyAndClearExpectations();
  ExpectNoStrokeAdded();
  ExpectUpdateStrokesActive(/*strokes_affected=*/1, /*expect_active=*/true);
  PerformRedo();
  EXPECT_THAT(StrokeInputPositions(), kMatcher);
  EXPECT_THAT(VisibleStrokeInputPositions(), kMatcher);
  EXPECT_EQ(1, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0, 0));

  // Spurious redo message is a no-op.
  VerifyAndClearExpectations();
  ExpectNoStrokeAdded();
  ExpectNoUpdateStrokeActive();
  PerformRedo();
  EXPECT_THAT(StrokeInputPositions(), kMatcher);
  EXPECT_THAT(VisibleStrokeInputPositions(), kMatcher);
  EXPECT_EQ(1, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0, 0));
}

TEST_F(PdfInkModuleUndoRedoTest, UndoRedoInvalidationsBasic) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // The default brush param size is 3.0.  Invalidation areas are in screen
  // coordinates.
  const gfx::Rect kInvalidationAreaMouseDown(gfx::Point(8.0f, 13.0f),
                                             gfx::Size(4.0f, 4.0f));
  const gfx::Rect kInvalidationAreaMouseMove(gfx::Point(8.0f, 13.0f),
                                             gfx::Size(14.0f, 14.0f));
  const gfx::Rect kInvalidationAreaMouseUp(gfx::Point(18.0f, 15.0f),
                                           gfx::Size(14.0f, 12.0f));
  // This size is smaller than the area of the merged invalidation constants
  // above because InkStrokeModeler modeled the "V" shaped input into an input
  // with a much gentler line slope.
  const gfx::Rect kInvalidationAreaEntireStroke(gfx::Point(8.0f, 13.0f),
                                                gfx::Size(25.0f, 7.0f));
  EXPECT_THAT(
      client().invalidations(),
      ElementsAre(kInvalidationAreaMouseDown, kInvalidationAreaMouseMove,
                  kInvalidationAreaMouseUp, kInvalidationAreaEntireStroke));

  PerformUndo();
  EXPECT_THAT(
      client().invalidations(),
      ElementsAre(kInvalidationAreaMouseDown, kInvalidationAreaMouseMove,
                  kInvalidationAreaMouseUp, kInvalidationAreaEntireStroke,
                  kInvalidationAreaEntireStroke));

  PerformRedo();
  EXPECT_THAT(
      client().invalidations(),
      ElementsAre(kInvalidationAreaMouseDown, kInvalidationAreaMouseMove,
                  kInvalidationAreaMouseUp, kInvalidationAreaEntireStroke,
                  kInvalidationAreaEntireStroke,
                  kInvalidationAreaEntireStroke));
}

TEST_F(PdfInkModuleUndoRedoTest, UndoRedoInvalidationsScaledRotated90) {
  InitializeScaledLandscapeSinglePageBasicLayout();
  client().set_orientation(PageOrientation::kClockwise90);
  client().set_zoom(2.0f);
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // The default brush param size is 3.0.  Invalidation areas are in screen
  // coordinates.
  const gfx::Rect kInvalidationAreaMouseDown(gfx::Point(8.0f, 13.0f),
                                             gfx::Size(4.0f, 4.0f));
  const gfx::Rect kInvalidationAreaMouseMove(gfx::Point(8.0f, 13.0f),
                                             gfx::Size(14.0f, 14.0f));
  const gfx::Rect kInvalidationAreaMouseUp(gfx::Point(18.0f, 15.0f),
                                           gfx::Size(14.0f, 12.0f));
  // This size is smaller than the area of the merged invalidation constants
  // above because InkStrokeModeler modeled the "V" shaped input into an input
  // with a much gentler line slope.
  const gfx::Rect kInvalidationAreaEntireStroke(gfx::Point(7.0f, 12.0f),
                                                gfx::Size(27.0f, 9.0f));
  EXPECT_THAT(
      client().invalidations(),
      ElementsAre(kInvalidationAreaMouseDown, kInvalidationAreaMouseMove,
                  kInvalidationAreaMouseUp, kInvalidationAreaEntireStroke));

  PerformUndo();
  EXPECT_THAT(
      client().invalidations(),
      ElementsAre(kInvalidationAreaMouseDown, kInvalidationAreaMouseMove,
                  kInvalidationAreaMouseUp, kInvalidationAreaEntireStroke,
                  kInvalidationAreaEntireStroke));

  PerformRedo();
  EXPECT_THAT(
      client().invalidations(),
      ElementsAre(kInvalidationAreaMouseDown, kInvalidationAreaMouseMove,
                  kInvalidationAreaMouseUp, kInvalidationAreaEntireStroke,
                  kInvalidationAreaEntireStroke,
                  kInvalidationAreaEntireStroke));
}

TEST_F(PdfInkModuleUndoRedoTest, UndoRedoAnnotationModeDisabled) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  const auto kMatcher =
      ElementsAre(Pair(0, ElementsAre(ElementsAreArray(kMousePoints))));
  EXPECT_THAT(StrokeInputPositions(), kMatcher);
  EXPECT_THAT(VisibleStrokeInputPositions(), kMatcher);
  // RunStrokeCheckTest() performed the only stroke.
  EXPECT_EQ(1, client().stroke_finished_count());
  const std::vector<int>& updated_thumbnail_page_indices =
      client().updated_thumbnail_page_indices();
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0));

  // Disable annotation mode. Undo/redo should still work.
  EXPECT_TRUE(
      ink_module().OnMessage(CreateSetAnnotationModeMessageForTesting(false)));
  EXPECT_EQ(false, ink_module().enabled());

  PerformUndo();
  EXPECT_THAT(StrokeInputPositions(), kMatcher);
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  EXPECT_EQ(1, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0));

  PerformRedo();
  EXPECT_THAT(StrokeInputPositions(), kMatcher);
  EXPECT_THAT(VisibleStrokeInputPositions(), kMatcher);
  EXPECT_EQ(1, client().stroke_finished_count());
  EXPECT_THAT(updated_thumbnail_page_indices, ElementsAre(0, 0, 0));
}

TEST_F(PdfInkModuleUndoRedoTest, UndoRedoBetweenDraws) {
  InitializeSimpleSinglePageBasicLayout();
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  constexpr gfx::PointF kMouseDownPoint1 = gfx::PointF(11.0f, 15.0f);
  constexpr gfx::PointF kMouseMovePoint1 = gfx::PointF(21.0f, 25.0f);
  constexpr gfx::PointF kMouseUpPoint1 = gfx::PointF(31.0f, 17.0f);
  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint1, base::span_from_ref(kMouseMovePoint1), kMouseUpPoint1);

  constexpr gfx::PointF kMouseDownPoint2 = gfx::PointF(12.0f, 15.0f);
  constexpr gfx::PointF kMouseMovePoint2 = gfx::PointF(22.0f, 25.0f);
  constexpr gfx::PointF kMouseUpPoint2 = gfx::PointF(32.0f, 17.0f);
  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint2, base::span_from_ref(kMouseMovePoint2), kMouseUpPoint2);

  constexpr gfx::PointF kMouseDownPoint3 = gfx::PointF(13.0f, 15.0f);
  constexpr gfx::PointF kMouseMovePoint3 = gfx::PointF(23.0f, 25.0f);
  constexpr gfx::PointF kMouseUpPoint3 = gfx::PointF(33.0f, 17.0f);
  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint3, base::span_from_ref(kMouseMovePoint3), kMouseUpPoint3);

  // After drawing 4 strokes above, there should be 4 strokes that are all
  // visible.
  const auto kInitial4StrokeMatchers = {
      ElementsAre(kMouseDownPoint, kMouseMovePoint, kMouseUpPoint),
      ElementsAre(kMouseDownPoint1, kMouseMovePoint1, kMouseUpPoint1),
      ElementsAre(kMouseDownPoint2, kMouseMovePoint2, kMouseUpPoint2),
      ElementsAre(kMouseDownPoint3, kMouseMovePoint3, kMouseUpPoint3)};
  const auto kInitial4StrokeMatchersSpan = base::span(kInitial4StrokeMatchers);
  EXPECT_THAT(
      StrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAreArray(kInitial4StrokeMatchersSpan))));
  EXPECT_THAT(
      VisibleStrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAreArray(kInitial4StrokeMatchersSpan))));

  // Undo makes 3 strokes visible.
  PerformUndo();
  EXPECT_THAT(
      StrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAreArray(kInitial4StrokeMatchersSpan))));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(Pair(
                  0, ElementsAreArray(kInitial4StrokeMatchersSpan.first(3u)))));

  // Undo again makes 2 strokes visible.
  PerformUndo();
  EXPECT_THAT(
      StrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAreArray(kInitial4StrokeMatchersSpan))));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(Pair(
                  0, ElementsAreArray(kInitial4StrokeMatchersSpan.first(2u)))));

  constexpr int kPageIndex = 0;
  EXPECT_CALL(client(), DiscardStroke(kPageIndex, InkStrokeId(2)));
  EXPECT_CALL(client(), DiscardStroke(kPageIndex, InkStrokeId(3)));

  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint3, base::span_from_ref(kMouseMovePoint3), kMouseUpPoint3);
  VerifyAndClearExpectations();

  EXPECT_CALL(client(), DiscardStroke(_, _)).Times(0);

  // The 2 strokes that were undone have been discarded, and the newly drawn
  // stroke takes their place.
  const auto kNext3StrokeMatchers = {
      ElementsAre(kMouseDownPoint, kMouseMovePoint, kMouseUpPoint),
      ElementsAre(kMouseDownPoint1, kMouseMovePoint1, kMouseUpPoint1),
      ElementsAre(kMouseDownPoint3, kMouseMovePoint3, kMouseUpPoint3)};
  const auto kNext3StrokeMatchersSpan = base::span(kNext3StrokeMatchers);
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(Pair(0, ElementsAreArray(kNext3StrokeMatchersSpan))));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(Pair(0, ElementsAreArray(kNext3StrokeMatchersSpan))));

  // Undo makes 2 strokes visible.
  PerformUndo();
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(Pair(0, ElementsAreArray(kNext3StrokeMatchersSpan))));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(Pair(
                  0, ElementsAreArray(kNext3StrokeMatchersSpan.first(2u)))));

  // Undo again makes 1 strokes visible.
  PerformUndo();
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(Pair(0, ElementsAreArray(kNext3StrokeMatchersSpan))));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(Pair(
                  0, ElementsAreArray(kNext3StrokeMatchersSpan.first(1u)))));

  // Undo again makes no strokes visible.
  PerformUndo();
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(Pair(0, ElementsAreArray(kNext3StrokeMatchersSpan))));
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());
  VerifyAndClearExpectations();

  EXPECT_CALL(client(), DiscardStroke(kPageIndex, InkStrokeId(0)));
  EXPECT_CALL(client(), DiscardStroke(kPageIndex, InkStrokeId(1)));
  EXPECT_CALL(client(), DiscardStroke(kPageIndex, InkStrokeId(2)));

  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint2, base::span_from_ref(kMouseMovePoint2), kMouseUpPoint2);

  // All strokes were undone, so they all got discarded. The newly drawn stroke
  // is the only one remaining.
  const auto kFinal1StrokeMatcher =
      ElementsAre(kMouseDownPoint2, kMouseMovePoint2, kMouseUpPoint2);
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(Pair(0, ElementsAre(kFinal1StrokeMatcher))));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(Pair(0, ElementsAre(kFinal1StrokeMatcher))));
}

TEST_F(PdfInkModuleUndoRedoTest, UndoRedoOnTwoPages) {
  EnableAnnotationMode();
  InitializeVerticalTwoPageLayout();

  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint1InsidePage0,
      base::span_from_ref(kTwoPageVerticalLayoutPoint2InsidePage0),
      kTwoPageVerticalLayoutPoint3InsidePage0);
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint1InsidePage1,
      base::span_from_ref(kTwoPageVerticalLayoutPoint2InsidePage1),
      kTwoPageVerticalLayoutPoint3InsidePage1);

  // Canonical coordinates.
  const auto kPage0Matcher =
      Pair(0, ElementsAre(ElementsAre(gfx::PointF(5.0f, 5.0f),
                                      gfx::PointF(10.0f, 10.0f),
                                      gfx::PointF(15.0f, 10.0f))));
  const auto kPage1Matcher =
      Pair(1, ElementsAre(ElementsAre(gfx::PointF(5.0f, 5.0f),
                                      gfx::PointF(10.0f, 10.0f),
                                      gfx::PointF(15.0f, 10.0f))));
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(kPage0Matcher, kPage1Matcher));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(kPage0Matcher, kPage1Matcher));

  PerformUndo();
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(kPage0Matcher, kPage1Matcher));
  EXPECT_THAT(VisibleStrokeInputPositions(), ElementsAre(kPage0Matcher));

  PerformUndo();
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(kPage0Matcher, kPage1Matcher));
  EXPECT_TRUE(VisibleStrokeInputPositions().empty());

  PerformRedo();
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(kPage0Matcher, kPage1Matcher));
  EXPECT_THAT(VisibleStrokeInputPositions(), ElementsAre(kPage0Matcher));

  PerformRedo();
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(kPage0Matcher, kPage1Matcher));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(kPage0Matcher, kPage1Matcher));
}

TEST_F(PdfInkModuleUndoRedoTest, UndoRedoEraseLoadedV2Shapes) {
  constexpr int kPageIndex = 0;
  constexpr InkModeledShapeId kShapeId0(0);
  constexpr InkModeledShapeId kShapeId1(1);

  const auto ink_points = base::ToVector(
      kMousePoints,
      [](const gfx::PointF& point) { return InkPointFromGfxPoint(point); });
  std::optional<ink::Mesh> mesh0 =
      CreateInkMeshFromPolylineForTesting(ink_points);
  ASSERT_TRUE(mesh0.has_value());
  auto shape0 =
      ink::PartitionedMesh::FromMeshes(base::span_from_ref(mesh0.value()));
  ASSERT_TRUE(shape0.ok());

  constexpr ink::Point kCornerPoints[] = {
      {49, 59},
      {48, 59},
      {48, 58},
  };
  std::optional<ink::Mesh> mesh1 =
      CreateInkMeshFromPolylineForTesting(kCornerPoints);
  ASSERT_TRUE(mesh1.has_value());
  auto shape1 =
      ink::PartitionedMesh::FromMeshes(base::span_from_ref(mesh1.value()));
  ASSERT_TRUE(shape1.ok());

  EXPECT_CALL(client(), LoadV2InkPathsFromPdf())
      .WillOnce(Return(PdfInkModuleClient::DocumentV2InkPathShapesMap{
          {kPageIndex, PdfInkModuleClient::PageV2InkPathShapesMap{
                           {kShapeId0, *shape0},
                           {kShapeId1, *shape1},
                       }}}));
  ExpectNoStrokeAdded();
  ExpectNoUpdateStrokeActive();
  EXPECT_CALL(client(), UpdateShapeActive(_, _, _)).Times(0);

  InitializeSimpleSinglePageBasicLayout();
  EnableAnnotationMode();
  ASSERT_TRUE(ink_module().enabled());

  // Stroke with the eraser tool in the corner opposite from `kCornerPoints`,
  // which does nothing.
  SelectEraserToolOfSize(3.0f);
  ApplyStrokeWithMouseAtPoints(
      gfx::PointF(), base::span_from_ref(gfx::PointF()), gfx::PointF());
  VerifyAndClearExpectations();

  // Stroke twice where `shape0` is, and that should deactivate only that shape
  // and only once.
  ExpectNoStrokeAdded();
  ExpectNoUpdateStrokeActive();
  EXPECT_CALL(client(),
              UpdateShapeActive(kPageIndex, kShapeId0, /*active=*/false));
  EXPECT_CALL(client(), UpdateShapeActive(_, kShapeId1, _)).Times(0);
  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint, base::span_from_ref(kMouseMovePoint), kMouseUpPoint);
  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint, base::span_from_ref(kMouseMovePoint), kMouseUpPoint);
  VerifyAndClearExpectations();

  // Undo should reactivate `shape0`.
  ExpectNoStrokeAdded();
  ExpectNoUpdateStrokeActive();
  EXPECT_CALL(client(),
              UpdateShapeActive(kPageIndex, kShapeId0, /*active=*/true));
  EXPECT_CALL(client(), UpdateShapeActive(_, kShapeId1, _)).Times(0);
  PerformUndo();
  VerifyAndClearExpectations();

  // Redo should deactivate `shape0`.
  ExpectNoStrokeAdded();
  ExpectNoUpdateStrokeActive();
  EXPECT_CALL(client(),
              UpdateShapeActive(kPageIndex, kShapeId0, /*active=*/false));
  EXPECT_CALL(client(), UpdateShapeActive(_, kShapeId1, _)).Times(0);
  PerformRedo();
}

// Regression test for crbug.com/378724153.
TEST_F(PdfInkModuleUndoRedoTest, StrokeStrokeUndoStroke) {
  InitializeSimpleSinglePageBasicLayout();

  // Draw stroke 1.
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  // Draw stroke 2.
  constexpr gfx::PointF kMouseDownPoint2 = gfx::PointF(11.0f, 15.0f);
  constexpr gfx::PointF kMouseMovePoint2 = gfx::PointF(21.0f, 25.0f);
  constexpr gfx::PointF kMouseUpPoint2 = gfx::PointF(31.0f, 17.0f);
  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint2, base::span_from_ref(kMouseMovePoint2), kMouseUpPoint2);

  // Strokes 1 and 2 should be visible.
  const auto kInitialStrokeMatchers = {
      ElementsAre(kMouseDownPoint, kMouseMovePoint, kMouseUpPoint),
      ElementsAre(kMouseDownPoint2, kMouseMovePoint2, kMouseUpPoint2)};
  const auto kInitialStrokeMatchersSpan = base::span(kInitialStrokeMatchers);
  EXPECT_THAT(
      StrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAreArray(kInitialStrokeMatchersSpan))));
  EXPECT_THAT(
      VisibleStrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAreArray(kInitialStrokeMatchersSpan))));

  // Undo makes 1 stroke visible.
  PerformUndo();
  EXPECT_THAT(
      StrokeInputPositions(),
      ElementsAre(Pair(0, ElementsAreArray(kInitialStrokeMatchersSpan))));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(Pair(
                  0, ElementsAreArray(kInitialStrokeMatchersSpan.first(1u)))));

  // Stroke IDs are 0-indexed, so stroke 2 has a stroke ID of 1.
  EXPECT_CALL(client(), DiscardStroke(/*page_index=*/0, InkStrokeId(1)));

  // Draw stroke 3. Stroke 2 was undone and should be discarded.
  constexpr gfx::PointF kMouseDownPoint3 = gfx::PointF(12.0f, 15.0f);
  constexpr gfx::PointF kMouseMovePoint3 = gfx::PointF(22.0f, 25.0f);
  constexpr gfx::PointF kMouseUpPoint3 = gfx::PointF(32.0f, 17.0f);
  ApplyStrokeWithMouseAtPoints(
      kMouseDownPoint3, base::span_from_ref(kMouseMovePoint3), kMouseUpPoint3);

  // Strokes 1 and 3 should be visible.
  const auto kNextStrokeMatchers = {
      ElementsAre(kMouseDownPoint, kMouseMovePoint, kMouseUpPoint),
      ElementsAre(kMouseDownPoint3, kMouseMovePoint3, kMouseUpPoint3)};
  const auto kNextStrokeMatchersSpan = base::span(kNextStrokeMatchers);
  EXPECT_THAT(StrokeInputPositions(),
              ElementsAre(Pair(0, ElementsAreArray(kNextStrokeMatchersSpan))));
  EXPECT_THAT(VisibleStrokeInputPositions(),
              ElementsAre(Pair(0, ElementsAreArray(kNextStrokeMatchersSpan))));
}

using PdfInkModuleGetVisibleStrokesTest = PdfInkModuleStrokeTest;

TEST_F(PdfInkModuleGetVisibleStrokesTest, NoPageStrokes) {
  std::map<int, std::vector<raw_ref<const ink::Stroke>>>
      collected_stroke_shapes =
          CollectVisibleStrokes(ink_module().GetVisibleStrokesIterator());
  ASSERT_EQ(collected_stroke_shapes.size(), 0u);
}

TEST_F(PdfInkModuleGetVisibleStrokesTest, MultiplePageStrokes) {
  EnableAnnotationMode();
  InitializeVerticalTwoPageLayout();

  // Multiple strokes on one page, plus a stroke on another page.
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint2InsidePage0,
      base::span_from_ref(kTwoPageVerticalLayoutPoint3InsidePage0),
      kTwoPageVerticalLayoutPoint3InsidePage0);
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint1InsidePage0,
      base::span_from_ref(kTwoPageVerticalLayoutPoint4InsidePage0),
      kTwoPageVerticalLayoutPoint4InsidePage0);
  ApplyStrokeWithMouseAtPoints(
      kTwoPageVerticalLayoutPoint2InsidePage1,
      base::span_from_ref(kTwoPageVerticalLayoutPoint3InsidePage1),
      kTwoPageVerticalLayoutPoint3InsidePage1);

  std::optional<ink::StrokeInputBatch> expected_page0_horz_line_input_batch =
      CreateInkInputBatch(kTwoPageVerticalLayoutHorzLinePage0Inputs);
  ASSERT_TRUE(expected_page0_horz_line_input_batch.has_value());
  std::optional<ink::StrokeInputBatch> expected_page0_vert_line_input_batch =
      CreateInkInputBatch(kTwoPageVerticalLayoutVertLinePage0Inputs);
  ASSERT_TRUE(expected_page0_vert_line_input_batch.has_value());
  std::optional<ink::StrokeInputBatch> expected_page1_horz_line_input_batch =
      CreateInkInputBatch(kTwoPageVerticalLayoutHorzLinePage1Inputs);
  ASSERT_TRUE(expected_page1_horz_line_input_batch.has_value());

  const PdfInkBrush* brush = ink_module().GetPdfInkBrushForTesting();
  ASSERT_TRUE(brush);

  std::map<int, std::vector<raw_ref<const ink::Stroke>>> collected_strokes =
      CollectVisibleStrokes(ink_module().GetVisibleStrokesIterator());
  EXPECT_THAT(
      collected_strokes,
      ElementsAre(
          Pair(0, Pointwise(InkStrokeEq(brush->ink_brush()),
                            {expected_page0_horz_line_input_batch.value(),
                             expected_page0_vert_line_input_batch.value()})),
          Pair(1, Pointwise(InkStrokeEq(brush->ink_brush()),
                            {expected_page1_horz_line_input_batch.value()}))));
}

class PdfInkModuleMetricsTest : public PdfInkModuleUndoRedoTest {
 protected:
  static constexpr char kPenColorMetric[] = "PDF.Ink2StrokePenColor";
  static constexpr char kHighlighterColorMetric[] =
      "PDF.Ink2StrokeHighlighterColor";
  static constexpr char kPenSizeMetric[] = "PDF.Ink2StrokePenSize";
  static constexpr char kHighlighterSizeMetric[] =
      "PDF.Ink2StrokeHighlighterSize";
  static constexpr char kEraserSizeMetric[] = "PDF.Ink2StrokeEraserSize";
  static constexpr char kTypeMetric[] = "PDF.Ink2StrokeBrushType";
};

TEST_F(PdfInkModuleMetricsTest, StrokeUndoRedoDoesNotAffectMetrics) {
  InitializeSimpleSinglePageBasicLayout();
  base::HistogramTester histograms;

  // Draw a pen stroke.
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  histograms.ExpectUniqueSample(kTypeMetric, StrokeMetricBrushType::kPen, 1);
  histograms.ExpectUniqueSample(kPenSizeMetric, StrokeMetricBrushSize::kMedium,
                                1);
  histograms.ExpectUniqueSample(kPenColorMetric, StrokeMetricPenColor::kBlack,
                                1);

  // Undo and redo.
  PerformUndo();
  PerformRedo();

  // The metrics should stay the same.
  histograms.ExpectUniqueSample(kTypeMetric, StrokeMetricBrushType::kPen, 1);
  histograms.ExpectUniqueSample(kPenSizeMetric, StrokeMetricBrushSize::kMedium,
                                1);
  histograms.ExpectUniqueSample(kPenColorMetric, StrokeMetricPenColor::kBlack,
                                1);
}

TEST_F(PdfInkModuleMetricsTest, StrokeBrushColorPen) {
  InitializeSimpleSinglePageBasicLayout();
  base::HistogramTester histograms;

  RunStrokeCheckTest(/*annotation_mode_enabled=*/false);

  histograms.ExpectTotalCount(kPenColorMetric, 0);

  // Draw a stroke with the default black color.
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  histograms.ExpectUniqueSample(kPenColorMetric, StrokeMetricPenColor::kBlack,
                                1);

  // Draw a stroke with "Red 1" color.
  TestAnnotationBrushMessageParams params = {/*color_r=*/0xF2, /*color_g=*/0x8B,
                                             /*color_b=*/0x82};
  SelectBrushTool(PdfInkBrush::Type::kPen, 3.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kPenColorMetric, StrokeMetricPenColor::kRed1, 1);
  histograms.ExpectTotalCount(kPenColorMetric, 2);

  // Draw a stroke with "Tan 3" color.
  params.color_r = 0x88;
  params.color_g = 0x59;
  params.color_b = 0x45;
  SelectBrushTool(PdfInkBrush::Type::kPen, 3.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kPenColorMetric, StrokeMetricPenColor::kTan3, 1);
  histograms.ExpectTotalCount(kPenColorMetric, 3);
  histograms.ExpectTotalCount(kHighlighterColorMetric, 0);
}

TEST_F(PdfInkModuleMetricsTest, StrokeBrushColorHighlighter) {
  EnableAnnotationMode();
  InitializeSimpleSinglePageBasicLayout();
  base::HistogramTester histograms;

  // Draw a stroke with "Light Red" color.
  TestAnnotationBrushMessageParams params = {/*color_r=*/0xF2, /*color_g=*/0x8B,
                                             /*color_b=*/0x82};
  SelectBrushTool(PdfInkBrush::Type::kHighlighter, 6.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kHighlighterColorMetric,
                               StrokeMetricHighlighterColor::kLightRed, 1);
  histograms.ExpectTotalCount(kHighlighterColorMetric, 1);

  // Draw a stroke with "Orange" color.
  params.color_r = 0xFF;
  params.color_g = 0x63;
  params.color_b = 0x0C;
  SelectBrushTool(PdfInkBrush::Type::kHighlighter, 6.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kHighlighterColorMetric,
                               StrokeMetricHighlighterColor::kOrange, 1);
  histograms.ExpectTotalCount(kHighlighterColorMetric, 2);
  histograms.ExpectTotalCount(kPenColorMetric, 0);
}

TEST_F(PdfInkModuleMetricsTest, StrokeBrushSizePen) {
  InitializeSimpleSinglePageBasicLayout();
  base::HistogramTester histograms;

  // Draw a stroke.
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  histograms.ExpectUniqueSample(kPenSizeMetric, StrokeMetricBrushSize::kMedium,
                                1);

  TestAnnotationBrushMessageParams params = {/*color_r=*/242, /*color_g=*/139,
                                             /*color_b=*/130};
  SelectBrushTool(PdfInkBrush::Type::kPen, 1.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kPenSizeMetric,
                               StrokeMetricBrushSize::kExtraThin, 1);
  histograms.ExpectTotalCount(kPenSizeMetric, 2);

  SelectBrushTool(PdfInkBrush::Type::kPen, 8.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kPenSizeMetric,
                               StrokeMetricBrushSize::kExtraThick, 1);
  histograms.ExpectTotalCount(kPenSizeMetric, 3);
  histograms.ExpectTotalCount(kHighlighterSizeMetric, 0);
  histograms.ExpectTotalCount(kEraserSizeMetric, 0);
}

TEST_F(PdfInkModuleMetricsTest, StrokeBrushSizeHighlighter) {
  EnableAnnotationMode();
  InitializeSimpleSinglePageBasicLayout();
  base::HistogramTester histograms;

  // Draw a stroke with medium size.
  TestAnnotationBrushMessageParams params = {/*color_r=*/242, /*color_g=*/139,
                                             /*color_b=*/130};
  SelectBrushTool(PdfInkBrush::Type::kHighlighter, 8.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectUniqueSample(kHighlighterSizeMetric,
                                StrokeMetricBrushSize::kMedium, 1);

  // Draw a stroke with extra thin size.
  SelectBrushTool(PdfInkBrush::Type::kHighlighter, 4.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kHighlighterSizeMetric,
                               StrokeMetricBrushSize::kExtraThin, 1);
  histograms.ExpectTotalCount(kHighlighterSizeMetric, 2);

  // Draw a stroke with extra thick size.
  SelectBrushTool(PdfInkBrush::Type::kHighlighter, 16.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kHighlighterSizeMetric,
                               StrokeMetricBrushSize::kExtraThick, 1);
  histograms.ExpectTotalCount(kPenSizeMetric, 0);
  histograms.ExpectTotalCount(kHighlighterSizeMetric, 3);
  histograms.ExpectTotalCount(kEraserSizeMetric, 0);
}

TEST_F(PdfInkModuleMetricsTest, StrokeBrushSizeEraser) {
  EnableAnnotationMode();
  InitializeSimpleSinglePageBasicLayout();
  base::HistogramTester histograms;

  // Draw a pen stroke. Draw an eraser stroke that erases it with medium size.
  TestAnnotationBrushMessageParams params = {/*color_r=*/242, /*color_g=*/139,
                                             /*color_b=*/130};
  SelectBrushTool(PdfInkBrush::Type::kPen, 3.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();
  SelectEraserToolOfSize(3.0f);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectUniqueSample(kEraserSizeMetric,
                                StrokeMetricBrushSize::kMedium, 1);

  // Draw a pen stroke. Draw an eraser stroke that erases it with extra thin
  // size.
  SelectBrushTool(PdfInkBrush::Type::kPen, 3.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();
  SelectEraserToolOfSize(1.0f);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kEraserSizeMetric,
                               StrokeMetricBrushSize::kExtraThin, 1);
  histograms.ExpectTotalCount(kEraserSizeMetric, 2);

  // Draw a pen stroke. Draw an eraser stroke that erases it with extra thick
  // size.
  SelectBrushTool(PdfInkBrush::Type::kPen, 3.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();
  SelectEraserToolOfSize(8.0f);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kEraserSizeMetric,
                               StrokeMetricBrushSize::kExtraThick, 1);

  // There should be no visible strokes on the page. Draw an eraser stroke that
  // does not erase any other strokes. The metric should stay the same.
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kEraserSizeMetric,
                               StrokeMetricBrushSize::kExtraThick, 1);

  histograms.ExpectTotalCount(kPenSizeMetric, 3);
  histograms.ExpectTotalCount(kHighlighterSizeMetric, 0);
  histograms.ExpectTotalCount(kEraserSizeMetric, 3);
}

TEST_F(PdfInkModuleMetricsTest, StrokeBrushType) {
  InitializeSimpleSinglePageBasicLayout();
  base::HistogramTester histograms;

  RunStrokeCheckTest(/*annotation_mode_enabled=*/false);

  histograms.ExpectTotalCount(kTypeMetric, 0);

  // Draw a pen stroke.
  RunStrokeCheckTest(/*annotation_mode_enabled=*/true);

  histograms.ExpectUniqueSample(kTypeMetric, StrokeMetricBrushType::kPen, 1);

  // Draw a highlighter stroke.
  TestAnnotationBrushMessageParams params = {/*color_r=*/242, /*color_g=*/139,
                                             /*color_b=*/130};
  SelectBrushTool(PdfInkBrush::Type::kHighlighter, 6.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kTypeMetric, StrokeMetricBrushType::kHighlighter,
                               1);
  histograms.ExpectTotalCount(kTypeMetric, 2);

  // Draw an eraser stroke.
  SelectEraserToolOfSize(3.0f);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kTypeMetric, StrokeMetricBrushType::kEraser, 1);
  histograms.ExpectTotalCount(kTypeMetric, 3);

  // Draw an eraser stroke at a different point that does not erase any other
  // strokes. The metric should stay the same.
  ApplyStrokeWithMouseAtPoints(
      kMouseUpPoint, base::span_from_ref(kMouseUpPoint), kMouseUpPoint);

  histograms.ExpectBucketCount(kTypeMetric, StrokeMetricBrushType::kEraser, 1);
  histograms.ExpectTotalCount(kTypeMetric, 3);

  // Draw another pen stroke.
  SelectBrushTool(PdfInkBrush::Type::kPen, 3.0f, params);
  ApplyStrokeWithMouseAtMouseDownPoint();

  histograms.ExpectBucketCount(kTypeMetric, StrokeMetricBrushType::kPen, 2);
  histograms.ExpectTotalCount(kTypeMetric, 4);
}

}  // namespace chrome_pdf