File: pdf_extension_accessibility_test.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1526 lines) | stat: -rw-r--r-- 59,332 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
// 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 <stddef.h>

#include <map>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <tuple>
#include <variant>
#include <vector>

#include "base/containers/contains.h"
#include "base/containers/flat_set.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "base/test/with_feature_override.h"
#include "base/threading/thread_restrictions.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/pdf/pdf_extension_test_base.h"
#include "chrome/browser/pdf/pdf_extension_test_util.h"
#include "chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/metrics/content/subprocess_metrics_provider.h"
#include "components/prefs/pref_service.h"
#include "components/zoom/zoom_controller.h"
#include "content/public/browser/ax_inspect_factory.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/accessibility_notification_waiter.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/context_menu_interceptor.h"
#include "content/public/test/scoped_accessibility_mode_override.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "pdf/pdf_features.h"
#include "services/screen_ai/buildflags/buildflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/context_menu_data/untrustworthy_context_menu_params.h"
#include "ui/accessibility/accessibility_features.h"
#include "ui/accessibility/accessibility_switches.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enum_util.h"
#include "ui/accessibility/ax_features.mojom-features.h"
#include "ui/accessibility/ax_mode.h"
#include "ui/accessibility/ax_node.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_id.h"
#include "ui/accessibility/platform/ax_platform_node_delegate.h"
#include "ui/accessibility/platform/inspect/ax_api_type.h"
#include "ui/accessibility/platform/inspect/ax_inspect_scenario.h"
#include "ui/accessibility/platform/inspect/ax_inspect_test_helper.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/accessibility/accessibility_manager.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

// Fake ScreenAI library returns empty results for all queries, so testing with
// it is not helpful.
#if BUILDFLAG(ENABLE_SCREEN_AI_BROWSERTESTS) && !BUILDFLAG(USE_FAKE_SCREEN_AI)
#define PDF_SEARCHIFY_INTEGRATION_TEST_ENABLED
#endif

#if defined(PDF_SEARCHIFY_INTEGRATION_TEST_ENABLED)
#include "base/scoped_observation.h"
#include "chrome/browser/screen_ai/screen_ai_install_state.h"
#include "chrome/browser/screen_ai/screen_ai_service_router.h"
#include "chrome/browser/screen_ai/screen_ai_service_router_factory.h"
#include "components/strings/grit/components_strings.h"
#include "services/screen_ai/public/cpp/utilities.h"
#include "ui/base/l10n/l10n_util.h"
#endif  // defined(PDF_SEARCHIFY_INTEGRATION_TEST_ENABLED)

namespace {

using ::content::WebContents;
using ::extensions::MimeHandlerViewGuest;

std::string DumpPdfAccessibilityTree(const ui::AXTreeUpdate& ax_tree,
                                     bool skip_status_subtree) {
  // Create a string representation of the tree starting with the kPdfRoot
  // object.
  std::string ax_tree_dump;
  std::map<int32_t, int> id_to_indentation;
  bool found_pdf_root = false;

  // Status node's subtree is in the form of:
  // pdfRoot -> banner -> status -> staticText.
  // If the subtree should be skipped, this variable keeps the ids of the
  // subtree nodes.
  std::set<ui::AXNodeID> status_subtree_ids;

  for (size_t i = 0; i < ax_tree.nodes.size(); i++) {
    const ui::AXNodeData& node = ax_tree.nodes[i];
    if (node.role == ax::mojom::Role::kPdfRoot) {
      found_pdf_root = true;
      if (skip_status_subtree) {
        if (i + 3 < ax_tree.nodes.size() &&
            ax_tree.nodes[i + 1].role == ax::mojom::Role::kBanner &&
            ax_tree.nodes[i + 2].role == ax::mojom::Role::kStatus &&
            ax_tree.nodes[i + 3].role == ax::mojom::Role::kStaticText) {
          status_subtree_ids = {ax_tree.nodes[i + 1].id,
                                ax_tree.nodes[i + 2].id,
                                ax_tree.nodes[i + 3].id};
        }
      }
    }
    if (!found_pdf_root) {
      continue;
    }

    // Exclude the status subtree from `ax_tree_dump` if they exist in the tree.
    // Tests don't expect them to be included in the dump.
    if (base::Contains(status_subtree_ids, node.id)) {
      continue;
    }

    auto indent_found = id_to_indentation.find(node.id);
    int indent = 0;
    if (indent_found != id_to_indentation.end()) {
      indent = indent_found->second;
    } else if (node.role != ax::mojom::Role::kPdfRoot) {
      // If this node has no indent and isn't the kPdfRoot object, finish dump
      // as this indicates the end of the PDF.
      break;
    }

    ax_tree_dump += std::string(2 * indent, ' ');
    ax_tree_dump += ui::ToString(node.role);

    std::string name =
        node.GetStringAttribute(ax::mojom::StringAttribute::kName);
    base::ReplaceChars(name, "\r\n", "", &name);
    if (node.role == ax::mojom::Role::kStaticText) {
      // OCR may detect and put trailing whitespace in `kStaticText`, so trim
      // it in that case.
      base::TrimWhitespaceASCII(name, base::TrimPositions::TRIM_TRAILING,
                                &name);
    }
    if (!name.empty()) {
      ax_tree_dump += " '" + name + "'";
    }
    ax_tree_dump += "\n";
    for (int32_t id : node.child_ids) {
      id_to_indentation[id] = indent + 1;
    }
  }

  EXPECT_TRUE(found_pdf_root);
  return ax_tree_dump;
}

constexpr char kExpectedPDFAXTree[] =
    "pdfRoot 'PDF document containing 3 pages'\n"
    "  region 'Page 1'\n"
    "    paragraph\n"
    "      staticText '1 First Section'\n"
    "        inlineTextBox '1 '\n"
    "        inlineTextBox 'First Section'\n"
    "    paragraph\n"
    "      staticText 'This is the first section.'\n"
    "        inlineTextBox 'This is the first section.'\n"
    "    paragraph\n"
    "      staticText '1'\n"
    "        inlineTextBox '1'\n"
    "  region 'Page 2'\n"
    "    paragraph\n"
    "      staticText '1.1 First Subsection'\n"
    "        inlineTextBox '1.1 '\n"
    "        inlineTextBox 'First Subsection'\n"
    "    paragraph\n"
    "      staticText 'This is the first subsection.'\n"
    "        inlineTextBox 'This is the first subsection.'\n"
    "    paragraph\n"
    "      staticText '2'\n"
    "        inlineTextBox '2'\n"
    "  region 'Page 3'\n"
    "    paragraph\n"
    "      staticText '2 Second Section'\n"
    "        inlineTextBox '2 '\n"
    "        inlineTextBox 'Second Section'\n"
    "    paragraph\n"
    "      staticText '3'\n"
    "        inlineTextBox '3'\n";

}  // namespace

// Using ASSERT_TRUE deliberately instead of ASSERT_EQ or ASSERT_STREQ
// in order to print a more readable message if the strings differ.
#define ASSERT_MULTILINE_STREQ(expected, actual)                 \
  ASSERT_TRUE(expected == actual) << "Expected:\n"               \
                                  << expected << "\n\nActual:\n" \
                                  << actual

class PDFExtensionAccessibilityTest : public PDFExtensionTestBase {
 public:
  PDFExtensionAccessibilityTest() = default;
  ~PDFExtensionAccessibilityTest() override = default;

