File: dictation_browsertest.cc

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

#include "chrome/browser/ash/accessibility/dictation.h"

#include <memory>
#include <optional>

#include "ash/constants/ash_pref_names.h"
#include "ash/public/cpp/accessibility_controller_enums.h"
#include "ash/public/cpp/system_tray_test_api.h"
#include "ash/public/cpp/test/accessibility_controller_test_api.h"
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/system/accessibility/dictation_button_tray.h"
#include "ash/system/notification_center/notification_center_test_api.h"
#include "ash/system/status_area_widget.h"
#include "ash/system/status_area_widget_test_helper.h"
#include "base/containers/fixed_flat_set.h"
#include "base/functional/bind.h"
#include "base/metrics/metrics_hashes.h"
#include "base/metrics/statistics_recorder.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/ash/accessibility/accessibility_feature_browsertest.h"
#include "chrome/browser/ash/accessibility/accessibility_manager.h"
#include "chrome/browser/ash/accessibility/accessibility_test_utils.h"
#include "chrome/browser/ash/accessibility/autoclick_test_utils.h"
#include "chrome/browser/ash/accessibility/automation_test_utils.h"
#include "chrome/browser/ash/accessibility/chromevox_test_utils.h"
#include "chrome/browser/ash/accessibility/dictation_bubble_test_helper.h"
#include "chrome/browser/ash/accessibility/dictation_test_utils.h"
#include "chrome/browser/ash/accessibility/select_to_speak_test_utils.h"
#include "chrome/browser/ash/accessibility/speech_monitor.h"
#include "chrome/browser/ash/accessibility/switch_access_test_utils.h"
#include "chrome/browser/ash/base/locale_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/speech/speech_recognition_constants.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/metrics/content/subprocess_metrics_provider.h"
#include "components/prefs/pref_service.h"
#include "components/soda/soda_installer.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_navigation_observer.h"
#include "extensions/browser/api/audio/audio_api.h"
#include "extensions/browser/api/audio/audio_service.h"
#include "extensions/browser/browsertest_util.h"
#include "extensions/browser/extension_host_test_helper.h"
#include "ui/accessibility/accessibility_features.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/clipboard_buffer.h"
#include "ui/events/test/event_generator.h"

namespace ash {

using EditableType = DictationTestUtils::EditableType;

namespace {

const char kFirstSpeechResult[] = "Help";
const char16_t kFirstSpeechResult16[] = u"Help";
const char kFinalSpeechResult[] = "Hello world";
const char16_t kFinalSpeechResult16[] = u"Hello world";
const char16_t kTrySaying[] = u"Try saying:";
const char16_t kType[] = u"\"Type [word / phrase]\"";
const char16_t kHelp[] = u"\"Help\"";
const char16_t kUndo[] = u"\"Undo\"";
const char16_t kDelete[] = u"\"Delete\"";
const char16_t kSelectAll[] = u"\"Select all\"";
const char16_t kUnselect[] = u"\"Unselect\"";
const char16_t kCopy[] = u"\"Copy\"";
const char* kOnDeviceListeningDurationMetric =
    "Accessibility.CrosDictation.ListeningDuration.OnDeviceRecognition";
const char* kNetworkListeningDurationMetric =
    "Accessibility.CrosDictation.ListeningDuration.NetworkRecognition";
const char* kLocaleMetric = "Accessibility.CrosDictation.Language";
const char* kOnDeviceSpeechMetric =
    "Accessibility.CrosDictation.UsedOnDeviceSpeech";
const char* kPumpkinUsedMetric = "Accessibility.CrosDictation.UsedPumpkin";
const char* kPumpkinSucceededMetric =
    "Accessibility.CrosDictation.PumpkinSucceeded";
const char* kMacroRecognizedMetric =
    "Accessibility.CrosDictation.MacroRecognized";
const char* kMacroSucceededMetric =
    "Accessibility.CrosDictation.MacroSucceeded";
const char* kMacroFailedMetric = "Accessibility.CrosDictation.MacroFailed";
const int kInputTextViewMetricValue = 1;

static const char* kEnglishDictationCommands[] = {
    "delete",
    "move to the previous character",
    "move to the next character",
    "move to the previous line",
    "move to the next line",
    "copy",
    "paste",
    "cut",
    "undo",
    "redo",
    "select all",
    "unselect",
    "help",
    "new line",
    "cancel",
    "delete the previous word",
    "delete the previous sentence",
    "move to the next word",
    "move to the previous word",
    "delete phrase",
    "replace phrase with another phrase",
    "insert phrase before another phrase",
    "select from phrase to another phrase",
    "move to the next sentence",
    "move to the previous sentence"};

constexpr auto kOfflineNotSupportedLocaleSet =
    base::MakeFixedFlatSet<std::string_view>({"af-ZA", "kn-IN"});

PrefService* GetActiveUserPrefs() {
  return ProfileManager::GetActiveUserProfile()->GetPrefs();
}

AccessibilityManager* GetManager() {
  return AccessibilityManager::Get();
}

// A class used to define the parameters of a test case.
class TestConfig {
 public:
  TestConfig(speech::SpeechRecognitionType speech_recognition_type,
             EditableType editable_type,
             ManifestVersion manifest_version)
      : speech_recognition_type_(speech_recognition_type),
        editable_type_(editable_type),
        manifest_version_(manifest_version) {}

  speech::SpeechRecognitionType speech_recognition_type() const {
    return speech_recognition_type_;
  }

  EditableType editable_type() const { return editable_type_; }

  ManifestVersion manifest_version() const { return manifest_version_; }

 private:
  speech::SpeechRecognitionType speech_recognition_type_;
  EditableType editable_type_;
  ManifestVersion manifest_version_;
};

}  // namespace

class DictationTestBase : public AccessibilityFeatureBrowserTest,
                          public ::testing::WithParamInterface<TestConfig> {
 public:
  DictationTestBase() = default;
  ~DictationTestBase() override = default;
  DictationTestBase(const DictationTestBase&) = delete;
  DictationTestBase& operator=(const DictationTestBase&) = delete;

 protected:
  // InProcessBrowserTest:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    utils_ = std::make_unique<DictationTestUtils>(speech_recognition_type(),
                                                  editable_type());
    std::vector<base::test::FeatureRef> enabled_features =
        utils_->GetEnabledFeatures();
    std::vector<base::test::FeatureRef> disabled_features =
        utils_->GetDisabledFeatures();
    disabled_features.push_back(
        ::features::kAccessibilityManifestV3SwitchAccess);
    if (manifest_version() == ManifestVersion::kTwo) {
      disabled_features.push_back(
          ::features::kAccessibilityManifestV3AccessibilityCommon);
    } else if (manifest_version() == ManifestVersion::kThree) {
      enabled_features.push_back(
          ::features::kAccessibilityManifestV3AccessibilityCommon);
    }
    scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features);
    AccessibilityFeatureBrowserTest::SetUpCommandLine(command_line);
  }

  void SetUpOnMainThread() override {
    InProcessBrowserTest::SetUpOnMainThread();
    utils_->EnableDictation(
        /*profile=*/GetProfile(),
        /*navigate_to_url=*/base::BindOnce(&DictationTestBase::NavigateToUrl,
                                           base::Unretained(this)));
  }

  // Routers to DictationTestUtils methods.
  void WaitForRecognitionStarted() { utils_->WaitForRecognitionStarted(); }

  void WaitForRecognitionStopped() { utils_->WaitForRecognitionStopped(); }

  void SendInterimResultAndWait(const std::string& transcript) {
    utils_->SendInterimResultAndWait(transcript);
  }

  void SendFinalResultAndWait(const std::string& transcript) {
    utils_->SendFinalResultAndWait(transcript);
  }

  void SendErrorAndWait() { utils_->SendErrorAndWait(); }

  void SendFinalResultAndWaitForEditableValue(const std::string& result,
                                              const std::string& value) {
    utils_->SendFinalResultAndWaitForEditableValue(result, value);
  }

  void SendFinalResultAndWaitForSelection(const std::string& result,
                                          int start,
                                          int end) {
    utils_->SendFinalResultAndWaitForSelection(result, start, end);
  }

  void SendFinalResultAndWaitForClipboardChanged(const std::string& result) {
    utils_->SendFinalResultAndWaitForClipboardChanged(result);
  }

  std::string GetEditableValue() { return utils_->GetEditableValue(); }

  void WaitForEditableValue(const std::string& value) {
    utils_->WaitForEditableValue(value);
  }

  void ToggleDictationWithKeystroke() {
    utils_->ToggleDictationWithKeystroke();
  }

  void InstallMockInputContextHandler() {
    utils_->InstallMockInputContextHandler();
  }

  // Retrieves the number of times commit text is updated.
  int GetCommitTextCallCount() { return utils_->GetCommitTextCallCount(); }

  void WaitForCommitText(const std::u16string& value) {
    utils_->WaitForCommitText(value);
  }

  const base::flat_map<std::string, Dictation::LocaleData>
  GetAllSupportedLocales() {
    return Dictation::GetAllSupportedLocales();
  }

  void DisablePumpkin() { utils_->DisablePumpkin(); }

  void ExecuteAccessibilityCommonScript(const std::string& script) {
    utils_->ExecuteAccessibilityCommonScript(script);
  }

  std::string GetClipboardText() {
    std::u16string text;
    ui::Clipboard::GetForCurrentThread()->ReadText(
        ui::ClipboardBuffer::kCopyPaste, /*data_dst=*/nullptr, &text);
    return base::UTF16ToUTF8(text);
  }

  void PressTab() {
    ui::test::EmulateFullKeyPressReleaseSequence(
        /*generator=*/generator(),
        /*key=*/ui::KeyboardCode::VKEY_TAB,
        /*control=*/false,
        /*shift=*/false,
        /*alt=*/false,
        /*command=*/false);
  }

  bool RunOnMultilineContent() {
    // TODO(b:259353252): Contenteditables have an error where inserting a \n
    // actually inserts two \n characters.
    // <input> represents a one-line plain text control, so multiline test cases
    // should be skipped. Run multiline test cases only on <textarea> for these
    // reasons.
    return editable_type() == EditableType::kTextArea;
  }

  speech::SpeechRecognitionType speech_recognition_type() {
    return GetParam().speech_recognition_type();
  }

  EditableType editable_type() { return GetParam().editable_type(); }
  ui::test::EventGenerator* generator() { return utils_->generator(); }
  ManifestVersion manifest_version() { return GetParam().manifest_version(); }

  void set_wait_for_accessibility_common_extension_load_(bool use) {
    utils_->set_wait_for_accessibility_common_extension_load_(use);
  }

  DictationTestUtils* utils() { return utils_.get(); }
 private:
  std::unique_ptr<DictationTestUtils> utils_;
  base::test::ScopedFeatureList scoped_feature_list_;
};

