File: system_access_process_print_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (4064 lines) | stat: -rw-r--r-- 162,286 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
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <optional>
#include <tuple>
#include <utility>
#include <vector>

#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/to_string.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/browser/printing/print_browsertest.h"
#include "chrome/browser/printing/print_job.h"
#include "chrome/browser/printing/print_test_utils.h"
#include "chrome/browser/printing/print_view_manager_base.h"
#include "chrome/browser/printing/print_view_manager_common.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/printing/test_print_preview_observer.h"
#include "chrome/browser/printing/test_print_view_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/enterprise/buildflags/buildflags.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/no_renderer_crashes_assertion.h"
#include "mojo/public/cpp/bindings/pending_associated_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "printing/buildflags/buildflags.h"
#include "printing/mojom/print.mojom.h"
#include "printing/printing_context.h"
#include "printing/printing_features.h"
#include "printing/printing_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/size_f.h"

#if BUILDFLAG(ENABLE_OOP_PRINTING)
#include "chrome/browser/printing/print_backend_service_manager.h"
#include "chrome/browser/printing/print_backend_service_test_impl.h"
#include "chrome/browser/printing/print_job_worker_oop.h"
#include "chrome/browser/printing/print_preview_dialog_controller.h"
#include "chrome/browser/printing/printer_query_oop.h"
#include "chrome/browser/task_manager/task_manager_browsertest_util.h"
#include "chrome/browser/task_manager/task_manager_interface.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/services/printing/public/mojom/print_backend_service.mojom.h"
#endif

#if BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
#include "chrome/browser/enterprise/connectors/analysis/content_analysis_dialog_controller.h"
#include "chrome/browser/enterprise/connectors/common.h"
#include "chrome/browser/enterprise/connectors/test/deep_scanning_test_utils.h"  // nogncheck
#include "chrome/browser/enterprise/connectors/test/fake_content_analysis_delegate.h"  // nogncheck
#include "chrome/browser/policy/dm_token_utils.h"
#include "components/enterprise/common/proto/connectors.pb.h"

#if BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)
#include "chrome/browser/enterprise/connectors/test/fake_content_analysis_sdk_manager.h"  // nogncheck
#endif  // BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)
#endif  // BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)

#if BUILDFLAG(IS_CHROMEOS)
// TODO(crbug.com/40567307)  ChromeOS uses different testing setup that isn't
// hooked up to make use of `TestPrintingContext` yet.
#error "ChromeOS not supported here yet"
#endif

using task_manager::TaskManagerInterface;
using task_manager::browsertest_util::MatchAnyTab;
using task_manager::browsertest_util::MatchUtility;
using task_manager::browsertest_util::WaitForTaskManagerRows;

namespace printing {

namespace {

#if BUILDFLAG(ENABLE_OOP_PRINTING) && !BUILDFLAG(IS_CHROMEOS)
constexpr gfx::SizeF kLetterPhysicalSize = gfx::SizeF(612, 792);
constexpr gfx::RectF kLetterPrintableArea = gfx::RectF(5, 5, 602, 782);
constexpr gfx::SizeF kLegalPhysicalSize = gfx::SizeF(612, 1008);
constexpr gfx::RectF kLegalPrintableArea = gfx::RectF(5, 5, 602, 998);

// The default margins are set to 1.0cm in //printing/print_settings.cc, which
// is about 28 printer units. The resulting content size is 556 x 736 for
// Letter, and similarly is 556 x 952 for Legal.
constexpr gfx::SizeF kLetterExpectedContentSize = gfx::SizeF(556, 736);
constexpr gfx::SizeF kLegalExpectedContentSize = gfx::SizeF(556, 952);
#endif  // BUILDFLAG(ENABLE_OOP_PRINTING) && !BUILDFLAG(IS_CHROMEOS)

#if BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
constexpr char kFakeDmToken[] = "fake-dm-token";

// The policy values below correspond to the schema described in
// https://chromeenterprise.google/policies/#OnPrintEnterpriseConnector
constexpr char kCloudAnalysisBlockingPolicy[] = R"({
  "service_provider": "google",
  "enable": [ {"url_list": ["*"], "tags": ["dlp"]} ],
  "block_until_verdict": 1,
  "block_large_files": true
})";

constexpr char kCloudAnalysisNonBlockingPolicy[] = R"({
  "service_provider": "google",
  "enable": [ {"url_list": ["*"], "tags": ["dlp"]} ],
  "block_until_verdict": 0,
  "block_large_files": true
})";

#if BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)
constexpr char kLocalAnalysisPolicy[] = R"({
  "service_provider": "local_user_agent",
  "enable": [ {"url_list": ["*"], "tags": ["dlp"]} ],
  "block_until_verdict": 1,
  "block_large_files": true
})";
#endif  // BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)

using OnDidCompositeForContentAnalysis =
    base::RepeatingCallback<void(bool allowed)>;
#endif  // BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)

#if BUILDFLAG(ENABLE_OOP_PRINTING)
void CancelPrintPreview(content::WebContents* preview_dialog) {
  // This script locates and clicks the Cancel button for a Print Preview
  // dialog.
  const char kScript[] = R"(
      const button = document.getElementsByTagName('print-preview-app')[0]
                       .$['sidebar']
                       .shadowRoot.querySelector('print-preview-button-strip')
                       .shadowRoot.querySelector('.cancel-button');
      button.click();)";

  // It is possible for sufficient processing for the cancel to complete such
  // that the renderer naturally terminates before ExecJs() returns here.  This
  // causes ExecJs() to return false, with a JavaScript error of
  // "Renderer terminated".  Since the termination can actually be a result of
  // a successful cancel, do not assert on this return result, just ignore the
  // error instead.  Rely upon tests using other methods to catch errors, such
  // as monitoring for the Print Preview to be done if that is needed.
  std::ignore = content::ExecJs(preview_dialog, kScript);
}

// Values for parameterized testing.
enum class PrintBackendFeatureVariation {
  // `PrintBackend` calls occur from browser process.
  kInBrowserProcess,
  // Use OOP `PrintBackend`.  Attempt to have `PrintBackendService` be
  // sandboxed.
  kOopSandboxedService,
  // Use OOP `PrintBackend`.  Always use `PrintBackendService` unsandboxed.
  kOopUnsandboxedService,
};

const char* GetPrintBackendString(PrintBackendFeatureVariation variation) {
  switch (variation) {
    case PrintBackendFeatureVariation::kInBrowserProcess:
      return "InBrowser";
    case PrintBackendFeatureVariation::kOopSandboxedService:
      return "OopSandboxed";
    case PrintBackendFeatureVariation::kOopUnsandboxedService:
      return "OopUnsandboxed";
  }
}

enum class PlatformPrintApiVariation {
#if BUILDFLAG(IS_WIN)
  // Windows print drivers can have a language type which alters how the print
  // data is processed.  While much of the GDI printing pipeline is not
  // concerned with the language type differences, certain portions of the
  // printing pipeline are impacted by it.  Most tests only need test against
  // one GDI language type.
  kGdiEmf,
  kGdiPostScriptLevel2,
  kGdiPostScriptLevel3,
  kGdiTextOnly,
  kXps,
#else
  kCups,
#endif
};

const char* GetPlatformPrintApiString(PlatformPrintApiVariation variation) {
  switch (variation) {
#if BUILDFLAG(IS_WIN)
    case PlatformPrintApiVariation::kGdiEmf:
      return "GdiEmf";
    case PlatformPrintApiVariation::kGdiPostScriptLevel2:
      return "GdiPostScriptLevel2";
    case PlatformPrintApiVariation::kGdiPostScriptLevel3:
      return "GdiPostScriptLevel3";
    case PlatformPrintApiVariation::kGdiTextOnly:
      return "GdiTextOnly";
    case PlatformPrintApiVariation::kXps:
      return "Xps";
#else
    case PlatformPrintApiVariation::kCups:
      return "Cups";
#endif
  }
}

// Caution must be taken with platform API variations, as `kXps` should not
// be generated with `kInBrowserProcess`.  Use of `testing::Combine()` between
// `PrintBackendFeatureVariation` and `PlatformPrintApiVariation` could
// inadvertently cause this illegal combination.  This can be avoided by using
// a local helper method to generate the allowed combinations.
//
// `SystemAccessProcessPrintBrowserTestBase` will check this constraint at
// runtime.
struct PrintBackendAndPlatformPrintApiVariation {
  PrintBackendFeatureVariation print_backend;
  PlatformPrintApiVariation platform_api;
};

// Tests using these variations are concerned with all the different language
// types on Windows.
constexpr PrintBackendAndPlatformPrintApiVariation
    kSandboxedServicePlatformPrintLanguageApiVariations[] = {
#if BUILDFLAG(IS_WIN)
        // TODO(crbug.com/40100562):  Include XPS variation.
        {PrintBackendFeatureVariation::kOopSandboxedService,
         PlatformPrintApiVariation::kGdiEmf},
        {PrintBackendFeatureVariation::kOopSandboxedService,
         PlatformPrintApiVariation::kGdiPostScriptLevel2},
        {PrintBackendFeatureVariation::kOopSandboxedService,
         PlatformPrintApiVariation::kGdiPostScriptLevel3},
        {PrintBackendFeatureVariation::kOopSandboxedService,
         PlatformPrintApiVariation::kGdiTextOnly},
#else
        {PrintBackendFeatureVariation::kOopSandboxedService,
         PlatformPrintApiVariation::kCups},
#endif
};

std::string GetPrintBackendAndPlatformPrintApiString(
    const PrintBackendAndPlatformPrintApiVariation& variation) {
  return base::JoinString({GetPrintBackendString(variation.print_backend),
                           GetPlatformPrintApiString(variation.platform_api)},
                          /*separator=*/"_");
}

std::string GetPrintBackendAndPlatformPrintApiTestSuffix(
    const testing::TestParamInfo<PrintBackendAndPlatformPrintApiVariation>&
        info) {
  return GetPrintBackendAndPlatformPrintApiString(info.param);
}

std::vector<PrintBackendAndPlatformPrintApiVariation>
GeneratePrintBackendAndPlatformPrintApiVariations(
    std::vector<PrintBackendFeatureVariation> print_backend_variations) {
  std::vector<PrintBackendAndPlatformPrintApiVariation> variations;

  for (PrintBackendFeatureVariation print_backend_variation :
       print_backend_variations) {
#if BUILDFLAG(IS_WIN)
    // Only need one GDI variation, not interested in different language types.
    // TODO(crbug.com/40100562):  Include XPS variation, only when the
    // `print_backend_variation` is not `kInBrowserProcess`.
    variations.emplace_back(print_backend_variation,
                            PlatformPrintApiVariation::kGdiEmf);
#else
    variations.emplace_back(print_backend_variation,
                            PlatformPrintApiVariation::kCups);
#endif
  }

  return variations;
}

std::string GetServiceLaunchTimingTestSuffix(
    const testing::TestParamInfo<bool>& info) {
  return info.param ? "EarlyStart" : "OnDemand";
}
#endif  // BUILDFLAG(ENABLE_OOP_PRINTING)

}  // namespace

#if BUILDFLAG(ENABLE_OOP_PRINTING)
using OnUseDefaultSettingsCallback = base::RepeatingClosure;
using OnGetSettingsWithUICallback = base::RepeatingClosure;

using ErrorCheckCallback =
    base::RepeatingCallback<void(mojom::ResultCode result)>;
using OnDidUseDefaultSettingsCallback =
    base::RepeatingCallback<void(mojom::ResultCode result)>;
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
using OnDidAskUserForSettingsCallback =
    base::RepeatingCallback<void(mojom::ResultCode result)>;
#endif
using OnDidUpdatePrintSettingsCallback =
    base::RepeatingCallback<void(mojom::ResultCode result)>;
using OnFinishDocumentDoneCallback = base::RepeatingCallback<void(int job_id)>;
using OnDidStartPrintingCallback =
    base::RepeatingCallback<void(mojom::ResultCode result)>;
#if BUILDFLAG(IS_WIN)
using OnDidRenderPrintedPageCallback =
    base::RepeatingCallback<void(uint32_t page_number,
                                 mojom::ResultCode result)>;
#endif
using OnDidRenderPrintedDocumentCallback =
    base::RepeatingCallback<void(mojom::ResultCode result)>;
using OnDidDocumentDoneCallback =
    base::RepeatingCallback<void(int job_id, mojom::ResultCode result)>;
using OnDidCancelCallback = base::RepeatingClosure;
using OnDidShowErrorDialog = base::RepeatingClosure;

class TestPrintJobWorker : public PrintJobWorker {
 public:
  // Callbacks to run for overrides.
  struct PrintCallbacks {
    ErrorCheckCallback error_check_callback;
    OnUseDefaultSettingsCallback did_use_default_settings_callback;
    OnGetSettingsWithUICallback did_get_settings_with_ui_callback;
    OnDidUpdatePrintSettingsCallback did_update_print_settings_callback;
    OnFinishDocumentDoneCallback did_finish_document_done_callback;
  };

  TestPrintJobWorker(
      std::unique_ptr<PrintingContext::Delegate> printing_context_delegate,
      std::unique_ptr<PrintingContext> printing_context,
      PrintJob* print_job,
      PrintCallbacks* callbacks)
      : PrintJobWorker(std::move(printing_context_delegate),
                       std::move(printing_context),
                       print_job),
        callbacks_(callbacks) {}
  TestPrintJobWorker(const TestPrintJobWorker&) = delete;
  TestPrintJobWorker& operator=(const TestPrintJobWorker&) = delete;

  // `PrintJobWorker` overrides:
  void Cancel() override {
    callbacks_->error_check_callback.Run(mojom::ResultCode::kCanceled);
    PrintJobWorker::Cancel();
  }

 private:
  // `PrintJobWorker` overrides:
  void FinishDocumentDone(int job_id) override {
    callbacks_->did_finish_document_done_callback.Run(job_id);
    PrintJobWorker::FinishDocumentDone(job_id);
  }
  void OnCancel() override {
    callbacks_->error_check_callback.Run(mojom::ResultCode::kCanceled);
    PrintJobWorker::OnCancel();
  }
  void OnFailure() override {
    callbacks_->error_check_callback.Run(mojom::ResultCode::kFailed);
    PrintJobWorker::OnFailure();
  }

  const raw_ptr<PrintCallbacks> callbacks_;
};

class TestPrinterQuery : public PrinterQuery {
 public:
  TestPrinterQuery(content::GlobalRenderFrameHostId rfh_id,
                   TestPrintJobWorker::PrintCallbacks* callbacks)
      : PrinterQuery(rfh_id), callbacks_(callbacks) {}

  void UpdatePrintSettings(base::Value::Dict new_settings,
                           SettingsCallback callback) override {
    PrinterQuery::UpdatePrintSettings(
        std::move(new_settings),
        base::BindOnce(&TestPrinterQuery::OnDidUpdatePrintSettings,
                       base::Unretained(this), std::move(callback)));
  }

  void UseDefaultSettings(SettingsCallback callback) override {
    DVLOG(1) << "Observed: invoke use default settings";
    PrinterQuery::UseDefaultSettings(std::move(callback));
    callbacks_->did_use_default_settings_callback.Run();
  }

  void GetSettingsWithUI(uint32_t document_page_count,
                         bool has_selection,
                         bool is_scripted,
                         SettingsCallback callback) override {
    DVLOG(1) << "Observed: invoke get settings with UI";
    PrinterQuery::GetSettingsWithUI(document_page_count, has_selection,
                                    is_scripted, std::move(callback));
    callbacks_->did_get_settings_with_ui_callback.Run();
  }

  void OnDidUpdatePrintSettings(SettingsCallback callback,
                                std::unique_ptr<PrintSettings> settings,
                                mojom::ResultCode result) {
    DVLOG(1) << "Observed: update print settings";
    std::move(callback).Run(std::move(settings), result);
    callbacks_->did_update_print_settings_callback.Run(result);
  }

  std::unique_ptr<PrintJobWorker> CreatePrintJobWorker(
      PrintJob* print_job) override {
    return std::make_unique<TestPrintJobWorker>(
        std::move(printing_context_delegate_), std::move(printing_context_),
        print_job, callbacks_);
  }

  const raw_ptr<TestPrintJobWorker::PrintCallbacks> callbacks_;
};