 protected:
  ui::AXTreeUpdate GetAccessibilityTreeSnapshotForPdf(
      content::WebContents* web_contents) {
    content::FindAccessibilityNodeCriteria find_criteria;
    find_criteria.role = ax::mojom::Role::kPdfRoot;
    ui::AXPlatformNodeDelegate* pdf_root =
        content::FindAccessibilityNode(web_contents, find_criteria);
    ui::AXTreeID pdf_tree_id = pdf_root->GetTreeData().tree_id;
    EXPECT_NE(pdf_tree_id, ui::AXTreeIDUnknown());
    EXPECT_EQ(pdf_root->GetTreeData().focus_id, pdf_root->GetId());

    return content::GetAccessibilityTreeSnapshotFromId(pdf_tree_id);
  }

  void EnableScreenReader() {
    // Spoof a screen reader.
    mode_override_.emplace(ui::kAXModeDefaultForTests);
  }

  void TearDownOnMainThread() override {
    mode_override_.reset();
    PDFExtensionTestBase::TearDownOnMainThread();
  }

 private:
  std::optional<content::ScopedAccessibilityModeOverride> mode_override_;
};

class PDFExtensionAccessibilityTestWithOopifOverride
    : public base::test::WithFeatureOverride,
      public PDFExtensionAccessibilityTest {
 public:
  PDFExtensionAccessibilityTestWithOopifOverride()
      : base::test::WithFeatureOverride(chrome_pdf::features::kPdfOopif) {}

  bool UseOopif() const override { return GetParam(); }
};

// The test is flaky on Mac: https://crbug.com/334099836.
#if BUILDFLAG(IS_MAC)
#define MAYBE_PdfAccessibility DISABLED_PdfAccessibility
#else
#define MAYBE_PdfAccessibility PdfAccessibility
#endif
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTestWithOopifOverride,
                       MAYBE_PdfAccessibility) {
  content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);

  ASSERT_TRUE(
      LoadPdf(embedded_test_server()->GetURL("/pdf/test-bookmarks.pdf")));

  WaitForAccessibilityTreeToContainNodeWithName(GetActiveWebContents(),
                                                "2 Second Section\r\n");
  ui::AXTreeUpdate ax_tree =
      GetAccessibilityTreeSnapshotForPdf(GetActiveWebContents());
  std::string ax_tree_dump =
      DumpPdfAccessibilityTree(ax_tree, /*skip_status_subtree=*/true);

  ASSERT_MULTILINE_STREQ(kExpectedPDFAXTree, ax_tree_dump);
}

// The test is flaky on Mac: https://crbug.com/334099836.
#if BUILDFLAG(IS_MAC)
#define MAYBE_PdfAccessibilityEnableLater DISABLED_PdfAccessibilityEnableLater
#else
#define MAYBE_PdfAccessibilityEnableLater PdfAccessibilityEnableLater
#endif
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTestWithOopifOverride,
                       MAYBE_PdfAccessibilityEnableLater) {
  // In this test, load the PDF file first, with accessibility off.
  ASSERT_TRUE(
      LoadPdf(embedded_test_server()->GetURL("/pdf/test-bookmarks.pdf")));

  // Now enable accessibility globally, and assert that the PDF
  // accessibility tree loads.
  content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);

  WebContents* contents = GetActiveWebContents();
  WaitForAccessibilityTreeToContainNodeWithName(contents,
                                                "2 Second Section\r\n");
  ui::AXTreeUpdate ax_tree = GetAccessibilityTreeSnapshotForPdf(contents);
  std::string ax_tree_dump =
      DumpPdfAccessibilityTree(ax_tree, /*skip_status_subtree=*/true);
  ASSERT_MULTILINE_STREQ(kExpectedPDFAXTree, ax_tree_dump);
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTestWithOopifOverride,
                       PdfAccessibilityInIframe) {
  content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("/pdf/test-iframe.html")));

  WebContents* contents = GetActiveWebContents();
  WaitForAccessibilityTreeToContainNodeWithName(contents,
                                                "2 Second Section\r\n");

  ui::AXTreeUpdate ax_tree = GetAccessibilityTreeSnapshotForPdf(contents);
  std::string ax_tree_dump =
      DumpPdfAccessibilityTree(ax_tree, /*skip_status_subtree=*/true);
  ASSERT_MULTILINE_STREQ(kExpectedPDFAXTree, ax_tree_dump);
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTestWithOopifOverride,
                       PdfAccessibilityInOOPIF) {
  content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(),
      embedded_test_server()->GetURL("/pdf/test-cross-site-iframe.html")));

  WebContents* contents = GetActiveWebContents();
  WaitForAccessibilityTreeToContainNodeWithName(contents,
                                                "2 Second Section\r\n");

  ui::AXTreeUpdate ax_tree = GetAccessibilityTreeSnapshotForPdf(contents);
  std::string ax_tree_dump =
      DumpPdfAccessibilityTree(ax_tree, /*skip_status_subtree=*/true);
  ASSERT_MULTILINE_STREQ(kExpectedPDFAXTree, ax_tree_dump);
}

// Flaky on ChromiumOS MSan. See https://crbug.com/1484869.
// Flaky on Mac: https://crbug.com/334099836.
#if (BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER)) || BUILDFLAG(IS_MAC)
#define MAYBE_PdfAccessibilityWordBoundaries \
  DISABLED_PdfAccessibilityWordBoundaries
#else
#define MAYBE_PdfAccessibilityWordBoundaries PdfAccessibilityWordBoundaries
#endif
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTestWithOopifOverride,
                       MAYBE_PdfAccessibilityWordBoundaries) {
  content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
  ASSERT_TRUE(
      LoadPdf(embedded_test_server()->GetURL("/pdf/test-bookmarks.pdf")));

  WebContents* contents = GetActiveWebContents();
  WaitForAccessibilityTreeToContainNodeWithName(contents,
                                                "1 First Section\r\n");
  ui::AXTreeUpdate ax_tree = GetAccessibilityTreeSnapshotForPdf(contents);

  bool found = false;
  for (auto& node : ax_tree.nodes) {
    std::string name =
        node.GetStringAttribute(ax::mojom::StringAttribute::kName);
    if (node.role == ax::mojom::Role::kInlineTextBox &&
        name == "First Section\r\n") {
      found = true;
      std::vector<int32_t> word_starts =
          node.GetIntListAttribute(ax::mojom::IntListAttribute::kWordStarts);
      std::vector<int32_t> word_ends =
          node.GetIntListAttribute(ax::mojom::IntListAttribute::kWordEnds);
      ASSERT_EQ(2U, word_starts.size());
      ASSERT_EQ(2U, word_ends.size());
      EXPECT_EQ(0, word_starts[0]);
      EXPECT_EQ(5, word_ends[0]);
      EXPECT_EQ(6, word_starts[1]);
      EXPECT_EQ(13, word_ends[1]);
    }
  }
  ASSERT_TRUE(found);
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTestWithOopifOverride,
                       PdfAccessibilitySelection) {
  // TODO(crbug.com/324636880): Remove this once the test passes for OOPIF PDF.
  if (UseOopif()) {
    GTEST_SKIP();
  }

  // TODO(accessibility): Forcing renderer accessibility means the accessibility
  // tree updates in a way unexpected by the test.
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kForceRendererAccessibility)) {
    GTEST_SKIP();
  }

  ASSERT_TRUE(
      LoadPdf(embedded_test_server()->GetURL("/pdf/test-bookmarks.pdf")));

  WebContents* contents = GetActiveWebContents();
  ASSERT_TRUE(
      content::ExecJs(contents,
                      "document.getElementsByTagName('embed')[0].postMessage("
                      "{type: 'selectAll'});"));

  content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
  WaitForAccessibilityTreeToContainNodeWithName(contents,
                                                "2 Second Section\r\n");
  ui::AXTreeUpdate ax_tree_update =
      GetAccessibilityTreeSnapshotForPdf(contents);
  ui::AXTree ax_tree(ax_tree_update);

  // Ensure that the selection spans the beginning of the first text
  // node to the end of the last one.
  ui::AXNode* sel_start_node =
      ax_tree.GetFromId(ax_tree.data().sel_anchor_object_id);
  ASSERT_TRUE(sel_start_node);
  EXPECT_EQ(ax::mojom::Role::kStaticText, sel_start_node->GetRole());
  std::string start_node_name =
      sel_start_node->GetStringAttribute(ax::mojom::StringAttribute::kName);
  EXPECT_EQ("1 First Section\r\n", start_node_name);
  EXPECT_EQ(0, ax_tree.data().sel_anchor_offset);
  ui::AXNode* para = sel_start_node->parent();
  EXPECT_EQ(ax::mojom::Role::kParagraph, para->GetRole());
  ui::AXNode* region = para->parent();
  EXPECT_EQ(ax::mojom::Role::kRegion, region->GetRole());

  ui::AXNode* sel_end_node =
      ax_tree.GetFromId(ax_tree.data().sel_focus_object_id);
  ASSERT_TRUE(sel_end_node);
  std::string end_node_name =
      sel_end_node->GetStringAttribute(ax::mojom::StringAttribute::kName);
  EXPECT_EQ("3", end_node_name);
  EXPECT_EQ(static_cast<int>(end_node_name.size()),
            ax_tree.data().sel_focus_offset);
  para = sel_end_node->parent();
  EXPECT_EQ(ax::mojom::Role::kParagraph, para->GetRole());
  region = para->parent();
  EXPECT_EQ(ax::mojom::Role::kRegion, region->GetRole());
}