class DictationTest : public DictationTestBase {
 public:
  DictationTest() = default;
  ~DictationTest() override = default;
  DictationTest(const DictationTest&) = delete;
  DictationTest& operator=(const DictationTest&) = delete;

 protected:
  void SetUpOnMainThread() override {
    GetActiveUserPrefs()->SetString(prefs::kAccessibilityDictationLocale,
                                    "en-US");
    DictationTestBase::SetUpOnMainThread();
  }
};

INSTANTIATE_TEST_SUITE_P(
    NetworkContentEditable,
    DictationTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kContentEditable,
                                 ManifestVersion::kTwo)));

INSTANTIATE_TEST_SUITE_P(
    OnDeviceTextArea,
    DictationTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kOnDevice,
                                 EditableType::kTextArea,
                                 ManifestVersion::kTwo)));

// Tests the behavior of the GetAllSupportedLocales method, specifically how
// it sets locale data.
IN_PROC_BROWSER_TEST_P(DictationTest, GetAllSupportedLocales) {
  auto locales = GetAllSupportedLocales();
  for (auto& it : locales) {
    const std::string locale = it.first;
    bool works_offline = it.second.works_offline;
    bool installed = it.second.installed;
    if (speech_recognition_type() == speech::SpeechRecognitionType::kOnDevice &&
        locale == speech::kUsEnglishLocale) {
      // We are certain that en_US works offline, so that must be true. There
      // are others too (depending on flags) but we can't test them.  We can be
      // certain that we haven't installed them though.
      EXPECT_TRUE(works_offline);
      EXPECT_TRUE(installed);
    } else {
      EXPECT_FALSE(installed) << " for locale " << locale;
      if (base::Contains(kOfflineNotSupportedLocaleSet, locale)) {
        EXPECT_FALSE(works_offline) << " for locale " << locale;
      }
    }
  }

  if (speech_recognition_type() == speech::SpeechRecognitionType::kOnDevice) {
    // Uninstall SODA and all language packs.
    speech::SodaInstaller::GetInstance()->UninstallSodaForTesting();
  } else {
    return;
  }

  locales = GetAllSupportedLocales();
  for (auto& it : locales) {
    const std::string locale = it.first;
    bool works_offline = it.second.works_offline;
    bool installed = it.second.installed;
    if (locale == speech::kUsEnglishLocale) {
      // We are certain that en_US works offline, so that must be true. There
      // are others too (depending on flags) but we can't test them.  We can be
      // certain that we haven't installed them though.
      EXPECT_TRUE(works_offline);
      EXPECT_FALSE(installed);
    } else {
      EXPECT_FALSE(installed) << " for locale " << locale;
      if (base::Contains(kOfflineNotSupportedLocaleSet, locale)) {
        EXPECT_FALSE(works_offline) << " for locale " << locale;
      }
    }
  }
}

IN_PROC_BROWSER_TEST_P(DictationTest, StartsAndStopsRecognition) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationTest, EntersFinalizedSpeech) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue(kFinalSpeechResult,
                                         kFinalSpeechResult);
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

// Tests that multiple finalized strings can be committed to the text area.
// Also ensures that spaces are added between finalized utterances.
IN_PROC_BROWSER_TEST_P(DictationTest, EntersMultipleFinalizedStrings) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("The rain in Spain",
                                         "The rain in Spain");
  SendFinalResultAndWaitForEditableValue(
      "falls mainly on the plain.",
      "The rain in Spain falls mainly on the plain.");
  SendFinalResultAndWaitForEditableValue(
      "Vega is a star.",
      "The rain in Spain falls mainly on the plain. Vega is a star.");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationTest, OnlyAddSpaceWhenNecessary) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("The rain in Spain",
                                         "The rain in Spain");
  // Artificially add a space to this utterance. Verify that only one space is
  // added.
  SendFinalResultAndWaitForEditableValue(
      " falls mainly on the plain.",
      "The rain in Spain falls mainly on the plain.");
  // Artificially add a space to this utterance. Verify that only one space is
  // added.
  SendFinalResultAndWaitForEditableValue(
      " Vega is a star.",
      "The rain in Spain falls mainly on the plain. Vega is a star.");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationTest, RecognitionEndsWhenInputFieldLosesFocus) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("Vega is a star", "Vega is a star");
  PressTab();
  WaitForRecognitionStopped();
  EXPECT_EQ("Vega is a star", GetEditableValue());
}

IN_PROC_BROWSER_TEST_P(DictationTest, UserEndsDictationWhenChromeVoxEnabled) {
  ChromeVoxTestUtils chromevox_test_utils;
  chromevox_test_utils.EnableChromeVox();

  EXPECT_TRUE(GetManager()->IsSpokenFeedbackEnabled());
  InstallMockInputContextHandler();

  GetManager()->ToggleDictation();
  WaitForRecognitionStarted();
  SendInterimResultAndWait(kFinalSpeechResult);
  GetManager()->ToggleDictation();
  WaitForRecognitionStopped();

  WaitForCommitText(kFinalSpeechResult16);
  chromevox_test_utils.sm()->Replay();
}

IN_PROC_BROWSER_TEST_P(DictationTest, ChromeVoxSilencedWhenToggledOn) {
  ChromeVoxTestUtils chromevox_test_utils;
  chromevox_test_utils.EnableChromeVox();
  EXPECT_TRUE(GetManager()->IsSpokenFeedbackEnabled());

  // Not yet forced to stop.
  EXPECT_EQ(0, chromevox_test_utils.sm()->stop_count());

  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();

  // Assert ChromeVox was asked to stop speaking at the toggle. Note: multiple
  // requests to stop speech can be sent, so we just expect stop_count() > 0.
  EXPECT_GT(chromevox_test_utils.sm()->stop_count(), 0);
  chromevox_test_utils.sm()->Replay();
}

IN_PROC_BROWSER_TEST_P(DictationTest, WorksWithSelectToSpeak) {
  // Set up Select to Speak.
  test::SpeechMonitor sm;
  EXPECT_FALSE(GetManager()->IsSelectToSpeakEnabled());
  sts_test_utils::TurnOnSelectToSpeakForTest(
      AccessibilityManager::Get()->profile());

  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue(
      "Not idly do the leaves of Lorien fall",
      "Not idly do the leaves of Lorien fall");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();

  aura::Window* root_window = Shell::Get()->GetPrimaryRootWindow();
  ui::test::EventGenerator generator(root_window);

  gfx::Rect bounds =
      utils()->automation_test_utils()->GetBoundsForNodeInRootByClassName(
          "editableForDictation");
  sts_test_utils::StartSelectToSpeakWithBounds(bounds, &generator);

  // Now ensure STS still works properly.
  sm.ExpectSpeechPattern("Not idly do the leaves of Lorien fall*");
  sm.Replay();
}

IN_PROC_BROWSER_TEST_P(DictationTest, EntersInterimSpeechWhenToggledOff) {
  InstallMockInputContextHandler();

  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendInterimResultAndWait(kFirstSpeechResult);
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
  WaitForCommitText(kFirstSpeechResult16);
}

// Tests that commit text is not updated if the user toggles dictation and no
// speech results are processed.
IN_PROC_BROWSER_TEST_P(DictationTest, UserEndsDictationBeforeSpeech) {
  InstallMockInputContextHandler();
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
  EXPECT_EQ(0, GetCommitTextCallCount());
}

// Ensures that the correct metrics are recorded when Dictation is toggled.
IN_PROC_BROWSER_TEST_P(DictationTest, Metrics) {
  base::HistogramTester histogram_tester_;
  bool on_device =
      speech_recognition_type() == speech::SpeechRecognitionType::kOnDevice;
  const char* metric_name = on_device ? kOnDeviceListeningDurationMetric
                                      : kNetworkListeningDurationMetric;
  HistogramWaiter waiter(metric_name);
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
  waiter.Wait();
  content::FetchHistogramsFromChildProcesses();
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  // Ensure that we recorded the correct locale.
  histogram_tester_.ExpectUniqueSample(/*name=*/kLocaleMetric,
                                       /*sample=*/base::HashMetricName("en-US"),
                                       /*expected_bucket_count=*/1);
  // Ensure that we recorded the type of speech recognition and listening
  // duration.
  if (on_device) {
    histogram_tester_.ExpectUniqueSample(/*name=*/kOnDeviceSpeechMetric,
                                         /*sample=*/true,
                                         /*expected_bucket_count=*/1);
    ASSERT_EQ(1u,
              histogram_tester_.GetAllSamples(kOnDeviceListeningDurationMetric)
                  .size());
    // Ensure there are no metrics for the other type of speech recognition.
    ASSERT_EQ(0u,
              histogram_tester_.GetAllSamples(kNetworkListeningDurationMetric)
                  .size());
  } else {
    histogram_tester_.ExpectUniqueSample(/*name=*/kOnDeviceSpeechMetric,
                                         /*sample=*/false,
                                         /*expected_bucket_count=*/1);
    ASSERT_EQ(1u,
              histogram_tester_.GetAllSamples(kNetworkListeningDurationMetric)
                  .size());
    // Ensure there are no metrics for the other type of speech recognition.
    ASSERT_EQ(0u,
              histogram_tester_.GetAllSamples(kOnDeviceListeningDurationMetric)
                  .size());
  }
}

IN_PROC_BROWSER_TEST_P(DictationTest,
                       DictationStopsWhenSystemTrayBecomesVisible) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SystemTrayTestApi::Create()->ShowBubble();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationTest, NoExtraSpaceForPunctuation) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("Hello world", "Hello world");
  SendFinalResultAndWaitForEditableValue(".", "Hello world.");
  SendFinalResultAndWaitForEditableValue("Goodnight", "Hello world. Goodnight");
  SendFinalResultAndWaitForEditableValue("!", "Hello world. Goodnight!");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationTest, StopListening) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWait("cancel");
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationTest, SmartCapitalization) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("this", "This");
  SendFinalResultAndWaitForEditableValue("Is", "This is");
  SendFinalResultAndWaitForEditableValue("a test.", "This is a test.");
  SendFinalResultAndWaitForEditableValue("you passed!",
                                         "This is a test. You passed!");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationTest, SmartCapitalizationWithComma) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("Hello,", "Hello,");
  SendFinalResultAndWaitForEditableValue("world", "Hello, world");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