class TestPrintJobWorkerOop : public PrintJobWorkerOop {
 public:
  // Callbacks to run for overrides are broken into the following steps:
  //   1.  Error case processing.  Call `error_check_callback` to reset any
  //       triggers that were primed to cause errors in the testing context.
  //   2.  Run the base class callback for normal handling.  If there was an
  //       access-denied error then this can lead to a retry.  The retry has a
  //       chance to succeed since error triggers were removed.
  //   3.  Exercise the associated test callback (e.g.,
  //       `did_start_printing_callback` when in `OnDidStartPrinting()`) to note
  //       the callback was observed and completed.  This ensures all base class
  //       processing was done before possibly quitting the test run loop.
  struct PrintCallbacks {
    ErrorCheckCallback error_check_callback;
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
    OnDidUseDefaultSettingsCallback did_use_default_settings_callback;
    OnDidAskUserForSettingsCallback did_ask_user_for_settings_callback;
#else
    // Need to use the base class version of callbacks when the system dialog
    // must be displayed from the browser process.
    OnUseDefaultSettingsCallback did_use_default_settings_callback;
    OnGetSettingsWithUICallback did_get_settings_with_ui_callback;
#endif
    OnDidUpdatePrintSettingsCallback did_update_print_settings_callback;
    OnDidStartPrintingCallback did_start_printing_callback;
#if BUILDFLAG(IS_WIN)
    OnDidRenderPrintedPageCallback did_render_printed_page_callback;
#endif
    OnDidRenderPrintedDocumentCallback did_render_printed_document_callback;
    OnDidDocumentDoneCallback did_document_done_callback;
    OnDidCancelCallback did_cancel_callback;
  };

  TestPrintJobWorkerOop(
      std::unique_ptr<PrintingContext::Delegate> printing_context_delegate,
      std::unique_ptr<PrintingContext> printing_context,
      std::optional<PrintBackendServiceManager::ClientId> client_id,
      std::optional<PrintBackendServiceManager::ContextId> context_id,
      PrintJob* print_job,
      bool print_from_system_dialog,
      bool simulate_spooling_memory_errors,
      TestPrintJobWorkerOop::PrintCallbacks* callbacks)
      : PrintJobWorkerOop(std::move(printing_context_delegate),
                          std::move(printing_context),
                          client_id,
                          context_id,
                          print_job,
                          print_from_system_dialog,
                          simulate_spooling_memory_errors),
        callbacks_(callbacks) {}
  TestPrintJobWorkerOop(const TestPrintJobWorkerOop&) = delete;
  TestPrintJobWorkerOop& operator=(const TestPrintJobWorkerOop&) = delete;
  ~TestPrintJobWorkerOop() override = default;

 private:
  void OnDidStartPrinting(mojom::ResultCode result, int job_id) override {
    DVLOG(1) << "Observed: start printing of document";
    callbacks_->error_check_callback.Run(result);
    PrintJobWorkerOop::OnDidStartPrinting(result, job_id);
    callbacks_->did_start_printing_callback.Run(result);
  }

#if BUILDFLAG(IS_WIN)
  void OnDidRenderPrintedPage(uint32_t page_number,
                              mojom::ResultCode result) override {
    DVLOG(1) << "Observed render for printed page " << page_number;
    callbacks_->error_check_callback.Run(result);
    PrintJobWorkerOop::OnDidRenderPrintedPage(page_number, result);
    callbacks_->did_render_printed_page_callback.Run(page_number, result);
  }
#endif  // BUILDFLAG(IS_WIN)

  void OnDidRenderPrintedDocument(mojom::ResultCode result) override {
    DVLOG(1) << "Observed render for printed document";
    callbacks_->error_check_callback.Run(result);
    PrintJobWorkerOop::OnDidRenderPrintedDocument(result);
    callbacks_->did_render_printed_document_callback.Run(result);
  }

  void OnDidDocumentDone(int job_id, mojom::ResultCode result) override {
    DVLOG(1) << "Observed: document done";
    callbacks_->error_check_callback.Run(result);
    PrintJobWorkerOop::OnDidDocumentDone(job_id, result);
    callbacks_->did_document_done_callback.Run(job_id, result);
  }

  void OnDidCancel(scoped_refptr<PrintJob> job,
                   mojom::ResultCode result) override {
    DVLOG(1) << "Observed: cancel";
    // Must not use `std::move(job)`, as that could potentially cause the `job`
    // (and consequentially `this`) to be destroyed before
    // `did_cancel_callback` is run.
    PrintJobWorkerOop::OnDidCancel(job, result);
    callbacks_->did_cancel_callback.Run();
  }

  const raw_ptr<PrintCallbacks> callbacks_;
};

class TestPrinterQueryOop : public PrinterQueryOop {
 public:
  TestPrinterQueryOop(
      content::GlobalRenderFrameHostId rfh_id,
      bool simulate_spooling_memory_errors,
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG) && BUILDFLAG(IS_WIN)
      base::OnceClosure terminate_service_after_update_print_settings_callback,
#endif
      base::OnceClosure terminate_service_after_ask_user_for_settings_callback,
      TestPrintJobWorkerOop::PrintCallbacks* callbacks)
      : PrinterQueryOop(rfh_id),
        simulate_spooling_memory_errors_(simulate_spooling_memory_errors),
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG) && BUILDFLAG(IS_WIN)
        terminate_service_after_update_print_settings_callback_(
            std::move(terminate_service_after_update_print_settings_callback)),
#endif
        terminate_service_after_ask_user_for_settings_callback_(
            std::move(terminate_service_after_ask_user_for_settings_callback)),
        callbacks_(callbacks) {
  }

#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
  void OnDidUseDefaultSettings(
      SettingsCallback callback,
      mojom::PrintSettingsResultPtr print_settings) override {
    DVLOG(1) << "Observed: use default settings";
    mojom::ResultCode result = print_settings->is_result_code()
                                   ? print_settings->get_result_code()
                                   : mojom::ResultCode::kSuccess;
    callbacks_->error_check_callback.Run(result);
    PrinterQueryOop::OnDidUseDefaultSettings(std::move(callback),
                                             std::move(print_settings));
    callbacks_->did_use_default_settings_callback.Run(result);
  }

  void OnDidAskUserForSettings(
      SettingsCallback callback,
      mojom::PrintSettingsResultPtr print_settings) override {
    DVLOG(1) << "Observed: ask user for settings";
    mojom::ResultCode result = print_settings->is_result_code()
                                   ? print_settings->get_result_code()
                                   : mojom::ResultCode::kSuccess;
    callbacks_->error_check_callback.Run(result);
    if (terminate_service_after_ask_user_for_settings_callback_) {
      std::move(terminate_service_after_ask_user_for_settings_callback_).Run();
    }
    PrinterQueryOop::OnDidAskUserForSettings(std::move(callback),
                                             std::move(print_settings));
    callbacks_->did_ask_user_for_settings_callback.Run(result);
  }
#else
  void UseDefaultSettings(SettingsCallback callback) override {
    DVLOG(1) << "Observed: invoke use default settings";
    PrinterQueryOop::UseDefaultSettings(std::move(callback));
    callbacks_->did_use_default_settings_callback.Run();
  }

  void GetSettingsWithUI(uint32_t document_page_count,
                         bool has_selection,
                         bool is_scripted,
                         SettingsCallback callback) override {
    DVLOG(1) << "Observed: invoke get settings with UI";
    if (terminate_service_after_ask_user_for_settings_callback_) {
      std::move(terminate_service_after_ask_user_for_settings_callback_).Run();
    }
    PrinterQueryOop::GetSettingsWithUI(document_page_count, has_selection,
                                       is_scripted, std::move(callback));
    callbacks_->did_get_settings_with_ui_callback.Run();
  }
#endif  // BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)

  void OnDidUpdatePrintSettings(
      const std::string& device_name,
      SettingsCallback callback,
      mojom::PrintSettingsResultPtr print_settings) override {
    DVLOG(1) << "Observed: update print settings";
    mojom::ResultCode result = print_settings->is_result_code()
                                   ? print_settings->get_result_code()
                                   : mojom::ResultCode::kSuccess;
    callbacks_->error_check_callback.Run(result);
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG) && BUILDFLAG(IS_WIN)
    if (terminate_service_after_update_print_settings_callback_) {
      std::move(terminate_service_after_update_print_settings_callback_).Run();
    }
#endif
    PrinterQueryOop::OnDidUpdatePrintSettings(device_name, std::move(callback),
                                              std::move(print_settings));
    callbacks_->did_update_print_settings_callback.Run(result);
  }

  std::unique_ptr<PrintJobWorkerOop> CreatePrintJobWorkerOop(
      PrintJob* print_job) override {
    return std::make_unique<TestPrintJobWorkerOop>(
        std::move(printing_context_delegate_), std::move(printing_context_),
        print_document_client_id(), context_id(), print_job,
        print_from_system_dialog(), simulate_spooling_memory_errors_,
        callbacks_);
  }

  const bool simulate_spooling_memory_errors_;
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG) && BUILDFLAG(IS_WIN)
  base::OnceClosure terminate_service_after_update_print_settings_callback_;
#endif
  base::OnceClosure terminate_service_after_ask_user_for_settings_callback_;
  const raw_ptr<TestPrintJobWorkerOop::PrintCallbacks> callbacks_;
};
#endif  // BUILDFLAG(ENABLE_OOP_PRINTING)

class SystemAccessProcessPrintBrowserTestBase
    : public PrintBrowserTest,
      public PrintJob::Observer,
      public PrintViewManagerBase::TestObserver {
 public:
  SystemAccessProcessPrintBrowserTestBase() = default;
  ~SystemAccessProcessPrintBrowserTestBase() override = default;

  virtual bool UseService() = 0;

  // Only of interest when `UseService()` returns true.
  virtual bool SandboxService() = 0;

  // Only applicable when `UseService()` returns true.
  virtual bool EarlyStartService() { return false; }

#if BUILDFLAG(IS_WIN)
  // Only applicable when `UseService()` returns true.
  virtual bool UseXps() = 0;
#endif

  void SetUpFeatures() {
    std::vector<base::test::FeatureRefAndParams> enabled_features;
    std::vector<base::test::FeatureRef> disabled_features;
#if BUILDFLAG(ENABLE_OOP_PRINTING)
    if (UseService()) {
      enabled_features.push_back(
          {features::kEnableOopPrintDrivers,
           {{features::kEnableOopPrintDriversEarlyStart.name,
             base::ToString(EarlyStartService())},
            {features::kEnableOopPrintDriversJobPrint.name, "true"},
            {features::kEnableOopPrintDriversSandbox.name,
             base::ToString(SandboxService())}}});
#if BUILDFLAG(IS_WIN)
      if (UseXps()) {
        enabled_features.push_back({features::kUseXpsForPrinting, {}});
      } else {
        disabled_features.push_back(features::kUseXpsForPrinting);
      }
      // TODO(crbug.com/40111626):  Support `kUseXpsForPrintingFromPdf`.
      disabled_features.push_back(features::kUseXpsForPrintingFromPdf);
      // TODO(crbug.com/40212677):  Support `kReadPrinterCapabilitiesWithXps`.
      disabled_features.push_back(features::kReadPrinterCapabilitiesWithXps);
#endif  // BUILDFLAG(IS_WIN)
    } else {
      disabled_features.push_back(features::kEnableOopPrintDrivers);
#if BUILDFLAG(IS_WIN)
      CHECK(!UseXps());
      disabled_features.push_back(features::kUseXpsForPrinting);
      disabled_features.push_back(features::kUseXpsForPrintingFromPdf);
      disabled_features.push_back(features::kReadPrinterCapabilitiesWithXps);
#endif  // BUILDFLAG(IS_WIN)
    }
#endif  // BUILDFLAG(ENABLE_OOP_PRINTING)
    feature_list_.InitWithFeaturesAndParameters(enabled_features,
                                                disabled_features);
  }

  void SetUp() override {
#if BUILDFLAG(ENABLE_OOP_PRINTING)
    SetUpFeatures();

    if (UseService()) {
      // Safe to use `base::Unretained(this)` since this testing class
      // necessarily must outlive all interactions from the tests which will
      // run through `TestPrintJobWorkerOop`, the user of these callbacks.
      test_print_job_worker_oop_callbacks_.error_check_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OopErrorCheck,
              base::Unretained(this));
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
      test_print_job_worker_oop_callbacks_.did_use_default_settings_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnDidUseDefaultSettings,
              base::Unretained(this));
      test_print_job_worker_oop_callbacks_.did_ask_user_for_settings_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnDidAskUserForSettings,
              base::Unretained(this));
#else
      test_print_job_worker_oop_callbacks_.did_use_default_settings_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnUseDefaultSettings,
              base::Unretained(this));
      test_print_job_worker_oop_callbacks_.did_get_settings_with_ui_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnGetSettingsWithUI,
              base::Unretained(this));
#endif  // BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
      test_print_job_worker_oop_callbacks_
          .did_update_print_settings_callback = base::BindRepeating(
          &SystemAccessProcessPrintBrowserTestBase::OnDidUpdatePrintSettings,
          base::Unretained(this));
      test_print_job_worker_oop_callbacks_.did_start_printing_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnDidStartPrinting,
              base::Unretained(this));
#if BUILDFLAG(IS_WIN)
      test_print_job_worker_oop_callbacks_.did_render_printed_page_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnDidRenderPrintedPage,
              base::Unretained(this));
#endif
      test_print_job_worker_oop_callbacks_
          .did_render_printed_document_callback = base::BindRepeating(
          &SystemAccessProcessPrintBrowserTestBase::OnDidRenderPrintedDocument,
          base::Unretained(this));
      test_print_job_worker_oop_callbacks_.did_document_done_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnDidDocumentDone,
              base::Unretained(this));
      test_print_job_worker_oop_callbacks_.did_cancel_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnDidCancel,
              base::Unretained(this));
    } else {
      test_print_job_worker_callbacks_.error_check_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::InProcessErrorCheck,
              base::Unretained(this));
      test_print_job_worker_callbacks_.did_use_default_settings_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnUseDefaultSettings,
              base::Unretained(this));
      test_print_job_worker_callbacks_.did_get_settings_with_ui_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnGetSettingsWithUI,
              base::Unretained(this));
      test_print_job_worker_callbacks_
          .did_update_print_settings_callback = base::BindRepeating(
          &SystemAccessProcessPrintBrowserTestBase::OnDidUpdatePrintSettings,
          base::Unretained(this));
      test_print_job_worker_callbacks_.did_finish_document_done_callback =
          base::BindRepeating(
              &SystemAccessProcessPrintBrowserTestBase::OnFinishDocumentDone,
              base::Unretained(this));
    }
    test_create_printer_query_callback_ = base::BindRepeating(
        &SystemAccessProcessPrintBrowserTestBase::CreatePrinterQuery,
        base::Unretained(this), UseService());
    PrinterQuery::SetCreatePrinterQueryCallbackForTest(
        &test_create_printer_query_callback_);
#endif  // BUILDFLAG(ENABLE_OOP_PRINTING)

    PrintBrowserTest::SetUp();
  }

  void SetUpOnMainThread() override {
#if BUILDFLAG(ENABLE_OOP_PRINTING)
    if (UseService() && !EarlyStartService()) {
      print_backend_service_ = PrintBackendServiceTestImpl::LaunchForTesting(
          test_remote_, test_print_backend(), /*sandboxed=*/true);
    }
#endif
    PrintBrowserTest::SetUpOnMainThread();
  }

  void TearDown() override {
    PrintBrowserTest::TearDown();
#if BUILDFLAG(ENABLE_OOP_PRINTING)
    PrinterQuery::SetCreatePrinterQueryCallbackForTest(/*callback=*/nullptr);
    if (UseService()) {
      // Check that there is never a straggler client registration.
      EXPECT_EQ(
          PrintBackendServiceManager::GetInstance().GetClientsRegisteredCount(),
          0u);
    }
#endif
    ASSERT_EQ(print_job_construction_count(), print_job_destruction_count());
  }

  void TearDownOnMainThread() override {
    PrintBrowserTest::TearDownOnMainThread();
#if BUILDFLAG(ENABLE_OOP_PRINTING)
    PrintBackendServiceManager::ResetForTesting();
#endif
  }

#if BUILDFLAG(ENABLE_OOP_PRINTING)
  // `PrintBackendServiceTestImpl` does a debug check on shutdown that there
  // are no residual persistent printing contexts left in the service.  For
  // tests which are known to break this (either by design, for test simplicity
  // or because a related change is only partly implemented), use this method
  // to notify the service to not DCHECK on such a condition.
  void SkipPersistentContextsCheckOnShutdown() {
    print_backend_service_->SkipPersistentContextsCheckOnShutdown();
  }

  // PrintViewManagerBase::TestObserver:
  void OnPrintPreviewDone() override {
    if (check_for_print_preview_done_) {
      CheckForQuit();
    }
  }

  void OnRegisterSystemPrintClient(bool succeeded) override {
    system_print_registration_succeeded_ = succeeded;
  }
#endif

  void OnDidPrintDocument() override {
    ++did_print_document_count_;
    CheckForQuit();
  }

  void OnRenderFrameDeleted() override {
    if (check_for_render_frame_deleted_) {
      CheckForQuit();
    }
  }

  // PrintJob::Observer:
  void OnDestruction() override {
    ++print_job_destruction_count_;
    CheckForQuit();
  }

  void OnCreatedPrintJob(PrintJob* print_job) {
    ++print_job_construction_count_;
    print_job->AddObserver(*this);
  }