// TODO(crbug.com/330202391): Fix the flakiness on Windows.
#if BUILDFLAG(IS_WIN)
#define MAYBE_PdfAccessibilityContextMenuAction \
  DISABLED_PdfAccessibilityContextMenuAction
#else
#define MAYBE_PdfAccessibilityContextMenuAction \
  PdfAccessibilityContextMenuAction
#endif  // BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTestWithOopifOverride,
                       MAYBE_PdfAccessibilityContextMenuAction) {
  // TODO(crbug.com/324636880): Remove this once the test passes for OOPIF PDF.
  if (UseOopif()) {
    GTEST_SKIP();
  }

  // TODO(accessibility): Forcing renderer accessibility means the accessibility
  // tree updates in a way unexpected by the test.
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kForceRendererAccessibility)) {
    GTEST_SKIP();
  }
  // Validate the context menu arguments for PDF selection when context menu is
  // invoked via accessibility tree.
  const char kExepectedPDFSelection[] =
      "1 First Section\n"
      "This is the first section.\n"
      "1\n"
      "1.1 First Subsection\n"
      "This is the first subsection.\n"
      "2\n"
      "2 Second Section\n"
      "3";

  ASSERT_TRUE(
      LoadPdf(embedded_test_server()->GetURL("/pdf/test-bookmarks.pdf")));

  WebContents* contents = GetActiveWebContents();
  content::RenderFrameHost* content_host =
      pdf_extension_test_util::GetOnlyPdfPluginFrame(contents);
  ASSERT_TRUE(content_host);

  ASSERT_TRUE(
      content::ExecJs(contents,
                      "document.getElementsByTagName('embed')[0].postMessage("
                      "{type: 'selectAll'});"));

  content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
  WaitForAccessibilityTreeToContainNodeWithName(contents,
                                                "1 First Section\r\n");

  // Find pdfRoot node in the accessibility tree.
  content::FindAccessibilityNodeCriteria find_criteria;
  find_criteria.role = ax::mojom::Role::kPdfRoot;
  ui::AXPlatformNodeDelegate* pdf_root =
      content::FindAccessibilityNode(contents, find_criteria);
  ASSERT_TRUE(pdf_root);

  content::ContextMenuInterceptor context_menu_interceptor(content_host);

  ContextMenuWaiter menu_waiter;
  // Invoke kShowContextMenu accessibility action on the node with the kPdfRoot
  // role.
  ui::AXActionData data;
  data.action = ax::mojom::Action::kShowContextMenu;
  pdf_root->AccessibilityPerformAction(data);
  menu_waiter.WaitForMenuOpenAndClose();

  context_menu_interceptor.Wait();
  blink::UntrustworthyContextMenuParams params =
      context_menu_interceptor.get_params();

  // Validate the context menu params for selection.
  EXPECT_EQ(blink::mojom::ContextMenuDataMediaType::kPlugin, params.media_type);
  std::string selected_text = base::UTF16ToUTF8(params.selection_text);
  base::ReplaceChars(selected_text, "\r", "", &selected_text);
  EXPECT_EQ(kExepectedPDFSelection, selected_text);
}

#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
// Test a particular PDF encountered in the wild that triggered a crash
// when accessibility is enabled.  (http://crbug.com/668724)
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTestWithOopifOverride,
                       PdfAccessibilityTextRunCrash) {
  content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
  ASSERT_TRUE(LoadPdf(embedded_test_server()->GetURL(
      "/pdf_private/accessibility_crash_2.pdf")));

  WaitForAccessibilityTreeToContainNodeWithName(GetActiveWebContents(),
                                                "Page 1");
}
#endif