// Note: this test runs the SMART_DELETE_PHRASE macro and at first glance
// should be categorized as a DictationRegexCommandsTest. However, this test
// stops speech recognition in the middle of the test, which directly conflicts
// with DictationRegexCommandsTest's behavior to automatically stop speech
// recognition during teardown. Thus we need this to be a DictationTest so that
// we don't try to stop speech recognition when it's already been stopped.
IN_PROC_BROWSER_TEST_P(DictationTest, SmartDeletePhraseNoChange) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("Hello world", "Hello world");
  SendFinalResultAndWait("delete banana");
  SendFinalResultAndWait("cancel");
  WaitForRecognitionStopped();
  // The text area value isn't changed because Dictation parses 'delete banana'
  // as the SMART_DELETE_PHRASE macro. Since there is no instance of 'banana' in
  // the text field, the macro does nothing and the text area value remains
  // unchanged. In the future, we can verify that context-checking failed and an
  // error was surfaced to the user.
  ASSERT_EQ("Hello world", GetEditableValue());
}

// Is a DictationTest for the same reason as the above test.
IN_PROC_BROWSER_TEST_P(DictationTest, Help) {
  // Setup a TestNavigationObserver, which will allow us to know when the help
  // center URL is loaded.
  auto observer = std::make_unique<content::TestNavigationObserver>(
      GURL("https://support.google.com/chromebook?p=text_dictation_m100"));
  observer->WatchExistingWebContents();
  observer->StartWatchingNewWebContents();

  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWait("help");

  // Speech recognition should automatically turn off.
  WaitForRecognitionStopped();
  // Wait for the help center URL to load.
  observer->Wait();
}

// Confirms that punctuation can be sent and entered into the editable. We
// unfortuantely can't test that "period" -> "." or "exclamation point" -> "!"
// since that computation happens in the speech recognition engine.
IN_PROC_BROWSER_TEST_P(DictationTest, Punctuation) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  std::string text = "Testing Dictation. It's a great feature!";
  SendFinalResultAndWaitForEditableValue(text, text);
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationTest,
                       TogglesOnIfSodaDownloadingInDifferentLanguage) {
  if (speech_recognition_type() != speech::SpeechRecognitionType::kOnDevice) {
    // SodaInstaller only works if on-device speech recognition is available.
    return;
  }

  speech::SodaInstaller::GetInstance()->NotifySodaProgressForTesting(
      30, speech::LanguageCode::kFrFr);
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

// Verifies that Dictation cannot be toggled on using the keyboard shortcut if
// a SODA download is in-progress.
IN_PROC_BROWSER_TEST_P(DictationTest,
                       NoToggleOnIfSodaDownloadingInDictationLanguage) {
  if (speech_recognition_type() != speech::SpeechRecognitionType::kOnDevice) {
    // SodaInstaller only works if on-device speech recognition is available.
    return;
  }

  // Dictation shouldn't work if SODA is downloading in the Dictation locale.
  speech::SodaInstaller::GetInstance()->NotifySodaProgressForTesting(
      30, speech::LanguageCode::kEnUs);
  ExecuteAccessibilityCommonScript(
      "dictationTestSupport.installFakeSpeechRecognitionPrivateStart();");
  ToggleDictationWithKeystroke();
  // Sanity check that speech recognition is off and that no calls to
  // chrome.speechRecognitionPrivate.start() were made.
  WaitForRecognitionStopped();
  ExecuteAccessibilityCommonScript(
      "dictationTestSupport.ensureNoSpeechRecognitionPrivateStartCalls();");
  ExecuteAccessibilityCommonScript(
      "dictationTestSupport.restoreSpeechRecognitionPrivateStart();");

  // Dictation should work again once the SODA download is finished.
  speech::SodaInstaller::GetInstance()->NotifySodaInstalledForTesting(
      speech::LanguageCode::kEnUs);
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

class DictationWithAutoclickTest : public DictationTestBase {
 public:
  DictationWithAutoclickTest() = default;
  ~DictationWithAutoclickTest() override = default;
  DictationWithAutoclickTest(const DictationWithAutoclickTest&) = delete;
  DictationWithAutoclickTest& operator=(const DictationWithAutoclickTest&) =
      delete;

 protected:
  void SetUpOnMainThread() override {
    // Setup Autoclick first, then setup Dictation. This is to ensure that
    // Autoclick doesn't steal focus away from the textarea (either by clicking
    // or via the presence of the Autoclick UI, which steals focus when
    // initially shown).
    autoclick_test_utils_ = std::make_unique<AutoclickTestUtils>(GetProfile());
    autoclick_test_utils_->SetAutoclickDelayMs(90 * 1000);
    // Don't install automation test utils JS, Dictation already does this.
    autoclick_test_utils_->LoadAutoclick(/*install_automation_utils=*/false);
    EXPECT_TRUE(GetManager()->IsAutoclickEnabled());
    // Don't use ExtensionHostTestHelper for Dictation because we already used
    // it for Autoclick.
    set_wait_for_accessibility_common_extension_load_(false);
    DictationTestBase::SetUpOnMainThread();
  }

  void TearDownOnMainThread() override { autoclick_test_utils_.reset(); }

  AutoclickTestUtils* autoclick_test_utils() {
    return autoclick_test_utils_.get();
  }

 private:
  std::unique_ptr<AutoclickTestUtils> autoclick_test_utils_;
};

INSTANTIATE_TEST_SUITE_P(
    NetworkTextArea,
    DictationWithAutoclickTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kTextArea,
                                 ManifestVersion::kTwo)));

IN_PROC_BROWSER_TEST_P(DictationWithAutoclickTest, UseBothFeatures) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("Hello world", "Hello world");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();

  autoclick_test_utils()->SetAutoclickEventTypeWithHover(
      generator(), AutoclickEventType::kDoubleClick);
  autoclick_test_utils()->SetAutoclickDelayMs(5);
  // Hovering over the editable should result in the text being selected.
  autoclick_test_utils()->HoverOverHtmlElement(generator(), "Hello world",
                                               "staticText");
  utils()->automation_test_utils()->WaitForTextSelectionChangedEvent();
}

IN_PROC_BROWSER_TEST_P(DictationWithAutoclickTest, UseAutoclickToToggle) {
  autoclick_test_utils()->SetAutoclickEventTypeWithHover(
      generator(), AutoclickEventType::kLeftClick);
  autoclick_test_utils()->SetAutoclickDelayMs(5);
  gfx::Rect dictation_button = Shell::Get()
                                   ->GetPrimaryRootWindowController()
                                   ->GetStatusAreaWidget()
                                   ->dictation_button_tray()
                                   ->GetBoundsInScreen();
  // Move the mouse to the Dictation button.
  generator()->MoveMouseTo(dictation_button.CenterPoint());
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("Hello world", "Hello world");
  // Move the mouse away from, then back to the Dictation button.
  generator()->MoveMouseTo(gfx::Point(20, 20));
  generator()->MoveMouseTo(dictation_button.CenterPoint());
  WaitForRecognitionStopped();
}

class DictationWithSwitchAccessTest : public DictationTestBase {
 public:
  DictationWithSwitchAccessTest() = default;
  ~DictationWithSwitchAccessTest() override = default;
  DictationWithSwitchAccessTest(const DictationWithSwitchAccessTest&) = delete;
  DictationWithSwitchAccessTest& operator=(
      const DictationWithSwitchAccessTest&) = delete;

 protected:
  void SetUpOnMainThread() override {
    switch_access_test_utils_ =
        std::make_unique<SwitchAccessTestUtils>(GetProfile());
    switch_access_test_utils_->EnableSwitchAccess({'1', 'A'} /* select */,
                                                  {'2', 'B'} /* next */,
                                                  {'3', 'C'} /* previous */);
    DictationTestBase::SetUpOnMainThread();
  }

 private:
  std::unique_ptr<SwitchAccessTestUtils> switch_access_test_utils_;
};

INSTANTIATE_TEST_SUITE_P(
    NetworkTextArea,
    DictationWithSwitchAccessTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kTextArea,
                                 ManifestVersion::kTwo)));

IN_PROC_BROWSER_TEST_P(DictationWithSwitchAccessTest, CanDictate) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("Hello", "Hello");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

// Tests the behavior of Dictation in Japanese.
class DictationJaTest : public DictationTestBase {
 public:
  DictationJaTest() = default;
  ~DictationJaTest() override = default;
  DictationJaTest(const DictationJaTest&) = delete;
  DictationJaTest& operator=(const DictationJaTest&) = delete;

 protected:
  void SetUpOnMainThread() override {
    locale_util::SwitchLanguage("ja", /*enable_locale_keyboard_layouts=*/true,
                                /*login_layouts_only*/ false, base::DoNothing(),
                                GetProfile());
    g_browser_process->SetApplicationLocale("ja");
    GetActiveUserPrefs()->SetString(prefs::kAccessibilityDictationLocale, "ja");

    DictationTestBase::SetUpOnMainThread();

    DisablePumpkin();
  }
};

// On-device speech recognition is currently limited to en-US, so
// DictationJaTest should use network speech recognition only.
INSTANTIATE_TEST_SUITE_P(
    NetworkTextArea,
    DictationJaTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kTextArea,
                                 ManifestVersion::kTwo)));

INSTANTIATE_TEST_SUITE_P(
    NetworkContentEditable,
    DictationJaTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kContentEditable,
                                 ManifestVersion::kTwo)));

IN_PROC_BROWSER_TEST_P(DictationJaTest, NoSmartCapitalization) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("this", "this");
  // Note that spaces get removed when the Dictation language is Japanese
  // (see the RemoveSpacesWithinUtterance) test case below.
  SendFinalResultAndWaitForEditableValue(" Is", "thisIs");
  SendFinalResultAndWaitForEditableValue("a test.", "thisIsatest.");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationJaTest, RemoveSpacesWithinUtterance) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  // Dictate "I like tennis". Include spaces within this utterance, since we can
  // receive results like this from the speech recognizer. Ensure that the
  // spaces within the utterance are stripped out.
  SendFinalResultAndWaitForEditableValue("私は テニス が好き です。",
                                         "私はテニスが好きです。");
  // Dictate "congratulations". Ensure that no spaces are added in between
  // utterances.
  SendFinalResultAndWaitForEditableValue("おめでとう",
                                         "私はテニスが好きです。おめでとう");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationJaTest, CanDictate) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("テニス", "テニス");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationJaTest, DeleteCharacter) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  // Dictate "tennis".
  SendFinalResultAndWaitForEditableValue("テニス", "テニス");
  // Perform the 'delete' command.
  SendFinalResultAndWaitForEditableValue("削除", "テニ");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationJaTest, SmartDeletePhrase) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  // Dictate "I like basketball".
  SendFinalResultAndWaitForEditableValue("私はバスケットボールが好きです。",
                                         "私はバスケットボールが好きです。");
  // Delete "I" e.g. the first two characters in the sentence.
  SendFinalResultAndWaitForEditableValue("私はを削除",
                                         "バスケットボールが好きです。");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationJaTest, SmartReplacePhrase) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  // Dictate "I like basketball".
  SendFinalResultAndWaitForEditableValue("私はバスケットボールが好きです。",
                                         "私はバスケットボールが好きです。");
  // Replace "basketball" with "tennis".
  SendFinalResultAndWaitForEditableValue("バスケットボールをテニスに置き換え",
                                         "私はテニスが好きです。");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationJaTest, SmartInsertBefore) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  // Dictate "I like tennis".
  SendFinalResultAndWaitForEditableValue("私はテニスが好きです。",
                                         "私はテニスが好きです。");
  // Insert "basketball and" before "tennis".
  // Final text area value should be "I like basketball and tennis".
  SendFinalResultAndWaitForEditableValue(
      "バスケットボールとをテニスの前に挿入",
      "私はバスケットボールとテニスが好きです。");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationJaTest, SmartSelectBetweenAndDictate) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  // Dictate "I like tennis".
  SendFinalResultAndWaitForEditableValue("私はテニスが好きです。",
                                         "私はテニスが好きです。");
  // Select the entire text using the SMART_SELECT_BETWEEN command.
  SendFinalResultAndWaitForSelection("私はから好きですまで選択", 0, 10);
  // Dictate "congratulations", which should replace the selected text.
  SendFinalResultAndWaitForEditableValue("おめでとう", "おめでとう。");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationJaTest, SmartSelectBetweenAndDelete) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  // Dictate "I like tennis".
  SendFinalResultAndWaitForEditableValue("私はテニスが好きです。",
                                         "私はテニスが好きです。");
  // Select between "I" and "tennis" using the SMART_SELECT_BETWEEN command
  // (roughly the first half of the text).
  SendFinalResultAndWaitForSelection("私はからテニスまで選択", 0, 5);
  // Perform the delete command.
  SendFinalResultAndWaitForEditableValue("削除", "が好きです。");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