#if BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
  void OnCompositedForContentAnalysis(bool allowed) {
    ++composited_for_content_analysis_count_;
    CheckForQuit();
  }
#endif

  TestPrintViewManager* SetUpAndReturnPrintViewManager(
      content::WebContents* web_contents) {
    // Safe to use `base::Unretained(this)` since this testing class
    // necessarily must outlive all interactions from the tests which will
    // run through `PrintViewManagerBase`, which is what causes new jobs to
    // be created and use this callback.
    auto manager = std::make_unique<TestPrintViewManager>(
        web_contents,
        base::BindRepeating(
            &SystemAccessProcessPrintBrowserTestBase::OnCreatedPrintJob,
            base::Unretained(this)));
    manager->AddTestObserver(*this);
#if BUILDFLAG(IS_WIN)
    if (simulate_pdf_conversion_error_on_page_index_.has_value()) {
      manager->set_simulate_pdf_conversion_error_on_page_index(
          *simulate_pdf_conversion_error_on_page_index_);
    }
#endif
    TestPrintViewManager* manager_ptr = manager.get();
    web_contents->SetUserData(PrintViewManager::UserDataKey(),
                              std::move(manager));
    return manager_ptr;
  }

  void SetUpPrintViewManager(content::WebContents* web_contents) {
    std::ignore = SetUpAndReturnPrintViewManager(web_contents);
  }

  content::WebContents* PrintAfterPreviewIsReadyAndLoaded() {
    return PrintAfterPreviewIsReadyAndLoaded(PrintParams());
  }

  content::WebContents* PrintAfterPreviewIsReadyAndLoaded(
      const PrintParams& params) {
    return PrintAfterPreviewIsReadyAndMaybeLoaded(params,
                                                  /*wait_for_loaded=*/true);
  }

  content::WebContents* PrintAfterPreviewIsReadyAndMaybeLoaded(
      const PrintParams& params,
      bool wait_for_loaded) {
    // First invoke the Print Preview dialog with requested method.
    content::WebContents* preview_dialog =
        wait_for_loaded ? PrintAndWaitUntilPreviewIsReadyAndLoaded(params)
                        : PrintAndWaitUntilPreviewIsReady(params);
    if (!preview_dialog) {
      ADD_FAILURE() << "Unable to get Print Preview dialog";
      return nullptr;
    }

    // Print Preview is completely ready, can now initiate printing.
    // This script locates and clicks the Print button.
    const char kScript[] = R"(
      const button = document.getElementsByTagName('print-preview-app')[0]
                       .$['sidebar']
                       .shadowRoot.querySelector('print-preview-button-strip')
                       .shadowRoot.querySelector('.action-button');
      button.click();)";
    auto result = content::ExecJs(preview_dialog, kScript);
    // TODO(crbug.com/40926610):  Update once it is known if the assertion
    // should not happen if the failure is just because the renderer
    // terminated.
    // If the renderer terminates, it will return a failing result.  It has
    // been observed in other tests that sometimes the renderer terminates
    // and the test was successful; all the needed callbacks happened before
    // ExecJs() returned.
    // Add a warning for the logs to help with debugging, and then only do
    // the assert check after having done the wait.
    // If the renderer terminated but the printing was all successful, then
    // `WaitUntilCallbackReceived()` should return successfully, and any crash
    // logs should show the assert.  Otherwise the crashes for this bug should
    // change to become the test timeouts.
    if (!result) {
      ADD_FAILURE() << "ExecJs() failed; if reason is because the renderer "
                       "terminated, it is possibly okay? "
                    << result.message();
    }
    WaitUntilCallbackReceived();
    return preview_dialog;
  }

  void AdjustMediaAfterPreviewIsReadyAndLoaded() {
    // First invoke the Print Preview dialog with `StartPrint()`.
    content::WebContents* preview_dialog =
        PrintAndWaitUntilPreviewIsReadyAndLoaded();
    ASSERT_TRUE(preview_dialog);

    // Initial Print Preview is completely ready.
    // Create an observer and modify the paper size.  This will initiate another
    // preview render.
    // The default paper size is first in the list at index zero, so choose
    // the second item from the list to cause a change.
    TestPrintPreviewObserver print_preview_observer(/*wait_for_loaded=*/true);
    const char kSetPaperSizeScript[] = R"(
      var element =
          document.getElementsByTagName('print-preview-app')[0]
              .$['sidebar']
              .shadowRoot.querySelector('print-preview-media-size-settings');
      element.setSetting('mediaSize', element.capability.option[1]);)";
    ASSERT_TRUE(content::ExecJs(preview_dialog, kSetPaperSizeScript));
    print_preview_observer.WaitUntilPreviewIsReady();
  }

#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)
  void SystemPrintFromPreviewOnceReadyAndLoaded(bool wait_for_callback) {
    // First invoke the Print Preview dialog with `StartPrint()`.
    content::WebContents* preview_dialog =
        PrintAndWaitUntilPreviewIsReadyAndLoaded();
    ASSERT_TRUE(preview_dialog);

    // Print Preview is completely ready, can now initiate printing.
    // This script locates and clicks the "Print using system dialog",
    // which is still enabled even if it is hidden.
    const char kPrintWithSystemDialogScript[] = R"(
      const printSystemDialog =
          document.getElementsByTagName('print-preview-app')[0]
              .$['sidebar']
              .shadowRoot.querySelector('print-preview-link-container')
              .$['systemDialogLink'];
      printSystemDialog.click();)";
    // It is possible for sufficient processing for the system print to
    // complete such that the renderer naturally terminates before ExecJs()
    // returns here.  This causes ExecJs() to return false, with a JavaScript
    // error of "Renderer terminated".  Since the termination can actually be
    // a result of successful print processing, do not assert on this return
    // result, just ignore the error instead.  Rely upon tests catching any
    // failure through the use of other expectation checks.
    std::ignore = content::ExecJs(preview_dialog, kPrintWithSystemDialogScript);
    if (wait_for_callback) {
      WaitUntilCallbackReceived();
    }
  }
#endif  // BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)

#if BUILDFLAG(IS_MAC)
  void OpenPdfInPreviewOnceReadyAndLoaded() {
    // First invoke the Print Preview dialog with `StartPrint()`.
    content::WebContents* preview_dialog =
        PrintAndWaitUntilPreviewIsReadyAndLoaded();
    ASSERT_TRUE(preview_dialog);

    // Print Preview is completely ready, can now initiate printing.
    // This script locates and clicks "Open PDF in Preview", which is still
    // enabled even if it is hidden.
    const char kOpenPdfWithPreviewScript[] = R"(
      const openPdfInPreview =
          document.getElementsByTagName('print-preview-app')[0]
              .$['sidebar']
              .shadowRoot.querySelector('print-preview-link-container')
              .$['openPdfInPreviewLink'];
      openPdfInPreview.click();)";
    ASSERT_TRUE(content::ExecJs(preview_dialog, kOpenPdfWithPreviewScript));
    WaitUntilCallbackReceived();
  }
#endif  // BUILDFLAG(IS_MAC)

  void PrimeAsRepeatingErrorGenerator() { reset_errors_after_check_ = false; }

#if BUILDFLAG(IS_WIN)
  void PrimeForPdfConversionErrorOnPageIndex(uint32_t page_index) {
    simulate_pdf_conversion_error_on_page_index_ = page_index;

    // Queuing converted pages to be spooled occurs on the UI thread, while the
    // actual spooling occurs on the worker thread.  The worker thread polls for
    // pages, making it difficult to know if earlier pages that are successfully
    // converted will get spooled before some other error causes the job to be
    // canceled.  Do not use rendered page counts as part of any test
    // expectations in this case.  Other events should be used to know when it
    // is safe to terminate the test.
    DisableCheckForOnRenderedPrintedPage();
  }
#endif

#if BUILDFLAG(ENABLE_OOP_PRINTING)
  void PrimeForSpoolingSharedMemoryErrors() {
    simulate_spooling_memory_errors_ = true;
  }

  void PrimeForFailInUseDefaultSettings() {
    test_printing_context_factory()->SetFailErrorOnUseDefaultSettings();
  }

#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)
  void PrimeForCancelInAskUserForSettings() {
    test_printing_context_factory()->SetCancelErrorOnAskUserForSettings();
  }

  void PrimeForFailInAskUserForSettings() {
    test_printing_context_factory()->SetFailErrorOnAskUserForSettings();
  }

  void PrimeForServiceTerminatesAfterGetUserSettings() {
    terminate_service_after_ask_user_for_settings_ = true;
  }
#endif

  void PrimeForFailInUpdatePrinterSettings() {
    test_printing_context_factory()->SetFailedErrorOnUpdatePrinterSettings();
  }

  void PrimeForCancelInNewDocument() {
    test_printing_context_factory()->SetCancelErrorOnNewDocument(
        /*cause_errors=*/true);
  }

  void PrimeForErrorsInNewDocument() {
    test_printing_context_factory()->SetFailedErrorOnNewDocument(
        /*cause_errors=*/true);
  }

  void PrimeForAccessDeniedErrorsInNewDocument() {
    test_printing_context_factory()->SetAccessDeniedErrorOnNewDocument(
        /*cause_errors=*/true);
  }

#if BUILDFLAG(IS_WIN)
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
  void PrimeForServiceTerminatesAfterUpdatePrintSettings() {
    terminate_service_after_update_print_settings_ = true;
  }
#endif

  void PrimeForAccessDeniedErrorsInRenderPrintedPage() {
    test_printing_context_factory()->SetAccessDeniedErrorOnRenderPage(
        /*cause_errors=*/true);
  }

  void PrimeForDelayedRenderingUntilPage(uint32_t page_number) {
    print_backend_service_->set_rendering_delayed_until_page(page_number);
  }

  void PrimeForRenderingErrorOnPage(uint32_t page_number) {
    test_printing_context_factory()->SetFailedErrorForRenderPage(page_number);
  }
#endif  // BUILDFLAG(IS_WIN)

  void PrimeForAccessDeniedErrorsInRenderPrintedDocument() {
    test_printing_context_factory()->SetAccessDeniedErrorOnRenderDocument(
        /*cause_errors=*/true);
  }

  void PrimeForAccessDeniedErrorsInDocumentDone() {
    test_printing_context_factory()->SetAccessDeniedErrorOnDocumentDone(
        /*cause_errors=*/true);
  }

#if BUILDFLAG(IS_WIN)
  void DisableCheckForOnRenderedPrintedPage() {
    check_for_rendered_printed_page_ = false;
  }
#endif

#if BUILDFLAG(ENABLE_OOP_PRINTING)
  void SetCheckForPrintPreviewDone(bool check) {
    check_for_print_preview_done_ = check;
  }
#endif

  void SetCheckForRenderFrameDeleted(bool check) {
    check_for_render_frame_deleted_ = check;
  }

  const std::optional<bool> system_print_registration_succeeded() const {
    return system_print_registration_succeeded_;
  }

  bool did_use_default_settings() const { return did_use_default_settings_; }

  bool did_get_settings_with_ui() const { return did_get_settings_with_ui_; }

  bool print_backend_service_use_detected() const {
    return print_backend_service_use_detected_;
  }
#endif  // BUILDFLAG(ENABLE_OOP_PRINTING)

  mojom::ResultCode use_default_settings_result() const {
    return use_default_settings_result_;
  }

#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)
  mojom::ResultCode ask_user_for_settings_result() const {
    return ask_user_for_settings_result_;
  }
#endif

  mojom::ResultCode update_print_settings_result() const {
    return update_print_settings_result_;
  }

  mojom::ResultCode start_printing_result() const {
    return start_printing_result_;
  }

#if BUILDFLAG(IS_WIN)
  mojom::ResultCode render_printed_page_result() const {
    return render_printed_page_result_;
  }
  int render_printed_page_count() const { return render_printed_pages_count_; }
#endif  // BUILDFLAG(IS_WIN)

  mojom::ResultCode render_printed_document_result() {
    return render_printed_document_result_;
  }

  mojom::ResultCode document_done_result() const {
    return document_done_result_;
  }

  std::optional<int> document_done_job_id() const {
    return document_done_job_id_;
  }

  int cancel_count() const { return cancel_count_; }
  std::optional<mojom::ResultCode> in_process_last_error_result_code() const {
    return in_process_last_error_result_code_;
  }

  int print_job_construction_count() const {
    return print_job_construction_count_;
  }
  int print_job_destruction_count() const {
    return print_job_destruction_count_;
  }
  int did_print_document_count() const { return did_print_document_count_; }
#if BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
  int composited_for_content_analysis_count() const {
    return composited_for_content_analysis_count_;
  }
#endif

 private:
#if BUILDFLAG(ENABLE_OOP_PRINTING)
  std::unique_ptr<PrinterQuery> CreatePrinterQuery(
      bool use_service,
      content::GlobalRenderFrameHostId rfh_id) {
    if (use_service) {
      return std::make_unique<TestPrinterQueryOop>(
          rfh_id, simulate_spooling_memory_errors_,
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG) && BUILDFLAG(IS_WIN)
          base::BindLambdaForTesting([&]() {
            if (terminate_service_after_update_print_settings_) {
              ResetService();
            }
          }),
#endif
          base::BindLambdaForTesting([&]() {
            if (terminate_service_after_ask_user_for_settings_) {
              ResetService();
            }
          }),
          &test_print_job_worker_oop_callbacks_);
    }
    return std::make_unique<TestPrinterQuery>(
        rfh_id, &test_print_job_worker_callbacks_);
  }

  void OnUseDefaultSettings() {
    did_use_default_settings_ = true;
    PrintBackendServiceDetectionCheck();
    CheckForQuit();
  }

  void OnGetSettingsWithUI() {
    did_get_settings_with_ui_ = true;
    PrintBackendServiceDetectionCheck();
    CheckForQuit();
  }

  void PrintBackendServiceDetectionCheck() {
    // Want to know if `PrintBackendService` clients are ever detected, since
    // registrations could have gone away by the time checks are made at the
    // end of tests.
    if (PrintBackendServiceManager::GetInstance().GetClientsRegisteredCount() >
        0) {
      print_backend_service_use_detected_ = true;
    }
  }
#endif  // BUILDFLAG(ENABLE_OOP_PRINTING)

  void OopErrorCheck(mojom::ResultCode result) {
    // Interested to reset any trigger for causing access-denied errors, so
    // that retry logic has a chance to be exercised and succeed.
    if (result == mojom::ResultCode::kAccessDenied) {
      ResetForNoAccessDeniedErrors();
    }
  }

  void InProcessErrorCheck(mojom::ResultCode result) {
    // This is expected to only be called with unsuccessful results.
    DCHECK_NE(result, mojom::ResultCode::kSuccess);
    in_process_last_error_result_code_ = result;
  }

  void OnDidUseDefaultSettings(mojom::ResultCode result) {
    use_default_settings_result_ = result;
    CheckForQuit();
  }

#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)
  void OnDidAskUserForSettings(mojom::ResultCode result) {
    ask_user_for_settings_result_ = result;
    CheckForQuit();
  }
#endif

  void OnDidUpdatePrintSettings(mojom::ResultCode result) {
    update_print_settings_result_ = result;
    CheckForQuit();
  }

  void OnDidStartPrinting(mojom::ResultCode result) {
    start_printing_result_ = result;
    CheckForQuit();
  }

#if BUILDFLAG(IS_WIN)
  void OnDidRenderPrintedPage(uint32_t page_number, mojom::ResultCode result) {
    render_printed_page_result_ = result;
    if (result == mojom::ResultCode::kSuccess) {
      render_printed_pages_count_++;
    }
    if (check_for_rendered_printed_page_) {
      CheckForQuit();
    }
  }
#endif

  void OnDidRenderPrintedDocument(mojom::ResultCode result) {
    render_printed_document_result_ = result;
    CheckForQuit();
  }

  void OnDidDocumentDone(int job_id, mojom::ResultCode result) {
    document_done_job_id_ = job_id;
    document_done_result_ = result;
    CheckForQuit();
  }

  void OnFinishDocumentDone(int job_id) { document_done_job_id_ = job_id; }

  void OnDidCancel() {
    ++cancel_count_;
    CheckForQuit();
  }

  void OnDidDestroyPrintJob() {
    ++print_job_destruction_count_;
    CheckForQuit();
  }

  void ResetForNoAccessDeniedErrors() {
    // Don't do the reset if test scenario is repeatedly return errors.
    if (!reset_errors_after_check_) {
      return;
    }

    test_printing_context_factory()->SetAccessDeniedErrorOnNewDocument(
        /*cause_errors=*/false);
#if BUILDFLAG(IS_WIN)
    test_printing_context_factory()->SetAccessDeniedErrorOnRenderPage(
        /*cause_errors=*/false);
#endif
    test_printing_context_factory()->SetAccessDeniedErrorOnRenderDocument(
        /*cause_errors=*/false);
    test_printing_context_factory()->SetAccessDeniedErrorOnDocumentDone(
        /*cause_errors=*/false);
  }

  void ResetService() {
    print_backend_service_.reset();
    test_remote_.reset();
  }

  base::test::ScopedFeatureList feature_list_;