// This test suite does a simple text-extraction based on the accessibility
// internals, breaking lines & paragraphs where appropriate.  Unlike
// TreeDumpTests, this allows us to verify the kNextOnLine and kPreviousOnLine
// relationships.
class PDFExtensionAccessibilityTextExtractionTest
    : public PDFExtensionAccessibilityTestWithOopifOverride {
 public:
  PDFExtensionAccessibilityTextExtractionTest() = default;
  ~PDFExtensionAccessibilityTextExtractionTest() override = default;

  void RunTextExtractionTest(const base::FilePath::CharType* pdf_file,
                             std::string_view expected_subtext) {
    base::FilePath test_path = ui_test_utils::GetTestFilePath(
        base::FilePath(FILE_PATH_LITERAL("pdf")),
        base::FilePath(FILE_PATH_LITERAL("accessibility")));
    {
      base::ScopedAllowBlockingForTesting allow_blocking;
      ASSERT_TRUE(base::PathExists(test_path)) << test_path.LossyDisplayName();
    }
    base::FilePath pdf_path = test_path.Append(pdf_file);

    RunTest(pdf_path, "pdf/accessibility", expected_subtext);
  }

 protected:
  std::vector<base::test::FeatureRefAndParams> GetEnabledFeatures()
      const override {
    std::vector<base::test::FeatureRefAndParams> enabled =
        PDFExtensionAccessibilityTestWithOopifOverride::GetEnabledFeatures();
    enabled.push_back({chrome_pdf::features::kAccessiblePDFForm, {}});
    return enabled;
  }

 private:
  // The test waits until the tree dump includes `expected_subtext`.
  void RunTest(const base::FilePath& test_file_path,
               const char* file_dir,
               std::string_view expected_subtext) {
    // Load the expectation file.
    ui::AXInspectTestHelper test_helper("content");
    std::optional<base::FilePath> expected_file_path =
        test_helper.GetExpectationFilePath(test_file_path);
    ASSERT_TRUE(expected_file_path) << "No expectation file present.";

    std::optional<std::vector<std::string>> expected_lines =
        test_helper.LoadExpectationFile(*expected_file_path);
    ASSERT_TRUE(expected_lines) << "Couldn't load expectation file.";

    // Enable accessibility and load the test file.
    content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
    const GURL test_file_url = embedded_test_server()->GetURL(base::StrCat(
        {"/", file_dir, "/", test_file_path.BaseName().MaybeAsASCII()}));
    ASSERT_TRUE(LoadPdf(test_file_url));
    WaitForAccessibilityTreeToContainNodeWithName(GetActiveWebContents(),
                                                  expected_subtext);

    // Extract the text content.
    ui::AXTreeUpdate ax_tree =
        GetAccessibilityTreeSnapshotForPdf(GetActiveWebContents());
    auto actual_lines = CollectLines(ax_tree);

    // Aborts if CollectLines() had a failure.
    if (HasFailure()) {
      return;
    }

    // Validate the dump against the expectation file.
    EXPECT_TRUE(test_helper.ValidateAgainstExpectation(
        test_file_path, *expected_file_path, actual_lines, *expected_lines));
  }

  std::vector<std::string> CollectLines(
      const ui::AXTreeUpdate& ax_tree_update) {
    std::vector<std::string> lines;

    ui::AXTree tree(ax_tree_update);
    std::vector<ui::AXNode*> pdf_root_objs;
    FindAXNodes(tree.root(), {ax::mojom::Role::kPdfRoot}, &pdf_root_objs);
    // Can't use ASSERT_EQ because CollectLines doesn't return void.
    if (pdf_root_objs.size() != 1u) {
      // Add a non-fatal failure here to make the test fail.
      ADD_FAILURE() << "Multiple PDF root nodes in the tree.";
      return {};
    }
    ui::AXNode* pdf_doc_root = pdf_root_objs[0];

    std::vector<ui::AXNode*> text_nodes;
    FindAXNodes(pdf_doc_root,
                {ax::mojom::Role::kStaticText, ax::mojom::Role::kInlineTextBox},
                &text_nodes);

    int previous_node_id = 0;
    int previous_node_next_id = 0;
    std::string line;
    for (ui::AXNode* node : text_nodes) {
      // StaticText begins a new paragraph.
      if (node->GetRole() == ax::mojom::Role::kStaticText && !line.empty()) {
        lines.push_back(line);
        lines.push_back("\u00b6");  // pilcrow/paragraph mark, Alt+0182
        line.clear();
      }

      // We collect all inline text boxes within the paragraph.
      if (node->GetRole() != ax::mojom::Role::kInlineTextBox) {
        continue;
      }

      std::string name =
          node->GetStringAttribute(ax::mojom::StringAttribute::kName);
      std::string_view trimmed_name =
          base::TrimString(name, "\r\n", base::TRIM_TRAILING);
      int prev_id =
          node->GetIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId);
      if (previous_node_next_id == node->id()) {
        // Previous node pointed to us, so we are part of the same line.
        EXPECT_EQ(previous_node_id, prev_id)
            << "Expect this node to point to previous node.";
        line.append(trimmed_name);
      } else {
        // Not linked with the previous node; this is a new line.
        EXPECT_EQ(previous_node_next_id, 0)
            << "Previous node pointed to something unexpected.";
        EXPECT_EQ(prev_id, 0)
            << "Our back pointer points to something unexpected.";
        if (!line.empty()) {
          lines.push_back(line);
        }
        line = std::string(trimmed_name);
      }

      previous_node_id = node->id();
      previous_node_next_id =
          node->GetIntAttribute(ax::mojom::IntAttribute::kNextOnLineId);
    }
    if (!line.empty()) {
      lines.push_back(line);
    }

    // Extra newline to match current expectations. TODO: get rid of this
    // and rebase the expectations files.
    if (!lines.empty()) {
      lines.push_back("\u00b6");  // pilcrow/paragraph mark, Alt+0182
    }

    return lines;
  }

  // Searches recursively through |current| and all descendants and
  // populates a vector with all nodes that match any of the roles
  // in |roles|.
  void FindAXNodes(ui::AXNode* current,
                   const base::flat_set<ax::mojom::Role>& roles,
                   std::vector<ui::AXNode*>* results) {
    if (base::Contains(roles, current->GetRole())) {
      results->push_back(current);
    }
    for (ui::AXNode* child : current->children()) {
      FindAXNodes(child, roles, results);
    }
  }
};

// Test that Previous/NextOnLineId attributes are present and properly linked on
// InlineTextBoxes within a line.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest,
                       NextOnLine) {
  RunTextExtractionTest(FILE_PATH_LITERAL("next-on-line.pdf"),
                        /*expected_subtext=*/"Page 1");
}

// Test that a drop-cap is grouped with the correct line.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest, DropCap) {
  RunTextExtractionTest(FILE_PATH_LITERAL("drop-cap.pdf"),
                        /*expected_subtext=*/"Page 1");
}

// Test that simulated superscripts and subscripts don't cause a line break.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest,
                       SuperscriptSubscript) {
  RunTextExtractionTest(FILE_PATH_LITERAL("superscript-subscript.pdf"),
                        /*expected_subtext=*/"Page 1");
}

// Test that simple font and font-size changes in the middle of a line don't
// cause line breaks.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest,
                       FontChange) {
  RunTextExtractionTest(FILE_PATH_LITERAL("font-change.pdf"),
                        /*expected_subtext=*/"Page 1");
}

// Test one property of pdf_private/accessibility_crash_2.pdf, where a page has
// only whitespace characters.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest,
                       OnlyWhitespaceText) {
  RunTextExtractionTest(FILE_PATH_LITERAL("whitespace.pdf"),
                        /*expected_subtext=*/"Page 1");
}

// Test data of inline text boxes for PDF with weblinks.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest, WebLinks) {
  RunTextExtractionTest(FILE_PATH_LITERAL("weblinks.pdf"),
                        /*expected_subtext=*/"Page 1");
}

// Test data of inline text boxes for PDF with highlights.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest,
                       Highlights) {
  RunTextExtractionTest(FILE_PATH_LITERAL("highlights.pdf"),
                        /*expected_subtext=*/"Page 1");
}

// Test data of inline text boxes for PDF with text fields.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest,
                       TextFields) {
  RunTextExtractionTest(FILE_PATH_LITERAL("text_fields.pdf"),
                        /*expected_subtext=*/"Page 1");
}

// Test data of inline text boxes for PDF with multi-line and various font-sized
// text.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest,
                       ParagraphsAndHeadingUntagged) {
  RunTextExtractionTest(
      FILE_PATH_LITERAL("paragraphs-and-heading-untagged.pdf"),
      /*expected_subtext=*/"Page 1");
}

// Test data of inline text boxes for PDF with text, weblinks, images and
// annotation links.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest,
                       LinksImagesAndText) {
  RunTextExtractionTest(FILE_PATH_LITERAL("text-image-link.pdf"),
                        /*expected_subtext=*/"Second Page");
}

// Test data of inline text boxes for PDF with overlapping annotations.
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTextExtractionTest,
                       OverlappingAnnots) {
  RunTextExtractionTest(FILE_PATH_LITERAL("overlapping-annots.pdf"),
                        /*expected_subtext=*/"Page 1");
}