// Tests Dictation regex-based commands (no Pumpkin).
class DictationRegexCommandsTest : public DictationTest {
 public:
  DictationRegexCommandsTest() = default;
  ~DictationRegexCommandsTest() override = default;
  DictationRegexCommandsTest(const DictationRegexCommandsTest&) = delete;
  DictationRegexCommandsTest& operator=(const DictationRegexCommandsTest&) =
      delete;

 protected:
  void SetUpOnMainThread() override {
    DictationTest::SetUpOnMainThread();
    // Disable Pumpkin so that we use regex parsing.
    DisablePumpkin();
    ToggleDictationWithKeystroke();
    WaitForRecognitionStarted();
  }

  void TearDownOnMainThread() override {
    ToggleDictationWithKeystroke();
    WaitForRecognitionStopped();
    DictationTest::TearDownOnMainThread();
  }
};

INSTANTIATE_TEST_SUITE_P(
    NetworkInput,
    DictationRegexCommandsTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kInput,
                                 ManifestVersion::kTwo)));

INSTANTIATE_TEST_SUITE_P(
    NetworkContentEditable,
    DictationRegexCommandsTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kContentEditable,
                                 ManifestVersion::kTwo)));

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, TypesCommands) {
  std::string expected_text = "";
  int i = 0;
  for (const char* command : kEnglishDictationCommands) {
    std::string type_command = "type ";
    if (i == 0) {
      expected_text += command;
      expected_text[0] = base::ToUpperASCII(expected_text[0]);
    } else {
      expected_text += " ";
      expected_text += command;
    }
    SendFinalResultAndWaitForEditableValue(type_command + command,
                                           expected_text);
    ++i;
  }
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, TypesNonCommands) {
  // The phrase should be entered without the word "type".
  SendFinalResultAndWaitForEditableValue("Type this is a test",
                                         "This is a test");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeleteCharacter) {
  SendFinalResultAndWaitForEditableValue("Vega", "Vega");
  // Capitalization and whitespace shouldn't matter.
  SendFinalResultAndWaitForEditableValue(" Delete", "Veg");
  SendFinalResultAndWaitForEditableValue("delete", "Ve");
  SendFinalResultAndWaitForEditableValue("  delete ", "V");
  SendFinalResultAndWaitForEditableValue(
      "DELETE",
      (editable_type() == EditableType::kContentEditable) ? "\n" : "");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, MoveByCharacter) {
  SendFinalResultAndWaitForEditableValue("Lyra", "Lyra");
  SendFinalResultAndWaitForSelection("Move to the Previous character", 3, 3);
  // White space is added to the text on the left of the text caret, but not
  // to the right of the text caret.
  SendFinalResultAndWaitForEditableValue("inserted", "Lyr inserted a");
  SendFinalResultAndWaitForSelection("move TO the next character ", 14, 14);
  SendFinalResultAndWaitForEditableValue("is a constellation",
                                         "Lyr inserted a is a constellation");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, NewLineAndMoveByLine) {
  if (!RunOnMultilineContent())
    return;

  SendFinalResultAndWaitForEditableValue("Line 1", "Line 1");
  SendFinalResultAndWaitForEditableValue("new line", "Line 1\n");
  SendFinalResultAndWaitForEditableValue("line 2", "Line 1\nline 2");
  SendFinalResultAndWaitForSelection("Move to the previous line ", 6, 6);
  SendFinalResultAndWaitForEditableValue("up", "Line 1 up\nline 2");
  SendFinalResultAndWaitForSelection("Move to the next line", 16, 16);
  SendFinalResultAndWaitForEditableValue("down", "Line 1 up\nline 2 down");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, UndoAndRedo) {
  SendFinalResultAndWaitForEditableValue("The constellation",
                                         "The constellation");
  SendFinalResultAndWaitForEditableValue(" Myra", "The constellation Myra");
  SendFinalResultAndWaitForEditableValue("undo", "The constellation");
  SendFinalResultAndWaitForEditableValue(" Lyra", "The constellation Lyra");
  SendFinalResultAndWaitForEditableValue("undo", "The constellation");
  SendFinalResultAndWaitForEditableValue("redo", "The constellation Lyra");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, SelectAllAndUnselect) {
  std::string first_text = "Vega is the brightest star in Lyra";
  SendFinalResultAndWaitForEditableValue(first_text, first_text);
  SendFinalResultAndWaitForSelection("Select all", 0, first_text.size());
  SendFinalResultAndWaitForEditableValue(
      "delete",
      (editable_type() == EditableType::kContentEditable) ? "\n" : "");
  std::string second_text = "Vega is the fifth brightest star in the sky";
  SendFinalResultAndWaitForEditableValue(second_text, second_text);
  SendFinalResultAndWaitForSelection("Select all", 0, second_text.size());
  SendFinalResultAndWaitForSelection("Unselect", second_text.size(),
                                     second_text.size());
  SendFinalResultAndWaitForEditableValue(
      "!", "Vega is the fifth brightest star in the sky!");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, CutCopyPaste) {
  SendFinalResultAndWaitForEditableValue("Star", "Star");
  SendFinalResultAndWaitForSelection("Select all", 0, 4);
  SendFinalResultAndWaitForClipboardChanged("Copy");
  EXPECT_EQ("Star", GetClipboardText());
  SendFinalResultAndWaitForSelection("unselect", 4, 4);
  SendFinalResultAndWaitForEditableValue("paste", "StarStar");
  SendFinalResultAndWaitForSelection("select ALL ", 0, 8);
  SendFinalResultAndWaitForClipboardChanged("cut");
  EXPECT_EQ("StarStar", GetClipboardText());
  WaitForEditableValue(
      (editable_type() == EditableType::kContentEditable) ? "\n" : "");
  SendFinalResultAndWaitForEditableValue("  PaStE ", "StarStar");
}

// Ensures that a metric is recorded when a macro succeeds.
// TODO(crbug.com/1288964): Add a test to ensure that a metric is recorded when
// a macro fails.
IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, MacroSucceededMetric) {
  base::HistogramTester histogram_tester_;
  SendFinalResultAndWaitForEditableValue("Vega is the brightest star in Lyra",
                                         "Vega is the brightest star in Lyra");
  histogram_tester_.ExpectUniqueSample(/*name=*/kMacroSucceededMetric,
                                       /*sample=*/kInputTextViewMetricValue,
                                       /*expected_bucket_count=*/1);
  histogram_tester_.ExpectUniqueSample(/*name=*/kMacroFailedMetric,
                                       /*sample=*/kInputTextViewMetricValue,
                                       /*expected_bucket_count=*/0);
  histogram_tester_.ExpectUniqueSample(/*name=*/kMacroRecognizedMetric,
                                       /*sample=*/kInputTextViewMetricValue,
                                       /*expected_bucket_count=*/1);
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeletePrevWordSimple) {
  SendFinalResultAndWaitForEditableValue("This is a test", "This is a test");
  SendFinalResultAndWaitForEditableValue("delete the previous word",
                                         "This is a ");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeletePrevWordExtraSpace) {
  SendFinalResultAndWaitForEditableValue("This is a test ", "This is a test ");
  SendFinalResultAndWaitForEditableValue("delete the previous word",
                                         "This is a ");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeletePrevWordNewLine) {
  if (!RunOnMultilineContent())
    return;

  SendFinalResultAndWaitForEditableValue("This is a test\n\n",
                                         "This is a test\n\n");
  SendFinalResultAndWaitForEditableValue("delete the previous word",
                                         "This is a test\n");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeletePrevWordPunctuation) {
  SendFinalResultAndWaitForEditableValue("This.is.a.test. ",
                                         "This.is.a.test. ");
  SendFinalResultAndWaitForEditableValue("delete the previous word",
                                         "This.is.a.test");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeletePrevWordMiddleOfWord) {
  SendFinalResultAndWaitForEditableValue("This is a test.", "This is a test.");
  // Move the text caret into the middle of the word "test".
  SendFinalResultAndWaitForSelection("Move to the Previous character", 14, 14);
  SendFinalResultAndWaitForSelection("Move to the Previous character", 13, 13);
  SendFinalResultAndWaitForEditableValue("delete the previous word",
                                         "This is a t.");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeletePrevSentSimple) {
  SendFinalResultAndWaitForEditableValue("Hello, world.", "Hello, world.");
  SendFinalResultAndWaitForEditableValue(
      "delete the previous sentence",
      (editable_type() == EditableType::kContentEditable) ? "\n" : "");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeletePrevSentWhiteSpace) {
  if (!RunOnMultilineContent())
    return;

  SendFinalResultAndWaitForEditableValue("  \nHello, world.\n  ",
                                         "  \nHello, world.\n  ");
  SendFinalResultAndWaitForEditableValue("delete the previous sentence", "");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeletePrevSentPunctuation) {
  SendFinalResultAndWaitForEditableValue(
      "Hello, world! Good afternoon; good evening? Goodnight, world.",
      "Hello, world! Good afternoon; good evening? Goodnight, world.");
  SendFinalResultAndWaitForEditableValue(
      "delete the previous sentence",
      "Hello, world! Good afternoon; good evening?");
  SendFinalResultAndWaitForEditableValue("delete the previous sentence",
                                         "Hello, world! Good afternoon;");
  SendFinalResultAndWaitForEditableValue("delete the previous sentence",
                                         "Hello, world!");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, DeletePrevSentTwoSentences) {
  SendFinalResultAndWaitForEditableValue("Hello, world. Goodnight, world.",
                                         "Hello, world. Goodnight, world.");
  SendFinalResultAndWaitForEditableValue("delete the previous sentence",
                                         "Hello, world.");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       DeletePrevSentMiddleOfSentence) {
  SendFinalResultAndWaitForEditableValue("Hello, world. Goodnight, world.",
                                         "Hello, world. Goodnight, world.");
  // Move the text caret into the middle of the second sentence.
  SendFinalResultAndWaitForSelection("Move to the Previous character", 30, 30);
  SendFinalResultAndWaitForSelection("Move to the Previous character", 29, 29);
  SendFinalResultAndWaitForEditableValue("delete the previous sentence",
                                         "Hello, world.d.");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, MoveByWord) {
  SendFinalResultAndWaitForEditableValue("This is a quiz", "This is a quiz");
  SendFinalResultAndWaitForSelection("move to the previous word", 10, 10);
  SendFinalResultAndWaitForEditableValue("pop ", "This is a pop quiz");
  SendFinalResultAndWaitForSelection("move to the next word", 18, 18);
  SendFinalResultAndWaitForEditableValue("folks!", "This is a pop quiz folks!");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, SmartDeletePhraseSimple) {
  SendFinalResultAndWaitForEditableValue("This is a difficult test",
                                         "This is a difficult test");
  SendFinalResultAndWaitForEditableValue("delete difficult", "This is a test");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       SmartDeletePhraseCaseInsensitive) {
  SendFinalResultAndWaitForEditableValue("This is a DIFFICULT test",
                                         "This is a DIFFICULT test");
  SendFinalResultAndWaitForEditableValue("delete difficult", "This is a test");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       SmartDeletePhraseDuplicateMatches) {
  SendFinalResultAndWaitForEditableValue("The cow jumped over the moon.",
                                         "The cow jumped over the moon.");
  // Deletes the right-most occurrence of "the".
  SendFinalResultAndWaitForEditableValue("delete the",
                                         "The cow jumped over moon.");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       SmartDeletePhraseDeletesLeftOfCaret) {
  SendFinalResultAndWaitForEditableValue("The cow jumped over the moon.",
                                         "The cow jumped over the moon.");
  SendFinalResultAndWaitForSelection("move to the previous word", 28, 28);
  SendFinalResultAndWaitForSelection("move to the previous word", 24, 24);
  SendFinalResultAndWaitForSelection("move to the previous word", 20, 20);
  SendFinalResultAndWaitForEditableValue("delete the",
                                         "cow jumped over the moon.");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       SmartDeletePhraseDeletesAtWordBoundaries) {
  SendFinalResultAndWaitForEditableValue("A square is also a rectangle.",
                                         "A square is also a rectangle.");
  // Deletes the first word "a", not the first character "a".
  SendFinalResultAndWaitForEditableValue("delete a",
                                         "A square is also rectangle.");
}