#if BUILDFLAG(IS_WIN)
  bool check_for_rendered_printed_page_ = true;
#endif
#if BUILDFLAG(ENABLE_OOP_PRINTING)
  bool check_for_print_preview_done_ = false;
  bool check_for_render_frame_deleted_ = false;
  TestPrintJobWorker::PrintCallbacks test_print_job_worker_callbacks_;
  TestPrintJobWorkerOop::PrintCallbacks test_print_job_worker_oop_callbacks_;
  CreatePrinterQueryCallback test_create_printer_query_callback_;
  std::optional<bool> system_print_registration_succeeded_;
  bool did_use_default_settings_ = false;
  bool did_get_settings_with_ui_ = false;
  bool print_backend_service_use_detected_ = false;
  bool simulate_spooling_memory_errors_ = false;
#if BUILDFLAG(IS_WIN)
  std::optional<uint32_t> simulate_pdf_conversion_error_on_page_index_;
#endif  // BUILDFLAG(IS_WIN)
  mojo::Remote<mojom::PrintBackendService> test_remote_;
  std::unique_ptr<PrintBackendServiceTestImpl> print_backend_service_;
#endif  // BUILDFLAG(ENABLE_OOP_PRINTING)
  std::optional<mojom::ResultCode> in_process_last_error_result_code_;
  bool reset_errors_after_check_ = true;
  int did_print_document_count_ = 0;
  mojom::ResultCode use_default_settings_result_ = mojom::ResultCode::kFailed;
#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)
  mojom::ResultCode ask_user_for_settings_result_ = mojom::ResultCode::kFailed;
  bool terminate_service_after_ask_user_for_settings_ = false;
#endif
  mojom::ResultCode update_print_settings_result_ = mojom::ResultCode::kFailed;
  mojom::ResultCode start_printing_result_ = mojom::ResultCode::kFailed;
#if BUILDFLAG(IS_WIN)
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
  bool terminate_service_after_update_print_settings_ = false;
#endif
  mojom::ResultCode render_printed_page_result_ = mojom::ResultCode::kFailed;
  int render_printed_pages_count_ = 0;
#endif  // BUILDFLAG(IS_WIN)
  mojom::ResultCode render_printed_document_result_ =
      mojom::ResultCode::kFailed;
  mojom::ResultCode document_done_result_ = mojom::ResultCode::kFailed;
  std::optional<int> document_done_job_id_;
  int cancel_count_ = 0;
  int print_job_construction_count_ = 0;
  int print_job_destruction_count_ = 0;
#if BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
  int composited_for_content_analysis_count_ = 0;
#endif
};

#if BUILDFLAG(ENABLE_OOP_PRINTING)

class SystemAccessProcessUnsandboxedEarlyStartServicePrintBrowserTest
    : public SystemAccessProcessPrintBrowserTestBase,
      public testing::WithParamInterface<bool> {
 public:
  SystemAccessProcessUnsandboxedEarlyStartServicePrintBrowserTest() = default;
  ~SystemAccessProcessUnsandboxedEarlyStartServicePrintBrowserTest() override =
      default;

  bool UseService() override { return true; }
  bool SandboxService() override { return false; }
  bool EarlyStartService() override { return GetParam(); }
#if BUILDFLAG(IS_WIN)
  bool UseXps() override { return false; }
#endif

  bool DoesPrintBackendServiceTaskExist() {
    TaskManagerInterface* task_mgr = TaskManagerInterface::GetTaskManager();
    std::u16string title = MatchUtility(u"Print Backend Service");
    for (auto task_id : task_mgr->GetTaskIdsList()) {
      if (title == task_mgr->GetTitle(task_id)) {
        return true;
      }
    }
    return false;
  }
};

INSTANTIATE_TEST_SUITE_P(
    All,
    SystemAccessProcessUnsandboxedEarlyStartServicePrintBrowserTest,
    /*EarlyStartService=*/testing::Bool(),
    GetServiceLaunchTimingTestSuffix);

class SystemAccessProcessPrintBrowserTest
    : public SystemAccessProcessPrintBrowserTestBase,
      public testing::WithParamInterface<
          PrintBackendAndPlatformPrintApiVariation> {
 public:
  SystemAccessProcessPrintBrowserTest() = default;
  ~SystemAccessProcessPrintBrowserTest() override = default;

  bool UseService() override {
    return GetParam().print_backend !=
           PrintBackendFeatureVariation::kInBrowserProcess;
  }
  bool SandboxService() override {
    return GetParam().print_backend ==
           PrintBackendFeatureVariation::kOopSandboxedService;
  }
#if BUILDFLAG(IS_WIN)
  bool UseXps() override {
    return GetParam().platform_api == PlatformPrintApiVariation::kXps;
  }
#endif

#if BUILDFLAG(IS_WIN)
  mojom::PrinterLanguageType UseLanguageType() {
    switch (GetParam().platform_api) {
      case PlatformPrintApiVariation::kGdiEmf:
        return mojom::PrinterLanguageType::kNone;
      case PlatformPrintApiVariation::kGdiPostScriptLevel2:
        return mojom::PrinterLanguageType::kPostscriptLevel2;
      case PlatformPrintApiVariation::kGdiPostScriptLevel3:
        return mojom::PrinterLanguageType::kPostscriptLevel3;
      case PlatformPrintApiVariation::kGdiTextOnly:
        return mojom::PrinterLanguageType::kTextOnly;
      case PlatformPrintApiVariation::kXps:
        return mojom::PrinterLanguageType::kXps;
    }
  }
#endif
};

INSTANTIATE_TEST_SUITE_P(
    All,
    SystemAccessProcessPrintBrowserTest,
    testing::ValuesIn(GeneratePrintBackendAndPlatformPrintApiVariations(
        {PrintBackendFeatureVariation::kInBrowserProcess,
         PrintBackendFeatureVariation::kOopSandboxedService,
         PrintBackendFeatureVariation::kOopUnsandboxedService})),
    GetPrintBackendAndPlatformPrintApiTestSuffix);

using SystemAccessProcessServicePrintBrowserTest =
    SystemAccessProcessPrintBrowserTest;

INSTANTIATE_TEST_SUITE_P(
    All,
    SystemAccessProcessServicePrintBrowserTest,
    testing::ValuesIn(GeneratePrintBackendAndPlatformPrintApiVariations(
        {PrintBackendFeatureVariation::kOopSandboxedService,
         PrintBackendFeatureVariation::kOopUnsandboxedService})),
    GetPrintBackendAndPlatformPrintApiTestSuffix);

using SystemAccessProcessSandboxedServicePrintBrowserTest =
    SystemAccessProcessServicePrintBrowserTest;

INSTANTIATE_TEST_SUITE_P(
    All,
    SystemAccessProcessSandboxedServicePrintBrowserTest,
    testing::ValuesIn(GeneratePrintBackendAndPlatformPrintApiVariations(
        {PrintBackendFeatureVariation::kOopSandboxedService})),
    GetPrintBackendAndPlatformPrintApiTestSuffix);

using SystemAccessProcessSandboxedServiceLanguagePrintBrowserTest =
    SystemAccessProcessServicePrintBrowserTest;

INSTANTIATE_TEST_SUITE_P(
    All,
    SystemAccessProcessSandboxedServiceLanguagePrintBrowserTest,
    testing::ValuesIn(kSandboxedServicePlatformPrintLanguageApiVariations),
    GetPrintBackendAndPlatformPrintApiTestSuffix);

IN_PROC_BROWSER_TEST_P(
    SystemAccessProcessUnsandboxedEarlyStartServicePrintBrowserTest,
    ServiceLaunched) {
  chrome::ShowTaskManager(browser());

  // Wait for browser to open with a tab.
  ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyTab()));

  // Now that startup is complete, look through the list of processes in the
  // Task Manager to see if a Print Backend service has been started (even
  // though there has not been any request for printing).
  CHECK_EQ(DoesPrintBackendServiceTaskExist(), EarlyStartService());
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       UpdatePrintSettings) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/3_pages.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  TestPrintViewManager print_view_manager(web_contents);
  PrintViewManager::SetReceiverImplForTesting(&print_view_manager);

  PrintAndWaitUntilPreviewIsReady();

  EXPECT_EQ(3u, rendered_page_count());

  const mojom::PrintPagesParamsPtr& snooped_params =
      print_view_manager.snooped_params();
  ASSERT_TRUE(snooped_params);
  EXPECT_EQ(test::kPrinterCapabilitiesDpi, snooped_params->params->dpi);

#if BUILDFLAG(IS_MAC)
  EXPECT_EQ(kLegalPhysicalSize, snooped_params->params->page_size);
  EXPECT_EQ(kLegalPrintableArea, snooped_params->params->printable_area);
  EXPECT_EQ(kLegalExpectedContentSize, snooped_params->params->content_size);
#else
  EXPECT_EQ(kLetterPhysicalSize, snooped_params->params->page_size);
  EXPECT_EQ(kLetterPrintableArea, snooped_params->params->printable_area);
  EXPECT_EQ(kLetterExpectedContentSize, snooped_params->params->content_size);
#endif
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       UpdatePrintSettingsPrintableArea) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  TestPrintViewManager print_view_manager(web_contents);
  PrintViewManager::SetReceiverImplForTesting(&print_view_manager);

  AdjustMediaAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(1u, rendered_page_count());

  const mojom::PrintPagesParamsPtr& snooped_params =
      print_view_manager.snooped_params();
  ASSERT_TRUE(snooped_params);
  EXPECT_EQ(test::kPrinterCapabilitiesDpi, snooped_params->params->dpi);

#if BUILDFLAG(IS_MAC)
  EXPECT_EQ(kLetterPhysicalSize, snooped_params->params->page_size);
  EXPECT_EQ(kLetterPrintableArea, snooped_params->params->printable_area);
  EXPECT_EQ(kLetterExpectedContentSize, snooped_params->params->content_size);
#else
  EXPECT_EQ(kLegalPhysicalSize, snooped_params->params->page_size);
  EXPECT_EQ(kLegalPrintableArea, snooped_params->params->printable_area);
  EXPECT_EQ(kLegalExpectedContentSize, snooped_params->params->content_size);
#endif
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       UpdatePrintSettingsFails) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForFailInUpdatePrinterSettings();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Update print settings, which fails.  No print job is created.
  // 2.  An error dialog is displayed.
  SetNumExpectedMessages(/*num=*/2);

  // Since the preview is loaded before initiating the Print, the error
  // is displayed in the preview and the dialog remains open.
  content::WebContents* preview_dialog = PrintAfterPreviewIsReadyAndLoaded();
  ASSERT_TRUE(preview_dialog);

  EXPECT_EQ(update_print_settings_result(), mojom::ResultCode::kFailed);
  EXPECT_EQ(error_dialog_shown_count(), 1u);

  // Need to close the dialog to ensure proper cleanup is done before
  // sanity checks at test termination.  This posts to UI thread to close,
  // so need to ensure that has a chance to run before terminating.
  CancelPrintPreview(preview_dialog);
  base::RunLoop().RunUntilIdle();
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       PrintWithPreviewBeforeLoadedUpdatePrintSettingsFails) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForFailInUpdatePrinterSettings();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Update print settings, which fails.  No print job is created.
  // 2.  An error dialog is displayed.
  SetNumExpectedMessages(/*num=*/2);
  PrintAfterPreviewIsReadyAndMaybeLoaded(PrintParams(),
                                         /*wait_for_loaded=*/false);

  // Print Preview dialog will have been closed, ensure that the UI thread
  // runs all posted tasks to reflect that before checking it is gone.
  base::RunLoop().RunUntilIdle();
  content::WebContents* preview_dialog =
      PrintPreviewDialogController::GetInstance()->GetPrintPreviewForContents(
          web_contents);
  ASSERT_FALSE(preview_dialog);

  EXPECT_EQ(update_print_settings_result(), mojom::ResultCode::kFailed);

  // Initiating printing before the document is ready hides the Print Preview
  // dialog.  An error dialog should get shown to notify the user.
  EXPECT_EQ(error_dialog_shown_count(), 1u);
}

IN_PROC_BROWSER_TEST_P(
    SystemAccessProcessSandboxedServiceLanguagePrintBrowserTest,
    StartPrinting) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
#if BUILDFLAG(IS_WIN)
  SetPrinterLanguageTypeForSubsequentContexts(UseLanguageType());
#endif
  constexpr int kJobId = 1;
  SetNewDocumentJobId(kJobId);

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Update print settings.
  // 2.  A print job is started.
  // 3.  Rendering for 1 page of document of content.
  // 4.  Completes with document done.
  // 5.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/5);
  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
#if BUILDFLAG(IS_WIN)
  // TODO(crbug.com/40100562)  Include Windows coverage of
  // RenderPrintedDocument() once XPS print pipeline is added.
  EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(render_printed_page_count(), 1);
#else
  EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kSuccess);
#endif
  EXPECT_EQ(document_done_result(), mojom::ResultCode::kSuccess);
  EXPECT_THAT(document_done_job_id(), testing::Optional(kJobId));
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 1);

#if BUILDFLAG(IS_LINUX) && BUILDFLAG(USE_CUPS)
  std::optional<PrintSettings> settings = document_print_settings();
  ASSERT_TRUE(settings);
  // Collect just the keys to compare the info options vs. advanced settings.
  std::vector<std::string> advanced_setting_keys;
  std::vector<std::string> print_info_options_keys;
  const PrintSettings::AdvancedSettings& advanced_settings =
      settings->advanced_settings();
  for (const auto& advanced_setting : advanced_settings) {
    advanced_setting_keys.push_back(advanced_setting.first);
  }
  for (const auto& option : test::kPrintInfoOptions) {
    print_info_options_keys.push_back(option.first);
  }
  EXPECT_THAT(advanced_setting_keys,
              testing::UnorderedElementsAreArray(print_info_options_keys));
#endif  // BUILDFLAG(IS_LINUX) && BUILDFLAG(USE_CUPS)
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartPrintingMultipage) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  constexpr int kJobId = 1;
  SetNewDocumentJobId(kJobId);

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/3_pages.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

#if BUILDFLAG(IS_WIN)
  // Windows GDI results in a callback for each rendered page.
  // The expected events for this are:
  // 1.  Update print settings.
  // 2.  A print job is started.
  // 3.  First page is rendered.
  // 4.  Second page is rendered.
  // 5.  Third page is rendered.
  // 6.  Completes with document done.
  // 7.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  // TODO(crbug.com/40100562)  Include Windows coverage of
  // RenderPrintedDocument() once XPS print pipeline is added.
  SetNumExpectedMessages(/*num=*/7);
#else
  // The expected events for this are:
  // 1.  Update print settings.
  // 2.  A print job is started.
  // 3.  Document is rendered.
  // 4.  Completes with document done.
  // 5.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/5);
#endif
  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
#if BUILDFLAG(IS_WIN)
  // TODO(crbug.com/40100562)  Include Windows coverage of
  // RenderPrintedDocument() once XPS print pipeline is added.
  EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(render_printed_page_count(), 3);
#else
  EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kSuccess);
#endif
  EXPECT_EQ(document_done_result(), mojom::ResultCode::kSuccess);
  EXPECT_THAT(document_done_job_id(), testing::Optional(kJobId));
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessServicePrintBrowserTest,
                       StartPrintingSpoolingSharedMemoryError) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForSpoolingSharedMemoryErrors();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // No attempt to retry is made if a job has a shared memory error when trying
  // to spool a page/document fails on a shared memory error.  The test
  // sequence for this is:
  // 1.  Update print settings.
  // 2.  A print job is started.
  // 3.  Spooling to send the render data will fail.  An error dialog is shown.
  // 4.  The print job is canceled.  The callback from the service could occur
  //     after the print job has been destroyed.
  // 5.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/5);

  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(cancel_count(), 1);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