class PDFExtensionAccessibilityTreeDumpTest
    : public PDFExtensionAccessibilityTest,
      public ::testing::WithParamInterface<
          std::tuple<ui::AXApiType::Type, bool>> {
 public:
  PDFExtensionAccessibilityTreeDumpTest() : test_helper_(ax_inspect_type()) {}
  ~PDFExtensionAccessibilityTreeDumpTest() override = default;

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

    // Each test pass might require custom feature setup
    test_helper_.InitializeFeatureList();
  }

  ui::AXApiType::Type ax_inspect_type() const {
    return std::get<0>(GetParam());
  }

  bool UseOopif() const override { return std::get<1>(GetParam()); }

  std::vector<base::test::FeatureRefAndParams> GetEnabledFeatures()
      const override {
    std::vector<base::test::FeatureRefAndParams> enabled =
        PDFExtensionAccessibilityTest::GetEnabledFeatures();
    enabled.push_back({chrome_pdf::features::kAccessiblePDFForm, {}});
    return enabled;
  }

 protected:
  void RunPDFTest(const base::FilePath::CharType* pdf_file,
                  std::string_view expected_subtext) {
    base::FilePath test_path = ui_test_utils::GetTestFilePath(
        base::FilePath(FILE_PATH_LITERAL("pdf")),
        base::FilePath(FILE_PATH_LITERAL("accessibility")));
    {
      base::ScopedAllowBlockingForTesting allow_blocking;
      ASSERT_TRUE(base::PathExists(test_path)) << test_path.LossyDisplayName();
    }
    base::FilePath pdf_path = test_path.Append(pdf_file);

    RunTest(pdf_path, "pdf/accessibility", expected_subtext);
  }

 private:
  using AXPropertyFilter = ui::AXPropertyFilter;

  //  See chrome/test/data/pdf/accessibility/readme.md for more info.
  ui::AXInspectScenario ParsePdfForExtraDirectives(
      const std::string& pdf_contents) {
    const char kCommentMark = '%';

    std::vector<std::string> lines;
    for (const std::string& line : base::SplitString(
             pdf_contents, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
      if (line.size() > 1 && line[0] == kCommentMark) {
        // Remove first character since it's the comment mark.
        lines.push_back(line.substr(1));
      }
    }

    return test_helper_.ParseScenario(lines, DefaultFilters());
  }

  // The test waits until the tree dump includes `expected_subtext`.
  void RunTest(const base::FilePath& test_file_path,
               const char* file_dir,
               std::string_view expected_subtext) {
    std::string pdf_contents;
    {
      base::ScopedAllowBlockingForTesting allow_blocking;
      ASSERT_TRUE(base::ReadFileToString(test_file_path, &pdf_contents));
    }

    // Set up the tree formatter. Parse filters and other directives in the test
    // file.
    ui::AXInspectScenario scenario = ParsePdfForExtraDirectives(pdf_contents);

    std::unique_ptr<ui::AXTreeFormatter> formatter =
        content::AXInspectFactory::CreateFormatter(ax_inspect_type());
    formatter->SetPropertyFilters(scenario.property_filters,
                                  ui::AXTreeFormatter::kFiltersDefaultSet);

    // Exit without running the test if we can't find an expectation file or if
    // the expectation file contains a skip marker.
    // This is used to skip certain tests on certain platforms.
    base::FilePath expected_file_path =
        test_helper_.GetExpectationFilePath(test_file_path);
    if (expected_file_path.empty()) {
      LOG(INFO) << "No expectation file present, ignoring test on this "
                   "platform.";
      return;
    }

    std::optional<std::vector<std::string>> expected_lines =
        test_helper_.LoadExpectationFile(expected_file_path);
    if (!expected_lines) {
      LOG(INFO) << "Skipping this test on this platform.";
      return;
    }

    // Enable accessibility and load the test file.
    content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
    const GURL test_file_url = embedded_test_server()->GetURL(base::StrCat(
        {"/", file_dir, "/", test_file_path.BaseName().MaybeAsASCII()}));
    ASSERT_TRUE(LoadPdf(test_file_url));
    WaitForAccessibilityTreeToContainNodeWithName(GetActiveWebContents(),
                                                  expected_subtext);

    // Find the embedded PDF and dump the accessibility tree.
    content::FindAccessibilityNodeCriteria find_criteria;
    find_criteria.role = ax::mojom::Role::kPdfRoot;
    ui::AXPlatformNodeDelegate* pdf_root =
        content::FindAccessibilityNode(GetActiveWebContents(), find_criteria);
    ASSERT_TRUE(pdf_root);

    std::string actual_contents = formatter->Format(pdf_root);

    std::vector<std::string> actual_lines =
        base::SplitString(actual_contents, "\n", base::KEEP_WHITESPACE,
                          base::SPLIT_WANT_NONEMPTY);
    RemoveStatusSubtreeFromFormatOutput(actual_lines, ax_inspect_type());

    // Validate the dump against the expectation file.
    EXPECT_TRUE(test_helper_.ValidateAgainstExpectation(
        test_file_path, expected_file_path, actual_lines, *expected_lines));
  }

  std::vector<AXPropertyFilter> DefaultFilters() const {
    std::vector<AXPropertyFilter> property_filters;

    property_filters.emplace_back("value='*'", AXPropertyFilter::ALLOW);
    // The value attribute on the document object contains the URL of the
    // current page which will not be the same every time the test is run.
    // The PDF plugin uses the 'chrome-extension' protocol, so block that as
    // well.
    property_filters.emplace_back("value='http*'", AXPropertyFilter::DENY);
    property_filters.emplace_back("value='chrome-extension*'",
                                  AXPropertyFilter::DENY);
    // Object attributes.value
    property_filters.emplace_back("layout-guess:*", AXPropertyFilter::ALLOW);

    property_filters.emplace_back("select*", AXPropertyFilter::ALLOW);
    property_filters.emplace_back("descript*", AXPropertyFilter::ALLOW);
    property_filters.emplace_back("check*", AXPropertyFilter::ALLOW);
    property_filters.emplace_back("horizontal", AXPropertyFilter::ALLOW);
    property_filters.emplace_back("multiselectable", AXPropertyFilter::ALLOW);
    property_filters.emplace_back("isPageBreakingObject*",
                                  AXPropertyFilter::ALLOW);

    // Deny most empty values
    property_filters.emplace_back("*=''", AXPropertyFilter::DENY);
    // After denying empty values, because we want to allow name=''
    property_filters.emplace_back("name=*", AXPropertyFilter::ALLOW_EMPTY);

    return property_filters;
  }

  void RemoveStatusSubtreeFromFormatOutput(
      std::vector<std::string>& output_lines,
      const ui::AXApiType::Type& platform_type) {
    // The status subtree is of the form banner -> status -> staticText and will
    // be in the second to fourth lines in the tree output. These nodes are
    // always added to the PDF accessibility tree after the PDF root node and
    // don't get deleted. So, it is safe to assume that they are always there in
    // the format output.
    // Thus, delete the second and third lines from the tree format output.
    ASSERT_GT(output_lines.size(), 3u);
    std::string banner_role;
    std::string status_role;
    std::string static_text_role;
    switch (platform_type) {
      case ui::AXApiType::kBlink:
        banner_role = "banner";
        status_role = "status";
        static_text_role = "static";
        break;
      case ui::AXApiType::kLinux:
        banner_role = "landmark";
        status_role = "statusbar";
        static_text_role = "static";
        break;
      case ui::AXApiType::kMac:
        banner_role = "AXLandmarkBanner";
        status_role = "AXApplicationStatus";
        static_text_role = "AXStaticText";
        break;
      case ui::AXApiType::kWinIA2:
        banner_role = "IA2_ROLE_LANDMARK";
        status_role = "ROLE_SYSTEM_STATUSBAR";
        static_text_role = "ROLE_SYSTEM_STATICTEXT";
        break;
      case ui::AXApiType::kWinUIA:
        banner_role = "Group";
        status_role = "StatusBar";
        static_text_role = "Text";
        break;
      case ui::AXApiType::kNone:
        [[fallthrough]];
      case ui::AXApiType::kAndroid:
        [[fallthrough]];
      case ui::AXApiType::kAndroidExternal:
        [[fallthrough]];
      case ui::AXApiType::kFuchsia:
        return;
    }
    EXPECT_TRUE(base::Contains(output_lines[1], banner_role))
        << output_lines[1];
    EXPECT_TRUE(base::Contains(output_lines[2], status_role))
        << output_lines[2];
    EXPECT_TRUE(base::Contains(output_lines[3], static_text_role))
        << output_lines[3];

    output_lines.erase(output_lines.begin() + 1, output_lines.begin() + 4);
  }

  ui::AXInspectTestHelper test_helper_;
};