// TODO(crbug.com/40901980): Test is flaky.
IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       DISABLED_SmartReplacePhrase) {
  SendFinalResultAndWaitForEditableValue("This is a difficult test.",
                                         "This is a difficult test.");
  SendFinalResultAndWaitForEditableValue("replace difficult with simple",
                                         "This is a simple test.");
  SendFinalResultAndWaitForEditableValue("replace is with isn't",
                                         "This isn't a simple test.");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, SmartInsertBefore) {
  SendFinalResultAndWaitForEditableValue("This is a test.", "This is a test.");
  SendFinalResultAndWaitForEditableValue("insert simple before test",
                                         "This is a simple test.");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, SmartSelectBetween) {
  SendFinalResultAndWaitForEditableValue("This is a test.", "This is a test.");
  SendFinalResultAndWaitForSelection("select from this to test", 0, 14);
  SendFinalResultAndWaitForEditableValue("Hello world", "Hello world.");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, MoveBySentence) {
  SendFinalResultAndWaitForEditableValue("Hello world! Goodnight world?",
                                         "Hello world! Goodnight world?");
  SendFinalResultAndWaitForSelection("move to the previous sentence", 12, 12);
  SendFinalResultAndWaitForEditableValue(
      "Good evening.", "Hello world! Good evening. Goodnight world?");
  SendFinalResultAndWaitForSelection("move to the next sentence", 43, 43);
  SendFinalResultAndWaitForEditableValue(
      "Time for a midnight snack",
      "Hello world! Good evening. Goodnight world? Time for a midnight snack");
}

// CursorPosition... tests verify the new cursor position after a command is
// performed. The new cursor position is verified by inserting text after the
// command under test is performed.

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       CursorPositionDeleteSentence) {
  SendFinalResultAndWaitForEditableValue("First. Second.", "First. Second.");
  SendFinalResultAndWaitForEditableValue("delete the previous sentence",
                                         "First.");
  SendFinalResultAndWaitForEditableValue("Third.", "First. Third.");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       CursorPositionSmartDeletePhrase) {
  SendFinalResultAndWaitForEditableValue("This is a difficult test",
                                         "This is a difficult test");
  SendFinalResultAndWaitForEditableValue("delete difficult", "This is a test");
  SendFinalResultAndWaitForEditableValue("simple", "This is a simple test");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       CursorPositionSmartReplacePhrase) {
  SendFinalResultAndWaitForEditableValue("This is a difficult test",
                                         "This is a difficult test");
  SendFinalResultAndWaitForEditableValue("replace difficult with simple",
                                         "This is a simple test");
  SendFinalResultAndWaitForEditableValue("biology",
                                         "This is a simple biology test");
  SendFinalResultAndWaitForEditableValue(
      "and chemistry", "This is a simple biology and chemistry test");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       CursorPositionSmartInsertBefore) {
  SendFinalResultAndWaitForEditableValue("This is a test", "This is a test");
  SendFinalResultAndWaitForEditableValue("insert simple before test",
                                         "This is a simple test");
  SendFinalResultAndWaitForEditableValue("biology",
                                         "This is a simple biology test");
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest,
                       SmartDeletePhraseLongContent) {
  if (!RunOnMultilineContent())
    return;

  std::string first_sentence_initial = R"(
    The dog (Canis familiaris or Canis lupus familiaris) is a domesticated
    descendant of the wolf.
  )";
  // The same as above, except the second instance of "familiaris" is removed.
  std::string first_sentence_final = R"(
    The dog (Canis familiaris or Canis lupus) is a domesticated
    descendant of the wolf.
  )";
  std::string remaining_text = R"(
    Also called the domestic dog, it is derived from an
    ancient, extinct wolf, and the modern wolf is the dog's nearest living
    relative. The dog was the first species to be domesticated, by
    hunter-gatherers over 15,000 years ago, before the development of
    agriculture. Due to their long association with humans, dogs have expanded
    to a large number of domestic individuals and gained the ability to thrive
    on a starch-rich diet that would be inadequate for other canids.

    The dog has been selectively bred over millennia for various behaviors,
    sensory capabilities, and physical attributes. Dog breeds vary widely in
    shape, size, and color. They perform many roles for humans, such as hunting,
    herding, pulling loads, protection, assisting police and the military,
    companionship, therapy, and aiding disabled people. Over the millennia, dogs
    became uniquely adapted to human behavior, and the human-canine bond has
    been a topic of frequent study. This influence on human society has given
    them the sobriquet of "man's best friend".
  )";

  std::string initial_value = first_sentence_initial + remaining_text;
  std::string final_value = first_sentence_final + remaining_text;
  SendFinalResultAndWaitForEditableValue(initial_value, initial_value);
  SendFinalResultAndWaitForEditableValue("delete familiaris", final_value);
}

IN_PROC_BROWSER_TEST_P(DictationRegexCommandsTest, Metrics) {
  base::HistogramTester histogram_tester_;
  HistogramWaiter waiter(kPumpkinUsedMetric);
  SendFinalResultAndWait("Undo");
  waiter.Wait();
  content::FetchHistogramsFromChildProcesses();
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester_.ExpectUniqueSample(/*name=*/kPumpkinUsedMetric,
                                       /*sample=*/false,
                                       /*expected_bucket_count=*/1);
}

// Tests the behavior of the Dictation bubble UI.
class DictationUITest : public DictationTest {
 public:
  DictationUITest() = default;
  ~DictationUITest() override = default;
  DictationUITest(const DictationUITest&) = delete;
  DictationUITest& operator=(const DictationUITest&) = delete;

 protected:
  void SetUpOnMainThread() override {
    DictationTest::SetUpOnMainThread();
    dictation_bubble_test_helper_ =
        std::make_unique<DictationBubbleTestHelper>();
  }

  void TearDownOnMainThread() override {
    dictation_bubble_test_helper_.reset();
    DictationTest::TearDownOnMainThread();
  }

  void WaitForProperties(
      bool visible,
      DictationBubbleIconType icon,
      const std::optional<std::u16string>& text,
      const std::optional<std::vector<std::u16string>>& hints) {
    dictation_bubble_test_helper_->WaitForVisibility(visible);
    dictation_bubble_test_helper_->WaitForVisibleIcon(icon);
    if (text.has_value())
      dictation_bubble_test_helper_->WaitForVisibleText(text.value());
    if (hints.has_value())
      dictation_bubble_test_helper_->WaitForVisibleHints(hints.value());
  }

 private:
  std::unique_ptr<DictationBubbleTestHelper> dictation_bubble_test_helper_;
};

INSTANTIATE_TEST_SUITE_P(
    NetworkTextArea,
    DictationUITest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kTextArea,
                                 ManifestVersion::kTwo)));

IN_PROC_BROWSER_TEST_P(DictationUITest, ShownWhenSpeechRecognitionStarts) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kStandby,
                    /*text=*/std::optional<std::u16string>(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
}

IN_PROC_BROWSER_TEST_P(DictationUITest, DisplaysInterimSpeechResults) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  // Send an interim speech result.
  SendInterimResultAndWait("Testing");
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kHidden,
                    /*text=*/u"Testing",
                    /*hints=*/std::optional<std::vector<std::u16string>>());
}

IN_PROC_BROWSER_TEST_P(DictationUITest, DisplaysMacroSuccess) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  // Perform a command.
  SendFinalResultAndWait("Select all");
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kMacroSuccess,
                    /*text=*/u"Select all",
                    /*hints=*/std::optional<std::vector<std::u16string>>());
  // UI should return to standby mode after a timeout.
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kStandby,
                    /*text=*/std::u16string(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
}