#if BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       StartPrintingPdfConversionFails) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForPdfConversionErrorOnPageIndex(/*page_index=*/1);

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/3_pages.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  if (UseService()) {
    // The expected events for this are:
    // 1.  Update print settings.
    // 2.  A print job is started.
    // 3.  PDF conversion fails, which results in the print job being
    //     canceled.
    // 4.  Wait for the print job to be destroyed, to ensure printing finished
    //     cleanly before completing the test.
    // No error dialog is shown.
    SetNumExpectedMessages(/*num=*/4);
  } else {
    // The expected events for this are:
    // 1.  Update print settings.
    // 2.  Print job is started, but is canceled and destroyed due to failure
    //     during PDF conversion failure.
    // No error dialog is shown.
    SetNumExpectedMessages(/*num=*/2);
  }
  PrintAfterPreviewIsReadyAndLoaded();

  // No tracking of start printing or cancel callbacks for in-browser tests,
  // only for OOP.
  if (UseService()) {
    EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
  } else {
    EXPECT_THAT(in_process_last_error_result_code(),
                testing::Optional(mojom::ResultCode::kCanceled));
  }
  // TODO(crbug.com/40288222):  Update expectation once an error is shown for
  // this failure.
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 1);
}
#endif  // BUILDFLAG(IS_WIN)

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       StartPrintingFails) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForErrorsInNewDocument();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  if (UseService()) {
    // The expected events for this are:
    // 1.  Update print settings.
    // 2.  A print job is started, but that fails.
    // 3.  An error dialog is shown.
    // 4.  The print job is canceled.  The callback from the service could occur
    //     after the print job has been destroyed.
    // 5.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/5);
  } else {
    // The print job is started, but that fails and gets canceled.
    // The expected events for this are:
    // 1.  Update print settings.
    // 2.  An error dialog is shown.
    // 3.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/3);
  }

  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(error_dialog_shown_count(), 1u);
  if (UseService()) {
    EXPECT_EQ(start_printing_result(), mojom::ResultCode::kFailed);
    EXPECT_EQ(cancel_count(), 1);
  } else {
    EXPECT_THAT(in_process_last_error_result_code(),
                testing::Optional(mojom::ResultCode::kCanceled));
  }
  EXPECT_EQ(print_job_destruction_count(), 1);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       StartPrintingCanceled) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForCancelInNewDocument();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  if (UseService()) {
    // The expected events for this are:
    // 1.  Update print settings.
    // 2.  A print job is started, but results in a cancel.
    // 3.  The print job is canceled.
    // 4.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/4);
  } else {
    // A print job is started, but results in a cancel.  There are no callbacks
    // to notice the start job.  The expected events for this are:
    // 1.  Update print settings.
    // 2.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/2);
  }

  PrintAfterPreviewIsReadyAndLoaded();

  if (UseService()) {
    EXPECT_EQ(start_printing_result(), mojom::ResultCode::kCanceled);
    EXPECT_EQ(cancel_count(), 1);
  } else {
    EXPECT_THAT(in_process_last_error_result_code(),
                testing::Optional(mojom::ResultCode::kCanceled));
  }
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartPrintingAccessDenied) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  constexpr int kJobId = 1;
  SetNewDocumentJobId(kJobId);
  PrimeForAccessDeniedErrorsInNewDocument();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Update print settings.
  // 2.  A print job is started, but has an access-denied error.
  // 3.  A retry to start the print job with adjusted access will succeed.
  // 4.  Rendering for 1 page of document of content.
  // 5.  Completes with document done.
  // 6.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/6);

  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
#if BUILDFLAG(IS_WIN)
  // TODO(crbug.com/40100562)  Include Windows coverage of
  // RenderPrintedDocument() once XPS print pipeline is added.
  EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(render_printed_page_count(), 1);
#else
  EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kSuccess);
#endif
  EXPECT_EQ(document_done_result(), mojom::ResultCode::kSuccess);
  EXPECT_THAT(document_done_job_id(), testing::Optional(kJobId));
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartPrintingRepeatedAccessDenied) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeAsRepeatingErrorGenerator();
  PrimeForAccessDeniedErrorsInNewDocument();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // Test of a misbehaving printer driver which only returns access-denied
  // errors.  The expected events for this are:
  // 1.  Update print settings.
  // 2.  A print job is started, but has an access-denied error.
  // 3.  A retry to start the print job with adjusted access will still fail.
  // 4.  An error dialog is shown.
  // 5.  The print job is canceled.  The callback from the service could occur
  //     after the print job has been destroyed.
  // 6.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/6);

  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kAccessDenied);
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(cancel_count(), 1);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

#if BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartPrintingRenderPageAccessDenied) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForAccessDeniedErrorsInRenderPrintedPage();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // No attempt to retry is made if an access-denied error occurs when trying
  // to render a page.  The expected events for this are:
  // 1.  Update print settings.
  // 2.  A print job is started.
  // 3.  Rendering for 1 page of document of content fails with access denied.
  // 4.  An error dialog is shown.
  // 5.  The print job is canceled.  The callback from the service could occur
  //     after the print job has been destroyed.
  // 6.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/6);

  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kAccessDenied);
  EXPECT_EQ(render_printed_page_count(), 0);
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(cancel_count(), 1);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartPrintingMultipageMidJobError) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  // Delay rendering until all pages have been sent, to avoid any race
  // conditions related to error handling.  This is to ensure that page 3 is in
  // the service queued for processing, before we let page 2 be processed and
  // have it trigger an error that could affect page 3 processing.
  PrimeForDelayedRenderingUntilPage(/*page_number=*/3);
  PrimeForRenderingErrorOnPage(/*page_number=*/2);

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/3_pages.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Update print settings.
  // 2.  Start the print job.
  // 3.  First page render callback shows success.
  // 4.  Second page render callback shows failure.  Will start failure
  //     processing to cancel the print job.
  // 5.  A printing error dialog is displayed.
  // 6.  Third page render callback will show it was canceled (due to prior
  //     failure).  This is disregarded by the browser, since the job has
  //     already been canceled.
  // 7.  The print job is canceled.  The callback from the service could occur
  //     after the print job has been destroyed.
  // 8.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/8);

  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
  // First failure page is `kFailed`, but is followed by another page with
  // status `kCanceled`.
  EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kCanceled);
  EXPECT_EQ(render_printed_page_count(), 1);
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(cancel_count(), 1);
  EXPECT_EQ(print_job_destruction_count(), 1);
}
#endif  // BUILDFLAG(IS_WIN)

// TODO(crbug.com/40100562)  Include Windows once XPS print pipeline is added.
#if !BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartPrintingRenderDocumentAccessDenied) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForAccessDeniedErrorsInRenderPrintedDocument();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // No attempt to retry is made if an access-denied error occurs when trying
  // to render a document.  The expected events for this are:
  // 1.  Update print settings.
  // 2.  A print job is started.
  // 3.  Rendering for 1 page of document of content fails with access denied.
  // 4.  An error dialog is shown.
  // 5.  The print job is canceled.  The callback from the service could occur
  //     after the print job has been destroyed.
  // 6.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/6);

  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kAccessDenied);
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(cancel_count(), 1);
  EXPECT_EQ(print_job_destruction_count(), 1);
}
#endif  // !BUILDFLAG(IS_WIN)

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartPrintingDocumentDoneAccessDenied) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForAccessDeniedErrorsInDocumentDone();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // No attempt to retry is made if an access-denied error occurs when trying
  // do wrap-up a rendered document.  The expected events are:
  // 1.  Update print settings.
  // 2.  A print job is started.
  // 3.  Rendering for 1 page of document of content.
  // 4.  Document done results in an access-denied error.
  // 5.  An error dialog is shown.
  // 6.  The print job is canceled.  The callback from the service could occur
  //     after the print job has been destroyed.
  // 7.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/7);

  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
#if BUILDFLAG(IS_WIN)
  // TODO(crbug.com/40100562)  Include Windows coverage of
  // RenderPrintedDocument() once XPS print pipeline is added.
  EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(render_printed_page_count(), 1);
#else
  EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kSuccess);
#endif
  EXPECT_EQ(document_done_result(), mojom::ResultCode::kAccessDenied);
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(cancel_count(), 1);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       SystemPrintFromPrintPreview) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  constexpr int kJobId = 1;
  SetNewDocumentJobId(kJobId);

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  if (UseService()) {
#if BUILDFLAG(IS_WIN)
    // Once the transition to system print is initiated, the expected events
    // are:
    // 1.  Update print settings.
    // 2.  A print job is started.
    // 3.  Rendering for 1 page of document of content.
    // 4.  Completes with document done.
    // 5.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/5);
#else
    // Once the transition to system print is initiated, the expected events
    // are:
    // 1.  Use default settings.
    // 2.  Ask the user for settings.
    // 3.  A print job is started.
    // 4.  Rendering for 1 page of document of content.
    // 5.  Completes with document done.
    // 6.  Wait until all processing for DidPrintDocument is known to have
    //     completed, to ensure printing finished cleanly before completing the
    //     test.
    // 7.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/7);
#endif  // BUILDFLAG(IS_WIN)
  } else {
#if BUILDFLAG(IS_WIN)
    // Once the transition to system print is initiated, the expected events
    // are:
    // 1.  Update print settings.
    // 2.  There are no other callbacks that trigger for print stages with
    //     in-browser printing for the Windows case.  The only other expected
    //     event for this is to wait for the one print job to be destroyed, to
    //     ensure printing finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/2);
#else
    // Once the transition to system print is initiated, the expected events
    // are:
    // 1.  Use default settings.
    // 2.  Ask the user for settings.
    // 3.  Wait until all processing for DidPrintDocument is known to have
    //     completed, to ensure printing finished cleanly before completing the
    //     test.
    // 4.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/4);
#endif  // BUILDFLAG(IS_WIN)
  }
  SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);

  if (UseService()) {
    EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
#if BUILDFLAG(IS_WIN)
    // TODO(crbug.com/40100562)  Include Windows coverage of
    // RenderPrintedDocument() once XPS print pipeline is added.
    EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kSuccess);
    EXPECT_EQ(render_printed_page_count(), 1);
#else
    EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kSuccess);
#endif
    EXPECT_EQ(document_done_result(), mojom::ResultCode::kSuccess);
    EXPECT_EQ(*test::MakeUserModifiedPrintSettings("printer1",
                                                   /*page_ranges=*/nullptr),
              *document_print_settings());
  } else {
#if !BUILDFLAG(IS_WIN)
    EXPECT_TRUE(did_get_settings_with_ui());
    EXPECT_EQ(did_print_document_count(), 1);
#endif
    EXPECT_TRUE(!in_process_last_error_result_code().has_value());
    EXPECT_EQ(*test::MakeUserModifiedPrintSettings("printer1",
                                                   /*page_ranges=*/nullptr),
              *document_print_settings());
  }
  EXPECT_THAT(document_done_job_id(), testing::Optional(kJobId));
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

#if BUILDFLAG(IS_WIN)
// This test is Windows-only because of Print Preview behavior in
// `onPrintWithSystemDialog_()`.  For Windows this call ends up going through
// `PrintViewManagerBase::PrintForPrintPreview()`, and thus invokes
// `UpdatePrintSettings()` before displaying the system dialog.  Other
// platforms end up going through `PrintViewManager::PrintForSystemDialogNow()`
// and thus do not update print settings before the system dialog is displayed.
IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       SystemPrintFromPrintPreviewUpdatePrintSettingsFails) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForFailInUpdatePrinterSettings();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // Once the transition to system print is initiated, the expected events
  // are:
  // 1.  Update the print settings, which fails.  No further printing calls
  //     are made.  No print job is created because of such an early failure.
  // 2.  An error dialog is displayed.
  SetNumExpectedMessages(/*num=*/2);

  SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);

  EXPECT_EQ(update_print_settings_result(), mojom::ResultCode::kFailed);
  EXPECT_EQ(error_dialog_shown_count(), 1u);
}

// This test is Windows-only because of Print Preview behavior in
// `onPrintWithSystemDialog_()`.  For Windows this call ends up going through
// `PrintViewManagerBase::PrintForPrintPreview()`, and thus invokes
// `UpdatePrintSettings()` before displaying the system dialog.  Other
// platforms end up going through `PrintViewManager::PrintForSystemDialogNow()`
// and thus do not update print settings before the system dialog is displayed.
IN_PROC_BROWSER_TEST_P(
    SystemAccessProcessSandboxedServicePrintBrowserTest,
    PrintPreviewAfterSystemPrintFromPrintPreviewUpdatePrintSettingsFails) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForFailInUpdatePrinterSettings();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // First invoke system print from Print Preview.  Must wait until the
  // PrintPreviewUI is completely done before proceeding to the second part
  // of this test to ensure that the client is unregistered from the
  // `PrintBackendServiceManager`.
  SetCheckForPrintPreviewDone(/*check=*/true);

  // Once the transition to system print is initiated, the expected events
  // are:
  // 1.  Update the print settings, which fails.  No further printing calls
  //     are made.  No print job is created because of such an early failure.
  // 2.  An error dialog is displayed.
  // 3.  Print Preview UI is done.
  SetNumExpectedMessages(/*num=*/3);
  SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);

  EXPECT_EQ(update_print_settings_result(), mojom::ResultCode::kFailed);
  EXPECT_EQ(error_dialog_shown_count(), 1u);

  // Reset before initiating another Print Preview.
  PrepareRunloop();
  ResetNumReceivedMessages();

  // No longer expect the `PrintPreviewUI` to issue a done callback as part of
  // the test expectations, since the Print Preview will stay open displaying
  // an error message.  There will still be a preview done callback during
  // test shutdown though, so disable doing an expectation check for that.
  SetCheckForPrintPreviewDone(/*check=*/false);

  // The expected events for this are:
  // 1.  Update the print settings, which fails.  No further printing calls
  //     are made.  No print job is created because of such an early failure.
  // 2.  An error dialog is displayed.
  SetNumExpectedMessages(/*num=*/2);
  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(update_print_settings_result(), mojom::ResultCode::kFailed);
  EXPECT_EQ(error_dialog_shown_count(), 2u);
}

// This test is Windows-only, since it is the only platform which can invoke
// the system print dialog from within `PrintingContext::UpdatePrintSettings()`.
// From that system dialog we can cause a cancel to occur.
// TODO(crbug.com/40561724):  Expand this to also cover in-browser, once an
// appropriate signal is available to use for tracking expected events.
IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       SystemPrintFromPrintPreviewCancelRetry) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForCancelInAskUserForSettings();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // First invoke system print from Print Preview.  Must wait until the
  // PrintPreviewUI is completely done before proceeding to the second part
  // of this test to ensure that the client is unregistered from the
  // `PrintBackendServiceManager`.
  SetCheckForPrintPreviewDone(/*check=*/true);

  // The expected events for this are:
  // 1.  Update the print settings, which indicates to cancel the print
  //     request.  No further printing calls are made.  No print job is
  //     created because of such an early cancel.
  // 2.  Print Preview UI is done.
  SetNumExpectedMessages(/*num=*/2);

  SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);

  EXPECT_EQ(update_print_settings_result(), mojom::ResultCode::kCanceled);
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 0);

  // Now try to initiate the system print from a Print Preview again.
  // Same number of expected events.
  PrepareRunloop();
  ResetNumReceivedMessages();

  SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);

  EXPECT_EQ(update_print_settings_result(), mojom::ResultCode::kCanceled);
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 0);
}

// TODO(crbug.com/40942272):  Enable test for Linux and macOS once renderer
// RunLoop behavior can be made to work with test expectations.
IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       SystemPrintAfterSystemPrintFromPrintPreview) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForCancelInAskUserForSettings();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // First invoke system print from Print Preview.  Wait until the
  // PrintPreviewUI is done before proceeding to the second part of the
  // test.
  SetCheckForPrintPreviewDone(/*check=*/true);

  if (UseService()) {
    // Once the transition to system print is initiated, the expected events
    // are:
    // 1.  Update the print settings.  This internally invokes the system
    //     print dialog which cancels.
    // 2.  Print Preview is done.
    // No print job is created because of such an early cancel.
    SetNumExpectedMessages(/*num=*/2);
  } else {
    // Once the transition to system print is initiated, the expected events
    // are:
    // 1.  Update the print settings.
    // 2.  Print Preview is done.
    // No print job is created because of such an early cancel.
    SetNumExpectedMessages(/*num=*/2);
  }
  SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);

  if (UseService()) {
    // Windows invokes system print dialog from UpdatePrintSettings().
    EXPECT_EQ(update_print_settings_result(), mojom::ResultCode::kCanceled);
  } else {
    // User settings are invoked from within UpdatePrintSettings().
    EXPECT_FALSE(did_use_default_settings());
    EXPECT_FALSE(did_get_settings_with_ui());

    // `PrintBackendService` should never be used when printing in-browser.
    EXPECT_FALSE(print_backend_service_use_detected());
  }

  // Reset before initiating system print.
  PrepareRunloop();
  ResetNumReceivedMessages();

  // The expected events for this are:
  // 1.  Get the default settings.
  // 2.  Ask the user for settings, which cancels out.  No further printing
  // calls are made.
  SetNumExpectedMessages(/*num=*/2);

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

  if (UseService()) {
    EXPECT_EQ(use_default_settings_result(), mojom::ResultCode::kSuccess);
    EXPECT_EQ(ask_user_for_settings_result(), mojom::ResultCode::kCanceled);
  } else {
    EXPECT_TRUE(did_use_default_settings());
    EXPECT_TRUE(did_get_settings_with_ui());
  }
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 0);
}
#endif  // BUILDFLAG(IS_WIN)

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       PrintPreviewPrintAfterSystemPrintRendererCrash) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  content::RenderFrameHost* frame = web_contents->GetPrimaryMainFrame();
  content::RenderProcessHost* frame_rph = frame->GetProcess();

  KillPrintRenderFrame frame_content(frame_rph,
                                     GetPrintRenderFrame(frame).get());
  frame_content.OverrideBinderForTesting(frame);

  // With the renderer being prepared to fake a crash, the test needs to watch
  // for it being deleted.
  SetCheckForRenderFrameDeleted(/*check=*/true);
  content::ScopedAllowRendererCrashes allow_renderer_crash;

  // First invoke system print directly.

  // The expected events for this are:
  // 1.  Printing is attempted, but quickly get notified that the render frame
  //     has been deleted because the renderer "crashed".
  SetNumExpectedMessages(/*num=*/1);

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

  // After renderer crash, reload the page again in the same tab.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  // Now try to initiate print from a Print Preview.
  PrepareRunloop();
  ResetNumReceivedMessages();

  // No longer interested in when the renderer is deleted.
  SetCheckForRenderFrameDeleted(/*check=*/false);

  // The expected events for this are:
  // 1.  Update print settings.
  // 2.  A print job is started.
  // 3.  Rendering for 1 page of document of content.
  // 4.  Completes with document done.
  // 5.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/5);

  PrintAfterPreviewIsReadyAndLoaded();

  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