// Constructs a list of accessibility tests, one for each accessibility tree
// formatter testpasses.
const std::vector<ui::AXApiType::Type> GetAXTestValues() {
  std::vector<ui::AXApiType::Type> passes =
      ui::AXInspectTestHelper::TreeTestPasses();
  return passes;
}

struct PDFExtensionAccessibilityTreeDumpTestPassToString {
  std::string operator()(
      const ::testing::TestParamInfo<std::tuple<ui::AXApiType::Type, bool>>& i)
      const {
    return std::string(std::get<1>(i.param) ? "OOPIF_" : "GUESTVIEW_") +
           std::string(std::get<0>(i.param));
  }
};

INSTANTIATE_TEST_SUITE_P(All,
                         PDFExtensionAccessibilityTreeDumpTest,
                         testing::Combine(testing::ValuesIn(GetAXTestValues()),
                                          testing::Bool()),
                         PDFExtensionAccessibilityTreeDumpTestPassToString());

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, HelloWorld) {
  base::HistogramTester histograms;
  RunPDFTest(FILE_PATH_LITERAL("hello-world.pdf"),
             /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest,
                       ParagraphsAndHeadingUntagged) {
  RunPDFTest(FILE_PATH_LITERAL("paragraphs-and-heading-untagged.pdf"),
             /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, MultiPage) {
  RunPDFTest(FILE_PATH_LITERAL("multi-page.pdf"),
             /*expected_subtext=*/"Page 2");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest,
                       DirectionalTextRuns) {
  RunPDFTest(FILE_PATH_LITERAL("directional-text-runs.pdf"),
             /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, TextDirection) {
  RunPDFTest(FILE_PATH_LITERAL("text-direction.pdf"),
             /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, WebLinks) {
  RunPDFTest(FILE_PATH_LITERAL("weblinks.pdf"), /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest,
                       OverlappingLinks) {
  RunPDFTest(FILE_PATH_LITERAL("overlapping-links.pdf"),
             /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, Highlights) {
  RunPDFTest(FILE_PATH_LITERAL("highlights.pdf"),
             /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, TextFields) {
  RunPDFTest(FILE_PATH_LITERAL("text_fields.pdf"),
             /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, Images) {
  RunPDFTest(FILE_PATH_LITERAL("image_alt_text.pdf"),
             /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest,
                       LinksImagesAndText) {
  RunPDFTest(FILE_PATH_LITERAL("text-image-link.pdf"),
             /*expected_subtext=*/"Page 2");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest,
                       TextRunStyleHeuristic) {
  RunPDFTest(FILE_PATH_LITERAL("text-run-style-heuristic.pdf"),
             /*expected_subtext=*/"Page 1");
}

IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, TextStyle) {
  RunPDFTest(FILE_PATH_LITERAL("text-style.pdf"),
             /*expected_subtext=*/"Page 1");
}

// TODO(crbug.com/40745411)
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityTreeDumpTest, XfaFields) {
  RunPDFTest(FILE_PATH_LITERAL("xfa_fields.pdf"),
             /*expected_subtext=*/"Page 1");
}

// This test suite validates the navigation done using the accessibility client.
using PDFExtensionAccessibilityNavigationTest =
    PDFExtensionAccessibilityTestWithOopifOverride;

// TODO(crbug.com/40934115): Fix the flakiness on ChromeOS.
#if BUILDFLAG(IS_CHROMEOS)
#define MAYBE_LinkNavigation DISABLED_LinkNavigation
#else
#define MAYBE_LinkNavigation LinkNavigation
#endif  // BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_P(PDFExtensionAccessibilityNavigationTest,
                       MAYBE_LinkNavigation) {
  // Enable accessibility and load the test file.
  content::ScopedAccessibilityModeOverride mode_override(ui::kAXModeComplete);
  ASSERT_TRUE(LoadPdf(
      embedded_test_server()->GetURL("/pdf/accessibility/weblinks.pdf")));

  WaitForAccessibilityTreeToContainNodeWithName(GetActiveWebContents(),
                                                "Page 1");

  // Find the specific link node.
  content::FindAccessibilityNodeCriteria find_criteria;
  find_criteria.role = ax::mojom::Role::kLink;
  find_criteria.name = "http://bing.com";
  ui::AXPlatformNodeDelegate* link_node =
      content::FindAccessibilityNode(GetActiveWebContents(), find_criteria);
  ASSERT_TRUE(link_node);

  // Invoke action on a link and wait for navigation to complete.
  EXPECT_EQ(ax::mojom::DefaultActionVerb::kJump,
            link_node->GetData().GetDefaultActionVerb());
  content::AccessibilityNotificationWaiter event_waiter(
      GetActiveWebContents(), ax::mojom::Event::kLoadComplete);
  ui::AXActionData action_data;
  action_data.action = ax::mojom::Action::kDoDefault;
  action_data.target_node_id = link_node->GetData().id;
  link_node->AccessibilityPerformAction(action_data);
  ASSERT_TRUE(event_waiter.WaitForNotification());

  // Test that navigation occurred correctly.
  const GURL& expected_url = GetActiveWebContents()->GetLastCommittedURL();
  EXPECT_EQ("https://bing.com/", expected_url.spec());
}

// This test suite contains simple tests for the PDF OCR feature.
class PdfOcrUmaTest : public PDFExtensionAccessibilityTest,
                      public ::testing::WithParamInterface<bool> {
 public:
  PdfOcrUmaTest() = default;
  ~PdfOcrUmaTest() override = default;

  // PDFExtensionAccessibilityTest:
  bool UseOopif() const override { return GetParam(); }

 protected:
  std::vector<base::test::FeatureRefAndParams> GetEnabledFeatures()
      const override {
    std::vector<base::test::FeatureRefAndParams> enabled =
        PDFExtensionAccessibilityTest::GetEnabledFeatures();
    if (UseOopif()) {
      enabled.push_back({chrome_pdf::features::kPdfOopif, {}});
    }
    return enabled;
  }

  std::vector<base::test::FeatureRef> GetDisabledFeatures() const override {
    std::vector<base::test::FeatureRef> disabled;
    if (!UseOopif()) {
      disabled.push_back(chrome_pdf::features::kPdfOopif);
    }
    return disabled;
  }
};

IN_PROC_BROWSER_TEST_P(PdfOcrUmaTest, CheckOpenedWithScreenReader) {
  // TODO(crbug.com/289010799): Remove this once the metrics are added for OOPIF
  // PDF.
  if (UseOopif()) {
    GTEST_SKIP();
  }

  EnableScreenReader();

  base::HistogramTester histograms;
  histograms.ExpectUniqueSample(
      "Accessibility.PDF.OpenedWithScreenReader.PdfOcr", true,
      /*expected_bucket_count=*/0);

  ASSERT_TRUE(LoadPdf(embedded_test_server()->GetURL("/pdf/test.pdf")));

  WebContents* contents = GetActiveWebContents();
  content::RenderFrameHost* extension_host =
      pdf_extension_test_util::GetOnlyPdfExtensionHost(contents);
  ASSERT_TRUE(extension_host);

  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
  histograms.ExpectUniqueSample(
      "Accessibility.PDF.OpenedWithScreenReader.PdfOcr", true,
      /*expected_bucket_count=*/1);
}

#if BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_P(PdfOcrUmaTest, CheckOpenedWithSelectToSpeak) {
  // TODO(crbug.com/289010799): Remove this once the metrics are added for OOPIF
  // PDF.
  if (UseOopif()) {
    GTEST_SKIP();
  }

  ::ash::AccessibilityManager::Get()->SetSelectToSpeakEnabled(true);

  base::HistogramTester histograms;
  histograms.ExpectUniqueSample(
      "Accessibility.PDF.OpenedWithSelectToSpeak.PdfOcr", true,
      /*expected_bucket_count=*/0);

  ASSERT_TRUE(LoadPdf(embedded_test_server()->GetURL("/pdf/test.pdf")));

  WebContents* contents = GetActiveWebContents();
  content::RenderFrameHost* extension_host =
      pdf_extension_test_util::GetOnlyPdfExtensionHost(contents);
  ASSERT_TRUE(extension_host);

  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
  histograms.ExpectUniqueSample(
      "Accessibility.PDF.OpenedWithSelectToSpeak.PdfOcr", true,
      /*expected_bucket_count=*/1);
}

IN_PROC_BROWSER_TEST_P(PdfOcrUmaTest,
                       CheckSelectToSpeakPagesOcredWithAccessiblePdf) {
  // TODO(crbug.com/289010799): Remove this once the metrics are added for OOPIF
  // PDF.
  if (UseOopif()) {
    GTEST_SKIP();
  }

  ::ash::AccessibilityManager::Get()->SetSelectToSpeakEnabled(true);

  base::HistogramTester histograms;
  histograms.ExpectTotalCount(
      "Accessibility.PdfOcr.CrosSelectToSpeak.PagesOcred",
      /*expected_count=*/0);

  ASSERT_TRUE(LoadPdf(embedded_test_server()->GetURL("/pdf/test.pdf")));

  WebContents* contents = GetActiveWebContents();
  content::RenderFrameHost* extension_host =
      pdf_extension_test_util::GetOnlyPdfExtensionHost(contents);
  ASSERT_TRUE(extension_host);

  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
  // The metric should record nothing for accessible PDFs.
  histograms.ExpectTotalCount(
      "Accessibility.PdfOcr.CrosSelectToSpeak.PagesOcred",
      /*expected_count=*/0);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

INSTANTIATE_TEST_SUITE_P(All,
                         PdfOcrUmaTest,
                         testing::Bool(),
                         [](const testing::TestParamInfo<bool>& info) {
                           return base::StringPrintf(
                               "OOPIF_%s", info.param ? "Enabled" : "Disabled");
                         });

// TODO(crbug.com/40268279): Stop testing both modes after OOPIF PDF viewer
// launches.
INSTANTIATE_FEATURE_OVERRIDE_TEST_SUITE(
    PDFExtensionAccessibilityTestWithOopifOverride);
INSTANTIATE_FEATURE_OVERRIDE_TEST_SUITE(
    PDFExtensionAccessibilityTextExtractionTest);
INSTANTIATE_FEATURE_OVERRIDE_TEST_SUITE(
    PDFExtensionAccessibilityNavigationTest);

#if defined(PDF_SEARCHIFY_INTEGRATION_TEST_ENABLED)

class PdfSearchifyIntegrationTest
    : public PDFExtensionAccessibilityTest,
      public screen_ai::ScreenAIInstallState::Observer,
      public ::testing::WithParamInterface<std::tuple<bool, bool, bool>> {
 public:
  PdfSearchifyIntegrationTest() = default;
  ~PdfSearchifyIntegrationTest() override = default;

  bool IsOcrServiceEnabled() const { return std::get<0>(GetParam()); }
  bool IsLibraryAvailable() const { return std::get<1>(GetParam()); }

  // PDFExtensionAccessibilityTest:
  bool UseOopif() const override { return std::get<2>(GetParam()); }

  bool IsOcrAvailable() const {
    return IsOcrServiceEnabled() && IsLibraryAvailable();
  }

  // PDFExtensionAccessibilityTest:
  void SetUpOnMainThread() override {
    PDFExtensionAccessibilityTest::SetUpOnMainThread();

    if (IsLibraryAvailable()) {
      screen_ai::ScreenAIInstallState::GetInstance()->SetComponentFolder(
          screen_ai::GetComponentBinaryPathForTests().DirName());
    } else {
      // Set an observer to mark download as failed when requested.
      component_download_observer_.Observe(
          screen_ai::ScreenAIInstallState::GetInstance());
    }

    EnableScreenReader();
  }

  void TearDownOnMainThread() override {
    component_download_observer_.Reset();
    PDFExtensionAccessibilityTest::TearDownOnMainThread();
  }

  void WaitForTextInTree(std::string_view expected_text) {
    WebContents* contents = GetActiveWebContents();
    ASSERT_TRUE(contents);
    WaitForAccessibilityTreeToContainNodeWithName(contents, expected_text);
  }

  // ScreenAIInstallState::Observer:
  void StateChanged(screen_ai::ScreenAIInstallState::State state) override {
    if (state == screen_ai::ScreenAIInstallState::State::kDownloading &&
        !IsLibraryAvailable()) {
      base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE, base::BindOnce([]() {
            screen_ai::ScreenAIInstallState::GetInstance()->SetState(
                screen_ai::ScreenAIInstallState::State::kDownloadFailed);
          }));
    }
  }

  int GetExpectedStatus(bool has_content) {
    if (!IsOcrAvailable()) {
      return IDS_PDF_OCR_FEATURE_ALERT;
    }
    return has_content ? IDS_PDF_OCR_COMPLETED : IDS_PDF_OCR_NO_RESULT;
  }

 protected:
  std::vector<base::test::FeatureRefAndParams> GetEnabledFeatures()
      const override {
    auto enabled = PDFExtensionAccessibilityTest::GetEnabledFeatures();
    enabled.push_back({::features::kScreenAITestMode, {}});
    if (IsOcrServiceEnabled()) {
      enabled.push_back({ax::mojom::features::kScreenAIOCREnabled, {}});
    }
    if (UseOopif()) {
      enabled.push_back({chrome_pdf::features::kPdfOopif, {}});
    }
    return enabled;
  }

  std::vector<base::test::FeatureRef> GetDisabledFeatures() const override {
    std::vector<base::test::FeatureRef> disabled;
    if (!IsOcrServiceEnabled()) {
      disabled.push_back(ax::mojom::features::kScreenAIOCREnabled);
    }
    if (!UseOopif()) {
      disabled.push_back(chrome_pdf::features::kPdfOopif);
    }
    return disabled;
  }

  void RunPDFAXTreeDumpTest(const char* pdf_file,
                            std::string_view expected_text) {
    base::FilePath test_path = ui_test_utils::GetTestFilePath(
        base::FilePath(FILE_PATH_LITERAL("pdf")),
        base::FilePath(FILE_PATH_LITERAL("accessibility")));
    base::FilePath test_pdf_path = test_path.AppendASCII(pdf_file);

    const GURL test_file_url = embedded_test_server()->GetURL(
        base::StrCat({"/pdf/accessibility/", pdf_file}));
    ASSERT_TRUE(LoadPdf(test_file_url));

    WaitForTextInTree(expected_text);

    ui::AXTreeUpdate ax_tree =
        GetAccessibilityTreeSnapshotForPdf(GetActiveWebContents());
    std::string ax_tree_dump =
        DumpPdfAccessibilityTree(ax_tree, /*skip_status_subtree=*/false);
    std::string expected_tree_dump =
        GetExpectedAXTreeDumpForPdf(test_pdf_path, IsOcrAvailable());
    ASSERT_NE("", expected_tree_dump);

    ASSERT_MULTILINE_STREQ(expected_tree_dump, ax_tree_dump);
  }

 private:
  std::string GetExpectedAXTreeDumpForPdf(const base::FilePath& pdf_path,
                                          bool is_ocr_available) {
    // If the given `pdf_path` contains a filename, "test.pdf", an expected
    // file path will have a filename, "test-expected-with-pdf-searchify.txt",
    // when OCR is available.
    // `expected_file_suffix` will be created based on whether OCR is available
    // and it has a separate output for Windows.
    base::FilePath::StringType expected_file_suffix;

    if (is_ocr_available) {
      expected_file_suffix = FILE_PATH_LITERAL("-expected-with-pdf-searchify");
    } else {
      expected_file_suffix =
          FILE_PATH_LITERAL("-expected-without-pdf-searchify");
    }
#if BUILDFLAG(IS_WIN)
    // When OCR is unavailable, each test input has a separate expected output
    // for Windows. Otherwise, only "blank_image.pdf" has a separate expected
    // output for Windows.
    if (!is_ocr_available ||
        pdf_path.BaseName().value() == FILE_PATH_LITERAL("blank_image.pdf")) {
      expected_file_suffix += FILE_PATH_LITERAL("-win");
    }
#endif  // BUILDFLAG(IS_WIN)
    expected_file_suffix += FILE_PATH_LITERAL(".txt");

    // Replace the extension of `pdf_path` with `expected_file_suffix`. However
    // `base::FilePath::ReplaceExtension()` won't work here as it appends '.'
    // to the beginning of the new extension given to the function if the new
    // extension doesn't start with '.'.
    base::FilePath expected_file_path = pdf_path.DirName().Append(
        pdf_path.BaseName().RemoveExtension().value() + expected_file_suffix);
    {
      base::ScopedAllowBlockingForTesting allow_blocking;
      if (!base::PathExists(expected_file_path)) {
        ADD_FAILURE() << "Unable to read an expected file at "
                      << expected_file_path;
        return std::string();
      }
    }

    return LoadExpectationFile(expected_file_path);
  }

  std::string LoadExpectationFile(const base::FilePath& expected_file) {
    base::ScopedAllowBlockingForTesting allow_blocking;

    std::string expected_contents_raw;
    if (!base::ReadFileToString(expected_file, &expected_contents_raw)) {
      ADD_FAILURE() << "Unable to read an expected file at " << expected_file;
    }

    // Tolerate Windows-style line endings (\r\n) in the expected file:
    // normalize by deleting all \r from the file (if any) to leave only \n.
    std::string expected_contents;
    base::RemoveChars(expected_contents_raw, "\r", &expected_contents);

    return expected_contents;
  }

  base::ScopedObservation<screen_ai::ScreenAIInstallState,
                          screen_ai::ScreenAIInstallState::Observer>
      component_download_observer_{this};
};

IN_PROC_BROWSER_TEST_P(PdfSearchifyIntegrationTest, EnsureScreenAIInitializes) {
  // Since screen reader is on, library download is triggered and if it is
  // successful, initialization of Screen AI OCR service will be successful.

  // Wait for Screen AI OCR service to either get ready or fail.
  base::test::TestFuture<bool> future;
  auto* router = screen_ai::ScreenAIServiceRouterFactory::GetForBrowserContext(
      browser()->profile());
  router->GetServiceStateAsync(screen_ai::ScreenAIServiceRouter::Service::kOCR,
                               future.GetCallback());
  ASSERT_TRUE(future.Wait());
  ASSERT_EQ(future.Get(), IsOcrAvailable());

  // Library download state should not depend on OcrService availability.
  screen_ai::ScreenAIInstallState::State expected_state =
      IsLibraryAvailable()
          ? screen_ai::ScreenAIInstallState::State::kDownloaded
          : screen_ai::ScreenAIInstallState::State::kDownloadFailed;
  EXPECT_EQ(expected_state,
            screen_ai::ScreenAIInstallState::GetInstance()->get_state());
}

// TODO(crbug.com/360803943): Add a test case with more than one image.

IN_PROC_BROWSER_TEST_P(PdfSearchifyIntegrationTest, HelloWorld) {
  base::HistogramTester histograms;
  RunPDFAXTreeDumpTest("hello-world-in-image.pdf", "Page 1");

// Notifications are flaky on Linux screen reader (crbug.com/348626870),
// hence they are only tested on other platforms.
#if BUILDFLAG(IS_LINUX)
  WaitForTextInTree(
      l10n_util::GetStringUTF8(GetExpectedStatus(/*has_content=*/true)));
#endif

  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();

  int expected_count = IsOcrAvailable() ? 1 : 0;
  // Screen Reader is always enabled for this test.
  histograms.ExpectUniqueSample(
      "Accessibility.ScreenAI.Searchify.ScreenReaderModeEnabled",
      /*sample=*/true, expected_count);
}

IN_PROC_BROWSER_TEST_P(PdfSearchifyIntegrationTest, ThreePagePDF) {
  base::HistogramTester histograms;
  RunPDFAXTreeDumpTest("inaccessible-text-in-three-page.pdf", "Page 3");

  metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
  int expected_count = IsOcrAvailable() ? 1 : 0;
  histograms.ExpectUniqueSample(
      "Accessibility.ScreenAI.Searchify.ScreenReaderModeEnabled",
      /*sample=*/true, expected_count);
}

IN_PROC_BROWSER_TEST_P(PdfSearchifyIntegrationTest,
                       NoOcrResultOnBlankImagePdf) {
  RunPDFAXTreeDumpTest("blank_image.pdf", "Page 1");

// Notifications are flaky on Linux screen reader (crbug.com/348626870),
// hence they are tested only on other platforms.
#if BUILDFLAG(IS_LINUX)
  WaitForTextInTree(
      l10n_util::GetStringUTF8(GetExpectedStatus(/*has_content=*/false)));
#endif
}

INSTANTIATE_TEST_SUITE_P(
    All,
    PdfSearchifyIntegrationTest,
    ::testing::Combine(testing::Bool(), testing::Bool(), testing::Bool()),
    [](const testing::TestParamInfo<std::tuple<bool, bool, bool>>& info) {
      return base::StringPrintf(
          "OcrService_%s_Library_%s_%s",
          std::get<0>(info.param) ? "Enabled" : "Disabled",
          std::get<1>(info.param) ? "Available" : "Unavailable",
          std::get<2>(info.param) ? "OOPIF" : "GuestView");
    });

#endif  // defined(PDF_SEARCHIFY_INTEGRATION_TEST_ENABLED)