IN_PROC_BROWSER_TEST_P(DictationUITest,
                       ResetsToStandbyModeAfterFinalSpeechResult) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kStandby,
                    /*text=*/std::optional<std::u16string>(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
  // Send an interim speech result.
  SendInterimResultAndWait("Testing");
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kHidden,
                    /*text=*/u"Testing",
                    /*hints=*/std::optional<std::vector<std::u16string>>());
  // Send a final speech result. UI should return to standby mode.
  SendFinalResultAndWait("Testing 123");
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kStandby,
                    /*text=*/std::u16string(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
}

IN_PROC_BROWSER_TEST_P(DictationUITest, HiddenWhenDictationDeactivates) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kStandby,
                    /*text=*/std::optional<std::u16string>(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
  // The UI should be hidden when Dictation deactivates.
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
  WaitForProperties(/*visible=*/false,
                    /*icon=*/DictationBubbleIconType::kHidden,
                    /*text=*/std::u16string(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
}

IN_PROC_BROWSER_TEST_P(DictationUITest, StandbyHints) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kStandby,
                    /*text=*/std::optional<std::u16string>(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
  // Hints should show up after a few seconds without speech.
  WaitForProperties(
      /*visible=*/true,
      /*icon=*/DictationBubbleIconType::kStandby,
      /*text=*/std::optional<std::u16string>(),
      /*hints=*/std::vector<std::u16string>{kTrySaying, kType, kHelp});
}

// Ensures that Search + D can be used to toggle Dictation when ChromeVox is
// active. Also verifies that ChromeVox announces hints when they are shown in
// the Dictation UI.
IN_PROC_BROWSER_TEST_P(DictationUITest, ChromeVoxAnnouncesHints) {
  // Setup ChromeVox first.
  ChromeVoxTestUtils chromevox_test_utils;
  chromevox_test_utils.EnableChromeVox();
  EXPECT_TRUE(GetManager()->IsSpokenFeedbackEnabled());

  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();

  // Hints should show up after a few seconds without speech.
  WaitForProperties(
      /*visible=*/true,
      /*icon=*/DictationBubbleIconType::kStandby,
      /*text=*/std::optional<std::u16string>(),
      /*hints=*/std::vector<std::u16string>{kTrySaying, kType, kHelp});

  // Assert speech from ChromeVox.
  chromevox_test_utils.sm()->ExpectSpeechPattern("Try saying*Type*Help*");
  chromevox_test_utils.sm()->Replay();

  // Check that Chromevox changed to a different pitch to announce hints. Note
  // that only if the whole text pattern used the same parameters this will
  // match.
  auto params =
      chromevox_test_utils.sm()->GetParamsForPreviouslySpokenTextPattern(
          "*Try saying*Type*Help*");
  ASSERT_TRUE(params);

  // Note: the Chromevox personality that sets this value has a relative pitch
  // of 0.3, so that's how this turns into 1.3.
  EXPECT_DOUBLE_EQ(params->pitch, 1.3);
}

IN_PROC_BROWSER_TEST_P(DictationUITest, HintsShownWhenTextCommitted) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();

  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kStandby,
                    /*text=*/std::optional<std::u16string>(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());

  // Send a final speech result. UI should return to standby mode.
  SendFinalResultAndWait("Testing");
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kStandby,
                    /*text=*/std::u16string(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());

  // Hints should show up after a few seconds without speech.
  WaitForProperties(
      /*visible=*/true,
      /*icon=*/DictationBubbleIconType::kStandby,
      /*text=*/std::optional<std::u16string>(),
      /*hints=*/
      std::vector<std::u16string>{kTrySaying, kUndo, kDelete, kSelectAll,
                                  kHelp});
}

IN_PROC_BROWSER_TEST_P(DictationUITest, HintsShownAfterTextSelected) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();

  // Perform a select all command.
  SendFinalResultAndWaitForEditableValue("Vega is the brightest star in Lyra",
                                         "Vega is the brightest star in Lyra");
  SendFinalResultAndWaitForSelection("Select all", 0, 34);
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kMacroSuccess,
                    /*text=*/u"Select all",
                    /*hints=*/std::optional<std::vector<std::u16string>>());

  // UI should return to standby mode with hints after a few seconds without
  // speech.
  WaitForProperties(
      /*visible=*/true,
      /*icon=*/DictationBubbleIconType::kStandby,
      /*text=*/std::optional<std::u16string>(),
      /*hints=*/
      std::vector<std::u16string>{kTrySaying, kUnselect, kCopy, kDelete,
                                  kHelp});
}

IN_PROC_BROWSER_TEST_P(DictationUITest, HintsShownAfterCommandExecuted) {
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();

  // Perform a command.
  SendFinalResultAndWait("Move to the previous character");
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kMacroSuccess,
                    /*text=*/u"Move to the previous character",
                    /*hints=*/std::optional<std::vector<std::u16string>>());

  // UI should return to standby mode with hints after a few seconds without
  // speech.
  WaitForProperties(
      /*visible=*/true,
      /*icon=*/DictationBubbleIconType::kStandby,
      /*text=*/std::optional<std::u16string>(),
      /*hints=*/std::vector<std::u16string>{kTrySaying, kUndo, kHelp});
}

// Tests behavior of Dictation using the Pumpkin semantic parser.
class DictationPumpkinTest : public DictationTest {
 public:
  DictationPumpkinTest() = default;
  ~DictationPumpkinTest() = default;
  DictationPumpkinTest(const DictationPumpkinTest&) = delete;
  DictationPumpkinTest& operator=(const DictationPumpkinTest&) = delete;

 protected:
  void SetUpOnMainThread() override {
    DictationTest::SetUpOnMainThread();
    ToggleDictationWithKeystroke();
    WaitForRecognitionStarted();
  }

  void TearDownOnMainThread() override {
    ToggleDictationWithKeystroke();
    WaitForRecognitionStopped();
    DictationTest::TearDownOnMainThread();
  }
};

INSTANTIATE_TEST_SUITE_P(
    NetworkTextArea,
    DictationPumpkinTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kTextArea,
                                 ManifestVersion::kTwo)));

INSTANTIATE_TEST_SUITE_P(
    NetworkContentEditable,
    DictationPumpkinTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kContentEditable,
                                 ManifestVersion::kTwo)));

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, Input) {
  SendFinalResultAndWaitForEditableValue("dictate hello", "Hello");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, DeletePrevCharacter) {
  SendFinalResultAndWaitForEditableValue("Testing", "Testing");
  SendFinalResultAndWaitForEditableValue("Delete three characters", "Test");
  SendFinalResultAndWaitForEditableValue("backspace", "Tes");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, NavByCharacter) {
  SendFinalResultAndWaitForEditableValue("Testing", "Testing");
  SendFinalResultAndWaitForSelection("left three characters", 4, 4);
  SendFinalResultAndWaitForEditableValue("!", "Test!ing");
  SendFinalResultAndWaitForSelection("right two characters", 7, 7);
  SendFinalResultAndWaitForEditableValue("@", "Test!in@g");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, NavByLine) {
  if (!RunOnMultilineContent())
    return;

  std::string text = "Line1\nLine2\nLine3\nLine4";
  SendFinalResultAndWaitForEditableValue(text, text);
  SendFinalResultAndWaitForSelection("Up two lines", 11, 11);
  std::string expected = "Line1\nLine2 insertion\nLine3\nLine4";
  SendFinalResultAndWaitForEditableValue("insertion", expected);
  SendFinalResultAndWaitForSelection("down two lines", 33, 33);
  expected = "Line1\nLine2 insertion\nLine3\nLine4 second insertion";
  SendFinalResultAndWaitForEditableValue("second insertion", expected);
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, CutCopyPasteSelectAll) {
  SendFinalResultAndWaitForEditableValue("Star", "Star");
  SendFinalResultAndWaitForSelection("Select everything", 0, 4);
  SendFinalResultAndWaitForClipboardChanged("Copy selected text");
  EXPECT_EQ("Star", GetClipboardText());
  SendFinalResultAndWaitForSelection("unselect selection", 4, 4);
  SendFinalResultAndWaitForEditableValue("paste copied text", "StarStar");
  SendFinalResultAndWaitForSelection("highlight everything", 0, 8);
  SendFinalResultAndWaitForClipboardChanged("cut highlighted text");
  EXPECT_EQ("StarStar", GetClipboardText());
  WaitForEditableValue(
      (editable_type() == EditableType::kContentEditable) ? "\n" : "");
  SendFinalResultAndWaitForEditableValue("paste the copied text", "StarStar");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, UndoAndRedo) {
  SendFinalResultAndWaitForEditableValue("The constellation",
                                         "The constellation");
  SendFinalResultAndWaitForEditableValue("myra", "The constellation myra");
  SendFinalResultAndWaitForEditableValue("take that back", "The constellation");
  SendFinalResultAndWaitForEditableValue("Lyra", "The constellation lyra");
  SendFinalResultAndWaitForEditableValue("undo that", "The constellation");
  SendFinalResultAndWaitForEditableValue("redo that", "The constellation lyra");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, DeletePrevWord) {
  SendFinalResultAndWaitForEditableValue("This is a test", "This is a test");
  SendFinalResultAndWaitForEditableValue("clear one word", "This is a ");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, DeletePrevSent) {
  SendFinalResultAndWaitForEditableValue("Hello, world.", "Hello, world.");
  SendFinalResultAndWaitForEditableValue(
      "erase sentence",
      (editable_type() == EditableType::kContentEditable) ? "\n" : "");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, MoveByWord) {
  SendFinalResultAndWaitForEditableValue("This is a quiz", "This is a quiz");
  SendFinalResultAndWaitForSelection("back one word", 10, 10);
  SendFinalResultAndWaitForEditableValue("pop", "This is a pop quiz");
  SendFinalResultAndWaitForSelection("right one word", 18, 18);
  SendFinalResultAndWaitForEditableValue("folks!", "This is a pop quiz folks!");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, SmartDeletePhrase) {
  SendFinalResultAndWaitForEditableValue("This is a difficult test",
                                         "This is a difficult test");
  SendFinalResultAndWaitForEditableValue("erase difficult", "This is a test");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, SmartReplacePhrase) {
  SendFinalResultAndWaitForEditableValue("This is a difficult test.",
                                         "This is a difficult test.");
  SendFinalResultAndWaitForEditableValue("substitute difficult with simple",
                                         "This is a simple test.");
  SendFinalResultAndWaitForEditableValue("replace is with isn't",
                                         "This isn't a simple test.");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, SmartInsertBefore) {
  SendFinalResultAndWaitForEditableValue("This is a test.", "This is a test.");
  SendFinalResultAndWaitForEditableValue("insert simple in front of test",
                                         "This is a simple test.");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, SmartSelectBetween) {
  SendFinalResultAndWaitForEditableValue("This is a test.", "This is a test.");
  SendFinalResultAndWaitForSelection("highlight everything between is and test",
                                     5, 14);
  SendFinalResultAndWaitForEditableValue("was a quiz", "This was a quiz.");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, MoveBySentence) {
  SendFinalResultAndWaitForEditableValue("Hello world! Goodnight world?",
                                         "Hello world! Goodnight world?");
  SendFinalResultAndWaitForSelection("one sentence back", 12, 12);
  SendFinalResultAndWaitForEditableValue(
      "Good evening.", "Hello world! Good evening. Goodnight world?");
  SendFinalResultAndWaitForSelection("forward one sentence", 43, 43);
  SendFinalResultAndWaitForEditableValue(
      "Time for a midnight snack",
      "Hello world! Good evening. Goodnight world? Time for a midnight snack");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, DeleteAllText) {
  SendFinalResultAndWaitForEditableValue("Hello, world.", "Hello, world.");
  SendFinalResultAndWaitForEditableValue(
      "clear", (editable_type() == EditableType::kContentEditable) ? "\n" : "");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, NavStartText) {
  SendFinalResultAndWaitForEditableValue("Is good", "Is good");
  SendFinalResultAndWaitForSelection("to start", 0, 0);
  SendFinalResultAndWaitForEditableValue("The weather outside",
                                         "The weather outside Is good");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, NavEndText) {
  SendFinalResultAndWaitForEditableValue("The weather outside is",
                                         "The weather outside is");
  SendFinalResultAndWaitForSelection("to start", 0, 0);
  SendFinalResultAndWaitForSelection("to end", 22, 22);
  std::string expected = "The weather outside is good";
  SendFinalResultAndWaitForEditableValue("good", expected);
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, SelectPrevWord) {
  SendFinalResultAndWaitForEditableValue("The weather today is bad",
                                         "The weather today is bad");
  SendFinalResultAndWaitForSelection("highlight back one word", 21, 24);
  std::string expected = "The weather today is nice";
  SendFinalResultAndWaitForEditableValue("nice", expected);
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, SelectNextWord) {
  SendFinalResultAndWaitForEditableValue("The weather today is bad",
                                         "The weather today is bad");
  SendFinalResultAndWaitForSelection("move to the previous word", 21, 21);
  SendFinalResultAndWaitForSelection("highlight right one word", 21, 24);
  std::string expected = "The weather today is nice";
  SendFinalResultAndWaitForEditableValue("nice", expected);
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, SelectNextChar) {
  SendFinalResultAndWaitForEditableValue("Text", "Text");
  SendFinalResultAndWaitForSelection("move to the previous word", 0, 0);
  SendFinalResultAndWaitForSelection("select next letter", 0, 1);
  std::string expected = "ext";
  SendFinalResultAndWaitForEditableValue("delete", expected);
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, SelectPrevChar) {
  SendFinalResultAndWaitForEditableValue("Text", "Text");
  SendFinalResultAndWaitForSelection("select previous letter", 3, 4);
  std::string expected = "Tex";
  SendFinalResultAndWaitForEditableValue("delete", expected);
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, Repeat) {
  SendFinalResultAndWaitForEditableValue("Test", "Test");
  SendFinalResultAndWaitForEditableValue("delete", "Tes");
  SendFinalResultAndWaitForEditableValue("try that action again", "Te");
  // Repeat also works for inputting text.
  SendFinalResultAndWaitForEditableValue("keyboard cat", "Te keyboard cat");
  SendFinalResultAndWaitForEditableValue("again",
                                         "Te keyboard cat keyboard cat");
}