#if BUILDFLAG(IS_WIN)
  // TODO(crbug.com/40100562)  Include Windows coverage of
  // RenderPrintedDocument() once XPS print pipeline is added.
  EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(render_printed_page_count(), 1);
#else
  EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kSuccess);
#endif
  EXPECT_EQ(document_done_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartBasicPrint) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  constexpr int kJobId = 1;
  SetNewDocumentJobId(kJobId);

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Get the default settings.
  // 2.  Ask the user for settings.
  // 3.  A print job is started.
  // 4.  The print compositor will complete generating the document.
  // 5.  The document is rendered.
  // 6.  Receive document done notification.
  // 7.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/7);

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

  // macOS and Linux currently have to invoke a system dialog from within the
  // browser process.  There is not a callback to capture the result in these
  // cases.
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
  EXPECT_EQ(use_default_settings_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(ask_user_for_settings_result(), mojom::ResultCode::kSuccess);
#else
  EXPECT_TRUE(did_use_default_settings());
  EXPECT_TRUE(did_get_settings_with_ui());
#endif
  EXPECT_EQ(*test::MakeUserModifiedPrintSettings("printer1",
                                                 /*page_ranges=*/nullptr),
            *document_print_settings());
  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
#if BUILDFLAG(IS_WIN)
  // TODO(crbug.com/40100562)  Include Windows coverage of
  // RenderPrintedDocument() once XPS print pipeline is added.
  EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(render_printed_page_count(), 1);
#else
  EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kSuccess);
#endif
  EXPECT_EQ(document_done_result(), mojom::ResultCode::kSuccess);
  EXPECT_THAT(document_done_job_id(), testing::Optional(kJobId));
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(did_print_document_count(), 1);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartBasicPrintPageRanges) {
  const PageRanges kPageRanges{{/*from=*/2, /*to=*/3}};
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  SetUserSettingsPageRangesForSubsequentContext(kPageRanges);
  constexpr int kJobId = 1;
  SetNewDocumentJobId(kJobId);

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/7_pages.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

#if BUILDFLAG(IS_WIN)
  // The expected events for this are:
  // 1.  Get the default settings.
  // 2.  Ask the user for settings.
  // 3.  A print job is started.
  // 4.  The print compositor will complete generating the document.
  // 5.  Page 2 of the document is rendered.
  // 6.  Page 3 of the document is rendered.
  // 7.  Receive document done notification.
  // 8.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  // TODO(crbug.com/40100562)  Include Windows coverage of
  // RenderPrintedDocument() once XPS print pipeline is added.
  SetNumExpectedMessages(/*num=*/8);
#else
  // The expected events for this are:
  // 1.  Get the default settings.
  // 2.  Ask the user for settings.
  // 3.  A print job is started.
  // 4.  The print compositor will complete generating the document.
  // 5.  The document is rendered.
  // 6.  Receive document done notification.
  // 7.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/7);
#endif

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

  // macOS and Linux currently have to invoke a system dialog from within the
  // browser process.  There is not a callback to capture the result in these
  // cases.
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
  EXPECT_EQ(use_default_settings_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(ask_user_for_settings_result(), mojom::ResultCode::kSuccess);
#else
  EXPECT_TRUE(did_use_default_settings());
  EXPECT_TRUE(did_get_settings_with_ui());
#endif
  EXPECT_EQ(*test::MakeUserModifiedPrintSettings("printer1", &kPageRanges),
            *document_print_settings());
  EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
#if BUILDFLAG(IS_WIN)
  // TODO(crbug.com/40100562)  Include Windows coverage of
  // RenderPrintedDocument() once XPS print pipeline is added.
  EXPECT_EQ(render_printed_page_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(render_printed_page_count(), 2);
#else
  EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kSuccess);
#endif
  EXPECT_EQ(document_done_result(), mojom::ResultCode::kSuccess);
  EXPECT_THAT(document_done_job_id(), testing::Optional(kJobId));
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(did_print_document_count(), 1);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       StartBasicPrintCancel) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForCancelInAskUserForSettings();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Get the default settings.
  // 2.  Ask the user for settings, which indicates to cancel the print
  //     request.  No further printing calls are made.
  // No print job is created because of such an early cancel.
  SetNumExpectedMessages(/*num=*/2);

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

  if (UseService()) {
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
    EXPECT_EQ(use_default_settings_result(), mojom::ResultCode::kSuccess);
    EXPECT_EQ(ask_user_for_settings_result(), mojom::ResultCode::kCanceled);
#else
    EXPECT_TRUE(did_use_default_settings());
    EXPECT_TRUE(did_get_settings_with_ui());
#endif
  } else {
    EXPECT_TRUE(did_use_default_settings());
    EXPECT_TRUE(did_get_settings_with_ui());

    // `PrintBackendService` should never be used when printing in-browser.
    EXPECT_FALSE(print_backend_service_use_detected());
  }
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(did_print_document_count(), 0);
  EXPECT_EQ(print_job_destruction_count(), 0);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       StartBasicPrintAskUserForSettingsFails) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForFailInAskUserForSettings();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Get the default settings.
  // 2.  Ask the user for settings, which indicates a failure from system print
  //     dialog.  No further printing calls are made.
  // 3.  An error dialog is displayed.
  // No print job is created because of such an early failure.
  SetNumExpectedMessages(/*num=*/3);

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

  if (UseService()) {
#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
    EXPECT_EQ(use_default_settings_result(), mojom::ResultCode::kSuccess);
    EXPECT_EQ(ask_user_for_settings_result(), mojom::ResultCode::kFailed);
#else
    EXPECT_TRUE(did_use_default_settings());
    EXPECT_TRUE(did_get_settings_with_ui());
#endif
  } else {
    EXPECT_TRUE(did_use_default_settings());
    EXPECT_TRUE(did_get_settings_with_ui());

    // `PrintBackendService` should never be used when printing in-browser.
    EXPECT_FALSE(print_backend_service_use_detected());
  }
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(did_print_document_count(), 0);
  EXPECT_EQ(print_job_destruction_count(), 0);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       StartBasicPrintFails) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForErrorsInNewDocument();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  if (UseService()) {
    // The expected events for this are:
    // 1.  Gets default settings.
    // 2.  Asks user for settings.
    // 3.  A print job is started, which fails.
    // 4.  An error dialog is shown.
    // 5.  The print job is canceled.  The callback from the service could occur
    //     after the print job has been destroyed.
    // 6.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    // 7.  The renderer will have initiated printing of document, which could
    //     invoke the print compositor.  Wait until all processing for
    //     DidPrintDocument is known to have completed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/7);
  } else {
    // There are only partial overrides to track most steps in the printing
    // pipeline, so the expected events for this are:
    // 1.  Gets default settings.
    // 2.  Asks user for settings.
    // 3.  A print job is started, but that fails and gets canceled.  This does
    //     cause an error dialog to be shown.
    // 4.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    // 5.  The renderer will have initiated printing of document, which could
    //     invoke the print compositor.  Wait until all processing for
    //     DidPrintDocument is known to have completed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/5);
  }

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

  if (UseService()) {
    EXPECT_EQ(start_printing_result(), mojom::ResultCode::kFailed);
    EXPECT_EQ(cancel_count(), 1);
  } else {
    EXPECT_THAT(in_process_last_error_result_code(),
                testing::Optional(mojom::ResultCode::kCanceled));
  }
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(did_print_document_count(), 1);
  EXPECT_EQ(print_job_destruction_count(), 1);
}

#if BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest,
                       StartBasicPrintPdfConversionFails) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForPdfConversionErrorOnPageIndex(/*page_index=*/1);

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/3_pages.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  if (UseService()) {
    // The expected events for this are:
    // 1.  Gets default settings.
    // 2.  Asks user for settings.
    // 3.  A print job is started.
    // 4.  Notified of DidPrintDocument(), that composition of the print
    //     document has completed.
    // 5.  The PDF conversion fails, resulting in canceling the print job.
    // 6.  The print job is destroyed.
    // No error dialog is shown.
    SetNumExpectedMessages(/*num=*/6);
  } else {
    // There are only partial overrides to track most steps in the printing
    // pipeline, so the expected events for this are:
    // 1.  Gets default settings.
    // 2.  Asks user for settings.
    // 3.  A print job is started, but is canceled due to failure during PDF
    //     conversion.
    // 4.  The renderer will have initiated printing of document, which could
    //     invoke the print compositor.  Wait until all processing for
    //     DidPrintDocument is known to have completed, to ensure printing
    //     finished cleanly before completing the test.
    // No error dialog is shown.
    SetNumExpectedMessages(/*num=*/4);
  }

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

  if (UseService()) {
    EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
  } else {
    EXPECT_THAT(in_process_last_error_result_code(),
                testing::Optional(mojom::ResultCode::kCanceled));
  }
  // TODO(crbug.com/40288222):  Update expectation once an error is shown for
  // this failure.
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 1);
}
#endif  // BUILDFLAG(IS_WIN)

#if BUILDFLAG(ENABLE_CONCURRENT_BASIC_PRINT_DIALOGS)

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartBasicPrintConcurrentAllowed) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  TestPrintViewManager* print_view_manager =
      SetUpAndReturnPrintViewManager(web_contents);

  // Pretend that a window has started a system print.
  std::optional<PrintBackendServiceManager::ClientId> client_id =
      PrintBackendServiceManager::GetInstance().RegisterQueryWithUiClient();
  ASSERT_TRUE(client_id.has_value());

  // The expected events for this are:
  // 1.  Gets default settings.
  // 2.  Asks user for settings.
  // 3.  Start the print job.
  // 4.  Rendering for 1 page of document of content.
  // 5.  Completes with document done.
  // 6.  Wait until all processing for DidPrintDocument is known to have
  //     completed, to ensure printing finished cleanly before completing the
  //     test.
  // 7.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/7);

  // Now initiate a system print that would exist concurrently with that.
  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

  EXPECT_THAT(print_view_manager->print_now_result(), testing::Optional(true));

  // Cleanup before test shutdown.
  PrintBackendServiceManager::GetInstance().UnregisterClient(*client_id);
}

#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       SystemPrintFromPrintPreviewConcurrentAllowed) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // Pretend that another tab has started a system print.
  // TODO(crbug.com/40561724)  Improve on this test by using a persistent fake
  // system print dialog.
  std::optional<PrintBackendServiceManager::ClientId> client_id =
      PrintBackendServiceManager::GetInstance().RegisterQueryWithUiClient();
  ASSERT_TRUE(client_id.has_value());

  // Now do a print preview which will try to switch to doing system print.
  // The expected events for this are:
  // 1.  Gets default settings.
  // 2.  Asks user for settings.
  // 3.  Start the print job.
  // 4.  Rendering for 1 page of document of content.
  // 5.  Completes with document done.
  // 6.  Wait until all processing for DidPrintDocument is known to have
  //     completed, to ensure printing finished cleanly before completing the
  //     test.
  // 7.  Wait for the one print job to be destroyed, to ensure printing
  //     finished cleanly before completing the test.
  SetNumExpectedMessages(/*num=*/7);

  SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);

  // Concurrent system print is allowed.
  EXPECT_THAT(system_print_registration_succeeded(), testing::Optional(true));

  // Cleanup before test shutdown.
  PrintBackendServiceManager::GetInstance().UnregisterClient(*client_id);
}
#endif  // BUILDFLAG(ENABLE_PRINT_PREVIEW)

#else  // BUILDFLAG(ENABLE_CONCURRENT_BASIC_PRINT_DIALOGS)

IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       StartBasicPrintConcurrentNotAllowed) {
  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  TestPrintViewManager* print_view_manager =
      SetUpAndReturnPrintViewManager(web_contents);

  // Pretend that a window has started a system print.
  std::optional<PrintBackendServiceManager::ClientId> client_id =
      PrintBackendServiceManager::GetInstance().RegisterQueryWithUiClient();
  ASSERT_TRUE(client_id.has_value());

  // Now initiate a system print that would exist concurrently with that.
  StartBasicPrint(web_contents);

  // Concurrent system print is not allowed.
  EXPECT_THAT(print_view_manager->print_now_result(), testing::Optional(false));
  // The denied concurrent print is silent without an error.
  EXPECT_EQ(error_dialog_shown_count(), 0u);

  // Cleanup before test shutdown.
  PrintBackendServiceManager::GetInstance().UnregisterClient(*client_id);
}

#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
IN_PROC_BROWSER_TEST_P(SystemAccessProcessSandboxedServicePrintBrowserTest,
                       SystemPrintFromPrintPreviewConcurrentNotAllowed) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // Pretend that another tab has started a system print.
  // TODO(crbug.com/40561724)  Improve on this test by using a persistent fake
  // system print dialog.
  std::optional<PrintBackendServiceManager::ClientId> client_id =
      PrintBackendServiceManager::GetInstance().RegisterQueryWithUiClient();
  ASSERT_TRUE(client_id.has_value());

  // Now do a print preview which will try to switch to doing system print.
  // Inability to support this should be detected immediately without needing
  // to wait for callback.
  SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/false);

  // Concurrent system print is not allowed.
  EXPECT_THAT(system_print_registration_succeeded(), testing::Optional(false));
  // The denied concurrent print is silent without an error.
  EXPECT_EQ(error_dialog_shown_count(), 0u);

  // Cleanup before test shutdown.
  PrintBackendServiceManager::GetInstance().UnregisterClient(*client_id);
}
#endif  // BUILDFLAG(ENABLE_PRINT_PREVIEW)

#endif  // BUILDFLAG(ENABLE_CONCURRENT_BASIC_PRINT_DIALOGS)

IN_PROC_BROWSER_TEST_P(SystemAccessProcessServicePrintBrowserTest,
                       StartBasicPrintUseDefaultFails) {
  PrimeForFailInUseDefaultSettings();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Get the default settings, which fails.
  // 2.  The print error dialog is shown.
  // No print job is created from such an early failure.
  SetNumExpectedMessages(/*num=*/2);

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
  EXPECT_EQ(use_default_settings_result(), mojom::ResultCode::kFailed);
#else
  EXPECT_TRUE(did_use_default_settings());
#endif
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(did_print_document_count(), 0);
  EXPECT_EQ(print_job_construction_count(), 0);
}

IN_PROC_BROWSER_TEST_P(SystemAccessProcessServicePrintBrowserTest,
                       StartBasicPrintServiceDisappearsAfterGetSettings) {
  PrimeForServiceTerminatesAfterGetUserSettings();

  // Pretending the service terminated will result in a stranded context left
  // in the test Print Backend service which actually does still exist.
  SkipPersistentContextsCheckOnShutdown();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // The expected events for this are:
  // 1.  Get the default settings.
  // 2.  Ask the user for settings.  This succeeds; however, because the
  //     service is detected to have terminated, the print request is aborted.
  // 3.  An error dialog is shown.
  // No print job is created from such an early failure.
  SetNumExpectedMessages(/*num=*/3);

  StartBasicPrint(web_contents);

  WaitUntilCallbackReceived();

#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG)
  EXPECT_EQ(use_default_settings_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(ask_user_for_settings_result(), mojom::ResultCode::kSuccess);
#else
  EXPECT_TRUE(did_use_default_settings());
  EXPECT_TRUE(did_get_settings_with_ui());
#endif
  EXPECT_EQ(error_dialog_shown_count(), 1u);
  EXPECT_EQ(did_print_document_count(), 0);
  EXPECT_EQ(print_job_construction_count(), 0);
}

#if BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG) && BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_P(
    SystemAccessProcessServicePrintBrowserTest,
    SystemPrintFromPrintPreviewUpdatePrintSettingsServiceDisappearsAfterGetSettings) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  PrimeForServiceTerminatesAfterUpdatePrintSettings();

  // Pretending the service terminated will result in a stranded context left
  // in the test Print Backend service which actually does still exist.
  SkipPersistentContextsCheckOnShutdown();

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  // Once the transition to system print is initiated, the expected events
  // are:
  // 1.  Ask the user for settings.  This succeeds; however, because the
  //     service is detected to have terminated, the print request is aborted.
  // 2.  An error dialog is shown.
  // No print job is created because of such an early failure.
  SetNumExpectedMessages(/*num=*/2);

  SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);

  EXPECT_EQ(update_print_settings_result(), mojom::ResultCode::kSuccess);
  EXPECT_EQ(error_dialog_shown_count(), 1u);
}
#endif  // BUILDFLAG(ENABLE_OOP_BASIC_PRINT_DIALOG) && BUILDFLAG(IS_WIN)
#endif  // BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)

