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
|
/*
* Copyright (C) 2008, 2009, 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "AccessibilityObject.h"
#include "AXObjectCache.h"
#include "AccessibilityRenderObject.h"
#include "AccessibilityScrollView.h"
#include "AccessibilityTable.h"
#include "DOMTokenList.h"
#include "Editor.h"
#include "ElementIterator.h"
#include "EventHandler.h"
#include "FloatRect.h"
#include "FocusController.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "HTMLDetailsElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HTMLParserIdioms.h"
#include "HitTestResult.h"
#include "LocalizedStrings.h"
#include "MainFrame.h"
#include "MathMLNames.h"
#include "NodeList.h"
#include "NodeTraversal.h"
#include "Page.h"
#include "RenderImage.h"
#include "RenderLayer.h"
#include "RenderListItem.h"
#include "RenderListMarker.h"
#include "RenderMenuList.h"
#include "RenderText.h"
#include "RenderTextControl.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "RenderedPosition.h"
#include "Settings.h"
#include "TextCheckerClient.h"
#include "TextCheckingHelper.h"
#include "TextIterator.h"
#include "UserGestureIndicator.h"
#include "VisibleUnits.h"
#include "htmlediting.h"
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/WTFString.h>
#include <wtf/unicode/CharacterNames.h>
namespace WebCore {
using namespace HTMLNames;
AccessibilityObject::AccessibilityObject()
: m_id(0)
, m_haveChildren(false)
, m_role(UnknownRole)
, m_lastKnownIsIgnoredValue(DefaultBehavior)
#if PLATFORM(GTK) || (PLATFORM(EFL) && HAVE(ACCESSIBILITY))
, m_wrapper(nullptr)
#endif
{
}
AccessibilityObject::~AccessibilityObject()
{
ASSERT(isDetached());
}
void AccessibilityObject::detach(AccessibilityDetachmentType detachmentType, AXObjectCache* cache)
{
// Menu close events need to notify the platform. No element is used in the notification because it's a destruction event.
if (detachmentType == ElementDestroyed && roleValue() == MenuRole && cache)
cache->postNotification(nullptr, &cache->document(), AXObjectCache::AXMenuClosed);
// Clear any children and call detachFromParent on them so that
// no children are left with dangling pointers to their parent.
clearChildren();
#if HAVE(ACCESSIBILITY)
setWrapper(nullptr);
#endif
}
bool AccessibilityObject::isDetached() const
{
#if HAVE(ACCESSIBILITY)
return !wrapper();
#else
return true;
#endif
}
bool AccessibilityObject::isAccessibilityObjectSearchMatchAtIndex(AccessibilityObject* axObject, AccessibilitySearchCriteria* criteria, size_t index)
{
switch (criteria->searchKeys[index]) {
// The AnyTypeSearchKey matches any non-null AccessibilityObject.
case AnyTypeSearchKey:
return true;
case BlockquoteSameLevelSearchKey:
return criteria->startObject
&& axObject->isBlockquote()
&& axObject->blockquoteLevel() == criteria->startObject->blockquoteLevel();
case BlockquoteSearchKey:
return axObject->isBlockquote();
case BoldFontSearchKey:
return axObject->hasBoldFont();
case ButtonSearchKey:
return axObject->isButton();
case CheckBoxSearchKey:
return axObject->isCheckbox();
case ControlSearchKey:
return axObject->isControl();
case DifferentTypeSearchKey:
return criteria->startObject
&& axObject->roleValue() != criteria->startObject->roleValue();
case FontChangeSearchKey:
return criteria->startObject
&& !axObject->hasSameFont(criteria->startObject->renderer());
case FontColorChangeSearchKey:
return criteria->startObject
&& !axObject->hasSameFontColor(criteria->startObject->renderer());
case FrameSearchKey:
return axObject->isWebArea();
case GraphicSearchKey:
return axObject->isImage();
case HeadingLevel1SearchKey:
return axObject->headingLevel() == 1;
case HeadingLevel2SearchKey:
return axObject->headingLevel() == 2;
case HeadingLevel3SearchKey:
return axObject->headingLevel() == 3;
case HeadingLevel4SearchKey:
return axObject->headingLevel() == 4;
case HeadingLevel5SearchKey:
return axObject->headingLevel() == 5;
case HeadingLevel6SearchKey:
return axObject->headingLevel() == 6;
case HeadingSameLevelSearchKey:
return criteria->startObject
&& axObject->isHeading()
&& axObject->headingLevel() == criteria->startObject->headingLevel();
case HeadingSearchKey:
return axObject->isHeading();
case HighlightedSearchKey:
return axObject->hasHighlighting();
case ItalicFontSearchKey:
return axObject->hasItalicFont();
case LandmarkSearchKey:
return axObject->isLandmark();
case LinkSearchKey:
return axObject->isLink();
case ListSearchKey:
return axObject->isList();
case LiveRegionSearchKey:
return axObject->supportsARIALiveRegion();
case MisspelledWordSearchKey:
return axObject->hasMisspelling();
case OutlineSearchKey:
return axObject->isTree();
case PlainTextSearchKey:
return axObject->hasPlainText();
case RadioGroupSearchKey:
return axObject->isRadioGroup();
case SameTypeSearchKey:
return criteria->startObject
&& axObject->roleValue() == criteria->startObject->roleValue();
case StaticTextSearchKey:
return axObject->isStaticText();
case StyleChangeSearchKey:
return criteria->startObject
&& !axObject->hasSameStyle(criteria->startObject->renderer());
case TableSameLevelSearchKey:
return criteria->startObject
&& is<AccessibilityTable>(*axObject) && downcast<AccessibilityTable>(*axObject).isExposableThroughAccessibility()
&& downcast<AccessibilityTable>(*axObject).tableLevel() == criteria->startObject->tableLevel();
case TableSearchKey:
return is<AccessibilityTable>(*axObject) && downcast<AccessibilityTable>(*axObject).isExposableThroughAccessibility();
case TextFieldSearchKey:
return axObject->isTextControl();
case UnderlineSearchKey:
return axObject->hasUnderline();
case UnvisitedLinkSearchKey:
return axObject->isUnvisited();
case VisitedLinkSearchKey:
return axObject->isVisited();
default:
return false;
}
}
bool AccessibilityObject::isAccessibilityObjectSearchMatch(AccessibilityObject* axObject, AccessibilitySearchCriteria* criteria)
{
if (!axObject || !criteria)
return false;
size_t length = criteria->searchKeys.size();
for (size_t i = 0; i < length; ++i) {
if (isAccessibilityObjectSearchMatchAtIndex(axObject, criteria, i)) {
if (criteria->visibleOnly && !axObject->isOnscreen())
return false;
return true;
}
}
return false;
}
bool AccessibilityObject::isAccessibilityTextSearchMatch(AccessibilityObject* axObject, AccessibilitySearchCriteria* criteria)
{
if (!axObject || !criteria)
return false;
return axObject->accessibilityObjectContainsText(&criteria->searchText);
}
bool AccessibilityObject::accessibilityObjectContainsText(String* text) const
{
// If text is null or empty we return true.
return !text
|| text->isEmpty()
|| title().contains(*text, false)
|| accessibilityDescription().contains(*text, false)
|| stringValue().contains(*text, false);
}
// ARIA marks elements as having their accessible name derive from either their contents, or their author provide name.
bool AccessibilityObject::accessibleNameDerivesFromContent() const
{
// First check for objects specifically identified by ARIA.
switch (ariaRoleAttribute()) {
case ApplicationAlertRole:
case ApplicationAlertDialogRole:
case ApplicationDialogRole:
case ApplicationLogRole:
case ApplicationMarqueeRole:
case ApplicationStatusRole:
case ApplicationTimerRole:
case ComboBoxRole:
case DefinitionRole:
case DocumentRole:
case DocumentArticleRole:
case DocumentMathRole:
case DocumentNoteRole:
case DocumentRegionRole:
case FormRole:
case GridRole:
case GroupRole:
case ImageRole:
case ListRole:
case ListBoxRole:
case LandmarkApplicationRole:
case LandmarkBannerRole:
case LandmarkComplementaryRole:
case LandmarkContentInfoRole:
case LandmarkNavigationRole:
case LandmarkMainRole:
case LandmarkSearchRole:
case MenuRole:
case MenuBarRole:
case ProgressIndicatorRole:
case RadioGroupRole:
case ScrollBarRole:
case SliderRole:
case SpinButtonRole:
case SplitterRole:
case TableRole:
case TabListRole:
case TabPanelRole:
case TextAreaRole:
case TextFieldRole:
case ToolbarRole:
case TreeGridRole:
case TreeRole:
return false;
default:
break;
}
// Now check for generically derived elements now that we know the element does not match a specific ARIA role.
switch (roleValue()) {
case SliderRole:
return false;
default:
break;
}
return true;
}
String AccessibilityObject::computedLabel()
{
// This method is being called by WebKit inspector, which may happen at any time, so we need to update our backing store now.
// Also hold onto this object in case updateBackingStore deletes this node.
RefPtr<AccessibilityObject> protector(this);
updateBackingStore();
Vector<AccessibilityText> text;
accessibilityText(text);
if (text.size())
return text[0].text;
return String();
}
bool AccessibilityObject::isBlockquote() const
{
return roleValue() == BlockquoteRole;
}
bool AccessibilityObject::isTextControl() const
{
switch (roleValue()) {
case ComboBoxRole:
case SearchFieldRole:
case TextAreaRole:
case TextFieldRole:
return true;
default:
return false;
}
}
bool AccessibilityObject::isARIATextControl() const
{
return ariaRoleAttribute() == TextAreaRole || ariaRoleAttribute() == TextFieldRole || ariaRoleAttribute() == SearchFieldRole;
}
bool AccessibilityObject::isNonNativeTextControl() const
{
return (isARIATextControl() || hasContentEditableAttributeSet()) && !isNativeTextControl();
}
bool AccessibilityObject::isLandmark() const
{
AccessibilityRole role = roleValue();
return role == LandmarkApplicationRole
|| role == LandmarkBannerRole
|| role == LandmarkComplementaryRole
|| role == LandmarkContentInfoRole
|| role == LandmarkMainRole
|| role == LandmarkNavigationRole
|| role == LandmarkSearchRole;
}
bool AccessibilityObject::hasMisspelling() const
{
if (!node())
return false;
Frame* frame = node()->document().frame();
if (!frame)
return false;
Editor& editor = frame->editor();
TextCheckerClient* textChecker = editor.textChecker();
if (!textChecker)
return false;
bool isMisspelled = false;
if (unifiedTextCheckerEnabled(frame)) {
Vector<TextCheckingResult> results;
checkTextOfParagraph(*textChecker, stringValue(), TextCheckingTypeSpelling, results);
if (!results.isEmpty())
isMisspelled = true;
return isMisspelled;
}
int misspellingLength = 0;
int misspellingLocation = -1;
textChecker->checkSpellingOfString(stringValue(), &misspellingLocation, &misspellingLength);
if (misspellingLength || misspellingLocation != -1)
isMisspelled = true;
return isMisspelled;
}
int AccessibilityObject::blockquoteLevel() const
{
int level = 0;
for (Node* elementNode = node(); elementNode; elementNode = elementNode->parentNode()) {
if (elementNode->hasTagName(blockquoteTag))
++level;
}
return level;
}
AccessibilityObject* AccessibilityObject::parentObjectUnignored() const
{
AccessibilityObject* parent;
for (parent = parentObject(); parent && parent->accessibilityIsIgnored(); parent = parent->parentObject()) {
}
return parent;
}
AccessibilityObject* AccessibilityObject::previousSiblingUnignored(int limit) const
{
AccessibilityObject* previous;
ASSERT(limit >= 0);
for (previous = previousSibling(); previous && previous->accessibilityIsIgnored(); previous = previous->previousSibling()) {
limit--;
if (limit <= 0)
break;
}
return previous;
}
AccessibilityObject* AccessibilityObject::nextSiblingUnignored(int limit) const
{
AccessibilityObject* next;
ASSERT(limit >= 0);
for (next = nextSibling(); next && next->accessibilityIsIgnored(); next = next->nextSibling()) {
limit--;
if (limit <= 0)
break;
}
return next;
}
AccessibilityObject* AccessibilityObject::firstAccessibleObjectFromNode(const Node* node)
{
if (!node)
return nullptr;
AXObjectCache* cache = node->document().axObjectCache();
if (!cache)
return nullptr;
AccessibilityObject* accessibleObject = cache->getOrCreate(node->renderer());
while (accessibleObject && accessibleObject->accessibilityIsIgnored()) {
node = NodeTraversal::next(*node);
while (node && !node->renderer())
node = NodeTraversal::nextSkippingChildren(*node);
if (!node)
return nullptr;
accessibleObject = cache->getOrCreate(node->renderer());
}
return accessibleObject;
}
static void appendAccessibilityObject(AccessibilityObject* object, AccessibilityObject::AccessibilityChildrenVector& results)
{
// Find the next descendant of this attachment object so search can continue through frames.
if (object->isAttachment()) {
Widget* widget = object->widgetForAttachmentView();
if (!is<FrameView>(widget))
return;
Document* document = downcast<FrameView>(*widget).frame().document();
if (!document || !document->hasLivingRenderTree())
return;
object = object->axObjectCache()->getOrCreate(document);
}
if (object)
results.append(object);
}
static void appendChildrenToArray(AccessibilityObject* object, bool isForward, AccessibilityObject* startObject, AccessibilityObject::AccessibilityChildrenVector& results)
{
// A table's children includes elements whose own children are also the table's children (due to the way the Mac exposes tables).
// The rows from the table should be queried, since those are direct descendants of the table, and they contain content.
const auto& searchChildren = is<AccessibilityTable>(*object) && downcast<AccessibilityTable>(*object).isExposableThroughAccessibility() ? downcast<AccessibilityTable>(*object).rows() : object->children();
size_t childrenSize = searchChildren.size();
size_t startIndex = isForward ? childrenSize : 0;
size_t endIndex = isForward ? 0 : childrenSize;
size_t searchPosition = startObject ? searchChildren.find(startObject) : WTF::notFound;
if (searchPosition != WTF::notFound) {
if (isForward)
endIndex = searchPosition + 1;
else
endIndex = searchPosition;
}
// This is broken into two statements so that it's easier read.
if (isForward) {
for (size_t i = startIndex; i > endIndex; i--)
appendAccessibilityObject(searchChildren.at(i - 1).get(), results);
} else {
for (size_t i = startIndex; i < endIndex; i++)
appendAccessibilityObject(searchChildren.at(i).get(), results);
}
}
// Returns true if the number of results is now >= the number of results desired.
bool AccessibilityObject::objectMatchesSearchCriteriaWithResultLimit(AccessibilityObject* object, AccessibilitySearchCriteria* criteria, AccessibilityChildrenVector& results)
{
if (isAccessibilityObjectSearchMatch(object, criteria) && isAccessibilityTextSearchMatch(object, criteria)) {
results.append(object);
// Enough results were found to stop searching.
if (results.size() >= criteria->resultsLimit)
return true;
}
return false;
}
void AccessibilityObject::findMatchingObjects(AccessibilitySearchCriteria* criteria, AccessibilityChildrenVector& results)
{
ASSERT(criteria);
if (!criteria)
return;
if (AXObjectCache* cache = axObjectCache())
cache->startCachingComputedObjectAttributesUntilTreeMutates();
// This search mechanism only searches the elements before/after the starting object.
// It does this by stepping up the parent chain and at each level doing a DFS.
// If there's no start object, it means we want to search everything.
AccessibilityObject* startObject = criteria->startObject;
if (!startObject)
startObject = this;
bool isForward = criteria->searchDirection == SearchDirectionNext;
// The first iteration of the outer loop will examine the children of the start object for matches. However, when
// iterating backwards, the start object children should not be considered, so the loop is skipped ahead. We make an
// exception when no start object was specified because we want to search everything regardless of search direction.
AccessibilityObject* previousObject = nullptr;
if (!isForward && startObject != this) {
previousObject = startObject;
startObject = startObject->parentObjectUnignored();
}
// The outer loop steps up the parent chain each time (unignored is important here because otherwise elements would be searched twice)
for (AccessibilityObject* stopSearchElement = parentObjectUnignored(); startObject != stopSearchElement; startObject = startObject->parentObjectUnignored()) {
// Only append the children after/before the previous element, so that the search does not check elements that are
// already behind/ahead of start element.
AccessibilityChildrenVector searchStack;
if (!criteria->immediateDescendantsOnly || startObject == this)
appendChildrenToArray(startObject, isForward, previousObject, searchStack);
// This now does a DFS at the current level of the parent.
while (!searchStack.isEmpty()) {
AccessibilityObject* searchObject = searchStack.last().get();
searchStack.removeLast();
if (objectMatchesSearchCriteriaWithResultLimit(searchObject, criteria, results))
break;
if (!criteria->immediateDescendantsOnly)
appendChildrenToArray(searchObject, isForward, 0, searchStack);
}
if (results.size() >= criteria->resultsLimit)
break;
// When moving backwards, the parent object needs to be checked, because technically it's "before" the starting element.
if (!isForward && startObject != this && objectMatchesSearchCriteriaWithResultLimit(startObject, criteria, results))
break;
previousObject = startObject;
}
}
// Returns the range that is fewer positions away from the reference range.
// NOTE: The after range is expected to ACTUALLY be after the reference range and the before
// range is expected to ACTUALLY be before. These are not checked for performance reasons.
static RefPtr<Range> rangeClosestToRange(Range* referenceRange, RefPtr<Range>&& afterRange, RefPtr<Range>&& beforeRange)
{
if (!referenceRange)
return nullptr;
// The treeScope for shadow nodes may not be the same scope as another element in a document.
// Comparisons may fail in that case, which are expected behavior and should not assert.
if (afterRange && ((afterRange->startPosition().anchorNode()->compareDocumentPosition(referenceRange->endPosition().anchorNode()) & Node::DOCUMENT_POSITION_DISCONNECTED) == Node::DOCUMENT_POSITION_DISCONNECTED))
return nullptr;
ASSERT(!afterRange || afterRange->startPosition() >= referenceRange->endPosition());
if (beforeRange && ((beforeRange->endPosition().anchorNode()->compareDocumentPosition(referenceRange->startPosition().anchorNode()) & Node::DOCUMENT_POSITION_DISCONNECTED) == Node::DOCUMENT_POSITION_DISCONNECTED))
return nullptr;
ASSERT(!beforeRange || beforeRange->endPosition() <= referenceRange->startPosition());
if (!afterRange && !beforeRange)
return nullptr;
if (afterRange && !beforeRange)
return afterRange;
if (!afterRange && beforeRange)
return beforeRange;
unsigned positionsToAfterRange = Position::positionCountBetweenPositions(afterRange->startPosition(), referenceRange->endPosition());
unsigned positionsToBeforeRange = Position::positionCountBetweenPositions(beforeRange->endPosition(), referenceRange->startPosition());
return positionsToAfterRange < positionsToBeforeRange ? afterRange : beforeRange;
}
RefPtr<Range> AccessibilityObject::rangeOfStringClosestToRangeInDirection(Range* referenceRange, AccessibilitySearchDirection searchDirection, Vector<String>& searchStrings) const
{
Frame* frame = this->frame();
if (!frame)
return nullptr;
if (!referenceRange)
return nullptr;
bool isBackwardSearch = searchDirection == SearchDirectionPrevious;
FindOptions findOptions = AtWordStarts | AtWordEnds | CaseInsensitive | StartInSelection;
if (isBackwardSearch)
findOptions |= Backwards;
RefPtr<Range> closestStringRange = nullptr;
for (const auto& searchString : searchStrings) {
if (RefPtr<Range> searchStringRange = frame->editor().rangeOfString(searchString, referenceRange, findOptions)) {
if (!closestStringRange)
closestStringRange = searchStringRange;
else {
// If searching backward, use the trailing range edges to correctly determine which
// range is closest. Similarly, if searching forward, use the leading range edges.
Position closestStringPosition = isBackwardSearch ? closestStringRange->endPosition() : closestStringRange->startPosition();
Position searchStringPosition = isBackwardSearch ? searchStringRange->endPosition() : searchStringRange->startPosition();
int closestPositionOffset = closestStringPosition.computeOffsetInContainerNode();
int searchPositionOffset = searchStringPosition.computeOffsetInContainerNode();
Node* closestContainerNode = closestStringPosition.containerNode();
Node* searchContainerNode = searchStringPosition.containerNode();
short result = Range::compareBoundaryPoints(closestContainerNode, closestPositionOffset, searchContainerNode, searchPositionOffset, ASSERT_NO_EXCEPTION);
if ((!isBackwardSearch && result > 0) || (isBackwardSearch && result < 0))
closestStringRange = searchStringRange;
}
}
}
return closestStringRange;
}
// Returns the range of the entire document if there is no selection.
RefPtr<Range> AccessibilityObject::selectionRange() const
{
Frame* frame = this->frame();
if (!frame)
return nullptr;
const VisibleSelection& selection = frame->selection().selection();
if (!selection.isNone())
return selection.firstRange();
return Range::create(*frame->document());
}
RefPtr<Range> AccessibilityObject::elementRange() const
{
return AXObjectCache::rangeForNodeContents(node());
}
String AccessibilityObject::selectText(AccessibilitySelectTextCriteria* criteria)
{
ASSERT(criteria);
if (!criteria)
return String();
Frame* frame = this->frame();
if (!frame)
return String();
AccessibilitySelectTextActivity& activity = criteria->activity;
AccessibilitySelectTextAmbiguityResolution& ambiguityResolution = criteria->ambiguityResolution;
String& replacementString = criteria->replacementString;
Vector<String>& searchStrings = criteria->searchStrings;
RefPtr<Range> selectedStringRange = selectionRange();
// When starting our search again, make this a zero length range so that search forwards will find this selected range if its appropriate.
selectedStringRange->setEnd(&selectedStringRange->startContainer(), selectedStringRange->startOffset());
RefPtr<Range> closestAfterStringRange = nullptr;
RefPtr<Range> closestBeforeStringRange = nullptr;
// Search forward if necessary.
if (ambiguityResolution == ClosestAfterSelectionAmbiguityResolution || ambiguityResolution == ClosestToSelectionAmbiguityResolution)
closestAfterStringRange = rangeOfStringClosestToRangeInDirection(selectedStringRange.get(), SearchDirectionNext, searchStrings);
// Search backward if necessary.
if (ambiguityResolution == ClosestBeforeSelectionAmbiguityResolution || ambiguityResolution == ClosestToSelectionAmbiguityResolution)
closestBeforeStringRange = rangeOfStringClosestToRangeInDirection(selectedStringRange.get(), SearchDirectionPrevious, searchStrings);
// Determine which candidate is closest to the selection and perform the activity.
if (RefPtr<Range> closestStringRange = rangeClosestToRange(selectedStringRange.get(), WTFMove(closestAfterStringRange), WTFMove(closestBeforeStringRange))) {
// If the search started within a text control, ensure that the result is inside that element.
if (element() && element()->isTextFormControl()) {
if (!closestStringRange->startContainer().isDescendantOrShadowDescendantOf(element()) || !closestStringRange->endContainer().isDescendantOrShadowDescendantOf(element()))
return String();
}
String closestString = closestStringRange->text();
bool replaceSelection = false;
if (frame->selection().setSelectedRange(closestStringRange.get(), DOWNSTREAM, true)) {
switch (activity) {
case FindAndCapitalize:
replacementString = closestString;
makeCapitalized(&replacementString, 0);
replaceSelection = true;
break;
case FindAndUppercase:
replacementString = closestString.convertToUppercaseWithoutLocale(); // FIXME: Needs locale to work correctly.
replaceSelection = true;
break;
case FindAndLowercase:
replacementString = closestString.convertToLowercaseWithoutLocale(); // FIXME: Needs locale to work correctly.
replaceSelection = true;
break;
case FindAndReplaceActivity: {
replaceSelection = true;
// When applying find and replace activities, we want to match the capitalization of the replaced text,
// (unless we're replacing with an abbreviation.)
if (closestString.length() > 0 && replacementString.length() > 2 && replacementString != replacementString.convertToUppercaseWithoutLocale()) {
if (closestString[0] == u_toupper(closestString[0]))
makeCapitalized(&replacementString, 0);
else
replacementString = replacementString.convertToLowercaseWithoutLocale(); // FIXME: Needs locale to work correctly.
}
break;
}
case FindAndSelectActivity:
break;
}
// A bit obvious, but worth noting the API contract for this method is that we should
// return the replacement string when replacing, but the selected string if not.
if (replaceSelection) {
frame->editor().replaceSelectionWithText(replacementString, true, true);
return replacementString;
}
return closestString;
}
}
return String();
}
bool AccessibilityObject::hasAttributesRequiredForInclusion() const
{
// These checks are simplified in the interest of execution speed.
if (!getAttribute(aria_helpAttr).isEmpty()
|| !getAttribute(aria_describedbyAttr).isEmpty()
|| !getAttribute(altAttr).isEmpty()
|| !getAttribute(titleAttr).isEmpty())
return true;
#if ENABLE(MATHML)
if (!getAttribute(MathMLNames::alttextAttr).isEmpty())
return true;
#endif
return false;
}
bool AccessibilityObject::isARIAInput(AccessibilityRole ariaRole)
{
return ariaRole == RadioButtonRole || ariaRole == CheckBoxRole || ariaRole == TextFieldRole || ariaRole == SwitchRole || ariaRole == SearchFieldRole;
}
bool AccessibilityObject::isARIAControl(AccessibilityRole ariaRole)
{
return isARIAInput(ariaRole) || ariaRole == TextAreaRole || ariaRole == ButtonRole
|| ariaRole == ComboBoxRole || ariaRole == SliderRole;
}
bool AccessibilityObject::isRangeControl() const
{
switch (roleValue()) {
case ProgressIndicatorRole:
case SliderRole:
case ScrollBarRole:
case SpinButtonRole:
return true;
default:
return false;
}
}
bool AccessibilityObject::isMeter() const
{
#if ENABLE(METER_ELEMENT)
RenderObject* renderer = this->renderer();
return renderer && renderer->isMeter();
#else
return false;
#endif
}
IntPoint AccessibilityObject::clickPoint()
{
LayoutRect rect = elementRect();
return roundedIntPoint(LayoutPoint(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2));
}
IntRect AccessibilityObject::boundingBoxForQuads(RenderObject* obj, const Vector<FloatQuad>& quads)
{
ASSERT(obj);
if (!obj)
return IntRect();
FloatRect result;
for (const auto& quad : quads) {
FloatRect r = quad.enclosingBoundingBox();
if (!r.isEmpty()) {
if (obj->style().hasAppearance())
obj->theme().adjustRepaintRect(*obj, r);
result.unite(r);
}
}
return snappedIntRect(LayoutRect(result));
}
bool AccessibilityObject::press()
{
// The presence of the actionElement will confirm whether we should even attempt a press.
Element* actionElem = actionElement();
if (!actionElem)
return false;
if (Frame* f = actionElem->document().frame())
f->loader().resetMultipleFormSubmissionProtection();
// Hit test at this location to determine if there is a sub-node element that should act
// as the target of the action.
Element* hitTestElement = nullptr;
Document* document = this->document();
if (document) {
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::AccessibilityHitTest);
HitTestResult hitTestResult(clickPoint());
document->renderView()->hitTest(request, hitTestResult);
if (hitTestResult.innerNode()) {
Node* innerNode = hitTestResult.innerNode()->deprecatedShadowAncestorNode();
if (is<Element>(*innerNode))
hitTestElement = downcast<Element>(innerNode);
else if (innerNode)
hitTestElement = innerNode->parentElement();
}
}
// Prefer the actionElement instead of this node, if the actionElement is inside this node.
Element* pressElement = this->element();
if (!pressElement || actionElem->isDescendantOf(pressElement))
pressElement = actionElem;
// Prefer the hit test element, if it is inside the target element.
if (hitTestElement && hitTestElement->isDescendantOf(pressElement))
pressElement = hitTestElement;
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture, document);
bool dispatchedTouchEvent = dispatchTouchEvent();
if (!dispatchedTouchEvent)
pressElement->accessKeyAction(true);
return true;
}
bool AccessibilityObject::dispatchTouchEvent()
{
bool handled = false;
#if ENABLE(IOS_TOUCH_EVENTS)
MainFrame* frame = mainFrame();
if (!frame)
return false;
frame->eventHandler().dispatchSimulatedTouchEvent(clickPoint());
#endif
return handled;
}
Frame* AccessibilityObject::frame() const
{
Node* node = this->node();
if (!node)
return nullptr;
return node->document().frame();
}
MainFrame* AccessibilityObject::mainFrame() const
{
Document* document = topDocument();
if (!document)
return nullptr;
Frame* frame = document->frame();
if (!frame)
return nullptr;
return &frame->mainFrame();
}
Document* AccessibilityObject::topDocument() const
{
if (!document())
return nullptr;
return &document()->topDocument();
}
String AccessibilityObject::language() const
{
const AtomicString& lang = getAttribute(langAttr);
if (!lang.isEmpty())
return lang;
AccessibilityObject* parent = parentObject();
// as a last resort, fall back to the content language specified in the meta tag
if (!parent) {
Document* doc = document();
if (doc)
return doc->contentLanguage();
return nullAtom;
}
return parent->language();
}
VisiblePositionRange AccessibilityObject::visiblePositionRangeForUnorderedPositions(const VisiblePosition& visiblePos1, const VisiblePosition& visiblePos2) const
{
if (visiblePos1.isNull() || visiblePos2.isNull())
return VisiblePositionRange();
// If there's no common tree scope between positions, return early.
if (!commonTreeScope(visiblePos1.deepEquivalent().deprecatedNode(), visiblePos2.deepEquivalent().deprecatedNode()))
return VisiblePositionRange();
VisiblePosition startPos;
VisiblePosition endPos;
bool alreadyInOrder;
// upstream is ordered before downstream for the same position
if (visiblePos1 == visiblePos2 && visiblePos2.affinity() == UPSTREAM)
alreadyInOrder = false;
// use selection order to see if the positions are in order
else
alreadyInOrder = VisibleSelection(visiblePos1, visiblePos2).isBaseFirst();
if (alreadyInOrder) {
startPos = visiblePos1;
endPos = visiblePos2;
} else {
startPos = visiblePos2;
endPos = visiblePos1;
}
return VisiblePositionRange(startPos, endPos);
}
VisiblePositionRange AccessibilityObject::positionOfLeftWord(const VisiblePosition& visiblePos) const
{
VisiblePosition startPosition = startOfWord(visiblePos, LeftWordIfOnBoundary);
VisiblePosition endPosition = endOfWord(startPosition);
return VisiblePositionRange(startPosition, endPosition);
}
VisiblePositionRange AccessibilityObject::positionOfRightWord(const VisiblePosition& visiblePos) const
{
VisiblePosition startPosition = startOfWord(visiblePos, RightWordIfOnBoundary);
VisiblePosition endPosition = endOfWord(startPosition);
return VisiblePositionRange(startPosition, endPosition);
}
static VisiblePosition updateAXLineStartForVisiblePosition(const VisiblePosition& visiblePosition)
{
// A line in the accessibility sense should include floating objects, such as aligned image, as part of a line.
// So let's update the position to include that.
VisiblePosition tempPosition;
VisiblePosition startPosition = visiblePosition;
while (true) {
tempPosition = startPosition.previous();
if (tempPosition.isNull())
break;
Position p = tempPosition.deepEquivalent();
RenderObject* renderer = p.deprecatedNode()->renderer();
if (!renderer || (renderer->isRenderBlock() && !p.deprecatedEditingOffset()))
break;
if (!RenderedPosition(tempPosition).isNull())
break;
startPosition = tempPosition;
}
return startPosition;
}
VisiblePositionRange AccessibilityObject::leftLineVisiblePositionRange(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return VisiblePositionRange();
// make a caret selection for the position before marker position (to make sure
// we move off of a line start)
VisiblePosition prevVisiblePos = visiblePos.previous();
if (prevVisiblePos.isNull())
return VisiblePositionRange();
VisiblePosition startPosition = startOfLine(prevVisiblePos);
// keep searching for a valid line start position. Unless the VisiblePosition is at the very beginning, there should
// always be a valid line range. However, startOfLine will return null for position next to a floating object,
// since floating object doesn't really belong to any line.
// This check will reposition the marker before the floating object, to ensure we get a line start.
if (startPosition.isNull()) {
while (startPosition.isNull() && prevVisiblePos.isNotNull()) {
prevVisiblePos = prevVisiblePos.previous();
startPosition = startOfLine(prevVisiblePos);
}
} else
startPosition = updateAXLineStartForVisiblePosition(startPosition);
VisiblePosition endPosition = endOfLine(prevVisiblePos);
return VisiblePositionRange(startPosition, endPosition);
}
VisiblePositionRange AccessibilityObject::rightLineVisiblePositionRange(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return VisiblePositionRange();
// make sure we move off of a line end
VisiblePosition nextVisiblePos = visiblePos.next();
if (nextVisiblePos.isNull())
return VisiblePositionRange();
VisiblePosition startPosition = startOfLine(nextVisiblePos);
// fetch for a valid line start position
if (startPosition.isNull()) {
startPosition = visiblePos;
nextVisiblePos = nextVisiblePos.next();
} else
startPosition = updateAXLineStartForVisiblePosition(startPosition);
VisiblePosition endPosition = endOfLine(nextVisiblePos);
// as long as the position hasn't reached the end of the doc, keep searching for a valid line end position
// Unless the VisiblePosition is at the very end, there should always be a valid line range. However, endOfLine will
// return null for position by a floating object, since floating object doesn't really belong to any line.
// This check will reposition the marker after the floating object, to ensure we get a line end.
while (endPosition.isNull() && nextVisiblePos.isNotNull()) {
nextVisiblePos = nextVisiblePos.next();
endPosition = endOfLine(nextVisiblePos);
}
return VisiblePositionRange(startPosition, endPosition);
}
VisiblePositionRange AccessibilityObject::sentenceForPosition(const VisiblePosition& visiblePos) const
{
// FIXME: FO 2 IMPLEMENT (currently returns incorrect answer)
// Related? <rdar://problem/3927736> Text selection broken in 8A336
VisiblePosition startPosition = startOfSentence(visiblePos);
VisiblePosition endPosition = endOfSentence(startPosition);
return VisiblePositionRange(startPosition, endPosition);
}
VisiblePositionRange AccessibilityObject::paragraphForPosition(const VisiblePosition& visiblePos) const
{
VisiblePosition startPosition = startOfParagraph(visiblePos);
VisiblePosition endPosition = endOfParagraph(startPosition);
return VisiblePositionRange(startPosition, endPosition);
}
static VisiblePosition startOfStyleRange(const VisiblePosition& visiblePos)
{
RenderObject* renderer = visiblePos.deepEquivalent().deprecatedNode()->renderer();
RenderObject* startRenderer = renderer;
RenderStyle* style = &renderer->style();
// traverse backward by renderer to look for style change
for (RenderObject* r = renderer->previousInPreOrder(); r; r = r->previousInPreOrder()) {
// skip non-leaf nodes
if (r->firstChildSlow())
continue;
// stop at style change
if (&r->style() != style)
break;
// remember match
startRenderer = r;
}
return firstPositionInOrBeforeNode(startRenderer->node());
}
static VisiblePosition endOfStyleRange(const VisiblePosition& visiblePos)
{
RenderObject* renderer = visiblePos.deepEquivalent().deprecatedNode()->renderer();
RenderObject* endRenderer = renderer;
const RenderStyle& style = renderer->style();
// traverse forward by renderer to look for style change
for (RenderObject* r = renderer->nextInPreOrder(); r; r = r->nextInPreOrder()) {
// skip non-leaf nodes
if (r->firstChildSlow())
continue;
// stop at style change
if (&r->style() != &style)
break;
// remember match
endRenderer = r;
}
return lastPositionInOrAfterNode(endRenderer->node());
}
VisiblePositionRange AccessibilityObject::styleRangeForPosition(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return VisiblePositionRange();
return VisiblePositionRange(startOfStyleRange(visiblePos), endOfStyleRange(visiblePos));
}
// NOTE: Consider providing this utility method as AX API
VisiblePositionRange AccessibilityObject::visiblePositionRangeForRange(const PlainTextRange& range) const
{
unsigned textLength = getLengthForTextRange();
if (range.start + range.length > textLength)
return VisiblePositionRange();
VisiblePosition startPosition = visiblePositionForIndex(range.start);
startPosition.setAffinity(DOWNSTREAM);
VisiblePosition endPosition = visiblePositionForIndex(range.start + range.length);
return VisiblePositionRange(startPosition, endPosition);
}
VisiblePositionRange AccessibilityObject::lineRangeForPosition(const VisiblePosition& visiblePosition) const
{
VisiblePosition startPosition = startOfLine(visiblePosition);
VisiblePosition endPosition = endOfLine(visiblePosition);
return VisiblePositionRange(startPosition, endPosition);
}
bool AccessibilityObject::replacedNodeNeedsCharacter(Node* replacedNode)
{
// we should always be given a rendered node and a replaced node, but be safe
// replaced nodes are either attachments (widgets) or images
if (!replacedNode || !isRendererReplacedElement(replacedNode->renderer()) || replacedNode->isTextNode())
return false;
// create an AX object, but skip it if it is not supposed to be seen
AccessibilityObject* object = replacedNode->renderer()->document().axObjectCache()->getOrCreate(replacedNode);
if (object->accessibilityIsIgnored())
return false;
return true;
}
// Finds a RenderListItem parent give a node.
static RenderListItem* renderListItemContainerForNode(Node* node)
{
for (; node; node = node->parentNode()) {
RenderBoxModelObject* renderer = node->renderBoxModelObject();
if (is<RenderListItem>(renderer))
return downcast<RenderListItem>(renderer);
}
return nullptr;
}
static String listMarkerTextForNode(Node* node)
{
RenderListItem* listItem = renderListItemContainerForNode(node);
if (!listItem)
return String();
// If this is in a list item, we need to manually add the text for the list marker
// because a RenderListMarker does not have a Node equivalent and thus does not appear
// when iterating text.
return listItem->markerTextWithSuffix();
}
// Returns the text associated with a list marker if this node is contained within a list item.
String AccessibilityObject::listMarkerTextForNodeAndPosition(Node* node, const VisiblePosition& visiblePositionStart) const
{
// If the range does not contain the start of the line, the list marker text should not be included.
if (!isStartOfLine(visiblePositionStart))
return String();
return listMarkerTextForNode(node);
}
String AccessibilityObject::stringForRange(RefPtr<Range> range) const
{
if (!range)
return String();
TextIterator it(range.get());
if (it.atEnd())
return String();
StringBuilder builder;
for (; !it.atEnd(); it.advance()) {
// non-zero length means textual node, zero length means replaced node (AKA "attachments" in AX)
if (it.text().length()) {
// Add a textual representation for list marker text.
builder.append(listMarkerTextForNode(it.node()));
it.appendTextToStringBuilder(builder);
} else {
// locate the node and starting offset for this replaced range
Node& node = it.range()->startContainer();
ASSERT(&node == &it.range()->endContainer());
int offset = it.range()->startOffset();
if (replacedNodeNeedsCharacter(node.traverseToChildAt(offset)))
builder.append(objectReplacementCharacter);
}
}
return builder.toString();
}
String AccessibilityObject::stringForVisiblePositionRange(const VisiblePositionRange& visiblePositionRange) const
{
if (visiblePositionRange.isNull())
return String();
StringBuilder builder;
RefPtr<Range> range = makeRange(visiblePositionRange.start, visiblePositionRange.end);
for (TextIterator it(range.get()); !it.atEnd(); it.advance()) {
// non-zero length means textual node, zero length means replaced node (AKA "attachments" in AX)
if (it.text().length()) {
// Add a textual representation for list marker text.
builder.append(listMarkerTextForNodeAndPosition(it.node(), visiblePositionRange.start));
it.appendTextToStringBuilder(builder);
} else {
// locate the node and starting offset for this replaced range
Node& node = it.range()->startContainer();
ASSERT(&node == &it.range()->endContainer());
int offset = it.range()->startOffset();
if (replacedNodeNeedsCharacter(node.traverseToChildAt(offset)))
builder.append(objectReplacementCharacter);
}
}
return builder.toString();
}
int AccessibilityObject::lengthForVisiblePositionRange(const VisiblePositionRange& visiblePositionRange) const
{
// FIXME: Multi-byte support
if (visiblePositionRange.isNull())
return -1;
int length = 0;
RefPtr<Range> range = makeRange(visiblePositionRange.start, visiblePositionRange.end);
for (TextIterator it(range.get()); !it.atEnd(); it.advance()) {
// non-zero length means textual node, zero length means replaced node (AKA "attachments" in AX)
if (it.text().length())
length += it.text().length();
else {
// locate the node and starting offset for this replaced range
Node& node = it.range()->startContainer();
ASSERT(&node == &it.range()->endContainer());
int offset = it.range()->startOffset();
if (replacedNodeNeedsCharacter(node.traverseToChildAt(offset)))
++length;
}
}
return length;
}
VisiblePosition AccessibilityObject::visiblePositionForBounds(const IntRect& rect, AccessibilityVisiblePositionForBounds visiblePositionForBounds) const
{
if (rect.isEmpty())
return VisiblePosition();
MainFrame* mainFrame = this->mainFrame();
if (!mainFrame)
return VisiblePosition();
// FIXME: Add support for right-to-left languages.
IntPoint corner = (visiblePositionForBounds == FirstVisiblePositionForBounds) ? rect.minXMinYCorner() : rect.maxXMaxYCorner();
VisiblePosition position = mainFrame->visiblePositionForPoint(corner);
if (rect.contains(position.absoluteCaretBounds().center()))
return position;
// If the initial position is located outside the bounds adjust it incrementally as needed.
VisiblePosition nextPosition = position.next();
VisiblePosition previousPosition = position.previous();
while (nextPosition.isNotNull() || previousPosition.isNotNull()) {
if (rect.contains(nextPosition.absoluteCaretBounds().center()))
return nextPosition;
if (rect.contains(previousPosition.absoluteCaretBounds().center()))
return previousPosition;
nextPosition = nextPosition.next();
previousPosition = previousPosition.previous();
}
return VisiblePosition();
}
VisiblePosition AccessibilityObject::nextWordEnd(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return VisiblePosition();
// make sure we move off of a word end
VisiblePosition nextVisiblePos = visiblePos.next();
if (nextVisiblePos.isNull())
return VisiblePosition();
return endOfWord(nextVisiblePos, LeftWordIfOnBoundary);
}
VisiblePosition AccessibilityObject::previousWordStart(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return VisiblePosition();
// make sure we move off of a word start
VisiblePosition prevVisiblePos = visiblePos.previous();
if (prevVisiblePos.isNull())
return VisiblePosition();
return startOfWord(prevVisiblePos, RightWordIfOnBoundary);
}
VisiblePosition AccessibilityObject::nextLineEndPosition(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return VisiblePosition();
// to make sure we move off of a line end
VisiblePosition nextVisiblePos = visiblePos.next();
if (nextVisiblePos.isNull())
return VisiblePosition();
VisiblePosition endPosition = endOfLine(nextVisiblePos);
// as long as the position hasn't reached the end of the doc, keep searching for a valid line end position
// There are cases like when the position is next to a floating object that'll return null for end of line. This code will avoid returning null.
while (endPosition.isNull() && nextVisiblePos.isNotNull()) {
nextVisiblePos = nextVisiblePos.next();
endPosition = endOfLine(nextVisiblePos);
}
return endPosition;
}
VisiblePosition AccessibilityObject::previousLineStartPosition(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return VisiblePosition();
// make sure we move off of a line start
VisiblePosition prevVisiblePos = visiblePos.previous();
if (prevVisiblePos.isNull())
return VisiblePosition();
VisiblePosition startPosition = startOfLine(prevVisiblePos);
// as long as the position hasn't reached the beginning of the doc, keep searching for a valid line start position
// There are cases like when the position is next to a floating object that'll return null for start of line. This code will avoid returning null.
if (startPosition.isNull()) {
while (startPosition.isNull() && prevVisiblePos.isNotNull()) {
prevVisiblePos = prevVisiblePos.previous();
startPosition = startOfLine(prevVisiblePos);
}
} else
startPosition = updateAXLineStartForVisiblePosition(startPosition);
return startPosition;
}
VisiblePosition AccessibilityObject::nextSentenceEndPosition(const VisiblePosition& visiblePos) const
{
// FIXME: FO 2 IMPLEMENT (currently returns incorrect answer)
// Related? <rdar://problem/3927736> Text selection broken in 8A336
if (visiblePos.isNull())
return VisiblePosition();
// make sure we move off of a sentence end
VisiblePosition nextVisiblePos = visiblePos.next();
if (nextVisiblePos.isNull())
return VisiblePosition();
// an empty line is considered a sentence. If it's skipped, then the sentence parser will not
// see this empty line. Instead, return the end position of the empty line.
VisiblePosition endPosition;
String lineString = plainText(makeRange(startOfLine(nextVisiblePos), endOfLine(nextVisiblePos)).get());
if (lineString.isEmpty())
endPosition = nextVisiblePos;
else
endPosition = endOfSentence(nextVisiblePos);
return endPosition;
}
VisiblePosition AccessibilityObject::previousSentenceStartPosition(const VisiblePosition& visiblePos) const
{
// FIXME: FO 2 IMPLEMENT (currently returns incorrect answer)
// Related? <rdar://problem/3927736> Text selection broken in 8A336
if (visiblePos.isNull())
return VisiblePosition();
// make sure we move off of a sentence start
VisiblePosition previousVisiblePos = visiblePos.previous();
if (previousVisiblePos.isNull())
return VisiblePosition();
// treat empty line as a separate sentence.
VisiblePosition startPosition;
String lineString = plainText(makeRange(startOfLine(previousVisiblePos), endOfLine(previousVisiblePos)).get());
if (lineString.isEmpty())
startPosition = previousVisiblePos;
else
startPosition = startOfSentence(previousVisiblePos);
return startPosition;
}
VisiblePosition AccessibilityObject::nextParagraphEndPosition(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return VisiblePosition();
// make sure we move off of a paragraph end
VisiblePosition nextPos = visiblePos.next();
if (nextPos.isNull())
return VisiblePosition();
return endOfParagraph(nextPos);
}
VisiblePosition AccessibilityObject::previousParagraphStartPosition(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return VisiblePosition();
// make sure we move off of a paragraph start
VisiblePosition previousPos = visiblePos.previous();
if (previousPos.isNull())
return VisiblePosition();
return startOfParagraph(previousPos);
}
AccessibilityObject* AccessibilityObject::accessibilityObjectForPosition(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull())
return nullptr;
RenderObject* obj = visiblePos.deepEquivalent().deprecatedNode()->renderer();
if (!obj)
return nullptr;
return obj->document().axObjectCache()->getOrCreate(obj);
}
// If you call node->hasEditableStyle() since that will return true if an ancestor is editable.
// This only returns true if this is the element that actually has the contentEditable attribute set.
bool AccessibilityObject::hasContentEditableAttributeSet() const
{
return contentEditableAttributeIsEnabled(element());
}
bool AccessibilityObject::supportsARIAReadOnly() const
{
AccessibilityRole role = roleValue();
return role == CheckBoxRole
|| role == ColumnHeaderRole
|| role == ComboBoxRole
|| role == GridRole
|| role == GridCellRole
|| role == ListBoxRole
|| role == MenuItemCheckboxRole
|| role == MenuItemRadioRole
|| role == RadioGroupRole
|| role == RowHeaderRole
|| role == SearchFieldRole
|| role == SliderRole
|| role == SpinButtonRole
|| role == SwitchRole
|| role == TextFieldRole
|| role == TreeGridRole
|| isPasswordField();
}
String AccessibilityObject::ariaReadOnlyValue() const
{
if (!hasAttribute(aria_readonlyAttr))
return ariaRoleAttribute() != UnknownRole && supportsARIAReadOnly() ? "false" : String();
return getAttribute(aria_readonlyAttr).string().convertToASCIILowercase();
}
bool AccessibilityObject::contentEditableAttributeIsEnabled(Element* element)
{
if (!element)
return false;
const AtomicString& contentEditableValue = element->fastGetAttribute(contenteditableAttr);
if (contentEditableValue.isNull())
return false;
// Both "true" (case-insensitive) and the empty string count as true.
return contentEditableValue.isEmpty() || equalLettersIgnoringASCIICase(contentEditableValue, "true");
}
#if HAVE(ACCESSIBILITY)
int AccessibilityObject::lineForPosition(const VisiblePosition& visiblePos) const
{
if (visiblePos.isNull() || !node())
return -1;
// If the position is not in the same editable region as this AX object, return -1.
Node* containerNode = visiblePos.deepEquivalent().containerNode();
if (!containerNode->containsIncludingShadowDOM(node()) && !node()->containsIncludingShadowDOM(containerNode))
return -1;
int lineCount = -1;
VisiblePosition currentVisiblePos = visiblePos;
VisiblePosition savedVisiblePos;
// move up until we get to the top
// FIXME: This only takes us to the top of the rootEditableElement, not the top of the
// top document.
do {
savedVisiblePos = currentVisiblePos;
VisiblePosition prevVisiblePos = previousLinePosition(currentVisiblePos, 0, HasEditableAXRole);
currentVisiblePos = prevVisiblePos;
++lineCount;
} while (currentVisiblePos.isNotNull() && !(inSameLine(currentVisiblePos, savedVisiblePos)));
return lineCount;
}
#endif
// NOTE: Consider providing this utility method as AX API
PlainTextRange AccessibilityObject::plainTextRangeForVisiblePositionRange(const VisiblePositionRange& positionRange) const
{
int index1 = index(positionRange.start);
int index2 = index(positionRange.end);
if (index1 < 0 || index2 < 0 || index1 > index2)
return PlainTextRange();
return PlainTextRange(index1, index2 - index1);
}
// The composed character range in the text associated with this accessibility object that
// is specified by the given screen coordinates. This parameterized attribute returns the
// complete range of characters (including surrogate pairs of multi-byte glyphs) at the given
// screen coordinates.
// NOTE: This varies from AppKit when the point is below the last line. AppKit returns an
// an error in that case. We return textControl->text().length(), 1. Does this matter?
PlainTextRange AccessibilityObject::doAXRangeForPosition(const IntPoint& point) const
{
int i = index(visiblePositionForPoint(point));
if (i < 0)
return PlainTextRange();
return PlainTextRange(i, 1);
}
// Given a character index, the range of text associated with this accessibility object
// over which the style in effect at that character index applies.
PlainTextRange AccessibilityObject::doAXStyleRangeForIndex(unsigned index) const
{
VisiblePositionRange range = styleRangeForPosition(visiblePositionForIndex(index, false));
return plainTextRangeForVisiblePositionRange(range);
}
// Given an indexed character, the line number of the text associated with this accessibility
// object that contains the character.
unsigned AccessibilityObject::doAXLineForIndex(unsigned index)
{
return lineForPosition(visiblePositionForIndex(index, false));
}
#if HAVE(ACCESSIBILITY)
void AccessibilityObject::updateBackingStore()
{
// Updating the layout may delete this object.
RefPtr<AccessibilityObject> protector(this);
if (Document* document = this->document()) {
if (!document->view()->isInRenderTreeLayout())
document->updateLayoutIgnorePendingStylesheets();
}
updateChildrenIfNecessary();
}
#endif
ScrollView* AccessibilityObject::scrollViewAncestor() const
{
for (const AccessibilityObject* scrollParent = this; scrollParent; scrollParent = scrollParent->parentObject()) {
if (is<AccessibilityScrollView>(*scrollParent))
return downcast<AccessibilityScrollView>(*scrollParent).scrollView();
}
return nullptr;
}
Document* AccessibilityObject::document() const
{
FrameView* frameView = documentFrameView();
if (!frameView)
return nullptr;
return frameView->frame().document();
}
Page* AccessibilityObject::page() const
{
Document* document = this->document();
if (!document)
return nullptr;
return document->page();
}
FrameView* AccessibilityObject::documentFrameView() const
{
const AccessibilityObject* object = this;
while (object && !object->isAccessibilityRenderObject())
object = object->parentObject();
if (!object)
return nullptr;
return object->documentFrameView();
}
#if HAVE(ACCESSIBILITY)
const AccessibilityObject::AccessibilityChildrenVector& AccessibilityObject::children(bool updateChildrenIfNeeded)
{
if (updateChildrenIfNeeded)
updateChildrenIfNecessary();
return m_children;
}
#endif
void AccessibilityObject::updateChildrenIfNecessary()
{
if (!hasChildren()) {
// Enable the cache in case we end up adding a lot of children, we don't want to recompute axIsIgnored each time.
AXAttributeCacheEnabler enableCache(axObjectCache());
addChildren();
}
}
void AccessibilityObject::clearChildren()
{
// Some objects have weak pointers to their parents and those associations need to be detached.
for (const auto& child : m_children)
child->detachFromParent();
m_children.clear();
m_haveChildren = false;
}
AccessibilityObject* AccessibilityObject::anchorElementForNode(Node* node)
{
RenderObject* obj = node->renderer();
if (!obj)
return nullptr;
RefPtr<AccessibilityObject> axObj = obj->document().axObjectCache()->getOrCreate(obj);
Element* anchor = axObj->anchorElement();
if (!anchor)
return nullptr;
RenderObject* anchorRenderer = anchor->renderer();
if (!anchorRenderer)
return nullptr;
return anchorRenderer->document().axObjectCache()->getOrCreate(anchorRenderer);
}
AccessibilityObject* AccessibilityObject::headingElementForNode(Node* node)
{
if (!node)
return nullptr;
RenderObject* renderObject = node->renderer();
if (!renderObject)
return nullptr;
AccessibilityObject* axObject = renderObject->document().axObjectCache()->getOrCreate(renderObject);
for (; axObject && axObject->roleValue() != HeadingRole; axObject = axObject->parentObject()) { }
return axObject;
}
void AccessibilityObject::ariaTreeRows(AccessibilityChildrenVector& result)
{
for (const auto& child : children()) {
// Add tree items as the rows.
if (child->roleValue() == TreeItemRole)
result.append(child);
// Now see if this item also has rows hiding inside of it.
child->ariaTreeRows(result);
}
}
void AccessibilityObject::ariaTreeItemContent(AccessibilityChildrenVector& result)
{
// The ARIA tree item content are the item that are not other tree items or their containing groups.
for (const auto& child : children()) {
AccessibilityRole role = child->roleValue();
if (role == TreeItemRole || role == GroupRole)
continue;
result.append(child);
}
}
void AccessibilityObject::ariaTreeItemDisclosedRows(AccessibilityChildrenVector& result)
{
for (const auto& obj : children()) {
// Add tree items as the rows.
if (obj->roleValue() == TreeItemRole)
result.append(obj);
// If it's not a tree item, then descend into the group to find more tree items.
else
obj->ariaTreeRows(result);
}
}
const String AccessibilityObject::defaultLiveRegionStatusForRole(AccessibilityRole role)
{
switch (role) {
case ApplicationAlertDialogRole:
case ApplicationAlertRole:
return ASCIILiteral("assertive");
case ApplicationLogRole:
case ApplicationStatusRole:
return ASCIILiteral("polite");
case ApplicationTimerRole:
case ApplicationMarqueeRole:
return ASCIILiteral("off");
default:
return nullAtom;
}
}
#if HAVE(ACCESSIBILITY)
const String& AccessibilityObject::actionVerb() const
{
#if !PLATFORM(IOS)
// FIXME: Need to add verbs for select elements.
static NeverDestroyed<const String> buttonAction(AXButtonActionVerb());
static NeverDestroyed<const String> textFieldAction(AXTextFieldActionVerb());
static NeverDestroyed<const String> radioButtonAction(AXRadioButtonActionVerb());
static NeverDestroyed<const String> checkedCheckBoxAction(AXCheckedCheckBoxActionVerb());
static NeverDestroyed<const String> uncheckedCheckBoxAction(AXUncheckedCheckBoxActionVerb());
static NeverDestroyed<const String> linkAction(AXLinkActionVerb());
static NeverDestroyed<const String> menuListAction(AXMenuListActionVerb());
static NeverDestroyed<const String> menuListPopupAction(AXMenuListPopupActionVerb());
static NeverDestroyed<const String> listItemAction(AXListItemActionVerb());
switch (roleValue()) {
case ButtonRole:
case ToggleButtonRole:
return buttonAction;
case TextFieldRole:
case TextAreaRole:
return textFieldAction;
case RadioButtonRole:
return radioButtonAction;
case CheckBoxRole:
case SwitchRole:
return isChecked() ? checkedCheckBoxAction : uncheckedCheckBoxAction;
case LinkRole:
case WebCoreLinkRole:
return linkAction;
case PopUpButtonRole:
return menuListAction;
case MenuListPopupRole:
return menuListPopupAction;
case ListItemRole:
return listItemAction;
default:
return nullAtom;
}
#else
return nullAtom;
#endif
}
#endif
bool AccessibilityObject::ariaIsMultiline() const
{
return equalLettersIgnoringASCIICase(getAttribute(aria_multilineAttr), "true");
}
String AccessibilityObject::invalidStatus() const
{
String grammarValue = ASCIILiteral("grammar");
String falseValue = ASCIILiteral("false");
String spellingValue = ASCIILiteral("spelling");
String trueValue = ASCIILiteral("true");
String undefinedValue = ASCIILiteral("undefined");
// aria-invalid can return false (default), grammar, spelling, or true.
String ariaInvalid = stripLeadingAndTrailingHTMLSpaces(getAttribute(aria_invalidAttr));
// If "false", "undefined" [sic, string value], empty, or missing, return "false".
if (ariaInvalid.isEmpty() || ariaInvalid == falseValue || ariaInvalid == undefinedValue)
return falseValue;
// Besides true/false/undefined, the only tokens defined by WAI-ARIA 1.0...
// ...for @aria-invalid are "grammar" and "spelling".
if (ariaInvalid == grammarValue)
return grammarValue;
if (ariaInvalid == spellingValue)
return spellingValue;
// Any other non empty string should be treated as "true".
return trueValue;
}
AccessibilityARIACurrentState AccessibilityObject::ariaCurrentState() const
{
// aria-current can return false (default), true, page, step, location, date or time.
String currentStateValue = stripLeadingAndTrailingHTMLSpaces(getAttribute(aria_currentAttr));
// If "false", empty, or missing, return false state.
if (currentStateValue.isEmpty() || currentStateValue == "false")
return ARIACurrentFalse;
if (currentStateValue == "page")
return ARIACurrentPage;
if (currentStateValue == "step")
return ARIACurrentStep;
if (currentStateValue == "location")
return ARIACurrentLocation;
if (currentStateValue == "date")
return ARIACurrentDate;
if (currentStateValue == "time")
return ARIACurrentTime;
// Any value not included in the list of allowed values should be treated as "true".
return ARIACurrentTrue;
}
bool AccessibilityObject::isAriaModalDescendant(Node* ariaModalNode) const
{
if (!ariaModalNode || !this->element())
return false;
if (this->element() == ariaModalNode)
return true;
// ARIA 1.1 aria-modal, indicates whether an element is modal when displayed.
// For the decendants of the modal object, they should also be considered as aria-modal=true.
for (auto& ancestor : elementAncestors(this->element())) {
if (&ancestor == ariaModalNode)
return true;
}
return false;
}
bool AccessibilityObject::ignoredFromARIAModalPresence() const
{
// We shouldn't ignore the top node.
if (!node() || !node()->parentNode())
return false;
AXObjectCache* cache = axObjectCache();
if (!cache)
return false;
// ariaModalNode is the current displayed modal dialog.
Node* ariaModalNode = cache->ariaModalNode();
if (!ariaModalNode)
return false;
// We only want to ignore the objects within the same frame as the modal dialog.
if (ariaModalNode->document().frame() != this->frame())
return false;
return !isAriaModalDescendant(ariaModalNode);
}
bool AccessibilityObject::hasTagName(const QualifiedName& tagName) const
{
Node* node = this->node();
return is<Element>(node) && downcast<Element>(*node).hasTagName(tagName);
}
bool AccessibilityObject::hasAttribute(const QualifiedName& attribute) const
{
Node* node = this->node();
if (!is<Element>(node))
return false;
return downcast<Element>(*node).fastHasAttribute(attribute);
}
const AtomicString& AccessibilityObject::getAttribute(const QualifiedName& attribute) const
{
if (Element* element = this->element())
return element->fastGetAttribute(attribute);
return nullAtom;
}
// Lacking concrete evidence of orientation, horizontal means width > height. vertical is height > width;
AccessibilityOrientation AccessibilityObject::orientation() const
{
LayoutRect bounds = elementRect();
if (bounds.size().width() > bounds.size().height())
return AccessibilityOrientationHorizontal;
if (bounds.size().height() > bounds.size().width())
return AccessibilityOrientationVertical;
return AccessibilityOrientationUndefined;
}
bool AccessibilityObject::isDescendantOfObject(const AccessibilityObject* axObject) const
{
if (!axObject || !axObject->hasChildren())
return false;
for (const AccessibilityObject* parent = parentObject(); parent; parent = parent->parentObject()) {
if (parent == axObject)
return true;
}
return false;
}
bool AccessibilityObject::isAncestorOfObject(const AccessibilityObject* axObject) const
{
if (!axObject)
return false;
return this == axObject || axObject->isDescendantOfObject(this);
}
AccessibilityObject* AccessibilityObject::firstAnonymousBlockChild() const
{
for (AccessibilityObject* child = firstChild(); child; child = child->nextSibling()) {
if (child->renderer() && child->renderer()->isAnonymousBlock())
return child;
}
return nullptr;
}
typedef HashMap<String, AccessibilityRole, ASCIICaseInsensitiveHash> ARIARoleMap;
typedef HashMap<AccessibilityRole, String, DefaultHash<int>::Hash, WTF::UnsignedWithZeroKeyHashTraits<int>> ARIAReverseRoleMap;
static ARIARoleMap* gAriaRoleMap = nullptr;
static ARIAReverseRoleMap* gAriaReverseRoleMap = nullptr;
struct RoleEntry {
String ariaRole;
AccessibilityRole webcoreRole;
};
static void initializeRoleMap()
{
if (gAriaRoleMap)
return;
ASSERT(!gAriaReverseRoleMap);
const RoleEntry roles[] = {
{ "alert", ApplicationAlertRole },
{ "alertdialog", ApplicationAlertDialogRole },
{ "application", LandmarkApplicationRole },
{ "article", DocumentArticleRole },
{ "banner", LandmarkBannerRole },
{ "button", ButtonRole },
{ "checkbox", CheckBoxRole },
{ "complementary", LandmarkComplementaryRole },
{ "contentinfo", LandmarkContentInfoRole },
{ "dialog", ApplicationDialogRole },
{ "directory", DirectoryRole },
{ "grid", GridRole },
{ "gridcell", GridCellRole },
{ "table", TableRole },
{ "cell", CellRole },
{ "columnheader", ColumnHeaderRole },
{ "combobox", ComboBoxRole },
{ "definition", DefinitionRole },
{ "document", DocumentRole },
{ "form", FormRole },
{ "rowheader", RowHeaderRole },
{ "group", GroupRole },
{ "heading", HeadingRole },
{ "img", ImageRole },
{ "link", WebCoreLinkRole },
{ "list", ListRole },
{ "listitem", ListItemRole },
{ "listbox", ListBoxRole },
{ "log", ApplicationLogRole },
// "option" isn't here because it may map to different roles depending on the parent element's role
{ "main", LandmarkMainRole },
{ "marquee", ApplicationMarqueeRole },
{ "math", DocumentMathRole },
{ "menu", MenuRole },
{ "menubar", MenuBarRole },
{ "menuitem", MenuItemRole },
{ "menuitemcheckbox", MenuItemCheckboxRole },
{ "menuitemradio", MenuItemRadioRole },
{ "none", PresentationalRole },
{ "note", DocumentNoteRole },
{ "navigation", LandmarkNavigationRole },
{ "option", ListBoxOptionRole },
{ "presentation", PresentationalRole },
{ "progressbar", ProgressIndicatorRole },
{ "radio", RadioButtonRole },
{ "radiogroup", RadioGroupRole },
{ "region", DocumentRegionRole },
{ "row", RowRole },
{ "rowgroup", RowGroupRole },
{ "scrollbar", ScrollBarRole },
{ "search", LandmarkSearchRole },
{ "searchbox", SearchFieldRole },
{ "separator", SplitterRole },
{ "slider", SliderRole },
{ "spinbutton", SpinButtonRole },
{ "status", ApplicationStatusRole },
{ "switch", SwitchRole },
{ "tab", TabRole },
{ "tablist", TabListRole },
{ "tabpanel", TabPanelRole },
{ "text", StaticTextRole },
{ "textbox", TextAreaRole },
{ "timer", ApplicationTimerRole },
{ "toolbar", ToolbarRole },
{ "tooltip", UserInterfaceTooltipRole },
{ "tree", TreeRole },
{ "treegrid", TreeGridRole },
{ "treeitem", TreeItemRole }
};
gAriaRoleMap = new ARIARoleMap;
gAriaReverseRoleMap = new ARIAReverseRoleMap;
size_t roleLength = WTF_ARRAY_LENGTH(roles);
for (size_t i = 0; i < roleLength; ++i) {
gAriaRoleMap->set(roles[i].ariaRole, roles[i].webcoreRole);
gAriaReverseRoleMap->set(roles[i].webcoreRole, roles[i].ariaRole);
}
}
static ARIARoleMap& ariaRoleMap()
{
initializeRoleMap();
return *gAriaRoleMap;
}
static ARIAReverseRoleMap& reverseAriaRoleMap()
{
initializeRoleMap();
return *gAriaReverseRoleMap;
}
AccessibilityRole AccessibilityObject::ariaRoleToWebCoreRole(const String& value)
{
ASSERT(!value.isEmpty());
Vector<String> roleVector;
value.split(' ', roleVector);
AccessibilityRole role = UnknownRole;
for (const auto& roleName : roleVector) {
role = ariaRoleMap().get(roleName);
if (role)
return role;
}
return role;
}
String AccessibilityObject::computedRoleString() const
{
// FIXME: Need a few special cases that aren't in the RoleMap: option, etc. http://webkit.org/b/128296
AccessibilityRole role = roleValue();
if (role == HorizontalRuleRole)
role = SplitterRole;
return reverseAriaRoleMap().get(role);
}
bool AccessibilityObject::hasHighlighting() const
{
for (Node* node = this->node(); node; node = node->parentNode()) {
if (node->hasTagName(markTag))
return true;
}
return false;
}
const AtomicString& AccessibilityObject::roleDescription() const
{
return getAttribute(aria_roledescriptionAttr);
}
static bool nodeHasPresentationRole(Node* node)
{
return nodeHasRole(node, "presentation") || nodeHasRole(node, "none");
}
bool AccessibilityObject::supportsPressAction() const
{
if (isButton())
return true;
if (roleValue() == DetailsRole)
return true;
Element* actionElement = this->actionElement();
if (!actionElement)
return false;
// [Bug: 136247] Heuristic: element handlers that have more than one accessible descendant should not be exposed as supporting press.
if (actionElement != element()) {
if (AccessibilityObject* axObj = axObjectCache()->getOrCreate(actionElement)) {
AccessibilityChildrenVector results;
// Search within for immediate descendants that are static text. If we find more than one
// then this is an event delegator actionElement and we should expose the press action.
Vector<AccessibilitySearchKey> keys({ StaticTextSearchKey, ControlSearchKey, GraphicSearchKey, HeadingSearchKey, LinkSearchKey });
AccessibilitySearchCriteria criteria(axObj, SearchDirectionNext, "", 2, false, false);
criteria.searchKeys = keys;
axObj->findMatchingObjects(&criteria, results);
if (results.size() > 1)
return false;
}
}
// [Bug: 133613] Heuristic: If the action element is presentational, we shouldn't expose press as a supported action.
return !nodeHasPresentationRole(actionElement);
}
bool AccessibilityObject::supportsDatetimeAttribute() const
{
return hasTagName(insTag) || hasTagName(delTag) || hasTagName(timeTag);
}
Element* AccessibilityObject::element() const
{
Node* node = this->node();
if (is<Element>(node))
return downcast<Element>(node);
return nullptr;
}
bool AccessibilityObject::isValueAutofilled() const
{
if (!isNativeTextControl())
return false;
Node* node = this->node();
if (!node || !is<HTMLInputElement>(*node))
return false;
return downcast<HTMLInputElement>(*node).isAutoFilled();
}
const AtomicString& AccessibilityObject::placeholderValue() const
{
const AtomicString& ariaPlaceholder = getAttribute(aria_placeholderAttr);
if (!ariaPlaceholder.isEmpty())
return ariaPlaceholder;
const AtomicString& placeholder = getAttribute(placeholderAttr);
if (!placeholder.isEmpty())
return placeholder;
return nullAtom;
}
bool AccessibilityObject::isInsideARIALiveRegion() const
{
if (supportsARIALiveRegion())
return true;
for (AccessibilityObject* axParent = parentObject(); axParent; axParent = axParent->parentObject()) {
if (axParent->supportsARIALiveRegion())
return true;
}
return false;
}
bool AccessibilityObject::supportsARIAAttributes() const
{
// This returns whether the element supports any global ARIA attributes.
return supportsARIALiveRegion()
|| supportsARIADragging()
|| supportsARIADropping()
|| supportsARIAFlowTo()
|| supportsARIAOwns()
|| hasAttribute(aria_atomicAttr)
|| hasAttribute(aria_busyAttr)
|| hasAttribute(aria_controlsAttr)
|| hasAttribute(aria_describedbyAttr)
|| hasAttribute(aria_disabledAttr)
|| hasAttribute(aria_haspopupAttr)
|| hasAttribute(aria_invalidAttr)
|| hasAttribute(aria_labelAttr)
|| hasAttribute(aria_labelledbyAttr)
|| hasAttribute(aria_relevantAttr);
}
bool AccessibilityObject::liveRegionStatusIsEnabled(const AtomicString& liveRegionStatus)
{
return equalLettersIgnoringASCIICase(liveRegionStatus, "polite") || equalLettersIgnoringASCIICase(liveRegionStatus, "assertive");
}
bool AccessibilityObject::supportsARIALiveRegion() const
{
return liveRegionStatusIsEnabled(ariaLiveRegionStatus());
}
AccessibilityObject* AccessibilityObject::elementAccessibilityHitTest(const IntPoint& point) const
{
// Send the hit test back into the sub-frame if necessary.
if (isAttachment()) {
Widget* widget = widgetForAttachmentView();
// Normalize the point for the widget's bounds.
if (widget && widget->isFrameView()) {
if (AXObjectCache* cache = axObjectCache())
return cache->getOrCreate(widget)->accessibilityHitTest(IntPoint(point - widget->frameRect().location()));
}
}
// Check if there are any mock elements that need to be handled.
for (const auto& child : m_children) {
if (child->isMockObject() && child->elementRect().contains(point))
return child->elementAccessibilityHitTest(point);
}
return const_cast<AccessibilityObject*>(this);
}
AXObjectCache* AccessibilityObject::axObjectCache() const
{
Document* doc = document();
if (doc)
return doc->axObjectCache();
return nullptr;
}
AccessibilityObject* AccessibilityObject::focusedUIElement() const
{
Document* doc = document();
if (!doc)
return nullptr;
Page* page = doc->page();
if (!page)
return nullptr;
return AXObjectCache::focusedUIElementForPage(page);
}
AccessibilitySortDirection AccessibilityObject::sortDirection() const
{
const AtomicString& sortAttribute = getAttribute(aria_sortAttr);
if (equalLettersIgnoringASCIICase(sortAttribute, "ascending"))
return SortDirectionAscending;
if (equalLettersIgnoringASCIICase(sortAttribute, "descending"))
return SortDirectionDescending;
if (equalLettersIgnoringASCIICase(sortAttribute, "other"))
return SortDirectionOther;
return SortDirectionNone;
}
bool AccessibilityObject::supportsRangeValue() const
{
return isProgressIndicator()
|| isSlider()
|| isScrollbar()
|| isSpinButton();
}
bool AccessibilityObject::supportsARIASetSize() const
{
return hasAttribute(aria_setsizeAttr);
}
bool AccessibilityObject::supportsARIAPosInSet() const
{
return hasAttribute(aria_posinsetAttr);
}
int AccessibilityObject::ariaSetSize() const
{
return getAttribute(aria_setsizeAttr).toInt();
}
int AccessibilityObject::ariaPosInSet() const
{
return getAttribute(aria_posinsetAttr).toInt();
}
String AccessibilityObject::identifierAttribute() const
{
return getAttribute(idAttr);
}
void AccessibilityObject::classList(Vector<String>& classList) const
{
Node* node = this->node();
if (!is<Element>(node))
return;
Element* element = downcast<Element>(node);
DOMTokenList& list = element->classList();
unsigned length = list.length();
for (unsigned k = 0; k < length; k++)
classList.append(list.item(k).string());
}
bool AccessibilityObject::supportsARIAPressed() const
{
const AtomicString& expanded = getAttribute(aria_pressedAttr);
return equalLettersIgnoringASCIICase(expanded, "true") || equalLettersIgnoringASCIICase(expanded, "false");
}
bool AccessibilityObject::supportsExpanded() const
{
// Undefined values should not result in this attribute being exposed to ATs according to ARIA.
const AtomicString& expanded = getAttribute(aria_expandedAttr);
if (equalLettersIgnoringASCIICase(expanded, "true") || equalLettersIgnoringASCIICase(expanded, "false"))
return true;
switch (roleValue()) {
case ComboBoxRole:
case DisclosureTriangleRole:
case DetailsRole:
return true;
default:
return false;
}
}
bool AccessibilityObject::isExpanded() const
{
if (equalLettersIgnoringASCIICase(getAttribute(aria_expandedAttr), "true"))
return true;
if (is<HTMLDetailsElement>(node()))
return downcast<HTMLDetailsElement>(node())->isOpen();
return false;
}
bool AccessibilityObject::supportsChecked() const
{
switch (roleValue()) {
case CheckBoxRole:
case MenuItemCheckboxRole:
case MenuItemRadioRole:
case RadioButtonRole:
case SwitchRole:
return true;
default:
return false;
}
}
AccessibilityButtonState AccessibilityObject::checkboxOrRadioValue() const
{
// If this is a real checkbox or radio button, AccessibilityRenderObject will handle.
// If it's an ARIA checkbox, radio, or switch the aria-checked attribute should be used.
// If it's a toggle button, the aria-pressed attribute is consulted.
if (isToggleButton()) {
const AtomicString& ariaPressed = getAttribute(aria_pressedAttr);
if (equalLettersIgnoringASCIICase(ariaPressed, "true"))
return ButtonStateOn;
if (equalLettersIgnoringASCIICase(ariaPressed, "mixed"))
return ButtonStateMixed;
return ButtonStateOff;
}
const AtomicString& result = getAttribute(aria_checkedAttr);
if (equalLettersIgnoringASCIICase(result, "true"))
return ButtonStateOn;
if (equalLettersIgnoringASCIICase(result, "mixed")) {
// ARIA says that radio, menuitemradio, and switch elements must NOT expose button state mixed.
AccessibilityRole ariaRole = ariaRoleAttribute();
if (ariaRole == RadioButtonRole || ariaRole == MenuItemRadioRole || ariaRole == SwitchRole)
return ButtonStateOff;
return ButtonStateMixed;
}
if (equalLettersIgnoringASCIICase(getAttribute(indeterminateAttr), "true"))
return ButtonStateMixed;
return ButtonStateOff;
}
// This is a 1-dimensional scroll offset helper function that's applied
// separately in the horizontal and vertical directions, because the
// logic is the same. The goal is to compute the best scroll offset
// in order to make an object visible within a viewport.
//
// If the object is already fully visible, returns the same scroll
// offset.
//
// In case the whole object cannot fit, you can specify a
// subfocus - a smaller region within the object that should
// be prioritized. If the whole object can fit, the subfocus is
// ignored.
//
// If possible, the object and subfocus are centered within the
// viewport.
//
// Example 1: the object is already visible, so nothing happens.
// +----------Viewport---------+
// +---Object---+
// +--SubFocus--+
//
// Example 2: the object is not fully visible, so it's centered
// within the viewport.
// Before:
// +----------Viewport---------+
// +---Object---+
// +--SubFocus--+
//
// After:
// +----------Viewport---------+
// +---Object---+
// +--SubFocus--+
//
// Example 3: the object is larger than the viewport, so the
// viewport moves to show as much of the object as possible,
// while also trying to center the subfocus.
// Before:
// +----------Viewport---------+
// +---------------Object--------------+
// +-SubFocus-+
//
// After:
// +----------Viewport---------+
// +---------------Object--------------+
// +-SubFocus-+
//
// When constraints cannot be fully satisfied, the min
// (left/top) position takes precedence over the max (right/bottom).
//
// Note that the return value represents the ideal new scroll offset.
// This may be out of range - the calling function should clip this
// to the available range.
static int computeBestScrollOffset(int currentScrollOffset, int subfocusMin, int subfocusMax, int objectMin, int objectMax, int viewportMin, int viewportMax)
{
int viewportSize = viewportMax - viewportMin;
// If the object size is larger than the viewport size, consider
// only a portion that's as large as the viewport, centering on
// the subfocus as much as possible.
if (objectMax - objectMin > viewportSize) {
// Since it's impossible to fit the whole object in the
// viewport, exit now if the subfocus is already within the viewport.
if (subfocusMin - currentScrollOffset >= viewportMin && subfocusMax - currentScrollOffset <= viewportMax)
return currentScrollOffset;
// Subfocus must be within focus.
subfocusMin = std::max(subfocusMin, objectMin);
subfocusMax = std::min(subfocusMax, objectMax);
// Subfocus must be no larger than the viewport size; favor top/left.
if (subfocusMax - subfocusMin > viewportSize)
subfocusMax = subfocusMin + viewportSize;
// Compute the size of an object centered on the subfocus, the size of the viewport.
int centeredObjectMin = (subfocusMin + subfocusMax - viewportSize) / 2;
int centeredObjectMax = centeredObjectMin + viewportSize;
objectMin = std::max(objectMin, centeredObjectMin);
objectMax = std::min(objectMax, centeredObjectMax);
}
// Exit now if the focus is already within the viewport.
if (objectMin - currentScrollOffset >= viewportMin
&& objectMax - currentScrollOffset <= viewportMax)
return currentScrollOffset;
// Center the object in the viewport.
return (objectMin + objectMax - viewportMin - viewportMax) / 2;
}
bool AccessibilityObject::isOnscreen() const
{
bool isOnscreen = true;
// To figure out if the element is onscreen, we start by building of a stack starting with the
// element, and then include every scrollable parent in the hierarchy.
Vector<const AccessibilityObject*> objects;
objects.append(this);
for (AccessibilityObject* parentObject = this->parentObject(); parentObject; parentObject = parentObject->parentObject()) {
if (parentObject->getScrollableAreaIfScrollable())
objects.append(parentObject);
}
// Now, go back through that chain and make sure each inner object is within the
// visible bounds of the outer object.
size_t levels = objects.size() - 1;
for (size_t i = levels; i >= 1; i--) {
const AccessibilityObject* outer = objects[i];
const AccessibilityObject* inner = objects[i - 1];
// FIXME: unclear if we need LegacyIOSDocumentVisibleRect.
const IntRect outerRect = i < levels ? snappedIntRect(outer->boundingBoxRect()) : outer->getScrollableAreaIfScrollable()->visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect);
const IntRect innerRect = snappedIntRect(inner->isAccessibilityScrollView() ? inner->parentObject()->boundingBoxRect() : inner->boundingBoxRect());
if (!outerRect.intersects(innerRect)) {
isOnscreen = false;
break;
}
}
return isOnscreen;
}
void AccessibilityObject::scrollToMakeVisible() const
{
IntRect objectRect = snappedIntRect(boundingBoxRect());
objectRect.setLocation(IntPoint());
scrollToMakeVisibleWithSubFocus(objectRect);
}
void AccessibilityObject::scrollToMakeVisibleWithSubFocus(const IntRect& subfocus) const
{
// Search up the parent chain until we find the first one that's scrollable.
AccessibilityObject* scrollParent = parentObject();
ScrollableArea* scrollableArea;
for (scrollableArea = nullptr;
scrollParent && !(scrollableArea = scrollParent->getScrollableAreaIfScrollable());
scrollParent = scrollParent->parentObject()) { }
if (!scrollableArea)
return;
LayoutRect objectRect = boundingBoxRect();
IntPoint scrollPosition = scrollableArea->scrollPosition();
// FIXME: unclear if we need LegacyIOSDocumentVisibleRect.
IntRect scrollVisibleRect = scrollableArea->visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect);
if (!scrollParent->isScrollView()) {
objectRect.moveBy(scrollPosition);
objectRect.moveBy(-snappedIntRect(scrollParent->elementRect()).location());
}
int desiredX = computeBestScrollOffset(
scrollPosition.x(),
objectRect.x() + subfocus.x(), objectRect.x() + subfocus.maxX(),
objectRect.x(), objectRect.maxX(),
0, scrollVisibleRect.width());
int desiredY = computeBestScrollOffset(
scrollPosition.y(),
objectRect.y() + subfocus.y(), objectRect.y() + subfocus.maxY(),
objectRect.y(), objectRect.maxY(),
0, scrollVisibleRect.height());
scrollParent->scrollTo(IntPoint(desiredX, desiredY));
// Convert the subfocus into the coordinates of the scroll parent.
IntRect newSubfocus = subfocus;
IntRect newElementRect = snappedIntRect(elementRect());
IntRect scrollParentRect = snappedIntRect(scrollParent->elementRect());
newSubfocus.move(newElementRect.x(), newElementRect.y());
newSubfocus.move(-scrollParentRect.x(), -scrollParentRect.y());
// Recursively make sure the scroll parent itself is visible.
if (scrollParent->parentObject())
scrollParent->scrollToMakeVisibleWithSubFocus(newSubfocus);
}
void AccessibilityObject::scrollToGlobalPoint(const IntPoint& globalPoint) const
{
// Search up the parent chain and create a vector of all scrollable parent objects
// and ending with this object itself.
Vector<const AccessibilityObject*> objects;
objects.append(this);
for (AccessibilityObject* parentObject = this->parentObject(); parentObject; parentObject = parentObject->parentObject()) {
if (parentObject->getScrollableAreaIfScrollable())
objects.append(parentObject);
}
objects.reverse();
// Start with the outermost scrollable (the main window) and try to scroll the
// next innermost object to the given point.
int offsetX = 0, offsetY = 0;
IntPoint point = globalPoint;
size_t levels = objects.size() - 1;
for (size_t i = 0; i < levels; i++) {
const AccessibilityObject* outer = objects[i];
const AccessibilityObject* inner = objects[i + 1];
ScrollableArea* scrollableArea = outer->getScrollableAreaIfScrollable();
LayoutRect innerRect = inner->isAccessibilityScrollView() ? inner->parentObject()->boundingBoxRect() : inner->boundingBoxRect();
LayoutRect objectRect = innerRect;
IntPoint scrollPosition = scrollableArea->scrollPosition();
// Convert the object rect into local coordinates.
objectRect.move(offsetX, offsetY);
if (!outer->isAccessibilityScrollView())
objectRect.move(scrollPosition.x(), scrollPosition.y());
int desiredX = computeBestScrollOffset(
0,
objectRect.x(), objectRect.maxX(),
objectRect.x(), objectRect.maxX(),
point.x(), point.x());
int desiredY = computeBestScrollOffset(
0,
objectRect.y(), objectRect.maxY(),
objectRect.y(), objectRect.maxY(),
point.y(), point.y());
outer->scrollTo(IntPoint(desiredX, desiredY));
if (outer->isAccessibilityScrollView() && !inner->isAccessibilityScrollView()) {
// If outer object we just scrolled is a scroll view (main window or iframe) but the
// inner object is not, keep track of the coordinate transformation to apply to
// future nested calculations.
scrollPosition = scrollableArea->scrollPosition();
offsetX -= (scrollPosition.x() + point.x());
offsetY -= (scrollPosition.y() + point.y());
point.move(scrollPosition.x() - innerRect.x(),
scrollPosition.y() - innerRect.y());
} else if (inner->isAccessibilityScrollView()) {
// Otherwise, if the inner object is a scroll view, reset the coordinate transformation.
offsetX = 0;
offsetY = 0;
}
}
}
void AccessibilityObject::scrollAreaAndAncestor(std::pair<ScrollableArea*, AccessibilityObject*>& scrollers) const
{
// Search up the parent chain until we find the first one that's scrollable.
scrollers.first = nullptr;
for (scrollers.second = parentObject(); scrollers.second; scrollers.second = scrollers.second->parentObject()) {
if ((scrollers.first = scrollers.second->getScrollableAreaIfScrollable()))
break;
}
}
ScrollableArea* AccessibilityObject::scrollableAreaAncestor() const
{
std::pair<ScrollableArea*, AccessibilityObject*> scrollers;
scrollAreaAndAncestor(scrollers);
return scrollers.first;
}
IntPoint AccessibilityObject::scrollPosition() const
{
if (auto scroller = scrollableAreaAncestor())
return scroller->scrollPosition();
return IntPoint();
}
IntRect AccessibilityObject::scrollVisibleContentRect() const
{
if (auto scroller = scrollableAreaAncestor())
return scroller->visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect);
return IntRect();
}
IntSize AccessibilityObject::scrollContentsSize() const
{
if (auto scroller = scrollableAreaAncestor())
return scroller->contentsSize();
return IntSize();
}
bool AccessibilityObject::scrollByPage(ScrollByPageDirection direction) const
{
std::pair<ScrollableArea*, AccessibilityObject*> scrollers;
scrollAreaAndAncestor(scrollers);
ScrollableArea* scrollableArea = scrollers.first;
AccessibilityObject* scrollParent = scrollers.second;
if (!scrollableArea)
return false;
IntPoint scrollPosition = scrollableArea->scrollPosition();
IntPoint newScrollPosition = scrollPosition;
IntSize scrollSize = scrollableArea->contentsSize();
IntRect scrollVisibleRect = scrollableArea->visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect);
switch (direction) {
case Right: {
int scrollAmount = scrollVisibleRect.size().width();
int newX = scrollPosition.x() - scrollAmount;
newScrollPosition.setX(std::max(newX, 0));
break;
}
case Left: {
int scrollAmount = scrollVisibleRect.size().width();
int newX = scrollAmount + scrollPosition.x();
int maxX = scrollSize.width() - scrollAmount;
newScrollPosition.setX(std::min(newX, maxX));
break;
}
case Up: {
int scrollAmount = scrollVisibleRect.size().height();
int newY = scrollPosition.y() - scrollAmount;
newScrollPosition.setY(std::max(newY, 0));
break;
}
case Down: {
int scrollAmount = scrollVisibleRect.size().height();
int newY = scrollAmount + scrollPosition.y();
int maxY = scrollSize.height() - scrollAmount;
newScrollPosition.setY(std::min(newY, maxY));
break;
}
default:
break;
}
if (newScrollPosition != scrollPosition) {
scrollParent->scrollTo(newScrollPosition);
document()->updateLayoutIgnorePendingStylesheets();
return true;
}
return false;
}
bool AccessibilityObject::lastKnownIsIgnoredValue()
{
if (m_lastKnownIsIgnoredValue == DefaultBehavior)
m_lastKnownIsIgnoredValue = accessibilityIsIgnored() ? IgnoreObject : IncludeObject;
return m_lastKnownIsIgnoredValue == IgnoreObject;
}
void AccessibilityObject::setLastKnownIsIgnoredValue(bool isIgnored)
{
m_lastKnownIsIgnoredValue = isIgnored ? IgnoreObject : IncludeObject;
}
void AccessibilityObject::notifyIfIgnoredValueChanged()
{
bool isIgnored = accessibilityIsIgnored();
if (lastKnownIsIgnoredValue() != isIgnored) {
if (AXObjectCache* cache = axObjectCache())
cache->childrenChanged(parentObject());
setLastKnownIsIgnoredValue(isIgnored);
}
}
bool AccessibilityObject::ariaPressedIsPresent() const
{
return !getAttribute(aria_pressedAttr).isEmpty();
}
TextIteratorBehavior AccessibilityObject::textIteratorBehaviorForTextRange() const
{
TextIteratorBehavior behavior = TextIteratorIgnoresStyleVisibility;
#if PLATFORM(GTK) || PLATFORM(EFL)
// We need to emit replaced elements for GTK, and present
// them with the 'object replacement character' (0xFFFC).
behavior = static_cast<TextIteratorBehavior>(behavior | TextIteratorEmitsObjectReplacementCharacters);
#endif
return behavior;
}
AccessibilityRole AccessibilityObject::buttonRoleType() const
{
// If aria-pressed is present, then it should be exposed as a toggle button.
// http://www.w3.org/TR/wai-aria/states_and_properties#aria-pressed
if (ariaPressedIsPresent())
return ToggleButtonRole;
if (ariaHasPopup())
return PopUpButtonRole;
// We don't contemplate RadioButtonRole, as it depends on the input
// type.
return ButtonRole;
}
bool AccessibilityObject::isButton() const
{
AccessibilityRole role = roleValue();
return role == ButtonRole || role == PopUpButtonRole || role == ToggleButtonRole;
}
bool AccessibilityObject::accessibilityIsIgnoredByDefault() const
{
return defaultObjectInclusion() == IgnoreObject;
}
// ARIA component of hidden definition.
// http://www.w3.org/TR/wai-aria/terms#def_hidden
bool AccessibilityObject::isARIAHidden() const
{
for (const AccessibilityObject* object = this; object; object = object->parentObject()) {
if (equalLettersIgnoringASCIICase(object->getAttribute(aria_hiddenAttr), "true"))
return true;
}
return false;
}
// DOM component of hidden definition.
// http://www.w3.org/TR/wai-aria/terms#def_hidden
bool AccessibilityObject::isDOMHidden() const
{
RenderObject* renderer = this->renderer();
if (!renderer)
return true;
const RenderStyle& style = renderer->style();
return style.display() == NONE || style.visibility() != VISIBLE;
}
AccessibilityObjectInclusion AccessibilityObject::defaultObjectInclusion() const
{
if (isARIAHidden())
return IgnoreObject;
if (ignoredFromARIAModalPresence())
return IgnoreObject;
if (isPresentationalChildOfAriaRole())
return IgnoreObject;
return accessibilityPlatformIncludesObject();
}
bool AccessibilityObject::accessibilityIsIgnored() const
{
AXComputedObjectAttributeCache* attributeCache = nullptr;
AXObjectCache* cache = axObjectCache();
if (cache)
attributeCache = cache->computedObjectAttributeCache();
if (attributeCache) {
AccessibilityObjectInclusion ignored = attributeCache->getIgnored(axObjectID());
switch (ignored) {
case IgnoreObject:
return true;
case IncludeObject:
return false;
case DefaultBehavior:
break;
}
}
bool result = computeAccessibilityIsIgnored();
// In case computing axIsIgnored disables attribute caching, we should refetch the object to see if it exists.
if (cache && (attributeCache = cache->computedObjectAttributeCache()))
attributeCache->setIgnored(axObjectID(), result ? IgnoreObject : IncludeObject);
return result;
}
void AccessibilityObject::elementsFromAttribute(Vector<Element*>& elements, const QualifiedName& attribute) const
{
Node* node = this->node();
if (!node || !node->isElementNode())
return;
TreeScope& treeScope = node->treeScope();
String idList = getAttribute(attribute).string();
if (idList.isEmpty())
return;
idList.replace('\n', ' ');
Vector<String> idVector;
idList.split(' ', idVector);
for (const auto& idName : idVector) {
if (Element* idElement = treeScope.getElementById(idName))
elements.append(idElement);
}
}
#if PLATFORM(COCOA)
bool AccessibilityObject::preventKeyboardDOMEventDispatch() const
{
Frame* frame = this->frame();
return frame && frame->settings().preventKeyboardDOMEventDispatch();
}
void AccessibilityObject::setPreventKeyboardDOMEventDispatch(bool on)
{
Frame* frame = this->frame();
if (!frame)
return;
frame->settings().setPreventKeyboardDOMEventDispatch(on);
}
#endif
bool AccessibilityObject::isStyleFormatGroup() const
{
Node* node = this->node();
if (!node)
return false;
return node->hasTagName(kbdTag) || node->hasTagName(codeTag)
|| node->hasTagName(preTag) || node->hasTagName(sampTag)
|| node->hasTagName(varTag) || node->hasTagName(citeTag)
|| node->hasTagName(insTag) || node->hasTagName(delTag);
}
bool AccessibilityObject::isContainedByPasswordField() const
{
Node* node = this->node();
if (!node)
return false;
if (ariaRoleAttribute() != UnknownRole)
return false;
Element* element = node->shadowHost();
return is<HTMLInputElement>(element) && downcast<HTMLInputElement>(*element).isPasswordField();
}
} // namespace WebCore
|