IN_PROC_BROWSER_TEST_P(DictationPumpkinTest, Metrics) {
  base::HistogramTester histogram_tester_;
  HistogramWaiter used_waiter(kPumpkinUsedMetric);
  HistogramWaiter succeeded_waiter(kPumpkinSucceededMetric);
  SendFinalResultAndWaitForEditableValue("dictate hello", "Hello");
  used_waiter.Wait();
  succeeded_waiter.Wait();
  content::FetchHistogramsFromChildProcesses();
  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  histogram_tester_.ExpectUniqueSample(/*name=*/kPumpkinUsedMetric,
                                       /*sample=*/true,
                                       /*expected_bucket_count=*/1);
  histogram_tester_.ExpectUniqueSample(/*name=*/kPumpkinSucceededMetric,
                                       /*sample=*/true,
                                       /*expected_bucket_count=*/1);
}

class DictationContextCheckingTest : public DictationTest {
 public:
  DictationContextCheckingTest() = default;
  ~DictationContextCheckingTest() override = default;
  DictationContextCheckingTest(const DictationContextCheckingTest&) = delete;
  DictationContextCheckingTest& operator=(const DictationContextCheckingTest&) =
      delete;

 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    DictationTest::SetUpCommandLine(command_line);

    std::vector<base::test::FeatureRef> enabled_features;
    enabled_features.emplace_back(base::test::FeatureRef(
        ::features::kExperimentalAccessibilityDictationContextChecking));
    scoped_feature_list_.InitWithFeatures(
        enabled_features, std::vector<base::test::FeatureRef>());
  }

  void SetUpOnMainThread() override {
    DictationTest::SetUpOnMainThread();
    ToggleDictationWithKeystroke();
    WaitForRecognitionStarted();
    dictation_bubble_test_helper_ =
        std::make_unique<DictationBubbleTestHelper>();
  }

  void TearDownOnMainThread() override {
    ToggleDictationWithKeystroke();
    WaitForRecognitionStopped();
    DictationTest::TearDownOnMainThread();
  }

  void WaitForProperties(
      bool visible,
      DictationBubbleIconType icon,
      const std::optional<std::u16string>& text,
      const std::optional<std::vector<std::u16string>>& hints) {
    dictation_bubble_test_helper_->WaitForVisibility(visible);
    dictation_bubble_test_helper_->WaitForVisibleIcon(icon);
    if (text.has_value()) {
      dictation_bubble_test_helper_->WaitForVisibleText(text.value());
    }
    if (hints.has_value()) {
      dictation_bubble_test_helper_->WaitForVisibleHints(hints.value());
    }
  }

  // Attempts to run `command` within an empty editable and waits for the UI to
  // show the appropriate context-checking failure.
  void RunEmptyEditableTest(const std::string& command) {
    SendFinalResultAndWait(command);
    std::u16string message =
        u"Can't " + base::ASCIIToUTF16(command) + u", text field is empty";
    WaitForProperties(
        /*visible=*/true,
        /*icon=*/DictationBubbleIconType::kMacroFail,
        /*text=*/message,
        /*hints=*/std::optional<std::vector<std::u16string>>());
  }

  // Attempts to run `command` on an editable with no selection and waits for
  // the UI to show the appropriate context-checking failure.
  void RunNoSelectionTest(const std::string& command) {
    SendFinalResultAndWaitForEditableValue("Hello world", "Hello world");
    SendFinalResultAndWait(command);
    std::u16string message =
        u"Can't " + base::ASCIIToUTF16(command) + u", no selected text";
    WaitForProperties(
        /*visible=*/true,
        /*icon=*/DictationBubbleIconType::kMacroFail,
        /*text=*/message,
        /*hints=*/std::optional<std::vector<std::u16string>>());
    SendFinalResultAndWaitForEditableValue(
        "delete all",
        (editable_type() == EditableType::kContentEditable) ? "\n" : "");
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
  std::unique_ptr<DictationBubbleTestHelper> dictation_bubble_test_helper_;
};

INSTANTIATE_TEST_SUITE_P(
    NetworkInput,
    DictationContextCheckingTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kInput,
                                 ManifestVersion::kTwo)));

INSTANTIATE_TEST_SUITE_P(
    NetworkContentEditable,
    DictationContextCheckingTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kContentEditable,
                                 ManifestVersion::kTwo)));

IN_PROC_BROWSER_TEST_P(DictationContextCheckingTest, EmptyEditable) {
  std::vector<std::string> commands{
      "unselect",
      "cut",
      "copy",
      "delete one character",
      "left one character",
      "right one character",
      "up one line",
      "down one line",
      "select all",
      "delete one word",
      "delete one sentence",
      "right one word",
      "left one word",
      "delete the phrase hello",
      "replace hello with world",
      "insert hello before world",
      "select between hello and world",
      "left one sentence",
      "right one sentence",
      "delete all",
      "to start",
      "to end",
      "select previous word",
      "select next word",
      "select previous letter",
      "select next letter",
  };

  for (const auto& command : commands) {
    RunEmptyEditableTest(command);
  }
}

IN_PROC_BROWSER_TEST_P(DictationContextCheckingTest, NoSelection) {
  std::vector<std::string> commands{
      "unselect",
      "cut",
      "copy",
  };

  for (const auto& command : commands) {
    RunNoSelectionTest(command);
  }
}