#if BUILDFLAG(IS_MAC)
IN_PROC_BROWSER_TEST_P(SystemAccessProcessPrintBrowserTest, OpenPdfInPreview) {
  AddPrinter("printer1");
  SetPrinterNameForSubsequentContexts("printer1");
  constexpr int kJobId = 1;
  SetNewDocumentJobId(kJobId);

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  SetUpPrintViewManager(web_contents);

  if (UseService()) {
    // The expected events for this are:
    // 1.  Update printer settings.
    // 2.  A print job is started.
    // 3.  Rendering for 1 page of document of content.
    // 4.  Completes with document done.
    // 5.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/5);
  } else {
    // The expected events for this are:
    // 1.  Update printer settings.
    // 2.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/2);
  }
  OpenPdfInPreviewOnceReadyAndLoaded();

  if (UseService()) {
    EXPECT_EQ(start_printing_result(), mojom::ResultCode::kSuccess);
    EXPECT_EQ(render_printed_document_result(), mojom::ResultCode::kSuccess);
    EXPECT_EQ(document_done_result(), mojom::ResultCode::kSuccess);
  } else {
    EXPECT_FALSE(in_process_last_error_result_code().has_value());
  }
  EXPECT_THAT(document_done_job_id(), testing::Optional(kJobId));
  EXPECT_TRUE(destination_is_preview());
  EXPECT_EQ(error_dialog_shown_count(), 0u);
  EXPECT_EQ(print_job_destruction_count(), 1);
}
#endif  // BUILDFLAG(IS_MAC)

#endif  // BUILDFLAG(ENABLE_OOP_PRINTING)

#if BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
class TestPrintViewManagerForContentAnalysis : public TestPrintViewManager {
 public:
  class Observer : public PrintViewManagerBase::TestObserver {
   public:
    void OnPrintNow(const content::RenderFrameHost* rfh) override {
      print_now_called_ = true;
    }

    void OnScriptedPrint() override { scripted_print_called_ = true; }

    void OnPrintPreviewDone() override {
      if (on_print_preview_done_) {
        std::move(on_print_preview_done_).Run();
      }
    }

    bool print_now_called() const { return print_now_called_; }

    bool scripted_print_called() const { return scripted_print_called_; }

    void set_on_print_preview_done_closure(base::OnceClosure closure) {
      on_print_preview_done_ = std::move(closure);
    }

   private:
    bool print_now_called_ = false;
    bool scripted_print_called_ = false;
    base::OnceClosure on_print_preview_done_;
  };

  TestPrintViewManagerForContentAnalysis(
      content::WebContents* web_contents,
      const char* policy_value,
      enterprise_connectors::ContentAnalysisRequest::Reason expected_reason,
      OnDidCreatePrintJobCallback create_print_job_callback,
      OnDidCompositeForContentAnalysis composite_for_content_analysis_callback)
      : TestPrintViewManager(web_contents,
                             std::move(create_print_job_callback)),
        expected_reason_(expected_reason),
        policy_value_(policy_value),
        did_composite_for_content_analysis_callback_(
            std::move(composite_for_content_analysis_callback)) {
    AddTestObserver(observer_);
    PrintViewManager::SetReceiverImplForTesting(this);
  }

  ~TestPrintViewManagerForContentAnalysis() override {
    PrintViewManager::SetReceiverImplForTesting(nullptr);
  }

  void WaitOnPreview() { preview_run_loop_.Run(); }

  bool print_now_called() const { return observer_.print_now_called(); }

  bool scripted_print_called() const {
    return observer_.scripted_print_called();
  }

  const std::optional<bool>& preview_allowed() const {
    return preview_allowed_;
  }

#if BUILDFLAG(IS_CHROMEOS)
  void set_allowed_by_dlp(bool allowed) { allowed_by_dlp_ = allowed; }
#endif  // BUILDFLAG(IS_CHROMEOS)

  void set_on_print_preview_done_closure(base::OnceClosure closure) {
    observer_.set_on_print_preview_done_closure(std::move(closure));
  }

 protected:
  void ContentAnalysisBeforePrintingDocument(
      enterprise_connectors::ContentAnalysisDelegate::Data scanning_data,
      scoped_refptr<base::RefCountedMemory> print_data,
      const gfx::Size& page_size,
      const gfx::Rect& content_area,
      const gfx::Point& offsets) override {
    // The settings passed to this function should match the content of the
    // print Connector policy.
    EXPECT_EQ(scanning_data.settings.tags.size(), 1u);
    EXPECT_TRUE(base::Contains(scanning_data.settings.tags, "dlp"));
    if (scanning_data.settings.cloud_or_local_settings.is_cloud_analysis()) {
      EXPECT_EQ(scanning_data.settings.cloud_or_local_settings.dm_token(),
                kFakeDmToken);
    } else {
      EXPECT_EQ(scanning_data.settings.cloud_or_local_settings.local_path(),
                "path_user");
      EXPECT_TRUE(
          scanning_data.settings.cloud_or_local_settings.user_specific());
    }
    EXPECT_TRUE(
        ExpectedBlockUntilVerdict(scanning_data.settings.block_until_verdict));
    EXPECT_TRUE(scanning_data.settings.block_large_files);
    EXPECT_EQ(scanning_data.url,
              web_contents()->GetOutermostWebContents()->GetLastCommittedURL());
    EXPECT_EQ(scanning_data.reason, expected_reason_);

    // The data of the document should be a valid PDF as this code should be
    // called as the print job is about to start printing.
    EXPECT_TRUE(LooksLikePdf(*print_data));

    TestPrintViewManager::ContentAnalysisBeforePrintingDocument(
        std::move(scanning_data), print_data, page_size, content_area, offsets);
  }

#if BUILDFLAG(IS_CHROMEOS)
  void OnDlpPrintingRestrictionsChecked(
      content::GlobalRenderFrameHostId rfh_id,
      base::OnceCallback<void(bool should_proceed)> callback,
      bool should_proceed) override {
    PrintViewManager::OnDlpPrintingRestrictionsChecked(
        rfh_id, std::move(callback), allowed_by_dlp_);
  }
#endif  // BUILDFLAG(IS_CHROMEOS)

  void CompleteScriptedPrint(content::RenderFrameHost* rfh,
                             mojom::ScriptedPrintParamsPtr params,
                             ScriptedPrintCallback callback) override {
    TestPrintViewManager::CompleteScriptedPrint(rfh, std::move(params),
                                                std::move(callback));

    for (auto& observer : GetTestObservers()) {
      observer.OnScriptedPrint();
    }
  }

 private:
  void PrintPreviewRejectedForTesting() override {
    preview_allowed_ = false;
    preview_run_loop_.Quit();
  }

  void PrintPreviewAllowedForTesting() override {
    preview_allowed_ = true;
    preview_run_loop_.Quit();
  }

  bool ExpectedBlockUntilVerdict(
      enterprise_connectors::BlockUntilVerdict block_until_verdict) {
    if (policy_value_ == kCloudAnalysisNonBlockingPolicy) {
      return block_until_verdict ==
             enterprise_connectors::BlockUntilVerdict::kNoBlock;
    }

    return block_until_verdict ==
           enterprise_connectors::BlockUntilVerdict::kBlock;
  }

#if BUILDFLAG(IS_CHROMEOS)
  bool allowed_by_dlp_ = true;
#endif  // BUILDFLAG(IS_CHROMEOS)

  // Indicates whether the preview was allowed after checking against content
  // analysis and DLP (if on CrOS). This is `std::nullopt` until then.
  std::optional<bool> preview_allowed_;

  // Used to validate the corresponding `ContentAnalysisDelegate::Data` passed
  // in various content analysis-related functions.
  enterprise_connectors::ContentAnalysisRequest::Reason expected_reason_;

  // Used to validate the corresponding `ContentAnalysisDelegate::Data` passed
  // in various content analysis-related functions. Corresponds to the value
  // return by `PolicyValue()` for the current test.
  const char* policy_value_ = nullptr;

  base::RunLoop preview_run_loop_;
  OnDidCompositeForContentAnalysis did_composite_for_content_analysis_callback_;
  Observer observer_;
};

using ContentAnalysisConfigurationVariation = testing::tuple<
    const char* /*policy_value*/,
    bool /*content_analysis_allows_print*/,
    PrintBackendAndPlatformPrintApiVariation /*backend_and_print_api*/>;

class ContentAnalysisPrintBrowserTestBase
    : public SystemAccessProcessPrintBrowserTestBase {
 public:
  ContentAnalysisPrintBrowserTestBase() {
    policy::SetDMTokenForTesting(
        policy::DMToken::CreateValidToken(kFakeDmToken));
    enterprise_connectors::ContentAnalysisDelegate::SetFactoryForTesting(
        base::BindRepeating(
            &enterprise_connectors::test::FakeContentAnalysisDelegate::Create,
            base::DoNothing(),
            base::BindRepeating(
                &ContentAnalysisPrintBrowserTestBase::ScanningResponse,
                base::Unretained(this)),
            kFakeDmToken));

    // These overrides make the overall tests faster as the content analysis
    // dialog won't stay in each state for mandatory minimum times.
    enterprise_connectors::ContentAnalysisDialogController::
        SetMinimumPendingDialogTimeForTesting(base::Milliseconds(0));
    enterprise_connectors::ContentAnalysisDialogController::
        SetShowDialogDelayForTesting(base::Milliseconds(0));
    enterprise_connectors::ContentAnalysisDialogController::
        SetSuccessDialogTimeoutForTesting(base::Milliseconds(0));
  }

  enterprise_connectors::ContentAnalysisResponse ScanningResponse(
      const std::string& contents,
      const base::FilePath& path) {
    ++scanning_responses_;
    enterprise_connectors::ContentAnalysisResponse response;

    auto* result = response.add_results();
    result->set_tag("dlp");
    result->set_status(
        enterprise_connectors::ContentAnalysisResponse::Result::SUCCESS);

    if (!ContentAnalysisAllowsPrint()) {
      auto* rule = result->add_triggered_rules();
      rule->set_rule_name("blocking_rule_name");
      rule->set_action(enterprise_connectors::TriggeredRule::BLOCK);
    }

    return response;
  }

  void SetUp() override {
    test_printing_context_factory()->SetPrinterNameForSubsequentContexts(
        "printer_name");
    SystemAccessProcessPrintBrowserTestBase::SetUp();
  }

  void SetUpOnMainThread() override {
    SystemAccessProcessPrintBrowserTestBase::SetUpOnMainThread();
    enterprise_connectors::test::SetAnalysisConnector(
        browser()->profile()->GetPrefs(),
        enterprise_connectors::AnalysisConnector::PRINT, PolicyValue());
  }

  void TearDownOnMainThread() override {
    enterprise_connectors::test::ClearAnalysisConnector(
        browser()->profile()->GetPrefs(),
        enterprise_connectors::AnalysisConnector::PRINT);
    SystemAccessProcessPrintBrowserTestBase::TearDownOnMainThread();
  }

  TestPrintViewManagerForContentAnalysis*
  SetUpAndReturnPrintViewManagerForContentAnalysis(
      content::WebContents* web_contents,
      enterprise_connectors::ContentAnalysisRequest::Reason expected_reason) {
    // Safe to use `base::Unretained(this)` since this testing class
    // necessarily must outlive all interactions from the tests which will
    // run through `PrintViewManagerBase`, which is what causes new jobs to
    // be created and use this callback.
    auto manager = std::make_unique<TestPrintViewManagerForContentAnalysis>(
        web_contents, PolicyValue(), expected_reason,
        base::BindRepeating(
            &SystemAccessProcessPrintBrowserTestBase::OnCreatedPrintJob,
            base::Unretained(this)),
        base::BindRepeating(&SystemAccessProcessPrintBrowserTestBase::
                                OnCompositedForContentAnalysis,
                            base::Unretained(this)));
    manager->AddTestObserver(*this);
    TestPrintViewManagerForContentAnalysis* manager_ptr = manager.get();
    web_contents->SetUserData(PrintViewManager::UserDataKey(),
                              std::move(manager));
    return manager_ptr;
  }

  int scanning_responses_count() { return scanning_responses_; }

  bool SandboxService() override { return true; }

  int GetExpectedNewDocumentCalledCount() {
    return PrintAllowedOrNonBlockingPolicy() ? (UseService() ? 2 : 1) : 0;
  }

  // The value OnPrintEnterpriseConnector should be set to.
  virtual const char* PolicyValue() const = 0;

  // Whether content analysis should let printing proceed.
  virtual bool ContentAnalysisAllowsPrint() const = 0;

  // Helper to check if printing is allowed altogether or not. It's possible for
  // the policy to be set to be non-blocking and still obtain a "block" verdict
  // from a content analysis server, and in such a case the printing will be
  // allowed to proceed.
  bool PrintAllowedOrNonBlockingPolicy() {
    return ContentAnalysisAllowsPrint() ||
           PolicyValue() == kCloudAnalysisNonBlockingPolicy;
  }

  static std::string GetTestSuffix(
      const testing::TestParamInfo<ContentAnalysisConfigurationVariation>&
          info) {
    return base::JoinString(
        {GetPolicyTypeString(std::get<0>(info.param)),
         GetAllowsPrintString(std::get<1>(info.param)),
         GetPrintBackendAndPlatformPrintApiString(std::get<2>(info.param))},
        /*separator=*/"_");
  }

 protected:
  static const char* GetPolicyTypeString(const char* policy_value) {
#if BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)
    if (policy_value == kLocalAnalysisPolicy) {
      return "LocalPolicy";
    }
#endif
    if (policy_value == kCloudAnalysisBlockingPolicy) {
      return "BlockingCloudPolicy";
    }
    CHECK_EQ(policy_value, kCloudAnalysisNonBlockingPolicy);
    return "NonBlockingCloudPolicy";
  }

  static const char* GetAllowsPrintString(bool allows_print) {
    return allows_print ? "AllowsPrint" : "DisallowsPrint";
  }

 private:
#if BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)
  enterprise_connectors::FakeContentAnalysisSdkManager sdk_manager_;
#endif  // BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)

  // Counts the number of times `ScanningResponse` is called, why is equivalent
  // to the number of times a printed page's bytes would reach a scanner.
  int scanning_responses_ = 0;
};

class ContentAnalysisAfterPrintPreviewBrowserTest
    : public ContentAnalysisPrintBrowserTestBase,
      public testing::WithParamInterface<
          ContentAnalysisConfigurationVariation> {
 public:
  const char* PolicyValue() const override { return std::get<0>(GetParam()); }
  bool ContentAnalysisAllowsPrint() const override {
    return std::get<1>(GetParam());
  }
  bool UseService() override {
    return backend_and_print_api().print_backend !=
           PrintBackendFeatureVariation::kInBrowserProcess;
  }
#if BUILDFLAG(IS_WIN)
  bool UseXps() override {
    return backend_and_print_api().platform_api ==
           PlatformPrintApiVariation::kXps;
  }
#endif

  // PrintJob::Observer:
  void OnCanceling() override { CheckForQuit(); }

 private:
  PrintBackendAndPlatformPrintApiVariation backend_and_print_api() const {
    return std::get<2>(GetParam());
  }
};

class ContentAnalysisScriptedPreviewlessPrintBrowserTestBase
    : public ContentAnalysisPrintBrowserTestBase,
      public testing::WithParamInterface<
          ContentAnalysisConfigurationVariation> {
 public:
  const char* PolicyValue() const override { return std::get<0>(GetParam()); }
  bool ContentAnalysisAllowsPrint() const override {
    return std::get<1>(GetParam());
  }
  bool UseService() override {
    return backend_and_print_api().print_backend !=
           PrintBackendFeatureVariation::kInBrowserProcess;
  }
#if BUILDFLAG(IS_WIN)
  bool UseXps() override {
    return backend_and_print_api().platform_api ==
           PlatformPrintApiVariation::kXps;
  }
#endif

  void SetUpCommandLine(base::CommandLine* cmd_line) override {
    cmd_line->AppendSwitch(switches::kDisablePrintPreview);
    ContentAnalysisPrintBrowserTestBase::SetUpCommandLine(cmd_line);
  }

 private:
  PrintBackendAndPlatformPrintApiVariation backend_and_print_api() const {
    return std::get<2>(GetParam());
  }
};