IN_PROC_BROWSER_TEST_P(DictationContextCheckingTest, UnselectSuccessful) {
  std::string text = "Hello world";
  SendFinalResultAndWaitForEditableValue(text, text);
  SendFinalResultAndWaitForSelection("Select all", 0, 11);
  SendFinalResultAndWaitForSelection("Unselect", 11, 11);
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kMacroSuccess,
                    /*text=*/std::optional<std::u16string>(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
}

IN_PROC_BROWSER_TEST_P(DictationContextCheckingTest, CutSuccessful) {
  std::string text = "Hello world";
  SendFinalResultAndWaitForEditableValue(text, text);
  SendFinalResultAndWaitForSelection("Select all", 0, 11);
  SendFinalResultAndWaitForClipboardChanged("Cut");
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kMacroSuccess,
                    /*text=*/std::optional<std::u16string>(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
}

IN_PROC_BROWSER_TEST_P(DictationContextCheckingTest, CopySuccessful) {
  std::string text = "Hello world";
  SendFinalResultAndWaitForEditableValue(text, text);
  SendFinalResultAndWaitForSelection("Select all", 0, 11);
  SendFinalResultAndWaitForClipboardChanged("Copy");
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kMacroSuccess,
                    /*text=*/std::optional<std::u16string>(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
}

IN_PROC_BROWSER_TEST_P(DictationContextCheckingTest, RepeatFail) {
  SendFinalResultAndWait("repeat");
  WaitForProperties(
      /*visible=*/true,
      /*icon=*/DictationBubbleIconType::kMacroFail,
      /*text=*/u"Can't repeat, no previous command",
      /*hints=*/std::optional<std::vector<std::u16string>>());
}

IN_PROC_BROWSER_TEST_P(DictationContextCheckingTest, RepeatFailUnselect) {
  RunEmptyEditableTest("unselect");
  // Wait for UI to return to standby mode.
  WaitForProperties(/*visible=*/true,
                    /*icon=*/DictationBubbleIconType::kStandby,
                    /*text=*/std::optional<std::u16string>(),
                    /*hints=*/std::optional<std::vector<std::u16string>>());
  RunEmptyEditableTest("repeat");
}

IN_PROC_BROWSER_TEST_P(DictationContextCheckingTest, RepeatSuccessful) {
  SendFinalResultAndWaitForEditableValue("Test", "Test");
  SendFinalResultAndWaitForEditableValue("Repeat", "Test test");
  SendFinalResultAndWaitForEditableValue("Repeat", "Test test test");
}

class NotificationCenterDictationTest : public DictationTest {
 public:
  NotificationCenterDictationTest() = default;
  NotificationCenterDictationTest(const NotificationCenterDictationTest&) =
      delete;
  NotificationCenterDictationTest& operator=(
      const NotificationCenterDictationTest&) = delete;
  ~NotificationCenterDictationTest() override = default;

 protected:
  void SetUpOnMainThread() override {
    DictationTest::SetUpOnMainThread();
    ToggleDictationWithKeystroke();
    WaitForRecognitionStarted();
  }

  void TearDownOnMainThread() override {
    ToggleDictationWithKeystroke();
    WaitForRecognitionStopped();
    DictationTest::TearDownOnMainThread();
  }

  NotificationCenterTestApi* test_api() {
    if (!test_api_) {
      test_api_ = std::make_unique<NotificationCenterTestApi>();
    }
    return test_api_.get();
  }

 private:
  std::unique_ptr<NotificationCenterTestApi> test_api_;
};

INSTANTIATE_TEST_SUITE_P(
    NetworkTextArea,
    NotificationCenterDictationTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kTextArea,
                                 ManifestVersion::kTwo)));

// Tests that clicking the notification center tray does not crash when
// dictation is enabled.
IN_PROC_BROWSER_TEST_P(NotificationCenterDictationTest, OpenBubble) {
  // Add a notification to ensure the tray is visible.
  test_api()->AddNotification();
  ASSERT_TRUE(test_api()->IsTrayShown());

  // Click on the tray and verify the bubble shows up.
  test_api()->ToggleBubble();
  EXPECT_TRUE(test_api()->GetWidget()->IsActive());
  EXPECT_TRUE(test_api()->IsBubbleShown());
}

// A test class that only runs on formatted content editables.
class DictationFormattedContentEditableTest : public DictationPumpkinTest {
 public:
  DictationFormattedContentEditableTest() = default;
  ~DictationFormattedContentEditableTest() override = default;
  DictationFormattedContentEditableTest(
      const DictationFormattedContentEditableTest&) = delete;
  DictationFormattedContentEditableTest& operator=(
      const DictationFormattedContentEditableTest&) = delete;

 protected:
  void SetUpOnMainThread() override {
    DictationPumpkinTest::SetUpOnMainThread();

    // Place the selection at the end of the content editable (the pre-populated
    // editable value has a length of 14).
    std::string script = "dictationTestSupport.setSelection(14, 14);";
    ExecuteAccessibilityCommonScript(script);
  }
};

// Note: For these tests, the content editable comes pre-populated with a value
// of "This is a test". See `kFormattedContentEditableUrl` for more details.
INSTANTIATE_TEST_SUITE_P(
    NetworkFormattedContentEditable,
    DictationFormattedContentEditableTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kFormattedContentEditable,
                                 ManifestVersion::kTwo)));

IN_PROC_BROWSER_TEST_P(DictationFormattedContentEditableTest, DeletePhrase) {
  SendFinalResultAndWaitForEditableValue("delete a", "This is test");
}

IN_PROC_BROWSER_TEST_P(DictationFormattedContentEditableTest,
                       ReplacePhraseMultipleWords) {
  std::string command = "replace the phrase is a test with was just one exam";
  std::string expected_value = "This was just one exam";
  SendFinalResultAndWaitForEditableValue(command, expected_value);
}

IN_PROC_BROWSER_TEST_P(DictationFormattedContentEditableTest,
                       ReplacePhraseFirstWord) {
  std::string command = "replace this with it";
  std::string expected_value = "It is a test";
  SendFinalResultAndWaitForEditableValue(command, expected_value);
}

IN_PROC_BROWSER_TEST_P(DictationFormattedContentEditableTest,
                       ReplacePhraseLastWord) {
  std::string command = "replace test with quiz";
  std::string expected_value = "This is a quiz";
  SendFinalResultAndWaitForEditableValue(command, expected_value);
}

IN_PROC_BROWSER_TEST_P(DictationFormattedContentEditableTest, InsertBefore) {
  std::string command = "insert the phrase simple before test";
  std::string expected_value = "This is a simple test";
  SendFinalResultAndWaitForEditableValue(command, expected_value);
}

IN_PROC_BROWSER_TEST_P(DictationFormattedContentEditableTest, MoveBySentence) {
  SendFinalResultAndWaitForEditableValue(", good luck.",
                                         "This is a test, good luck.");
  SendFinalResultAndWaitForSelection("move to the previous sentence", 0, 0);
  SendFinalResultAndWaitForEditableValue(
      "Good morning. ", "Good morning. This is a test, good luck.");
  SendFinalResultAndWaitForSelection("forward one sentence", 40, 40);
  SendFinalResultAndWaitForEditableValue(
      " Have fun.", "Good morning. This is a test, good luck. Have fun.");
}

IN_PROC_BROWSER_TEST_P(DictationFormattedContentEditableTest,
                       SmartSelectBetween) {
  SendFinalResultAndWaitForSelection("highlight everything between is and a", 5,
                                     9);
  SendFinalResultAndWaitForEditableValue("was one", "This was one test");
}

class AccessibilityToastCallbackManager {
 public:
  void OnToastShown(AccessibilityToastType type) {
    if (type == type_) {
      run_loop_.Quit();
    }
  }

  void WaitForToastShown(AccessibilityToastType type) {
    type_ = type;
    run_loop_.Run();
  }

 private:
  AccessibilityToastType type_;
  base::RunLoop run_loop_;
};

class AudioCallbackManager {
 public:
  void OnSetMute(bool success) {
    if (success) {
      run_loop_.Quit();
    }
  }

  void WaitForSetMute() { run_loop_.Run(); }

 private:
  base::RunLoop run_loop_;
};

class DictationKeyboardImprovementsTest : public DictationTestBase {
 public:
  DictationKeyboardImprovementsTest() = default;
  ~DictationKeyboardImprovementsTest() override = default;
  DictationKeyboardImprovementsTest(const DictationKeyboardImprovementsTest&) =
      delete;
  DictationKeyboardImprovementsTest& operator=(
      const DictationKeyboardImprovementsTest&) = delete;

 protected:
  void SetUpOnMainThread() override {
    DictationTestBase::SetUpOnMainThread();
    test_api_ = AccessibilityControllerTestApi::Create();
    toast_callback_manager_ =
        std::make_unique<AccessibilityToastCallbackManager>();
    test_api_->AddShowToastCallbackForTesting(
        base::BindRepeating(&AccessibilityToastCallbackManager::OnToastShown,
                            base::Unretained(toast_callback_manager_.get())));
  }

  void TabAwayFromEditableAndReduceNoFocusedImeTimeout() {
    PressTab();
    // Reduce the no focused IME timeout so that the nudge will be shown
    // promptly.
    ExecuteAccessibilityCommonScript(
        "dictationTestSupport.setNoFocusedImeTimeout(500);");
  }

  void WaitForToastShown(AccessibilityToastType type) {
    toast_callback_manager_->WaitForToastShown(type);
  }

  void MuteMicrophone(bool mute) {
    AudioCallbackManager audio_callback_manager = AudioCallbackManager();
    extensions::AudioService* service =
        extensions::AudioAPI::GetFactoryInstance()
            ->Get(GetProfile())
            ->GetService();
    service->SetMute(/*is_input=*/true, /*is_muted=*/mute,
                     base::BindOnce(&AudioCallbackManager::OnSetMute,
                                    base::Unretained(&audio_callback_manager)));
    audio_callback_manager.WaitForSetMute();
  }

 private:
  std::unique_ptr<AccessibilityControllerTestApi> test_api_;
  std::unique_ptr<AccessibilityToastCallbackManager> toast_callback_manager_;
};

INSTANTIATE_TEST_SUITE_P(
    NetworkDictationKeyboardImprovementsTest,
    DictationKeyboardImprovementsTest,
    ::testing::Values(TestConfig(speech::SpeechRecognitionType::kNetwork,
                                 EditableType::kInput,
                                 ManifestVersion::kTwo)));

// Verifies that a nudge is shown in the system UI when Dictation is toggled
// when there is no focused editable.
IN_PROC_BROWSER_TEST_P(DictationKeyboardImprovementsTest,
                       ToggledWithNoFocusShowsNudge) {
  TabAwayFromEditableAndReduceNoFocusedImeTimeout();
  // Disable the console observer because toggling Dictation in the following
  // manner will cause an error to be emitted to the console.
  utils()->DisableConsoleObserver();
  ToggleDictationWithKeystroke();
  WaitForToastShown(AccessibilityToastType::kDictationNoFocusedTextField);
  WaitForRecognitionStopped();
}

IN_PROC_BROWSER_TEST_P(DictationKeyboardImprovementsTest,
                       ToggledWithMuteShowsNudge) {
  MuteMicrophone(true);
  // Disable the console observer because toggling Dictation in the following
  // manner will cause an error to be emitted to the console.
  utils()->DisableConsoleObserver();
  ToggleDictationWithKeystroke();
  WaitForToastShown(AccessibilityToastType::kDictationMicMuted);
  WaitForRecognitionStopped();

  MuteMicrophone(false);
  ToggleDictationWithKeystroke();
  WaitForRecognitionStarted();
  SendFinalResultAndWaitForEditableValue("Testing", "Testing");
  ToggleDictationWithKeystroke();
  WaitForRecognitionStopped();
}

// Verifies that ChromeVox announces a message when when Dictation is toggled
// when there is no focused editable.
// TODO(b:259352600): Flaky on MSAN & ASAN and Linux ChromiumOS in general.
IN_PROC_BROWSER_TEST_P(DictationKeyboardImprovementsTest,
                       DISABLED_ToggledWithNoFocusTriggersSpeech) {
  TabAwayFromEditableAndReduceNoFocusedImeTimeout();

  // Setup ChromeVox.
  ChromeVoxTestUtils chromevox_test_utils;
  chromevox_test_utils.EnableChromeVox();
  EXPECT_TRUE(GetManager()->IsSpokenFeedbackEnabled());

  // Disable the console observer because toggling Dictation in the following
  // manner will cause an error to be emitted to the console.
  utils()->DisableConsoleObserver();
  ToggleDictationWithKeystroke();
  WaitForToastShown(AccessibilityToastType::kDictationNoFocusedTextField);
  WaitForRecognitionStopped();

  // Assert speech from ChromeVox.
  chromevox_test_utils.sm()->ExpectSpeechPattern(
      "*Go to a text field to use Dictation*");
  chromevox_test_utils.sm()->Replay();
}

}  // namespace ash