class ContentAnalysisScriptedPreviewlessPrintAfterDialogBrowserTest
    : public ContentAnalysisScriptedPreviewlessPrintBrowserTestBase {
 public:
  void RunScriptedPrintTest(const std::string& script) {
    AddPrinter("printer_name");

    if (UseService() && !PrintAllowedOrNonBlockingPolicy()) {
      // This results in a stranded context left in the Print Backend service.
      // It will persist harmlessly until the service terminates after a short
      // period of no printing activity.
      SkipPersistentContextsCheckOnShutdown();
    }

    ASSERT_TRUE(embedded_test_server()->Started());
    GURL url(embedded_test_server()->GetURL("/printing/test1.html"));
    ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    ASSERT_TRUE(web_contents);
    auto* print_view_manager = SetUpAndReturnPrintViewManagerForContentAnalysis(
        web_contents,
        enterprise_connectors::ContentAnalysisRequest::SYSTEM_DIALOG_PRINT);

    if (PrintAllowedOrNonBlockingPolicy()) {
      if (UseService()) {
        // The expected events are:
        // 1.  Get the default settings.
        // 2.  Ask the user for settings.
        // 3.  A print job is started.
        // 4.  The one page of the document is rendered.
        // 5.  Receive document done notification.
        // 6.  Wait until all processing for DidPrintDocument is known to have
        //     completed, to ensure printing finished cleanly before
        //     completing the test.
        // 7.  Wait for the one print job to be destroyed, to ensure printing
        //     finished cleanly before completing the test.
        SetNumExpectedMessages(/*num=*/7);
      } else {
        // The expected events for this are:
        // 1.  Use default settings.
        // 2.  Ask the user for settings.
        // 3.  The print compositor will complete generating the document.
        // 4.  The print job is destroyed.
        SetNumExpectedMessages(/*num=*/4);
      }
    } else {
      // The expected events for this are:
      // 1.  Use default settings.
      // 2.  Ask the user for settings.
      // 3.  Wait until all processing for DidPrintDocument is known to have
      //     completed, to ensure printing finished cleanly before
      //     completing the test.
      // 4.  Wait for the actual printing job to be destroyed, to ensure
      //     printing finished cleanly before completing the test.
      SetNumExpectedMessages(/*num=*/4);
    }

    content::ExecuteScriptAsync(web_contents->GetPrimaryMainFrame(), script);

    WaitUntilCallbackReceived();

    ASSERT_TRUE(print_view_manager->scripted_print_called());
    EXPECT_EQ(composited_for_content_analysis_count(), 0);
    EXPECT_EQ(scanning_responses_count(), 1);

    // Validate that `NewDocument()` is only called for actual printing, not as
    // part of content analysis, since that can needlessly prompt the user.
    // When printing OOP, an extra call for a new document will occur since it
    // gets called in both the browser process and in the Print Backend service.
    EXPECT_EQ(new_document_called_count(), GetExpectedNewDocumentCalledCount());
  }
};

#if !BUILDFLAG(IS_CHROMEOS)

IN_PROC_BROWSER_TEST_P(ContentAnalysisAfterPrintPreviewBrowserTest,
                       PrintWithPreviewBeforeLoaded) {
  AddPrinter("printer_name");

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test1.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  auto* print_view_manager = SetUpAndReturnPrintViewManagerForContentAnalysis(
      web_contents,
      enterprise_connectors::ContentAnalysisRequest::PRINT_PREVIEW_PRINT);

  if (PrintAllowedOrNonBlockingPolicy() && UseService()) {
    // The expected events for this are:
    // 1.  Update print settings.
    // 2.  A print job is started.
    // 3.  Rendering for 1 page of document of content.
    // 4.  Completes with document done.
    // 5.  Wait for the one print job to be destroyed, to ensure printing
    //     finished cleanly before completing the test.
    SetNumExpectedMessages(/*num=*/5);
  } else {
    print_view_manager->set_on_print_preview_done_closure(base::BindOnce(
        &ContentAnalysisAfterPrintPreviewBrowserTest::CheckForQuit,
        base::Unretained(this)));
    if (PrintAllowedOrNonBlockingPolicy()) {
      // The expected events for this are:
      // 1.  Update print settings.
      // 2.  Print preview completes.
      // 3.  Wait for the one print job to be destroyed, to ensure printing
      //     finished cleanly before completing the test.
      SetNumExpectedMessages(/*num=*/3);
    } else {
      // The expected events for this are:
      // 1.  Print preview completes.  No print job is created.
      SetNumExpectedMessages(/*num=*/1);
    }
  }

  PrintAfterPreviewIsReadyAndMaybeLoaded(PrintParams(),
                                         /*wait_for_loaded=*/false);

  EXPECT_THAT(print_view_manager->preview_allowed(), testing::Optional(true));
  EXPECT_EQ(scanning_responses_count(), 1);

  // Validate that `NewDocument()` is only called for actual printing, not as
  // part of content analysis, since that can needlessly prompt the user.
  // When printing OOP, an extra call for a new document will occur since it
  // gets called in both the browser process and in the Print Backend service.
  EXPECT_EQ(new_document_called_count(), GetExpectedNewDocumentCalledCount());
}

IN_PROC_BROWSER_TEST_P(ContentAnalysisAfterPrintPreviewBrowserTest,
                       SystemPrintFromPrintPreview) {
  AddPrinter("printer_name");

  if (UseService() && !PrintAllowedOrNonBlockingPolicy()) {
    // This results in a stranded context left in the Print Backend service.
    // It will persist harmlessly until the service terminates after a short
    // period of no printing activity.
    SkipPersistentContextsCheckOnShutdown();
  }

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test1.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  auto* print_view_manager = SetUpAndReturnPrintViewManagerForContentAnalysis(
      web_contents,
      enterprise_connectors::ContentAnalysisRequest::SYSTEM_DIALOG_PRINT);

  if (PrintAllowedOrNonBlockingPolicy()) {
    if (UseService()) {
#if BUILDFLAG(IS_WIN)
      // The expected events for this are:
      // 1.  Update print settings.
      // 2.  A print job is started, for actual printing.
      // 3.  Rendering for 1 page of document of content.
      // 4.  Completes with document done.
      // 5.  Wait for the actual printing job to be destroyed, to ensure
      //     printing finished cleanly before completing the test.
      SetNumExpectedMessages(/*num=*/5);
#else
      // The expected events for this are:
      // 1.  Get the default settings.
      // 2.  Ask the user for settings.
      // 3.  A print job is started for actual printing.
      // 4.  The print compositor will complete generating the document.
      // 5.  Rendering for 1 page of document of content.
      // 6.  Completes with document done.
      // 7.  Wait for the actual printing job to be destroyed, to ensure
      //     printing finished cleanly before completing the test.
      SetNumExpectedMessages(/*num=*/7);
#endif  // BUILDFLAG(IS_WIN)
    } else {
#if BUILDFLAG(IS_WIN)
      // The expected event for this is:
      // 1.  Update print settings.
      // 2.  Wait for the actual printing job to be destroyed, to ensure
      //     printing finished cleanly before completing the test.
      SetNumExpectedMessages(/*num=*/2);
#else
      // The expected events for this are:
      // 1.  Get the default settings.
      // 2.  Ask the user for settings.
      // 3.  The print compositor will complete generating the document.
      // 4.  Wait for the actual printing job to be destroyed, to ensure
      //     printing finished cleanly before completing the test.
      SetNumExpectedMessages(/*num=*/4);
#endif  // BUILDFLAG(IS_WIN)
    }
    SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);
  } else {
#if BUILDFLAG(IS_WIN)
    // The expected events for this are:
    // 1.  Update print settings.
    // 2.  The print job is cancelled.
    // 3.  The print job is destroyed.
    SetNumExpectedMessages(/*num=*/3);
#else
    // The expected events for this are:
    // 1.  Use default settings.
    // 2.  Ask the user for settings.
    // 3.  The print compositor will complete generating the document.
    // 4.  The print job is cancelled.
    // 5.  The print job is destroyed.
    SetNumExpectedMessages(/*num=*/5);
#endif  // BUILDFLAG(IS_WIN)
    SystemPrintFromPreviewOnceReadyAndLoaded(/*wait_for_callback=*/true);
  }

  EXPECT_THAT(print_view_manager->preview_allowed(), testing::Optional(true));
  EXPECT_EQ(print_job_destruction_count(), 1);
  EXPECT_EQ(scanning_responses_count(), 1);

  // Validate that `NewDocument()` is only called for actual printing, not as
  // part of content analysis, since that can needlessly prompt the user.
  // When printing OOP, an extra call for a new document will occur since it
  // gets called in both the browser process and in the Print Backend service.
  EXPECT_EQ(new_document_called_count(), GetExpectedNewDocumentCalledCount());
}

#if BUILDFLAG(IS_MAC)
IN_PROC_BROWSER_TEST_P(ContentAnalysisAfterPrintPreviewBrowserTest,
                       OpenPdfInPreviewFromPrintPreview) {
  AddPrinter("printer_name");

  if (UseService() && !PrintAllowedOrNonBlockingPolicy()) {
    // This results in a stranded context left in the Print Backend service.
    // It will persist harmlessly until the service terminates after a short
    // period of no printing activity.
    SkipPersistentContextsCheckOnShutdown();
  }

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test3.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  auto* print_view_manager = SetUpAndReturnPrintViewManagerForContentAnalysis(
      web_contents,
      enterprise_connectors::ContentAnalysisRequest::PRINT_PREVIEW_PRINT);

  if (PrintAllowedOrNonBlockingPolicy()) {
    if (UseService()) {
      // The expected events for this are:
      // 1.  Ask the user for settings.
      // 2.  A print job is started for actual printing.
      // 3.  The print compositor will complete generating the document.
      // 4.  Completes with document done.
      // 5.  Wait for the actual printing job to be destroyed, to ensure
      //     printing finished cleanly before completing the test.
      SetNumExpectedMessages(/*num=*/5);
    } else {
      // The expected events for this are:
      // 1.  Update print settings.
      // 2.  Wait for the actual printing job to be destroyed, to ensure
      //     printing finished cleanly before completing the test.
      SetNumExpectedMessages(/*num=*/2);
    }
  } else {
    print_view_manager->set_on_print_preview_done_closure(base::BindOnce(
        &ContentAnalysisAfterPrintPreviewBrowserTest::CheckForQuit,
        base::Unretained(this)));
    // The expected events for this are:
    // 1.  Print Preview is done.
    SetNumExpectedMessages(/*num=*/1);
  }
  OpenPdfInPreviewOnceReadyAndLoaded();

  EXPECT_THAT(print_view_manager->preview_allowed(), testing::Optional(true));

  EXPECT_EQ(print_job_destruction_count(),
            PrintAllowedOrNonBlockingPolicy() ? 1 : 0);
  EXPECT_EQ(scanning_responses_count(), 1);

  // Validate that `NewDocument()` is only called for actual printing, not as
  // part of content analysis, since that can needlessly prompt the user.
  // When printing OOP, an extra call for a new document will occur since it
  // gets called in both the browser process and in the Print Backend service.
  EXPECT_EQ(new_document_called_count(), GetExpectedNewDocumentCalledCount());
}
#endif  // BUILDFLAG(IS_MAC)

IN_PROC_BROWSER_TEST_P(
    ContentAnalysisScriptedPreviewlessPrintAfterDialogBrowserTest,
    PrintNow) {
  AddPrinter("printer_name");

  if (UseService() && !PrintAllowedOrNonBlockingPolicy()) {
    // This results in a stranded context left in the Print Backend service.
    // It will persist harmlessly until the service terminates after a short
    // period of no printing activity.
    SkipPersistentContextsCheckOnShutdown();
  }

  ASSERT_TRUE(embedded_test_server()->Started());
  GURL url(embedded_test_server()->GetURL("/printing/test1.html"));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(web_contents);
  auto* print_view_manager = SetUpAndReturnPrintViewManagerForContentAnalysis(
      web_contents,
      enterprise_connectors::ContentAnalysisRequest::SYSTEM_DIALOG_PRINT);

  if (PrintAllowedOrNonBlockingPolicy()) {
    if (UseService()) {
      // The expected events are:
      // 1.  Get the default settings.
      // 2.  Ask the user for settings.
      // 3.  A print job is started.
      // 4.  The one page of the document is rendered.
      // 5.  Receive document done notification.
      // 6.  Wait until all processing for DidPrintDocument is known to have
      //     completed, to ensure printing finished cleanly before completing
      //     the test.
      // 7.  Wait for the one print job to be destroyed, to ensure printing
      //     finished cleanly before completing the test.
      SetNumExpectedMessages(/*num=*/7);
    } else {
      // The expected events for this are:
      // 1.  Use default settings.
      // 2.  Ask the user for settings.
      // 3.  The print compositor will complete generating the document.
      // 4.  The print job is destroyed.
      SetNumExpectedMessages(/*num=*/4);
    }
  } else {
    // The expected events for this are:
    // 1.  Use default settings.
    // 2.  Ask the user for settings.
    // 3.  The print compositor will complete generating the document.
    // 4.  The print job is destroyed.
    SetNumExpectedMessages(/*num=*/4);
  }

  StartPrint(browser()->tab_strip_model()->GetActiveWebContents(),
             /*print_preview_disabled=*/true,
             /*has_selection=*/false);

  WaitUntilCallbackReceived();

  ASSERT_TRUE(print_view_manager->scripted_print_called());
  EXPECT_EQ(scanning_responses_count(), 1);

  // Validate that `NewDocument()` is only called for actual printing, not as
  // part of content analysis, since that can needlessly prompt the user.
  // When printing OOP, an extra call for a new document will occur since it
  // gets called in both the browser process and in the Print Backend service.
  EXPECT_EQ(new_document_called_count(), GetExpectedNewDocumentCalledCount());
}

IN_PROC_BROWSER_TEST_P(
    ContentAnalysisScriptedPreviewlessPrintAfterDialogBrowserTest,
    DocumentExecPrint) {
  RunScriptedPrintTest("document.execCommand('print');");
}

IN_PROC_BROWSER_TEST_P(
    ContentAnalysisScriptedPreviewlessPrintAfterDialogBrowserTest,
    WindowPrint) {
  RunScriptedPrintTest("window.print()");
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

INSTANTIATE_TEST_SUITE_P(
    All,
    ContentAnalysisAfterPrintPreviewBrowserTest,
    testing::Combine(
#if BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)
        /*policy_value=*/testing::Values(kCloudAnalysisBlockingPolicy,
                                         kCloudAnalysisNonBlockingPolicy,
                                         kLocalAnalysisPolicy),
#else
        /*policy_value=*/testing::Values(kCloudAnalysisBlockingPolicy,
                                         kCloudAnalysisNonBlockingPolicy),
#endif
        /*content_analysis_allows_print=*/testing::Bool(),
        /*backend_and_print_api=*/
        testing::ValuesIn(GeneratePrintBackendAndPlatformPrintApiVariations(
            {PrintBackendFeatureVariation::kInBrowserProcess,
             PrintBackendFeatureVariation::kOopSandboxedService}))),
    ContentAnalysisAfterPrintPreviewBrowserTest::GetTestSuffix);

#if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)

INSTANTIATE_TEST_SUITE_P(
    All,
    ContentAnalysisScriptedPreviewlessPrintAfterDialogBrowserTest,
    testing::Combine(
#if BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)
        /*policy_value=*/testing::Values(kCloudAnalysisBlockingPolicy,
                                         kCloudAnalysisNonBlockingPolicy,
                                         kLocalAnalysisPolicy),
#else
        /*policy_value=*/testing::Values(kCloudAnalysisBlockingPolicy,
                                         kCloudAnalysisNonBlockingPolicy),
#endif  // BUILDFLAG(ENTERPRISE_LOCAL_CONTENT_ANALYSIS)
        /*content_analysis_allows_print=*/testing::Bool(),
        /*backend_and_print_api=*/
        testing::ValuesIn(GeneratePrintBackendAndPlatformPrintApiVariations(
            {PrintBackendFeatureVariation::kInBrowserProcess,
             PrintBackendFeatureVariation::kOopSandboxedService}))),
    ContentAnalysisScriptedPreviewlessPrintAfterDialogBrowserTest::
        GetTestSuffix);

#endif  // BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG)

#endif  // BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)

}  // namespace printing