1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433
|
/*
* Copyright (C) 2012, Google 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 Computer, 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 "third_party/blink/renderer/modules/accessibility/ax_node_object.h"
#include <math.h>
#include <algorithm>
#include <array>
#include <memory>
#include <optional>
#include <queue>
#include "base/auto_reset.h"
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_set.h"
#include "base/metrics/histogram_functions.h"
#include "base/numerics/safe_conversions.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/input/web_keyboard_event.h"
#include "third_party/blink/public/mojom/frame/user_activation_notification_type.mojom-blink.h"
#include "third_party/blink/public/strings/grit/blink_strings.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_image_bitmap_options.h"
#include "third_party/blink/renderer/core/css/counter_style_map.h"
#include "third_party/blink/renderer/core/css/css_resolution_units.h"
#include "third_party/blink/renderer/core/css/properties/longhands.h"
#include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/focus_params.h"
#include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
#include "third_party/blink/renderer/core/dom/node_traversal.h"
#include "third_party/blink/renderer/core/dom/qualified_name.h"
#include "third_party/blink/renderer/core/dom/range.h"
#include "third_party/blink/renderer/core/dom/scroll_marker_pseudo_element.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/markers/custom_highlight_marker.h"
#include "third_party/blink/renderer/core/editing/markers/document_marker_controller.h"
#include "third_party/blink/renderer/core/editing/position.h"
#include "third_party/blink/renderer/core/events/event_util.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/highlight/highlight.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/html/canvas/image_data.h"
#include "third_party/blink/renderer/core/html/custom/element_internals.h"
#include "third_party/blink/renderer/core/html/fenced_frame/html_fenced_frame_element.h"
#include "third_party/blink/renderer/core/html/forms/html_button_element.h"
#include "third_party/blink/renderer/core/html/forms/html_data_list_element.h"
#include "third_party/blink/renderer/core/html/forms/html_field_set_element.h"
#include "third_party/blink/renderer/core/html/forms/html_form_control_element.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_label_element.h"
#include "third_party/blink/renderer/core/html/forms/html_legend_element.h"
#include "third_party/blink/renderer/core/html/forms/html_opt_group_element.h"
#include "third_party/blink/renderer/core/html/forms/html_option_element.h"
#include "third_party/blink/renderer/core/html/forms/html_output_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
#include "third_party/blink/renderer/core/html/forms/html_text_area_element.h"
#include "third_party/blink/renderer/core/html/forms/labels_node_list.h"
#include "third_party/blink/renderer/core/html/forms/radio_input_type.h"
#include "third_party/blink/renderer/core/html/forms/text_control_element.h"
#include "third_party/blink/renderer/core/html/html_anchor_element.h"
#include "third_party/blink/renderer/core/html/html_body_element.h"
#include "third_party/blink/renderer/core/html/html_details_element.h"
#include "third_party/blink/renderer/core/html/html_dialog_element.h"
#include "third_party/blink/renderer/core/html/html_directory_element.h"
#include "third_party/blink/renderer/core/html/html_div_element.h"
#include "third_party/blink/renderer/core/html/html_dlist_element.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_embed_element.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_hr_element.h"
#include "third_party/blink/renderer/core/html/html_html_element.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/html_li_element.h"
#include "third_party/blink/renderer/core/html/html_map_element.h"
#include "third_party/blink/renderer/core/html/html_menu_element.h"
#include "third_party/blink/renderer/core/html/html_meter_element.h"
#include "third_party/blink/renderer/core/html/html_olist_element.h"
#include "third_party/blink/renderer/core/html/html_paragraph_element.h"
#include "third_party/blink/renderer/core/html/html_permission_element.h"
#include "third_party/blink/renderer/core/html/html_plugin_element.h"
#include "third_party/blink/renderer/core/html/html_progress_element.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
#include "third_party/blink/renderer/core/html/html_span_element.h"
#include "third_party/blink/renderer/core/html/html_summary_element.h"
#include "third_party/blink/renderer/core/html/html_table_caption_element.h"
#include "third_party/blink/renderer/core/html/html_table_cell_element.h"
#include "third_party/blink/renderer/core/html/html_table_col_element.h"
#include "third_party/blink/renderer/core/html/html_table_element.h"
#include "third_party/blink/renderer/core/html/html_table_row_element.h"
#include "third_party/blink/renderer/core/html/html_table_section_element.h"
#include "third_party/blink/renderer/core/html/html_time_element.h"
#include "third_party/blink/renderer/core/html/html_ulist_element.h"
#include "third_party/blink/renderer/core/html/media/html_audio_element.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_names.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
#include "third_party/blink/renderer/core/input_type_names.h"
#include "third_party/blink/renderer/core/layout/hit_test_location.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/inline/abstract_inline_text_box.h"
#include "third_party/blink/renderer/core/layout/inline/inline_cursor.h"
#include "third_party/blink/renderer/core/layout/inline/inline_node.h"
#include "third_party/blink/renderer/core/layout/inline/offset_mapping.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
#include "third_party/blink/renderer/core/layout/layout_html_canvas.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/table/layout_table.h"
#include "third_party/blink/renderer/core/layout/table/layout_table_cell.h"
#include "third_party/blink/renderer/core/layout/table/layout_table_row.h"
#include "third_party/blink/renderer/core/layout/table/layout_table_section.h"
#include "third_party/blink/renderer/core/loader/progress_tracker.h"
#include "third_party/blink/renderer/core/mathml/mathml_element.h"
#include "third_party/blink/renderer/core/mathml_names.h"
#include "third_party/blink/renderer/core/navigation_api/navigation_api.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/core/svg/svg_a_element.h"
#include "third_party/blink/renderer/core/svg/svg_desc_element.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/core/svg/svg_foreign_object_element.h"
#include "third_party/blink/renderer/core/svg/svg_g_element.h"
#include "third_party/blink/renderer/core/svg/svg_svg_element.h"
#include "third_party/blink/renderer/core/svg/svg_symbol_element.h"
#include "third_party/blink/renderer/core/svg/svg_text_element.h"
#include "third_party/blink/renderer/core/svg/svg_title_element.h"
#include "third_party/blink/renderer/core/svg/svg_use_element.h"
#include "third_party/blink/renderer/core/xlink_names.h"
#include "third_party/blink/renderer/modules/accessibility/ax_block_flow_iterator.h"
#include "third_party/blink/renderer/modules/accessibility/ax_image_map_link.h"
#include "third_party/blink/renderer/modules/accessibility/ax_inline_text_box.h"
#include "third_party/blink/renderer/modules/accessibility/ax_node_object.h"
#include "third_party/blink/renderer/modules/accessibility/ax_object-inl.h"
#include "third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h"
#include "third_party/blink/renderer/modules/accessibility/ax_position.h"
#include "third_party/blink/renderer/modules/accessibility/ax_range.h"
#include "third_party/blink/renderer/modules/accessibility/ax_relation_cache.h"
#include "third_party/blink/renderer/platform/graphics/image_data_buffer.h"
#include "third_party/blink/renderer/platform/keyboard_codes.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/skia/include/core/SkImage.h"
#include "ui/accessibility/accessibility_features.h"
#include "ui/accessibility/ax_common.h"
#include "ui/accessibility/ax_role_properties.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/keycode_converter.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/size_f.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/strings/grit/ax_strings.h"
namespace blink {
namespace {
bool ShouldUseLayoutNG(const blink::LayoutObject& layout_object) {
return layout_object.IsInline() &&
layout_object.IsInLayoutNGInlineFormattingContext();
}
// It is not easily possible to find out if an element is the target of an
// in-page link.
// As a workaround, we consider the following to be potential targets:
// - <a name>
// - <foo id> -- an element with an id that is not SVG, a <label> or <optgroup>.
// <label> does not make much sense as an in-page link target.
// Exposing <optgroup> is redundant, as the group is already exposed via a
// child in its shadow DOM, which contains the accessible name.
// #document -- this is always a potential link target via <a name="#">.
// This is a compromise that does not include too many elements, and
// has minimal impact on tests.
bool IsPotentialInPageLinkTarget(blink::Node& node) {
auto* element = blink::DynamicTo<blink::Element>(&node);
if (!element) {
// The document itself is a potential link target, e.g. via <a name="#">.
return blink::IsA<blink::Document>(node);
}
// We exclude elements that are in the shadow DOM. They cannot be linked by a
// document fragment from the main page:as they have their own id namespace.
if (element->ContainingShadowRoot())
return false;
// SVG elements are unlikely link targets, and we want to avoid creating
// a lot of noise in the AX tree or breaking tests unnecessarily.
if (element->IsSVGElement())
return false;
// <a name>
if (auto* anchor = blink::DynamicTo<blink::HTMLAnchorElement>(element)) {
if (anchor->HasName())
return true;
}
// <foo id> not in an <optgroup> or <label>.
if (element->HasID() && !blink::IsA<blink::HTMLLabelElement>(element) &&
!blink::IsA<blink::HTMLOptGroupElement>(element)) {
return true;
}
return false;
}
bool IsLinkable(const blink::AXObject& object) {
if (!object.GetLayoutObject()) {
return false;
}
// See https://wiki.mozilla.org/Accessibility/AT-Windows-API for the elements
// Mozilla considers linkable.
return object.IsLink() || object.IsImage() ||
object.GetLayoutObject()->IsText();
}
bool IsImageOrAltText(blink::LayoutObject* layout_object, blink::Node* node) {
DCHECK(layout_object);
if (layout_object->IsImage()) {
return true;
}
if (IsA<blink::HTMLImageElement>(node)) {
return true;
}
auto* html_input_element = DynamicTo<blink::HTMLInputElement>(node);
return html_input_element && html_input_element->HasFallbackContent();
}
bool ShouldIgnoreListItem(blink::Node* node) {
DCHECK(node);
// http://www.w3.org/TR/wai-aria/complete#presentation
// A list item is presentational if its parent is a native list but
// it has an explicit ARIA role set on it that's anything other than "list".
blink::Element* parent = blink::FlatTreeTraversal::ParentElement(*node);
if (!parent) {
return false;
}
if (IsA<blink::HTMLMenuElement>(*parent) ||
IsA<blink::HTMLUListElement>(*parent) ||
IsA<blink::HTMLOListElement>(*parent)) {
AtomicString role =
blink::AXObject::AriaAttribute(*parent, blink::html_names::kRoleAttr);
if (!role.empty() && role != "list" && role != "directory") {
return true;
}
}
return false;
}
bool IsNeutralWithinTable(blink::AXObject* obj) {
if (!obj)
return false;
ax::mojom::blink::Role role = obj->RoleValue();
return role == ax::mojom::blink::Role::kGroup ||
role == ax::mojom::blink::Role::kGenericContainer ||
role == ax::mojom::blink::Role::kRowGroup;
}
// Within a table, provide the accessible, semantic parent of |node|,
// by traversing the DOM tree, ignoring elements that are neutral in a table.
// Return the AXObject for the ancestor.
blink::AXObject* GetDOMTableAXAncestor(blink::Node* node,
blink::AXObjectCacheImpl& cache) {
// Used by code to determine roles of elements inside of an HTML table,
// Use DOM to get parent since parent_ is not initialized yet when role is
// being computed, and because HTML table structure should not take into
// account aria-owns.
if (!node)
return nullptr;
while (true) {
node = blink::LayoutTreeBuilderTraversal::Parent(*node);
if (!node)
return nullptr;
blink::AXObject* ax_object = cache.Get(node);
if (ax_object && !IsNeutralWithinTable(ax_object))
return ax_object;
}
}
// Return the first LayoutTableSection if maybe_table is a non-anonymous
// table. If non-null, set table_out to the containing table.
blink::LayoutTableSection* FirstTableSection(
blink::LayoutObject* maybe_table,
blink::LayoutTable** table_out = nullptr) {
if (auto* table = DynamicTo<blink::LayoutTable>(maybe_table)) {
if (table->GetNode()) {
if (table_out) {
*table_out = table;
}
return table->FirstSection();
}
}
if (table_out) {
*table_out = nullptr;
}
return nullptr;
}
enum class AXAction {
kActionIncrement = 0,
kActionDecrement,
};
blink::KeyboardEvent* CreateKeyboardEvent(
blink::LocalDOMWindow* local_dom_window,
blink::WebInputEvent::Type type,
AXAction action,
blink::AccessibilityOrientation orientation,
ax::mojom::blink::WritingDirection text_direction) {
blink::WebKeyboardEvent key(type,
blink::WebInputEvent::Modifiers::kNoModifiers,
base::TimeTicks::Now());
if (action == AXAction::kActionIncrement) {
if (orientation == blink::kAccessibilityOrientationVertical) {
key.dom_key = ui::DomKey::ARROW_UP;
key.dom_code = static_cast<int>(ui::DomCode::ARROW_UP);
key.native_key_code = key.windows_key_code = blink::VKEY_UP;
} else if (text_direction == ax::mojom::blink::WritingDirection::kRtl) {
key.dom_key = ui::DomKey::ARROW_LEFT;
key.dom_code = static_cast<int>(ui::DomCode::ARROW_LEFT);
key.native_key_code = key.windows_key_code = blink::VKEY_LEFT;
} else { // horizontal and left to right
key.dom_key = ui::DomKey::ARROW_RIGHT;
key.dom_code = static_cast<int>(ui::DomCode::ARROW_RIGHT);
key.native_key_code = key.windows_key_code = blink::VKEY_RIGHT;
}
} else if (action == AXAction::kActionDecrement) {
if (orientation == blink::kAccessibilityOrientationVertical) {
key.dom_key = ui::DomKey::ARROW_DOWN;
key.dom_code = static_cast<int>(ui::DomCode::ARROW_DOWN);
key.native_key_code = key.windows_key_code = blink::VKEY_DOWN;
} else if (text_direction == ax::mojom::blink::WritingDirection::kRtl) {
key.dom_key = ui::DomKey::ARROW_RIGHT;
key.dom_code = static_cast<int>(ui::DomCode::ARROW_RIGHT);
key.native_key_code = key.windows_key_code = blink::VKEY_RIGHT;
} else { // horizontal and left to right
key.dom_key = ui::DomKey::ARROW_LEFT;
key.dom_code = static_cast<int>(ui::DomCode::ARROW_LEFT);
key.native_key_code = key.windows_key_code = blink::VKEY_LEFT;
}
}
return blink::KeyboardEvent::Create(key, local_dom_window, true);
}
unsigned TextStyleFlag(ax::mojom::blink::TextStyle text_style_enum) {
return static_cast<unsigned>(1 << static_cast<int>(text_style_enum));
}
ax::mojom::blink::TextDecorationStyle
TextDecorationStyleToAXTextDecorationStyle(
const blink::ETextDecorationStyle text_decoration_style) {
switch (text_decoration_style) {
case blink::ETextDecorationStyle::kDashed:
return ax::mojom::blink::TextDecorationStyle::kDashed;
case blink::ETextDecorationStyle::kSolid:
return ax::mojom::blink::TextDecorationStyle::kSolid;
case blink::ETextDecorationStyle::kDotted:
return ax::mojom::blink::TextDecorationStyle::kDotted;
case blink::ETextDecorationStyle::kDouble:
return ax::mojom::blink::TextDecorationStyle::kDouble;
case blink::ETextDecorationStyle::kWavy:
return ax::mojom::blink::TextDecorationStyle::kWavy;
}
NOTREACHED();
}
String GetTitle(blink::Element* element) {
if (!element)
return String();
if (blink::SVGElement* svg_element =
blink::DynamicTo<blink::SVGElement>(element)) {
// Don't use title() in SVG, as it calls innerText() which updates layout.
// Unfortunately, this must duplicate some logic from SVGElement::title().
if (svg_element->InUseShadowTree()) {
String title = GetTitle(svg_element->OwnerShadowHost());
if (!title.empty())
return title;
}
// If we aren't an instance in a <use> or the <use> title was not found,
// then find the first <title> child of this element. If a title child was
// found, return the text contents.
if (auto* title_element =
blink::Traversal<blink::SVGTitleElement>::FirstChild(*element)) {
return title_element->GetInnerTextWithoutUpdate();
}
return String();
}
return element->title();
}
bool HasLayoutText(const blink::AXObject* obj) {
// This method should only be used when layout is clean.
#if DCHECK_IS_ON()
DCHECK(obj->GetDocument()->Lifecycle().GetState() >=
blink::DocumentLifecycle::kLayoutClean)
<< "Unclean document at lifecycle "
<< obj->GetDocument()->Lifecycle().ToString();
#endif
// If no layout object, could be display:none or display locked.
if (!obj->GetLayoutObject()) {
return false;
}
if (blink::DisplayLockUtilities::LockedAncestorPreventingPaint(
*obj->GetLayoutObject())) {
return false;
}
// Only text has inline textbox children.
if (!obj->GetLayoutObject()->IsText()) {
return false;
}
// TODO(accessibility): Unclear why text would need layout if it's not display
// locked and the document is currently in a clean layout state.
// It seems to be fairly rare, but is creating some crashes, and there is
// no repro case yet.
if (obj->GetLayoutObject()->NeedsLayout()) {
DCHECK(false) << "LayoutText needed layout but was not display locked: "
<< obj;
return false;
}
return true;
}
// TODO(crbug.com/371011661): Use single list marker representation for a11y.
// Accessibility is treating list markers in two different ways:
// 1. As a regular list marker object;
// 2. As a object of type none, thus ignoring the list marker, and adding the
// text as its child. Regardless of the way being used for a particular list
// item, we need to know how to connect the list marker with the next text on
// the line. `layout_object`represents the node being investigated, and `parent`
// may contain the parent of this object, if it is included in the tree.
const LayoutObject* GetListMarker(const LayoutObject& layout_object,
const AXObject* parent) {
if (layout_object.IsLayoutOutsideListMarker()) {
// This is the default case: this LayoutObject represents a list marker.
return &layout_object;
}
if (parent && parent->RoleValue() == ax::mojom::blink::Role::kNone &&
parent->GetLayoutObject() &&
parent->GetLayoutObject()->IsLayoutOutsideListMarker()) {
// The parent of the node being investigated is a list marker, so it will be
// used in the computation to connect things in the same line.
return parent->GetLayoutObject();
}
return nullptr;
}
bool ElementHasAnyAriaRelation(Element& element) {
return element.HasAnyExplicitlySetAttrAssociatedElements() ||
AXObject::HasAriaAttribute(element, html_names::kAriaActionsAttr) ||
AXObject::HasAriaAttribute(element,
html_names::kAriaActivedescendantAttr) ||
AXObject::HasAriaAttribute(element, html_names::kAriaControlsAttr) ||
AXObject::HasAriaAttribute(element,
html_names::kAriaDescribedbyAttr) ||
AXObject::HasAriaAttribute(element, html_names::kAriaDetailsAttr) ||
AXObject::HasAriaAttribute(element,
html_names::kAriaErrormessageAttr) ||
AXObject::HasAriaAttribute(element, html_names::kAriaFlowtoAttr) ||
AXObject::HasAriaAttribute(element, html_names::kAriaLabelledbyAttr) ||
AXObject::HasAriaAttribute(element, html_names::kAriaLabeledbyAttr) ||
AXObject::HasAriaAttribute(element, html_names::kAriaOwnsAttr);
}
bool IsAddedOnlyViaSpecialTraversal(const Node* node) {
// Terminology:
// * Scroll button pseudo element: these are the left/right buttons
// automatically added for CSS carousels,
// * Scroll marker group pseudo element: this is a group of navigation
// buttons (often dots) for controlling the CSS carousel.
// * Scroll marker pseudo element: this is an individual navigation button.
//
// ::scroll-markers have their layout object nested under
// ::scroll-marker-group, which isn't related to its node traversal. So we
// shouldn't use node or layout traversals for this. Instead this is handled
// in AXNodeObject::AddScrollMarkerGroupChildren, and any time we walk the
// layout tree starting from ::scroll-marker-group. See the comment in
// AXNodeObject::AddScrollMarkerGroupChildren for a more detailed explanation.
if (node->IsScrollMarkerPseudoElement()) {
return true;
}
// ScrollButtons and ScrollMarkerGroup are added as siblings of their
// originating element. See `AddNodeChild`.
if (node->IsScrollMarkerGroupPseudoElement() ||
node->IsScrollButtonPseudoElement()) {
return true;
}
if (RuntimeEnabledFeatures::SelectAccessibilityReparentInputEnabled()) {
// The first descendant <input> in a <select> gets taken out of the listbox
// because it is not an <option>. It controls the listbox.
if (auto* input = DynamicTo<HTMLInputElement>(node)) {
if (input->IsFirstTextInputInAncestorSelect()) {
return true;
}
}
}
return false;
}
VectorOf<Node> UnpackScrollerWithSiblingControls(Element* element) {
CHECK(element->HasScrollButtonOrMarkerGroupPseudos());
// This is the order of how the pseudo elements should appear according to
// https://drafts.csswg.org/css-overflow-5/
PseudoId ordered_pseudos[] = {
kPseudoIdScrollMarkerGroupBefore, kPseudoIdScrollButtonBlockStart,
kPseudoIdScrollButtonInlineStart, kPseudoIdScrollButtonInlineEnd,
kPseudoIdScrollButtonBlockEnd, kPseudoIdNone,
kPseudoIdScrollMarkerGroupAfter,
};
VectorOf<Node> result;
for (PseudoId pseudo_id : ordered_pseudos) {
if (pseudo_id == kPseudoIdNone) {
result.push_back(element);
} else if (auto* pseudo = element->GetPseudoElement(pseudo_id)) {
result.push_back(pseudo);
}
}
// We should have at least added the element itself.
CHECK(!result.empty());
return result;
}
void CollectLayoutTextContentRecursive(StringBuilder& builder,
const LayoutObject* object) {
if (auto* text_object = DynamicTo<LayoutText>(object)) {
builder.Append(text_object->TransformedText());
}
for (auto* child = object->SlowFirstChild(); child;
child = child->NextSibling()) {
CollectLayoutTextContentRecursive(builder, child);
}
}
} // namespace
using html_names::kAltAttr;
using html_names::kTitleAttr;
using html_names::kTypeAttr;
using html_names::kValueAttr;
using mojom::blink::FormControlType;
// In ARIA 1.1, default value of aria-level was changed to 2.
const int kDefaultHeadingLevel = 2;
// When an AXNodeObject is created with a Node instead of a LayoutObject it
// means that the LayoutObject is purposely being set to null, as it is not
// relevant for this object in the AX tree.
AXNodeObject::AXNodeObject(Node* node, AXObjectCacheImpl& ax_object_cache)
: AXObject(ax_object_cache, /*is_node_object=*/true), node_(node) {}
AXNodeObject::AXNodeObject(LayoutObject* layout_object,
AXObjectCacheImpl& ax_object_cache)
: AXObject(ax_object_cache, /*is_node_object=*/true),
node_(layout_object->GetNode()),
layout_object_(layout_object) {
#if DCHECK_IS_ON()
layout_object_->SetHasAXObject(true);
#endif
}
AXNodeObject::~AXNodeObject() {
DCHECK(!node_);
DCHECK(!layout_object_);
}
void AXNodeObject::AlterSliderOrSpinButtonValue(bool increase) {
if (!GetNode())
return;
if (!IsSlider() && !IsSpinButton())
return;
float value;
if (!ValueForRange(&value))
return;
if (!RuntimeEnabledFeatures::
SynthesizedKeyboardEventsForAccessibilityActionsEnabled()) {
// If synthesized keyboard events are disabled, we need to set the value
// directly here.
// If no step was provided on the element, use a default value.
float step;
if (!StepValueForRange(&step)) {
if (IsNativeSlider() || IsNativeSpinButton()) {
step = StepRange().Step().ToString().ToFloat();
} else {
return;
}
}
value += increase ? step : -step;
if (native_role_ == ax::mojom::blink::Role::kSlider ||
native_role_ == ax::mojom::blink::Role::kSpinButton) {
OnNativeSetValueAction(String::Number(value));
// Dispatching an event could result in changes to the document, like
// this AXObject becoming detached.
if (IsDetached())
return;
AXObjectCache().HandleValueChanged(GetNode());
return;
}
}
// If we have synthesized keyboard events enabled, we generate a keydown
// event:
// * For a native slider, the dispatch of the event will reach
// RangeInputType::HandleKeydownEvent(), where the value will be set and the
// AXObjectCache notified. The corresponding keydown/up JS events will be
// fired so the website doesn't know it was produced by an AT action.
// * For an ARIA slider, the corresponding keydown/up JS events will be
// fired. It is expected that the handlers for those events manage the
// update of the slider value.
AXAction action =
increase ? AXAction::kActionIncrement : AXAction::kActionDecrement;
LocalDOMWindow* local_dom_window = GetDocument()->domWindow();
AccessibilityOrientation orientation = Orientation();
ax::mojom::blink::WritingDirection text_direction = GetTextDirection();
// A kKeyDown event is kRawKeyDown + kChar events. We cannot synthesize it
// because the KeyboardEvent constructor will prevent it, to force us to
// decide if we must produce both events. In our case, we don't have to
// produce a kChar event because we are synthesizing arrow key presses, and
// only keys that output characters are expected to produce kChar events.
KeyboardEvent* keydown =
CreateKeyboardEvent(local_dom_window, WebInputEvent::Type::kRawKeyDown,
action, orientation, text_direction);
GetNode()->DispatchEvent(*keydown);
// The keydown handler may have caused the node to be removed.
if (!GetNode())
return;
KeyboardEvent* keyup =
CreateKeyboardEvent(local_dom_window, WebInputEvent::Type::kKeyUp, action,
orientation, text_direction);
// Add a 100ms delay between keydown and keyup to make events look less
// evidently synthesized.
GetDocument()
->GetTaskRunner(TaskType::kUserInteraction)
->PostDelayedTask(
FROM_HERE,
WTF::BindOnce(
[](Node* node, KeyboardEvent* evt) {
if (node) {
node->DispatchEvent(*evt);
}
},
WrapWeakPersistent(GetNode()), WrapPersistent(keyup)),
base::Milliseconds(100));
}
AXObject* AXNodeObject::ActiveDescendant() const {
Element* element = GetElement();
if (!element)
return nullptr;
if (RoleValue() == ax::mojom::blink::Role::kMenuListPopup) {
if (HTMLSelectElement* select =
DynamicTo<HTMLSelectElement>(parent_->GetNode())) {
// TODO(accessibility): as a simplification, just expose the active
// descendant of a <select size=1> at all times, like we do for other
// active descendant situations,
return select->PopupIsVisible() || select->IsFocusedElementInDocument()
? AXObjectCache().Get(select->OptionToBeShown())
: nullptr;
}
}
if (auto* select = DynamicTo<HTMLSelectElement>(GetNode())) {
if (!select->UsesMenuList()) {
return AXObjectCache().Get(select->ActiveSelectionEnd());
}
}
const Element* descendant = ElementFromAttributeOrInternals(
element, html_names::kAriaActivedescendantAttr);
if (!descendant) {
return nullptr;
}
AXObject* ax_descendant = AXObjectCache().Get(descendant);
return ax_descendant && ax_descendant->IsVisible() ? ax_descendant : nullptr;
}
bool IsExemptFromInlineBlockCheck(ax::mojom::blink::Role role) {
return role == ax::mojom::blink::Role::kSvgRoot ||
role == ax::mojom::blink::Role::kCanvas ||
role == ax::mojom::blink::Role::kEmbeddedObject;
}
bool AXNodeObject::HasCustomElementTreeProcessing() const {
if (!RuntimeEnabledFeatures::AccessibilityCustomElementRoleNoneEnabled()) {
return false;
}
if (!GetElement()) {
return false;
}
if (!GetElement()->IsCustomElement()) {
return false;
}
return true;
}
bool AXNodeObject::ShouldIncludeCustomElement() const {
Element* element = GetElement();
DCHECK(element);
DCHECK(element->IsCustomElement()) << element;
// Check whether author has forced it to be ignored via role="none".
if (RoleValue() == ax::mojom::blink::Role::kNone) {
return false;
}
// Custom elements are ignored in the tree by default, with some exceptions:
// * Has implicit or explicit (role attribute) role.
if (RoleValue() != ax::mojom::blink::Role::kGenericContainer) {
return true;
}
//* No shadow root attached.
if (!element->GetShadowRoot()) {
return true;
}
// * Has aria-live. This is a legitimate use case for ARIA semantics on
// a custom element.
if (HasAriaAttribute(html_names::kAriaLiveAttr)) {
return true;
}
// * Uses element internals with an accessibility attribute set.
// As element internals are not a convenient way to declare semantics, this
// indicates that it is more about hiding an implementation of semantics on
// the custom element, they are not likely to be used for semantics that
// are to be passed down into the shadow subtree by copying.
if (element->GetElementInternals() &&
element->GetElementInternals()->HasAnyAttribute()) {
return true;
}
// * Focusable.
if (element->IsKeyboardFocusableSlow(
Element::UpdateBehavior::kNoneForAccessibility)) {
return true;
}
// * <webview> (special deprecated element used in ChromeOS WebUI apps, and
// kept in tree to pass AutomationApiTest.LocationInWebView).
// Custom elements in actual web content always have a hyphenated name,
// and therefore <webview> in real web content cannot be a custom element.
DEFINE_STATIC_LOCAL(const AtomicString, web_view_tag, ("webview"));
if (element->HasLocalName(web_view_tag)) {
return true;
}
return false;
}
AXObjectInclusion AXNodeObject::ShouldIncludeBasedOnSemantics(
IgnoredReasons* ignored_reasons) const {
DCHECK(GetDocument());
// All nodes must have an unignored parent within their tree under
// the root node of the web area, so force that node to always be unignored.
if (IsA<Document>(GetNode())) {
return kIncludeObject;
}
if (IsPresentational()) {
if (ignored_reasons)
ignored_reasons->push_back(IgnoredReason(kAXPresentational));
return kIgnoreObject;
}
Node* node = GetNode();
if (!node) {
// Nodeless pseudo element images are included, even if they don't have CSS
// alt text. This can allow auto alt to be applied to them.
if (IsImage())
return kIncludeObject;
return kDefaultBehavior;
}
// Include carousel controls.
if (node->IsScrollMarkerGroupPseudoElement() ||
node->IsScrollMarkerPseudoElement() ||
node->IsScrollButtonPseudoElement()) {
return kIncludeObject;
}
// Avoid double speech. The ruby text describes pronunciation of the ruby
// base, and generally produces redundant screen reader output. Expose it only
// as a description on the <ruby> element so that screen reader users can
// toggle it on/off as with other descriptions/annotations.
if (RoleValue() == ax::mojom::blink::Role::kRubyAnnotation ||
(RoleValue() == ax::mojom::blink::Role::kStaticText && ParentObject() &&
ParentObject()->RoleValue() ==
ax::mojom::blink::Role::kRubyAnnotation)) {
return kIgnoreObject;
}
Element* element = GetElement();
if (!element) {
return kDefaultBehavior;
}
if (IsExcludedByFormControlsFilter()) {
if (ignored_reasons) {
ignored_reasons->push_back(IgnoredReason(kAXUninteresting));
}
return kIgnoreObject;
}
if (IsA<SVGElement>(node)) {
// The symbol element is used to define graphical templates which can be
// instantiated by a use element but which are not rendered directly. We
// don't want to include these template objects, or their subtrees, where
// they appear in the DOM. Any associated semantic information (e.g. the
// title child of a symbol) may participate in the text alternative
// computation where it is instantiated by the use element.
// https://svgwg.org/svg2-draft/struct.html#SymbolElement
if (Traversal<SVGSymbolElement>::FirstAncestorOrSelf(*node))
return kIgnoreObject;
// Include non-empty SVG root as clients may want to treat it as an image.
if (IsA<SVGSVGElement>(node) && GetLayoutObject() &&
GetLayoutObject()->IsSVGRoot() && element->firstElementChild()) {
return kIncludeObject;
}
// The SVG-AAM states that user agents MUST provide an accessible object
// for rendered SVG elements that have at least one direct child title or
// desc element that is not empty after trimming whitespace. But it also
// says, "User agents MAY include elements with these child elements without
// checking for valid text content." So just check for their existence in
// order to be performant. https://w3c.github.io/svg-aam/#include_elements
if (ElementTraversal::FirstChild(
*To<ContainerNode>(node), [](auto& element) {
return element.HasTagName(svg_names::kTitleTag) ||
element.HasTagName(svg_names::kDescTag);
})) {
return kIncludeObject;
}
// If setting enabled, do not ignore SVG grouping (<g>) elements.
if (IsA<SVGGElement>(node)) {
Settings* settings = GetDocument()->GetSettings();
if (settings->GetAccessibilityIncludeSvgGElement()) {
return kIncludeObject;
}
}
// If we return kDefaultBehavior here, the logic related to inclusion of
// clickable objects, links, controls, etc. will not be reached. We handle
// SVG elements early to ensure properties in a <symbol> subtree do not
// result in inclusion.
}
if (IsTableLikeRole() || IsTableRowLikeRole() || IsTableCellLikeRole() ||
element->HasTagName(html_names::kTheadTag) ||
element->HasTagName(html_names::kTfootTag)) {
return kIncludeObject;
}
if (IsA<HTMLHtmlElement>(node)) {
if (ignored_reasons) {
ignored_reasons->push_back(IgnoredReason(kAXUninteresting));
}
return kIgnoreObject;
}
// All focusable elements except the <body> and <html> are included.
if (!IsA<HTMLBodyElement>(node) && CanSetFocusAttribute())
return kIncludeObject;
if (IsLink())
return kIncludeObject;
// A click handler might be placed on an otherwise ignored non-empty block
// element, e.g. a div. We shouldn't ignore such elements because if an AT
// sees the |ax::mojom::blink::DefaultActionVerb::kClickAncestor|, it will
// look for the clickable ancestor and it expects to find one.
if (IsClickable())
return kIncludeObject;
if (IsHeading())
return kIncludeObject;
// Header and footer tags may also be exposed as landmark roles but not
// always.
if (node->HasTagName(html_names::kHeaderTag) ||
node->HasTagName(html_names::kFooterTag))
return kIncludeObject;
// All controls are accessible.
if (IsControl())
return kIncludeObject;
if (IsA<HTMLOptGroupElement>(node)) {
return kIncludeObject;
}
// Anything with an explicit ARIA role should be included.
if (RawAriaRole() != ax::mojom::blink::Role::kUnknown) {
return kIncludeObject;
}
// Anything that is an editable root should not be ignored. However, one
// cannot just call `AXObject::IsEditable()` since that will include the
// contents of an editable region too. Only the editable root should always be
// exposed.
if (IsEditableRoot())
return kIncludeObject;
// Custom elements are generally ignored in the tree, with some exceptions.
if (HasCustomElementTreeProcessing()) {
return ShouldIncludeCustomElement() ? kIncludeObject : kIgnoreObject;
}
// Don't ignored legends, because JAWS uses them to determine redundant text.
if (IsA<HTMLLegendElement>(node)) {
if (RuntimeEnabledFeatures::CustomizableSelectEnabled()) {
// When a <legend> is used inside an <optgroup>, it is used to set the
// name of the <optgroup> and shouldn't be redundantly repeated.
for (auto* ancestor = node->parentNode(); ancestor;
ancestor = ancestor->parentNode()) {
if (IsA<HTMLOptGroupElement>(ancestor)) {
return kIgnoreObject;
}
}
}
return kIncludeObject;
}
static constexpr auto always_included_computed_roles =
base::MakeFixedFlatSet<ax::mojom::blink::Role>({
ax::mojom::blink::Role::kAbbr,
ax::mojom::blink::Role::kApplication,
ax::mojom::blink::Role::kArticle,
ax::mojom::blink::Role::kAudio,
ax::mojom::blink::Role::kBanner,
ax::mojom::blink::Role::kBlockquote,
ax::mojom::blink::Role::kCode,
ax::mojom::blink::Role::kComplementary,
ax::mojom::blink::Role::kContentDeletion,
ax::mojom::blink::Role::kContentInfo,
ax::mojom::blink::Role::kContentInsertion,
ax::mojom::blink::Role::kDefinition,
ax::mojom::blink::Role::kDescriptionList,
ax::mojom::blink::Role::kDetails,
ax::mojom::blink::Role::kDialog,
ax::mojom::blink::Role::kDocAcknowledgments,
ax::mojom::blink::Role::kDocAfterword,
ax::mojom::blink::Role::kDocAppendix,
ax::mojom::blink::Role::kDocBibliography,
ax::mojom::blink::Role::kDocChapter,
ax::mojom::blink::Role::kDocConclusion,
ax::mojom::blink::Role::kDocCredits,
ax::mojom::blink::Role::kDocEndnotes,
ax::mojom::blink::Role::kDocEpilogue,
ax::mojom::blink::Role::kDocErrata,
ax::mojom::blink::Role::kDocForeword,
ax::mojom::blink::Role::kDocGlossary,
ax::mojom::blink::Role::kDocIntroduction,
ax::mojom::blink::Role::kDocPart,
ax::mojom::blink::Role::kDocPreface,
ax::mojom::blink::Role::kDocPrologue,
ax::mojom::blink::Role::kDocToc,
ax::mojom::blink::Role::kEmphasis,
ax::mojom::blink::Role::kFigcaption,
ax::mojom::blink::Role::kFigure,
ax::mojom::blink::Role::kFooter,
ax::mojom::blink::Role::kForm,
ax::mojom::blink::Role::kHeader,
ax::mojom::blink::Role::kList,
ax::mojom::blink::Role::kListItem,
ax::mojom::blink::Role::kMain,
ax::mojom::blink::Role::kMark,
ax::mojom::blink::Role::kMath,
ax::mojom::blink::Role::kMathMLMath,
// Don't ignore MathML nodes by default, since MathML
// relies on child positions to determine semantics
// (e.g. numerator is the first child of a fraction).
ax::mojom::blink::Role::kMathMLFraction,
ax::mojom::blink::Role::kMathMLIdentifier,
ax::mojom::blink::Role::kMathMLMultiscripts,
ax::mojom::blink::Role::kMathMLNoneScript,
ax::mojom::blink::Role::kMathMLNumber,
ax::mojom::blink::Role::kMathMLOperator,
ax::mojom::blink::Role::kMathMLOver,
ax::mojom::blink::Role::kMathMLPrescriptDelimiter,
ax::mojom::blink::Role::kMathMLRoot,
ax::mojom::blink::Role::kMathMLRow,
ax::mojom::blink::Role::kMathMLSquareRoot,
ax::mojom::blink::Role::kMathMLStringLiteral,
ax::mojom::blink::Role::kMathMLSub,
ax::mojom::blink::Role::kMathMLSubSup,
ax::mojom::blink::Role::kMathMLSup,
ax::mojom::blink::Role::kMathMLTable,
ax::mojom::blink::Role::kMathMLTableCell,
ax::mojom::blink::Role::kMathMLTableRow,
ax::mojom::blink::Role::kMathMLText,
ax::mojom::blink::Role::kMathMLUnder,
ax::mojom::blink::Role::kMathMLUnderOver,
ax::mojom::blink::Role::kMeter,
ax::mojom::blink::Role::kMenuListOption,
ax::mojom::blink::Role::kMenuListPopup,
ax::mojom::blink::Role::kNavigation,
ax::mojom::blink::Role::kPluginObject,
ax::mojom::blink::Role::kProgressIndicator,
ax::mojom::blink::Role::kRegion,
ax::mojom::blink::Role::kRuby,
ax::mojom::blink::Role::kSearch,
ax::mojom::blink::Role::kSection,
ax::mojom::blink::Role::kSplitter,
ax::mojom::blink::Role::kSubscript,
ax::mojom::blink::Role::kSuperscript,
ax::mojom::blink::Role::kStrong,
ax::mojom::blink::Role::kTerm,
ax::mojom::blink::Role::kTime,
ax::mojom::blink::Role::kVideo,
});
if (base::Contains(always_included_computed_roles, RoleValue())) {
return kIncludeObject;
}
// An <hgroup> element has the "group" aria role.
if (GetNode()->HasTagName(html_names::kHgroupTag)) {
return kIncludeObject;
}
// Interesting ARIA properties are enough to cause objects to be included,
// unless the computed role is none. Note that global ARIA properties usually
// undo role=none (exception has been made for custom roles).
// See https://w3c.github.io/aria/#conflict_resolution_presentation_none
// for more details.
if (ElementHasAnyAriaAttribute()) {
return kIncludeObject;
}
// Using a title for a name or description causes an object to be included.
if (!GetElement()->FastGetAttribute(kTitleAttr).empty()) {
return kIncludeObject;
}
if (IsImage() && !IsA<SVGElement>(node)) {
String alt = GetElement()->FastGetAttribute(kAltAttr);
// A null alt attribute means the attribute is not present. We assume this
// is a mistake, and expose the image so that it can be repaired.
// In contrast, alt="" is treated as intentional markup to ignore the image.
if (!alt.empty() || alt.IsNull())
return kIncludeObject;
if (ignored_reasons)
ignored_reasons->push_back(IgnoredReason(kAXEmptyAlt));
return kIgnoreObject;
}
// Process potential in-page link targets
if (IsPotentialInPageLinkTarget(*element))
return kIncludeObject;
if (AXObjectCache().GetAXMode().has_mode(ui::AXMode::kInlineTextBoxes)) {
// We are including inline block elements since we might rely on these for
// NextOnLine/PreviousOnLine computations.
//
// If we have an element with inline
// block specified, we should include. There are some roles where we
// shouldn't include even if inline block, or we'll get test failures.
//
// We also only want to include in the tree if the inline block element has
// siblings.
// Otherwise we will include nodes that we don't need for anything.
// Consider a structure where we have a subtree of 12 layers, where each
// layer has an inline-block node with a single child that points to the
// next layer. All nodes have a single child, meaning that this child has no
// siblings.
if (!IsExemptFromInlineBlockCheck(native_role_) && GetLayoutObject() &&
GetLayoutObject()->IsInline() &&
GetLayoutObject()->IsAtomicInlineLevel() &&
node->parentNode()->childElementCount() > 1) {
return kIncludeObject;
}
}
// Anything with non empty CSS alt should be included.
// https://drafts.csswg.org/css-content/#alt
// Descendants are pruned: IsRelevantPseudoElementDescendant() returns false.
std::optional<String> alt_text = GetCSSAltText(GetElement());
if (alt_text) {
if (alt_text->empty()) {
return kIgnoreObject;
} else {
return kIncludeObject;
}
}
// <span> tags are inline tags and not meant to convey information if they
// have no other ARIA information on them. If we don't ignore them, they may
// emit signals expected to come from their parent.
if (IsA<HTMLSpanElement>(node)) {
if (ignored_reasons)
ignored_reasons->push_back(IgnoredReason(kAXUninteresting));
return kIgnoreObject;
}
// Ignore labels that are already used to name a control.
// See IsRedundantLabel() for more commentary.
if (HTMLLabelElement* label = DynamicTo<HTMLLabelElement>(node)) {
if (IsRedundantLabel(label)) {
if (ignored_reasons) {
ignored_reasons->push_back(
IgnoredReason(kAXLabelFor, AXObjectCache().Get(label->Control())));
}
return kIgnoreObject;
}
return kIncludeObject;
}
// The SVG-AAM says the foreignObject element is normally presentational.
if (IsA<SVGForeignObjectElement>(node)) {
if (ignored_reasons) {
ignored_reasons->push_back(IgnoredReason(kAXPresentational));
}
return kIgnoreObject;
}
return kDefaultBehavior;
}
bool AXNodeObject::ComputeIsIgnored(IgnoredReasons* ignored_reasons) const {
Node* node = GetNode();
if (ShouldIgnoreForHiddenOrInert(ignored_reasons)) {
if (IsAriaHidden()) {
return true;
}
// Keep structure of <select size=1> even when collapsed.
if (const AXObject* ax_menu_list = ParentObject()->AncestorMenuList()) {
// The author provided <button> is marked as inert so it falls into this
// case. We want it and all of its descendants to be ignored. If any of
// them aren't ignored, then they will make it into the mappings. The
// button can't be pruned from the tree because it is used to compute the
// value of the MenuList.
if (RuntimeEnabledFeatures::CustomizableSelectEnabled()) {
for (const AXObject* ancestor = this;
ancestor && ancestor != ax_menu_list;
ancestor = ancestor->ParentObject()) {
if (HTMLSelectElement::IsSlottedButton(ancestor->GetNode())) {
return true;
}
}
}
return ax_menu_list->IsIgnored();
}
// Fallback elements inside of a <canvas> are invisible, but are not ignored
if (IsHiddenViaStyle() || !node || !node->parentElement() ||
!node->parentElement()->IsInCanvasSubtree()) {
return true;
}
}
// Handle content that is either visible or in a canvas subtree.
AXObjectInclusion include = ShouldIncludeBasedOnSemantics(ignored_reasons);
if (include == kIncludeObject) {
return false;
}
if (include == kIgnoreObject) {
return true;
}
if (!GetLayoutObject()) {
// Text without a layout object that has reached this point is not
// explicitly hidden, e.g. is in a <canvas> fallback or is display locked.
if (IsA<Text>(node)) {
return false;
}
if (ignored_reasons) {
ignored_reasons->push_back(IgnoredReason(kAXUninteresting));
}
return true;
}
// Inner editor element of editable area with empty text provides bounds
// used to compute the character extent for index 0. This is the same as
// what the caret's bounds would be if the editable area is focused.
if (node) {
const TextControlElement* text_control = EnclosingTextControl(node);
if (text_control) {
// Keep only the inner editor element and it's children.
// If inline textboxes are being loaded, then the inline textbox for the
// text wil be included by AXNodeObject::AddInlineTextboxChildren().
// By only keeping the inner editor and its text, it makes finding the
// inner editor simpler on the browser side.
// See BrowserAccessibility::GetTextFieldInnerEditorElement().
// TODO(accessibility) In the future, we may want to keep all descendants
// of the inner text element -- right now we only include one internally
// used container, it's text, and possibly the text's inlinext text box.
return text_control->InnerEditorElement() != node &&
text_control->InnerEditorElement() != NodeTraversal::Parent(*node);
}
}
// A LayoutEmbeddedContent is an iframe element or embedded object element or
// something like that. We don't want to ignore those.
if (GetLayoutObject()->IsLayoutEmbeddedContent()) {
return false;
}
if (node && node->IsInUserAgentShadowRoot()) {
Element* host = node->OwnerShadowHost();
if (auto* containing_media_element = DynamicTo<HTMLMediaElement>(host)) {
if (!containing_media_element->ShouldShowControls()) {
return true;
}
}
if (IsA<HTMLOptGroupElement>(host)) {
return false;
}
}
if (IsCanvas()) {
if (CanvasHasFallbackContent()) {
return false;
}
// A 1x1 canvas is too small for the user to see and thus ignored.
const auto* canvas = DynamicTo<LayoutHTMLCanvas>(GetLayoutObject());
if (canvas && (canvas->Size().height <= 1 || canvas->Size().width <= 1)) {
if (ignored_reasons) {
ignored_reasons->push_back(IgnoredReason(kAXProbablyPresentational));
}
return true;
}
// Otherwise fall through; use presence of help text, title, or description
// to decide.
}
if (GetLayoutObject()->IsBR()) {
return false;
}
if (GetLayoutObject()->IsText()) {
if (GetLayoutObject()->IsInListMarker()) {
// Ignore TextAlternative of the list marker for SUMMARY because:
// - TextAlternatives for disclosure-* are triangle symbol characters
// used to visually indicate the expansion state.
// - It's redundant. The host DETAILS exposes the expansion state.
// Also ignore text descendants of any non-ignored list marker because the
// text descendants do not provide any extra information than the
// TextAlternative on the list marker. Besides, with 'speak-as', they will
// be inconsistent with the list marker.
const AXObject* list_marker_object =
ContainerListMarkerIncludingIgnored();
if (list_marker_object &&
(list_marker_object->GetLayoutObject()->IsListMarkerForSummary() ||
!list_marker_object->IsIgnored())) {
if (ignored_reasons) {
ignored_reasons->push_back(IgnoredReason(kAXPresentational));
}
return true;
}
}
// Ignore text inside of an ignored <label>.
// To save processing, only walk up the ignored objects.
// This means that other interesting objects inside the <label> will
// cause the text to be unignored.
if (IsUsedForLabelOrDescription()) {
const AXObject* ancestor = ParentObject();
while (ancestor && ancestor->IsIgnored()) {
if (ancestor->RoleValue() == ax::mojom::blink::Role::kLabelText) {
if (ignored_reasons) {
ignored_reasons->push_back(IgnoredReason(kAXPresentational));
}
return true;
}
ancestor = ancestor->ParentObject();
}
}
return false;
}
if (GetLayoutObject()->IsListMarker()) {
// Ignore TextAlternative of the list marker for SUMMARY because:
// - TextAlternatives for disclosure-* are triangle symbol characters used
// to visually indicate the expansion state.
// - It's redundant. The host DETAILS exposes the expansion state.
if (GetLayoutObject()->IsListMarkerForSummary()) {
if (ignored_reasons) {
ignored_reasons->push_back(IgnoredReason(kAXPresentational));
}
return true;
}
return false;
}
// Positioned elements and scrollable containers are important for determining
// bounding boxes, so don't ignore them unless they are pseudo-content.
if (!GetLayoutObject()->IsPseudoElement()) {
if (IsScrollableContainer()) {
return false;
}
if (GetLayoutObject()->IsPositioned()) {
return false;
}
}
// Ignore a block flow (display:block, display:inline-block), unless it
// directly parents inline children.
// This effectively trims a lot of uninteresting divs out of the tree.
if (auto* block_flow = DynamicTo<LayoutBlockFlow>(GetLayoutObject())) {
if (block_flow->ChildrenInline() && block_flow->FirstChild()) {
return false;
}
}
// By default, objects should be ignored so that the AX hierarchy is not
// filled with unnecessary items.
if (ignored_reasons) {
ignored_reasons->push_back(IgnoredReason(kAXUninteresting));
}
return true;
}
// static
std::optional<String> AXNodeObject::GetCSSAltText(const Element* element) {
// CSS alt text rules allow text to be assigned to ::before/::after content.
// For example, the following CSS assigns "bullet" text to bullet.png:
// .something::before {
// content: url(bullet.png) / "bullet";
// }
if (!element) {
return std::nullopt;
}
const ComputedStyle* style = element->GetComputedStyle();
if (!style || style->ContentBehavesAsNormal()) {
return std::nullopt;
}
if (element->IsPseudoElement()) {
for (const ContentData* content_data = style->GetContentData();
content_data; content_data = content_data->Next()) {
if (content_data->IsAlt()) {
return ContentData::ConcatenateAltText(*content_data);
}
}
return std::nullopt;
}
// If the content property is used on a non-pseudo element, match the
// behaviour of LayoutObject::CreateObject and only honour the style if
// there is exactly one piece of content, which is an image.
const ContentData* content_data = style->GetContentData();
if (content_data && content_data->IsImage() && content_data->Next() &&
content_data->Next()->IsAlt()) {
return ContentData::ConcatenateAltText(*content_data->Next());
}
return std::nullopt;
}
std::optional<String> AXNodeObject::GetCSSContentText(const Element* element) {
if (!element || !element->IsPseudoElement() || !element->GetLayoutObject()) {
return std::nullopt;
}
StringBuilder builder;
CollectLayoutTextContentRecursive(builder, element->GetLayoutObject());
return builder.ToString();
}
// The following lists are for deciding whether the tags aside,
// header and footer can be interpreted as roles complementary, banner and
// contentInfo or if they should be interpreted as generic, sectionheader, or
// sectionfooter.
// This function only handles the complementary, banner, and contentInfo roles,
// which belong to the landmark roles set.
static HashSet<ax::mojom::blink::Role>& GetLandmarkIsNotAllowedAncestorRoles(
ax::mojom::blink::Role landmark) {
// clang-format off
DEFINE_STATIC_LOCAL(
// https://html.spec.whatwg.org/multipage/dom.html#sectioning-content-2
// The aside element should not assume the complementary role when nested
// within the following sectioning content elements.
HashSet<ax::mojom::blink::Role>, complementary_is_not_allowed_roles,
({
ax::mojom::blink::Role::kArticle,
ax::mojom::blink::Role::kComplementary,
ax::mojom::blink::Role::kNavigation,
ax::mojom::blink::Role::kSection
}));
// https://w3c.github.io/html-aam/#el-header-ancestorbody
// The header and footer elements should not assume the banner and
// contentInfo roles, respectively, when nested within any of the
// sectioning content elements or the main element.
DEFINE_STATIC_LOCAL(
HashSet<ax::mojom::blink::Role>, landmark_is_not_allowed_roles,
({
ax::mojom::blink::Role::kArticle,
ax::mojom::blink::Role::kComplementary,
ax::mojom::blink::Role::kMain,
ax::mojom::blink::Role::kNavigation,
ax::mojom::blink::Role::kSection
}));
// clang-format on
if (landmark == ax::mojom::blink::Role::kComplementary) {
return complementary_is_not_allowed_roles;
}
return landmark_is_not_allowed_roles;
}
bool AXNodeObject::IsDescendantOfLandmarkDisallowedElement() const {
if (!GetNode())
return false;
auto role_names = GetLandmarkIsNotAllowedAncestorRoles(RoleValue());
for (AXObject* parent = ParentObjectUnignored(); parent;
parent = parent->ParentObjectUnignored()) {
if (role_names.Contains(parent->RoleValue())) {
return true;
}
}
return false;
}
static bool IsNonEmptyNonHeaderCell(const Node* cell) {
return cell && cell->hasChildren() && cell->HasTagName(html_names::kTdTag);
}
static bool IsHeaderCell(const Node* cell) {
return cell && cell->HasTagName(html_names::kThTag);
}
static ax::mojom::blink::Role DecideRoleFromSiblings(Element* cell) {
// If this header is only cell in its row, it is a column header.
// It is also a column header if it has a header on either side of it.
// If instead it has a non-empty td element next to it, it is a row header.
const Node* next_cell = LayoutTreeBuilderTraversal::NextSibling(*cell);
const Node* previous_cell =
LayoutTreeBuilderTraversal::PreviousSibling(*cell);
if (!next_cell && !previous_cell)
return ax::mojom::blink::Role::kColumnHeader;
if (IsHeaderCell(next_cell) && IsHeaderCell(previous_cell))
return ax::mojom::blink::Role::kColumnHeader;
if (IsNonEmptyNonHeaderCell(next_cell) ||
IsNonEmptyNonHeaderCell(previous_cell))
return ax::mojom::blink::Role::kRowHeader;
const auto* row = DynamicTo<HTMLTableRowElement>(cell->parentNode());
if (!row)
return ax::mojom::blink::Role::kColumnHeader;
// If this row's first or last cell is a non-empty td, this is a row header.
// Do the same check for the second and second-to-last cells because tables
// often have an empty cell at the intersection of the row and column headers.
const Element* first_cell = ElementTraversal::FirstChild(*row);
DCHECK(first_cell);
const Element* last_cell = ElementTraversal::LastChild(*row);
DCHECK(last_cell);
if (IsNonEmptyNonHeaderCell(first_cell) || IsNonEmptyNonHeaderCell(last_cell))
return ax::mojom::blink::Role::kRowHeader;
if (IsNonEmptyNonHeaderCell(ElementTraversal::NextSibling(*first_cell)) ||
IsNonEmptyNonHeaderCell(ElementTraversal::PreviousSibling(*last_cell)))
return ax::mojom::blink::Role::kRowHeader;
// We have no evidence that this is not a column header.
return ax::mojom::blink::Role::kColumnHeader;
}
ax::mojom::blink::Role AXNodeObject::DetermineTableSectionRole() const {
if (!GetElement())
return ax::mojom::blink::Role::kGenericContainer;
AXObject* parent = GetDOMTableAXAncestor(GetNode(), AXObjectCache());
if (!parent || !parent->IsTableLikeRole())
return ax::mojom::blink::Role::kGenericContainer;
if (parent->RoleValue() == ax::mojom::blink::Role::kLayoutTable)
return ax::mojom::blink::Role::kGenericContainer;
return ax::mojom::blink::Role::kRowGroup;
}
ax::mojom::blink::Role AXNodeObject::DetermineTableRowRole() const {
AXObject* parent = GetDOMTableAXAncestor(GetNode(), AXObjectCache());
if (!parent || !parent->IsTableLikeRole())
return ax::mojom::blink::Role::kGenericContainer;
if (parent->RoleValue() == ax::mojom::blink::Role::kLayoutTable)
return ax::mojom::blink::Role::kLayoutTableRow;
return ax::mojom::blink::Role::kRow;
}
ax::mojom::blink::Role AXNodeObject::DetermineTableCellRole() const {
AXObject* parent = GetDOMTableAXAncestor(GetNode(), AXObjectCache());
if (!parent || !parent->IsTableRowLikeRole())
return ax::mojom::blink::Role::kGenericContainer;
// Ensure table container.
AXObject* grandparent =
GetDOMTableAXAncestor(parent->GetNode(), AXObjectCache());
if (!grandparent || !grandparent->IsTableLikeRole())
return ax::mojom::blink::Role::kGenericContainer;
if (parent->RoleValue() == ax::mojom::blink::Role::kLayoutTableRow)
return ax::mojom::blink::Role::kLayoutTableCell;
if (!GetElement() || !GetNode()->HasTagName(html_names::kThTag))
return ax::mojom::blink::Role::kCell;
const AtomicString& scope =
GetElement()->FastGetAttribute(html_names::kScopeAttr);
if (EqualIgnoringASCIICase(scope, "row") ||
EqualIgnoringASCIICase(scope, "rowgroup"))
return ax::mojom::blink::Role::kRowHeader;
if (EqualIgnoringASCIICase(scope, "col") ||
EqualIgnoringASCIICase(scope, "colgroup"))
return ax::mojom::blink::Role::kColumnHeader;
return DecideRoleFromSiblings(GetElement());
}
unsigned AXNodeObject::ColumnCount() const {
if (RawAriaRole() != ax::mojom::blink::Role::kUnknown) {
return AXObject::ColumnCount();
}
if (const auto* table = DynamicTo<LayoutTable>(GetLayoutObject())) {
return table->EffectiveColumnCount();
}
return AXObject::ColumnCount();
}
unsigned AXNodeObject::RowCount() const {
if (RawAriaRole() != ax::mojom::blink::Role::kUnknown) {
return AXObject::RowCount();
}
LayoutTable* table;
auto* table_section = FirstTableSection(GetLayoutObject(), &table);
if (!table_section) {
return AXObject::RowCount();
}
unsigned row_count = 0;
while (table_section) {
row_count += table_section->NumRows();
table_section = table->NextSection(table_section);
}
return row_count;
}
unsigned AXNodeObject::ColumnIndex() const {
auto* cell = DynamicTo<LayoutTableCell>(GetLayoutObject());
if (cell && cell->GetNode()) {
return cell->Table()->AbsoluteColumnToEffectiveColumn(
cell->AbsoluteColumnIndex());
}
return AXObject::ColumnIndex();
}
unsigned AXNodeObject::RowIndex() const {
LayoutObject* layout_object = GetLayoutObject();
if (!layout_object || !layout_object->GetNode()) {
return AXObject::RowIndex();
}
unsigned row_index = 0;
const LayoutTableSection* row_section = nullptr;
const LayoutTable* table = nullptr;
if (const auto* row = DynamicTo<LayoutTableRow>(layout_object)) {
row_index = row->RowIndex();
row_section = row->Section();
table = row->Table();
} else if (const auto* cell = DynamicTo<LayoutTableCell>(layout_object)) {
row_index = cell->RowIndex();
row_section = cell->Section();
table = cell->Table();
} else {
return AXObject::RowIndex();
}
if (!table || !row_section) {
return AXObject::RowIndex();
}
// Since our table might have multiple sections, we have to offset our row
// appropriately.
const LayoutTableSection* section = table->FirstSection();
while (section && section != row_section) {
row_index += section->NumRows();
section = table->NextSection(section);
}
return row_index;
}
unsigned AXNodeObject::ColumnSpan() const {
auto* cell = DynamicTo<LayoutTableCell>(GetLayoutObject());
if (!cell) {
return AXObject::ColumnSpan();
}
LayoutTable* table = cell->Table();
unsigned absolute_first_col = cell->AbsoluteColumnIndex();
unsigned absolute_last_col = absolute_first_col + cell->ColSpan() - 1;
unsigned effective_first_col =
table->AbsoluteColumnToEffectiveColumn(absolute_first_col);
unsigned effective_last_col =
table->AbsoluteColumnToEffectiveColumn(absolute_last_col);
return effective_last_col - effective_first_col + 1;
}
unsigned AXNodeObject::RowSpan() const {
auto* cell = DynamicTo<LayoutTableCell>(GetLayoutObject());
return cell ? cell->ResolvedRowSpan() : AXObject::RowSpan();
}
ax::mojom::blink::SortDirection AXNodeObject::GetSortDirection() const {
if (RoleValue() != ax::mojom::blink::Role::kRowHeader &&
RoleValue() != ax::mojom::blink::Role::kColumnHeader) {
return ax::mojom::blink::SortDirection::kNone;
}
if (const AtomicString& aria_sort =
AriaTokenAttribute(html_names::kAriaSortAttr)) {
if (EqualIgnoringASCIICase(aria_sort, "none")) {
return ax::mojom::blink::SortDirection::kNone;
}
if (EqualIgnoringASCIICase(aria_sort, "ascending")) {
return ax::mojom::blink::SortDirection::kAscending;
}
if (EqualIgnoringASCIICase(aria_sort, "descending")) {
return ax::mojom::blink::SortDirection::kDescending;
}
// Technically, illegal values should be exposed as is, but this does
// not seem to be worth the implementation effort at this time.
return ax::mojom::blink::SortDirection::kOther;
}
return ax::mojom::blink::SortDirection::kNone;
}
AXObject* AXNodeObject::CellForColumnAndRow(unsigned target_column_index,
unsigned target_row_index) const {
LayoutTable* table;
auto* table_section = FirstTableSection(GetLayoutObject(), &table);
if (!table_section) {
return AXObject::CellForColumnAndRow(target_column_index, target_row_index);
}
unsigned row_offset = 0;
while (table_section) {
// Iterate backwards through the rows in case the desired cell has a rowspan
// and exists in a previous row.
for (LayoutTableRow* row = table_section->LastRow(); row;
row = row->PreviousRow()) {
unsigned row_index = row->RowIndex() + row_offset;
for (LayoutTableCell* cell = row->LastCell(); cell;
cell = cell->PreviousCell()) {
unsigned absolute_first_col = cell->AbsoluteColumnIndex();
unsigned absolute_last_col = absolute_first_col + cell->ColSpan() - 1;
unsigned effective_first_col =
table->AbsoluteColumnToEffectiveColumn(absolute_first_col);
unsigned effective_last_col =
table->AbsoluteColumnToEffectiveColumn(absolute_last_col);
unsigned row_span = cell->ResolvedRowSpan();
if (target_column_index >= effective_first_col &&
target_column_index <= effective_last_col &&
target_row_index >= row_index &&
target_row_index < row_index + row_span) {
return AXObjectCache().Get(cell);
}
}
}
row_offset += table_section->NumRows();
table_section = table->NextSection(table_section);
}
return nullptr;
}
bool AXNodeObject::FindAllTableCellsWithRole(ax::mojom::blink::Role role,
AXObjectVector& cells) const {
LayoutTable* table;
auto* table_section = FirstTableSection(GetLayoutObject(), &table);
if (!table_section) {
return false;
}
while (table_section) {
for (LayoutTableRow* row = table_section->FirstRow(); row;
row = row->NextRow()) {
for (LayoutTableCell* cell = row->FirstCell(); cell;
cell = cell->NextCell()) {
AXObject* ax_cell = AXObjectCache().Get(cell);
if (ax_cell && ax_cell->RoleValue() == role) {
cells.push_back(ax_cell);
}
}
}
table_section = table->NextSection(table_section);
}
return true;
}
void AXNodeObject::ColumnHeaders(AXObjectVector& headers) const {
if (!FindAllTableCellsWithRole(ax::mojom::blink::Role::kColumnHeader,
headers)) {
AXObject::ColumnHeaders(headers);
}
}
void AXNodeObject::RowHeaders(AXObjectVector& headers) const {
if (!FindAllTableCellsWithRole(ax::mojom::blink::Role::kRowHeader, headers)) {
AXObject::RowHeaders(headers);
}
}
AXObject* AXNodeObject::HeaderObject() const {
auto* row = DynamicTo<LayoutTableRow>(GetLayoutObject());
if (!row) {
return nullptr;
}
for (LayoutTableCell* cell = row->FirstCell(); cell;
cell = cell->NextCell()) {
AXObject* ax_cell = cell ? AXObjectCache().Get(cell) : nullptr;
if (ax_cell && ax_cell->RoleValue() == ax::mojom::blink::Role::kRowHeader) {
return ax_cell;
}
}
return nullptr;
}
// The following is a heuristic used to determine if a
// <table> should be with ax::mojom::blink::Role::kTable or
// ax::mojom::blink::Role::kLayoutTable.
// Only "data" tables should be exposed as tables.
// Unfortunately, there is no determinsistic or precise way to differentiate a
// layout table vs a data table. Fortunately, CSS authoring techniques have
// improved a lot and mostly supplanted the practice of using tables for layout.
bool AXNodeObject::IsDataTable() const {
DCHECK(!IsDetached());
auto* table_element = DynamicTo<HTMLTableElement>(GetNode());
if (!table_element) {
return false;
}
if (!GetLayoutObject()) {
// The table is not rendered, so the author has no reason to use the table
// for layout. Treat as a data table by default as there is not enough
// information to decide otherwise.
// One useful result of this is that a table inside a canvas fallback is
// treated as a data table.
return true;
}
// If it has an ARIA role, it's definitely a data table.
if (HasAriaAttribute(html_names::kRoleAttr)) {
return true;
}
// When a section of the document is contentEditable, all tables should be
// treated as data tables, otherwise users may not be able to work with rich
// text editors that allow creating and editing tables.
if (GetNode() && blink::IsEditable(*GetNode())) {
return true;
}
// If there is a caption element, summary, THEAD, or TFOOT section, it's most
// certainly a data table
if (!table_element->Summary().empty() || table_element->tHead() ||
table_element->tFoot() || table_element->caption()) {
return true;
}
// if someone used "rules" attribute than the table should appear
if (!table_element->Rules().empty()) {
return true;
}
// if there's a colgroup or col element, it's probably a data table.
if (Traversal<HTMLTableColElement>::FirstChild(*table_element)) {
return true;
}
// If there are at least 20 rows, we'll call it a data table.
HTMLTableRowsCollection* rows = table_element->rows();
int num_rows = rows->length();
if (num_rows >= AXObjectCacheImpl::kDataTableHeuristicMinRows) {
return true;
}
if (num_rows <= 0) {
return false;
}
int num_cols_in_first_body = rows->Item(0)->cells()->length();
// If there's only one cell, it's not a good AXTable candidate.
if (num_rows == 1 && num_cols_in_first_body == 1) {
return false;
}
// Store the background color of the table to check against cell's background
// colors.
const ComputedStyle* table_style = GetLayoutObject()->Style();
if (!table_style) {
return false;
}
Color table_bg_color =
table_style->VisitedDependentColor(GetCSSPropertyBackgroundColor());
bool has_cell_spacing = table_style->HorizontalBorderSpacing() &&
table_style->VerticalBorderSpacing();
// check enough of the cells to find if the table matches our criteria
// Criteria:
// 1) must have at least one valid cell (and)
// 2) at least half of cells have borders (or)
// 3) at least half of cells have different bg colors than the table, and
// there is cell spacing
unsigned valid_cell_count = 0;
unsigned bordered_cell_count = 0;
unsigned background_difference_cell_count = 0;
unsigned cells_with_top_border = 0;
unsigned cells_with_bottom_border = 0;
unsigned cells_with_left_border = 0;
unsigned cells_with_right_border = 0;
std::array<Color, 5> alternating_row_colors;
int alternating_row_color_count = 0;
for (int row = 0; row < num_rows; ++row) {
HTMLTableRowElement* row_element = rows->Item(row);
int n_cols = row_element->cells()->length();
for (int col = 0; col < n_cols; ++col) {
const Element* cell = row_element->cells()->item(col);
if (!cell) {
continue;
}
// Any <th> tag -> treat as data table.
if (cell->HasTagName(html_names::kThTag)) {
return true;
}
// Check for an explicitly assigned a "data" table attribute.
auto* cell_elem = DynamicTo<HTMLTableCellElement>(*cell);
if (cell_elem) {
if (!cell_elem->Headers().empty() || !cell_elem->Abbr().empty() ||
!cell_elem->Axis().empty() ||
!cell_elem->FastGetAttribute(html_names::kScopeAttr).empty()) {
return true;
}
}
LayoutObject* cell_layout_object = cell->GetLayoutObject();
if (!cell_layout_object || !cell_layout_object->IsLayoutBlock()) {
continue;
}
const LayoutBlock* cell_layout_block =
To<LayoutBlock>(cell_layout_object);
if (cell_layout_block->Size().width < 1 ||
cell_layout_block->Size().height < 1) {
continue;
}
valid_cell_count++;
const ComputedStyle* computed_style = cell_layout_block->Style();
if (!computed_style) {
continue;
}
// If the empty-cells style is set, we'll call it a data table.
if (computed_style->EmptyCells() == EEmptyCells::kHide) {
return true;
}
// If a cell has matching bordered sides, call it a (fully) bordered cell.
if ((cell_layout_block->BorderTop() > 0 &&
cell_layout_block->BorderBottom() > 0) ||
(cell_layout_block->BorderLeft() > 0 &&
cell_layout_block->BorderRight() > 0)) {
bordered_cell_count++;
}
// Also keep track of each individual border, so we can catch tables where
// most cells have a bottom border, for example.
if (cell_layout_block->BorderTop() > 0) {
cells_with_top_border++;
}
if (cell_layout_block->BorderBottom() > 0) {
cells_with_bottom_border++;
}
if (cell_layout_block->BorderLeft() > 0) {
cells_with_left_border++;
}
if (cell_layout_block->BorderRight() > 0) {
cells_with_right_border++;
}
// If the cell has a different color from the table and there is cell
// spacing, then it is probably a data table cell (spacing and colors take
// the place of borders).
Color cell_color = computed_style->VisitedDependentColor(
GetCSSPropertyBackgroundColor());
if (has_cell_spacing && table_bg_color != cell_color &&
!cell_color.IsFullyTransparent()) {
background_difference_cell_count++;
}
// If we've found 10 "good" cells, we don't need to keep searching.
if (bordered_cell_count >= 10 || background_difference_cell_count >= 10) {
return true;
}
// For the first 5 rows, cache the background color so we can check if
// this table has zebra-striped rows.
if (row < 5 && row == alternating_row_color_count) {
LayoutObject* layout_row = cell_layout_block->Parent();
if (!layout_row || !layout_row->IsBoxModelObject() ||
!layout_row->IsTableRow()) {
continue;
}
const ComputedStyle* row_computed_style = layout_row->Style();
if (!row_computed_style) {
continue;
}
Color row_color = row_computed_style->VisitedDependentColor(
GetCSSPropertyBackgroundColor());
alternating_row_colors[alternating_row_color_count] = row_color;
alternating_row_color_count++;
}
}
}
// if there is less than two valid cells, it's not a data table
if (valid_cell_count <= 1) {
return false;
}
// half of the cells had borders, it's a data table
unsigned needed_cell_count = valid_cell_count / 2;
if (bordered_cell_count >= needed_cell_count ||
cells_with_top_border >= needed_cell_count ||
cells_with_bottom_border >= needed_cell_count ||
cells_with_left_border >= needed_cell_count ||
cells_with_right_border >= needed_cell_count) {
return true;
}
// half had different background colors, it's a data table
if (background_difference_cell_count >= needed_cell_count) {
return true;
}
// Check if there is an alternating row background color indicating a zebra
// striped style pattern.
if (alternating_row_color_count > 2) {
Color first_color = alternating_row_colors[0];
for (int k = 1; k < alternating_row_color_count; k++) {
// If an odd row was the same color as the first row, its not alternating.
if (k % 2 == 1 && alternating_row_colors[k] == first_color) {
return false;
}
// If an even row is not the same as the first row, its not alternating.
if (!(k % 2) && alternating_row_colors[k] != first_color) {
return false;
}
}
return true;
}
return false;
}
// TODO(accessibility) Consider combining with NativeRoleIgnoringAria().
ax::mojom::blink::Role AXNodeObject::RoleFromLayoutObjectOrNode() const {
if (!GetLayoutObject()) {
return ax::mojom::blink::Role::kGenericContainer;
}
DCHECK(GetLayoutObject());
if (GetLayoutObject()->IsListMarker()) {
Node* list_item = GetLayoutObject()->GeneratingNode();
if (list_item && ShouldIgnoreListItem(list_item)) {
return ax::mojom::blink::Role::kNone;
}
return ax::mojom::blink::Role::kListMarker;
}
if (GetLayoutObject()->IsListItem()) {
return ax::mojom::blink::Role::kListItem;
}
if (GetLayoutObject()->IsBR()) {
return ax::mojom::blink::Role::kLineBreak;
}
if (GetLayoutObject()->IsText()) {
return ax::mojom::blink::Role::kStaticText;
}
Node* node = GetNode(); // Can be null in the case of pseudo content.
// Chrome exposes both table markup and table CSS as a tables, letting
// the screen reader determine what to do for CSS tables. If this line
// is reached, then it is not an HTML table, and therefore will only be
// considered a data table if ARIA markup indicates it is a table.
// Additionally, as pseudo elements don't have any structure it doesn't make
// sense to report their table-related layout roles that could be set via the
// display property.
if (node && !node->IsPseudoElement()) {
if (GetLayoutObject()->IsTable()) {
return ax::mojom::blink::Role::kLayoutTable;
}
if (GetLayoutObject()->IsTableSection()) {
return DetermineTableSectionRole();
}
if (GetLayoutObject()->IsTableRow()) {
return DetermineTableRowRole();
}
if (GetLayoutObject()->IsTableCell()) {
return DetermineTableCellRole();
}
}
if (IsImageOrAltText(GetLayoutObject(), node)) {
if (IsA<HTMLInputElement>(node)) {
return ButtonRoleType();
}
return ax::mojom::blink::Role::kImage;
}
if (IsA<HTMLCanvasElement>(node)) {
return ax::mojom::blink::Role::kCanvas;
}
if (IsA<LayoutView>(GetLayoutObject())) {
return ParentObject() ? ax::mojom::blink::Role::kGroup
: ax::mojom::blink::Role::kRootWebArea;
}
if (node && node->IsSVGElement()) {
if (GetLayoutObject()->IsSVGImage()) {
return ax::mojom::blink::Role::kImage;
}
if (IsA<SVGSVGElement>(node)) {
// Exposing a nested <svg> as a group (rather than a generic container)
// increases the likelihood that an author-provided name will be presented
// by assistive technologies. Note that this mapping is not yet in the
// SVG-AAM, which currently maps all <svg> elements as graphics-document.
// See https://github.com/w3c/svg-aam/issues/18.
return GetLayoutObject()->IsSVGRoot() ? ax::mojom::blink::Role::kSvgRoot
: ax::mojom::blink::Role::kGroup;
}
if (GetLayoutObject()->IsSVGShape()) {
return ax::mojom::blink::Role::kGraphicsSymbol;
}
if (GetLayoutObject()->IsSVGForeignObject()) {
return ax::mojom::blink::Role::kGroup;
}
if (IsA<SVGUseElement>(node)) {
return ax::mojom::blink::Role::kGraphicsObject;
}
}
if (GetLayoutObject()->IsHR()) {
return ax::mojom::blink::Role::kSplitter;
}
// Minimum role:
// TODO(accessibility) if (AXObjectCache().IsInternalUICheckerOn()) assert,
// because it is a bad code smell and usually points to other problems.
if (GetElement() && !HasAriaAttribute(html_names::kRoleAttr)) {
if (IsPopup() != ax::mojom::blink::IsPopup::kNone ||
GetElement()->FastHasAttribute(html_names::kAutofocusAttr) ||
GetElement()->FastHasAttribute(html_names::kDraggableAttr)) {
return ax::mojom::blink::Role::kGroup;
}
if (RuntimeEnabledFeatures::AccessibilityMinRoleTabbableEnabled()) {
if (GetElement()->tabIndex() >= 0) {
return ax::mojom::blink::Role::kGroup;
}
}
}
// Custom elements have additional minimum role rules.
if (HasCustomElementTreeProcessing()) {
if (ElementHasAnyAriaRelation(*GetElement()) ||
GetElement()->tabIndex() >= 0) {
return ax::mojom::blink::Role::kGroup;
}
}
if (IsA<HTMLPermissionElement>(node)) {
return ax::mojom::blink::Role::kButton;
}
// Anything that needs to be exposed but doesn't have a more specific role
// should be considered a generic container. Examples are layout blocks with
// no node, in-page link targets, and plain elements such as a <span> with
// an aria- property.
return ax::mojom::blink::Role::kGenericContainer;
}
// Does not check ARIA role, but does check some ARIA properties, specifically
// @aria-haspopup/aria-pressed via ButtonType().
ax::mojom::blink::Role AXNodeObject::NativeRoleIgnoringAria() const {
if (!GetNode()) {
// Can be null in the case of pseudo content.
return RoleFromLayoutObjectOrNode();
}
if (GetNode()->IsPseudoElement()) {
// This is for carousel scroll buttons (left/right/up/down) which are meant
// to look and act like buttons, but are generated as ::scroll-button(...)
// pseudos.
if (GetNode()->IsScrollButtonPseudoElement()) {
return ax::mojom::blink::Role::kButton;
}
// Carousel ::scroll-marker-group is a kTabList.
if (GetNode()->IsScrollMarkerGroupPseudoElement()) {
return ax::mojom::blink::Role::kTabList;
}
// Carousel ::scroll-marker within a group is a kTab.
if (GetNode()->IsScrollMarkerPseudoElement()) {
return ax::mojom::blink::Role::kTab;
}
if (GetCSSAltText(GetElement())) {
const ComputedStyle* style = GetElement()->GetComputedStyle();
ContentData* content_data = style->GetContentData();
// We just check the first item of the content list to determine the
// appropriate role, should only ever be image or text.
// TODO(accessibility) Is it possible to use CSS alt text on an HTML tag
// with strong semantics? If so, why are we overriding the role here?
// We only need to ensure the accessible name gets the CSS alt text.
// Note: by doing this, we are often hiding child pseudo element content
// because IsRelevantPseudoElementDescendant() returns false when an
// ancestor has CSS alt text.
if (content_data->IsImage()) {
return ax::mojom::blink::Role::kImage;
}
return ax::mojom::blink::Role::kStaticText;
}
}
if (GetNode()->IsTextNode())
return ax::mojom::blink::Role::kStaticText;
if (IsA<HTMLImageElement>(GetNode()))
return ax::mojom::blink::Role::kImage;
// <a> or <svg:a>.
if (IsA<HTMLAnchorElement>(GetNode()) || IsA<SVGAElement>(GetNode())) {
// Assume that an anchor element is a Role::kLink if it has an href or a
// click event listener.
if (GetNode()->IsLink() ||
GetNode()->HasAnyEventListeners(event_util::MouseButtonEventTypes())) {
return ax::mojom::blink::Role::kLink;
}
// According to the SVG-AAM, a non-link 'a' element should be exposed like
// a 'g' if it does not descend from a 'text' element and like a 'tspan'
// if it does. This is consistent with the SVG spec which states that an
// 'a' within 'text' acts as an inline element, whereas it otherwise acts
// as a container element.
if (IsA<SVGAElement>(GetNode()) &&
!Traversal<SVGTextElement>::FirstAncestor(*GetNode())) {
return ax::mojom::blink::Role::kGroup;
}
return ax::mojom::blink::Role::kGenericContainer;
}
if (IsA<SVGGElement>(*GetNode())) {
return ax::mojom::blink::Role::kGroup;
}
if (IsA<HTMLButtonElement>(*GetNode()))
return ButtonRoleType();
if (IsA<HTMLDetailsElement>(*GetNode()))
return ax::mojom::blink::Role::kDetails;
if (IsA<HTMLSummaryElement>(*GetNode())) {
ContainerNode* parent = LayoutTreeBuilderTraversal::Parent(*GetNode());
if (ToHTMLSlotElementIfSupportsAssignmentOrNull(parent))
parent = LayoutTreeBuilderTraversal::Parent(*parent);
if (HTMLDetailsElement* parent_details =
DynamicTo<HTMLDetailsElement>(parent)) {
if (parent_details->GetName().empty()) {
return ax::mojom::blink::Role::kDisclosureTriangle;
} else {
return ax::mojom::blink::Role::kDisclosureTriangleGrouped;
}
}
return ax::mojom::blink::Role::kGenericContainer;
}
// Chrome exposes both table markup and table CSS as a table, letting
// the screen reader determine what to do for CSS tables.
if (IsA<HTMLTableElement>(*GetNode())) {
if (IsDataTable())
return ax::mojom::blink::Role::kTable;
else
return ax::mojom::blink::Role::kLayoutTable;
}
if (IsA<HTMLTableRowElement>(*GetNode()))
return DetermineTableRowRole();
if (IsA<HTMLTableCellElement>(*GetNode()))
return DetermineTableCellRole();
if (IsA<HTMLTableSectionElement>(*GetNode()))
return DetermineTableSectionRole();
if (const auto* input = DynamicTo<HTMLInputElement>(*GetNode())) {
FormControlType type = input->FormControlType();
if (input->DataList() && type != FormControlType::kInputColor) {
return ax::mojom::blink::Role::kTextFieldWithComboBox;
}
switch (type) {
case FormControlType::kInputButton:
case FormControlType::kInputReset:
case FormControlType::kInputSubmit:
return ButtonRoleType();
case FormControlType::kInputCheckbox:
return ax::mojom::blink::Role::kCheckBox;
case FormControlType::kInputDate:
return ax::mojom::blink::Role::kDate;
case FormControlType::kInputDatetimeLocal:
case FormControlType::kInputMonth:
case FormControlType::kInputWeek:
return ax::mojom::blink::Role::kDateTime;
case FormControlType::kInputFile:
return ax::mojom::blink::Role::kButton;
case FormControlType::kInputRadio:
return ax::mojom::blink::Role::kRadioButton;
case FormControlType::kInputNumber:
return ax::mojom::blink::Role::kSpinButton;
case FormControlType::kInputRange:
return ax::mojom::blink::Role::kSlider;
case FormControlType::kInputSearch:
return ax::mojom::blink::Role::kSearchBox;
case FormControlType::kInputColor:
return ax::mojom::blink::Role::kColorWell;
case FormControlType::kInputTime:
return ax::mojom::blink::Role::kInputTime;
case FormControlType::kInputImage:
return ax::mojom::blink::Role::kButton;
default:
return ax::mojom::blink::Role::kTextField;
}
}
if (auto* select_element = DynamicTo<HTMLSelectElement>(*GetNode())) {
if (select_element->UsesMenuList() && !select_element->IsMultiple()) {
return ax::mojom::blink::Role::kComboBoxSelect;
} else {
return ax::mojom::blink::Role::kListBox;
}
}
if (ParentObjectIfPresent() && ParentObjectIfPresent()->RoleValue() ==
ax::mojom::blink::Role::kComboBoxSelect) {
if (!RuntimeEnabledFeatures::CustomizableSelectEnabled() ||
HTMLSelectElement::IsPopoverForAppearanceBase(GetNode())) {
return ax::mojom::blink::Role::kMenuListPopup;
}
}
if (auto* option = DynamicTo<HTMLOptionElement>(*GetNode())) {
HTMLSelectElement* select_element = option->OwnerSelectElement();
if (select_element && select_element->UsesMenuList() &&
!select_element->IsMultiple()) {
return ax::mojom::blink::Role::kMenuListOption;
} else {
return ax::mojom::blink::Role::kListBoxOption;
}
}
if (IsA<HTMLOptGroupElement>(GetNode())) {
return ax::mojom::blink::Role::kGroup;
}
if (IsA<HTMLTextAreaElement>(*GetNode()))
return ax::mojom::blink::Role::kTextField;
if (HeadingLevel())
return ax::mojom::blink::Role::kHeading;
if (IsA<HTMLDivElement>(*GetNode()))
return RoleFromLayoutObjectOrNode();
if (IsA<HTMLMenuElement>(*GetNode()) || IsA<HTMLUListElement>(*GetNode()) ||
IsA<HTMLOListElement>(*GetNode())) {
// <menu> is a deprecated feature of HTML 5, but is included for semantic
// compatibility with HTML3, and may contain list items. Exposing it as an
// unordered list works better than the current HTML-AAM recommendaton of
// exposing as a role=menu, because if it's just used semantically, it won't
// be interactive. If used as a widget, the author must provide role=menu.
return ax::mojom::blink::Role::kList;
}
if (IsA<HTMLLIElement>(*GetNode())) {
if (ShouldIgnoreListItem(GetNode())) {
return ax::mojom::blink::Role::kNone;
}
return ax::mojom::blink::Role::kListItem;
}
if (IsA<HTMLMeterElement>(*GetNode()))
return ax::mojom::blink::Role::kMeter;
if (IsA<HTMLProgressElement>(*GetNode()))
return ax::mojom::blink::Role::kProgressIndicator;
if (IsA<HTMLOutputElement>(*GetNode()))
return ax::mojom::blink::Role::kStatus;
if (IsA<HTMLParagraphElement>(*GetNode()))
return ax::mojom::blink::Role::kParagraph;
if (IsA<HTMLLabelElement>(*GetNode()))
return ax::mojom::blink::Role::kLabelText;
if (IsA<HTMLLegendElement>(*GetNode()))
return ax::mojom::blink::Role::kLegend;
if (GetNode()->HasTagName(html_names::kRubyTag)) {
return ax::mojom::blink::Role::kRuby;
}
if (IsA<HTMLDListElement>(*GetNode()))
return ax::mojom::blink::Role::kDescriptionList;
if (IsA<HTMLDirectoryElement>(*GetNode())) {
return ax::mojom::blink::Role::kList;
}
if (IsA<HTMLAudioElement>(*GetNode()))
return ax::mojom::blink::Role::kAudio;
if (IsA<HTMLVideoElement>(*GetNode()))
return ax::mojom::blink::Role::kVideo;
if (GetNode()->HasTagName(html_names::kDdTag))
return ax::mojom::blink::Role::kDefinition;
if (GetNode()->HasTagName(html_names::kDfnTag))
return ax::mojom::blink::Role::kTerm;
if (GetNode()->HasTagName(html_names::kDtTag))
return ax::mojom::blink::Role::kTerm;
// Mapping of MathML elements. See https://w3c.github.io/mathml-aam/
if (auto* element = DynamicTo<MathMLElement>(GetNode())) {
if (element->HasTagName(mathml_names::kMathTag)) {
return ax::mojom::blink::Role::kMathMLMath;
}
if (element->HasTagName(mathml_names::kMfracTag))
return ax::mojom::blink::Role::kMathMLFraction;
if (element->HasTagName(mathml_names::kMiTag))
return ax::mojom::blink::Role::kMathMLIdentifier;
if (element->HasTagName(mathml_names::kMmultiscriptsTag))
return ax::mojom::blink::Role::kMathMLMultiscripts;
if (element->HasTagName(mathml_names::kMnTag))
return ax::mojom::blink::Role::kMathMLNumber;
if (element->HasTagName(mathml_names::kMoTag))
return ax::mojom::blink::Role::kMathMLOperator;
if (element->HasTagName(mathml_names::kMoverTag))
return ax::mojom::blink::Role::kMathMLOver;
if (element->HasTagName(mathml_names::kMunderTag))
return ax::mojom::blink::Role::kMathMLUnder;
if (element->HasTagName(mathml_names::kMunderoverTag))
return ax::mojom::blink::Role::kMathMLUnderOver;
if (element->HasTagName(mathml_names::kMrootTag))
return ax::mojom::blink::Role::kMathMLRoot;
if (element->HasTagName(mathml_names::kMrowTag) ||
element->HasTagName(mathml_names::kAnnotationXmlTag) ||
element->HasTagName(mathml_names::kMactionTag) ||
element->HasTagName(mathml_names::kMerrorTag) ||
element->HasTagName(mathml_names::kMpaddedTag) ||
element->HasTagName(mathml_names::kMphantomTag) ||
element->HasTagName(mathml_names::kMstyleTag) ||
element->HasTagName(mathml_names::kSemanticsTag)) {
return ax::mojom::blink::Role::kMathMLRow;
}
if (element->HasTagName(mathml_names::kMprescriptsTag))
return ax::mojom::blink::Role::kMathMLPrescriptDelimiter;
if (element->HasTagName(mathml_names::kNoneTag))
return ax::mojom::blink::Role::kMathMLNoneScript;
if (element->HasTagName(mathml_names::kMsqrtTag))
return ax::mojom::blink::Role::kMathMLSquareRoot;
if (element->HasTagName(mathml_names::kMsTag))
return ax::mojom::blink::Role::kMathMLStringLiteral;
if (element->HasTagName(mathml_names::kMsubTag))
return ax::mojom::blink::Role::kMathMLSub;
if (element->HasTagName(mathml_names::kMsubsupTag))
return ax::mojom::blink::Role::kMathMLSubSup;
if (element->HasTagName(mathml_names::kMsupTag))
return ax::mojom::blink::Role::kMathMLSup;
if (element->HasTagName(mathml_names::kMtableTag))
return ax::mojom::blink::Role::kMathMLTable;
if (element->HasTagName(mathml_names::kMtdTag))
return ax::mojom::blink::Role::kMathMLTableCell;
if (element->HasTagName(mathml_names::kMtrTag))
return ax::mojom::blink::Role::kMathMLTableRow;
if (element->HasTagName(mathml_names::kMtextTag) ||
element->HasTagName(mathml_names::kAnnotationTag)) {
return ax::mojom::blink::Role::kMathMLText;
}
}
if (GetNode()->HasTagName(html_names::kRpTag) ||
GetNode()->HasTagName(html_names::kRtTag)) {
return ax::mojom::blink::Role::kRubyAnnotation;
}
if (IsA<HTMLFormElement>(*GetNode())) {
// Only treat <form> as role="form" when it has an accessible name, which
// can only occur when the name is assigned by the author via aria-label,
// aria-labelledby, or title. Otherwise, treat as a <section>.
return IsNameFromAuthorAttribute() ? ax::mojom::blink::Role::kForm
: ax::mojom::blink::Role::kSection;
}
if (GetNode()->HasTagName(html_names::kAbbrTag))
return ax::mojom::blink::Role::kAbbr;
if (GetNode()->HasTagName(html_names::kArticleTag))
return ax::mojom::blink::Role::kArticle;
if (GetNode()->HasTagName(html_names::kCodeTag))
return ax::mojom::blink::Role::kCode;
if (GetNode()->HasTagName(html_names::kEmTag))
return ax::mojom::blink::Role::kEmphasis;
if (GetNode()->HasTagName(html_names::kStrongTag))
return ax::mojom::blink::Role::kStrong;
if (GetNode()->HasTagName(html_names::kSearchTag)) {
return ax::mojom::blink::Role::kSearch;
}
if (GetNode()->HasTagName(html_names::kDelTag) ||
GetNode()->HasTagName(html_names::kSTag)) {
return ax::mojom::blink::Role::kContentDeletion;
}
if (GetNode()->HasTagName(html_names::kInsTag))
return ax::mojom::blink::Role::kContentInsertion;
if (GetNode()->HasTagName(html_names::kSubTag))
return ax::mojom::blink::Role::kSubscript;
if (GetNode()->HasTagName(html_names::kSupTag))
return ax::mojom::blink::Role::kSuperscript;
if (GetNode()->HasTagName(html_names::kMainTag))
return ax::mojom::blink::Role::kMain;
if (GetNode()->HasTagName(html_names::kMarkTag))
return ax::mojom::blink::Role::kMark;
if (GetNode()->HasTagName(html_names::kNavTag))
return ax::mojom::blink::Role::kNavigation;
if (GetNode()->HasTagName(html_names::kAsideTag))
return ax::mojom::blink::Role::kComplementary;
if (GetNode()->HasTagName(html_names::kSectionTag)) {
return ax::mojom::blink::Role::kSection;
}
if (GetNode()->HasTagName(html_names::kAddressTag))
return ax::mojom::blink::Role::kGroup;
if (GetNode()->HasTagName(html_names::kHgroupTag)) {
return ax::mojom::blink::Role::kGroup;
}
if (IsA<HTMLDialogElement>(*GetNode()))
return ax::mojom::blink::Role::kDialog;
// The HTML element.
if (IsA<HTMLHtmlElement>(GetNode()))
return ax::mojom::blink::Role::kGenericContainer;
// Treat <iframe>, <frame> and <fencedframe> the same.
if (IsFrame(GetNode()))
return ax::mojom::blink::Role::kIframe;
if (GetNode()->HasTagName(html_names::kHeaderTag)) {
return ax::mojom::blink::Role::kHeader;
}
if (GetNode()->HasTagName(html_names::kFooterTag)) {
return ax::mojom::blink::Role::kFooter;
}
if (GetNode()->HasTagName(html_names::kBlockquoteTag))
return ax::mojom::blink::Role::kBlockquote;
if (IsA<HTMLTableCaptionElement>(GetNode()))
return ax::mojom::blink::Role::kCaption;
if (GetNode()->HasTagName(html_names::kFigcaptionTag))
return ax::mojom::blink::Role::kFigcaption;
if (GetNode()->HasTagName(html_names::kFigureTag))
return ax::mojom::blink::Role::kFigure;
if (IsA<HTMLTimeElement>(GetNode()))
return ax::mojom::blink::Role::kTime;
if (IsA<HTMLPlugInElement>(GetNode())) {
if (IsA<HTMLEmbedElement>(GetNode()))
return ax::mojom::blink::Role::kEmbeddedObject;
return ax::mojom::blink::Role::kPluginObject;
}
if (IsA<HTMLHRElement>(*GetNode()))
return ax::mojom::blink::Role::kSplitter;
if (IsFieldset())
return ax::mojom::blink::Role::kGroup;
return RoleFromLayoutObjectOrNode();
}
ax::mojom::blink::Role AXNodeObject::DetermineRoleValue() {
#if DCHECK_IS_ON()
base::AutoReset<bool> reentrancy_protector(&is_computing_role_, true);
#endif
if (IsDetached()) {
NOTREACHED() << "Do not compute role on detached object: " << this;
}
native_role_ = NativeRoleIgnoringAria();
aria_role_ = DetermineAriaRole();
return aria_role_ == ax::mojom::blink::Role::kUnknown ? native_role_
: aria_role_;
}
static Element* SiblingWithAriaRole(String role, Node* node) {
Node* parent = LayoutTreeBuilderTraversal::Parent(*node);
if (!parent)
return nullptr;
for (Node* sibling = LayoutTreeBuilderTraversal::FirstChild(*parent); sibling;
sibling = LayoutTreeBuilderTraversal::NextSibling(*sibling)) {
auto* element = DynamicTo<Element>(sibling);
if (!element)
continue;
const AtomicString& sibling_aria_role =
blink::AXObject::AriaAttribute(*element, html_names::kRoleAttr);
if (EqualIgnoringASCIICase(sibling_aria_role, role))
return element;
}
return nullptr;
}
Element* AXNodeObject::MenuItemElementForMenu() const {
if (RawAriaRole() != ax::mojom::blink::Role::kMenu) {
return nullptr;
}
return SiblingWithAriaRole("menuitem", GetNode());
}
void AXNodeObject::Init(AXObject* parent) {
#if DCHECK_IS_ON()
DCHECK(!initialized_);
initialized_ = true;
#endif
AXObject::Init(parent);
DCHECK(role_ == native_role_ || role_ == aria_role_)
<< "Role must be either the cached native role or cached aria role: "
<< "\n* Final role: " << role_ << "\n* Native role: " << native_role_
<< "\n* Aria role: " << aria_role_ << "\n* Node: " << GetNode();
DCHECK(node_ || (GetLayoutObject() &&
AXObjectCacheImpl::IsRelevantPseudoElementDescendant(
*GetLayoutObject())))
<< "Nodeless AXNodeObject can only exist inside a pseudo element: "
<< GetLayoutObject();
}
void AXNodeObject::Detach() {
#if AX_FAIL_FAST_BUILD()
SANITIZER_CHECK(!is_adding_children_)
<< "Cannot detach |this| during AddChildren(): " << GetNode();
#endif
AXObject::Detach();
node_ = nullptr;
#if DCHECK_IS_ON()
if (layout_object_) {
layout_object_->SetHasAXObject(false);
}
#endif
layout_object_ = nullptr;
}
bool AXNodeObject::IsAXNodeObject() const {
return true;
}
bool AXNodeObject::IsControl() const {
Node* node = GetNode();
if (!node)
return false;
auto* element = DynamicTo<Element>(node);
return ((element && element->IsFormControlElement()) ||
ui::IsControl(RawAriaRole()));
}
bool AXNodeObject::IsAutofillAvailable() const {
// Autofill suggestion availability is stored in AXObjectCache.
WebAXAutofillSuggestionAvailability suggestion_availability =
AXObjectCache().GetAutofillSuggestionAvailability(AXObjectID());
return suggestion_availability ==
WebAXAutofillSuggestionAvailability::kAutofillAvailable;
}
bool AXNodeObject::IsDefault() const {
if (IsDetached())
return false;
// Checks for any kind of disabled, including aria-disabled.
if (Restriction() == kRestrictionDisabled ||
RoleValue() != ax::mojom::blink::Role::kButton) {
return false;
}
// Will only match :default pseudo class if it's the first default button in
// a form.
return GetElement()->MatchesDefaultPseudoClass();
}
bool AXNodeObject::IsFieldset() const {
return IsA<HTMLFieldSetElement>(GetNode());
}
bool AXNodeObject::IsHovered() const {
if (Node* node = GetNode())
return node->IsHovered();
return false;
}
bool AXNodeObject::IsImageButton() const {
return IsNativeImage() && IsButton();
}
bool AXNodeObject::IsInputImage() const {
auto* html_input_element = DynamicTo<HTMLInputElement>(GetNode());
if (html_input_element && RoleValue() == ax::mojom::blink::Role::kButton) {
return html_input_element->FormControlType() ==
FormControlType::kInputImage;
}
return false;
}
bool AXNodeObject::IsLineBreakingObject() const {
// According to Blink Editing, objects without an associated DOM node such as
// pseudo-elements and list bullets, are never considered as paragraph
// boundaries.
if (IsDetached() || !GetNode())
return false;
// Presentational objects should not contribute any of their semantic meaning
// to the accessibility tree, including to its text representation.
if (IsPresentational())
return false;
// `IsEnclosingBlock` includes all elements with display block, inline block,
// table related, flex, grid, list item, flow-root, webkit-box, and display
// contents. This is the same function used by Blink > Editing for determining
// paragraph boundaries, i.e. line breaking objects.
if (IsEnclosingBlock(GetNode()))
return true;
// Not all <br> elements have an associated layout object. They might be
// "visibility: hidden" or within a display locked region. We need to check
// their DOM node first.
if (IsA<HTMLBRElement>(GetNode()))
return true;
const LayoutObject* layout_object = GetLayoutObject();
if (!layout_object)
return AXObject::IsLineBreakingObject();
if (layout_object->IsBR())
return true;
// LayoutText objects could include a paragraph break in their text. This can
// only occur if line breaks are preserved and a newline character is present
// in their collapsed text. Text collapsing removes all whitespace found in
// the HTML file, but a special style rule could be used to preserve line
// breaks.
//
// The best example is the <pre> element:
// <pre>Line 1
// Line 2</pre>
if (const LayoutText* layout_text = DynamicTo<LayoutText>(layout_object)) {
const ComputedStyle& style = layout_object->StyleRef();
if (layout_text->HasNonCollapsedText() && style.ShouldPreserveBreaks() &&
layout_text->PlainText().find('\n') != WTF::kNotFound) {
return true;
}
}
// Rely on the ARIA role to figure out if this object is line breaking.
return AXObject::IsLineBreakingObject();
}
bool AXNodeObject::IsLoaded() const {
if (!GetDocument())
return false;
if (!GetDocument()->IsLoadCompleted())
return false;
// Check for a navigation API single-page app navigation in progress.
if (auto* window = GetDocument()->domWindow()) {
if (window->navigation()->HasNonDroppedOngoingNavigation())
return false;
}
return true;
}
bool AXNodeObject::IsMultiSelectable() const {
switch (RoleValue()) {
case ax::mojom::blink::Role::kGrid:
case ax::mojom::blink::Role::kTreeGrid:
case ax::mojom::blink::Role::kTree:
case ax::mojom::blink::Role::kListBox:
case ax::mojom::blink::Role::kTabList:
bool multiselectable;
if (AriaBooleanAttribute(html_names::kAriaMultiselectableAttr,
&multiselectable)) {
return multiselectable;
}
break;
default:
break;
}
auto* html_select_element = DynamicTo<HTMLSelectElement>(GetNode());
return html_select_element && html_select_element->IsMultiple();
}
bool AXNodeObject::IsNativeImage() const {
Node* node = GetNode();
if (!node)
return false;
if (IsA<HTMLImageElement>(*node) || IsA<HTMLPlugInElement>(*node))
return true;
if (const auto* input = DynamicTo<HTMLInputElement>(*node))
return input->FormControlType() == FormControlType::kInputImage;
return false;
}
bool AXNodeObject::IsVisible() const {
// Any descendant of a <select size=1> should be considered invisible if
// the select is collapsed.
if (RoleValue() == ax::mojom::blink::Role::kMenuListPopup) {
CHECK(parent_);
return parent_->IsExpanded() == kExpandedExpanded;
}
if (IsRoot()) {
return true;
}
// Anything else inside of a collapsed select is also invisible.
if (const AXObject* ax_select = ParentObject()->AncestorMenuList()) {
// If the select is invisible, so is everything inside of it.
if (!ax_select->IsVisible()) {
return false;
}
// Inside of a collapsed select:
// - The selected option's subtree is visible.
// - Everything else is invisible.
if (ax_select->IsExpanded() == kExpandedCollapsed) {
if (const AXObject* ax_option = AncestorMenuListOption()) {
return ax_option->IsSelected() == kSelectedStateTrue;
}
return false;
}
}
return AXObject::IsVisible();
}
bool AXNodeObject::IsLinked() const {
if (!IsLinkable(*this)) {
return false;
}
if (auto* anchor = DynamicTo<HTMLAnchorElementBase>(AnchorElement())) {
return !anchor->Href().IsEmpty();
}
return false;
}
bool AXNodeObject::IsVisited() const {
return GetLayoutObject() && GetLayoutObject()->Style()->IsLink() &&
GetLayoutObject()->Style()->InsideLink() ==
EInsideLink::kInsideVisitedLink;
}
bool AXNodeObject::IsProgressIndicator() const {
return RoleValue() == ax::mojom::blink::Role::kProgressIndicator;
}
bool AXNodeObject::IsSlider() const {
return RoleValue() == ax::mojom::blink::Role::kSlider;
}
bool AXNodeObject::IsSpinButton() const {
return RoleValue() == ax::mojom::blink::Role::kSpinButton;
}
bool AXNodeObject::IsNativeSlider() const {
if (const auto* input = DynamicTo<HTMLInputElement>(GetNode()))
return input->FormControlType() == FormControlType::kInputRange;
return false;
}
bool AXNodeObject::IsNativeSpinButton() const {
if (const auto* input = DynamicTo<HTMLInputElement>(GetNode()))
return input->FormControlType() == FormControlType::kInputNumber;
return false;
}
bool AXNodeObject::IsEmbeddingElement() const {
return ui::IsEmbeddingElement(native_role_);
}
bool AXNodeObject::IsClickable() const {
// Determine whether the element is clickable either because there is a
// mouse button handler or because it has a native element where click
// performs an action. Disabled nodes are never considered clickable.
// Note: we can't call |node->WillRespondToMouseClickEvents()| because that
// triggers a style recalc and can delete this.
// Treat mouse button listeners on the |window|, |document| as if they're on
// the |documentElement|.
if (GetNode() == GetDocument()->documentElement()) {
return GetNode()->HasAnyEventListeners(
event_util::MouseButtonEventTypes()) ||
GetDocument()->HasAnyEventListeners(
event_util::MouseButtonEventTypes()) ||
GetDocument()->domWindow()->HasAnyEventListeners(
event_util::MouseButtonEventTypes());
}
// Look for mouse listeners only on element nodes, e.g. skip text nodes.
const Element* element = GetElement();
if (!element)
return false;
if (IsDisabled())
return false;
if (element->HasAnyEventListeners(event_util::MouseButtonEventTypes()))
return true;
if (HasContentEditableAttributeSet())
return true;
// Certain user-agent shadow DOM elements are expected to be clickable but
// they do not have event listeners attached or a clickable native role. We
// whitelist them here.
if (element->ShadowPseudoId() ==
shadow_element_names::kPseudoCalendarPickerIndicator) {
return true;
}
// Only use native roles. For ARIA elements, require a click listener.
return ui::IsClickable(native_role_);
}
bool AXNodeObject::IsFocused() const {
if (!GetDocument())
return false;
// A web area is represented by the Document node in the DOM tree, which isn't
// focusable. Check instead if the frame's selection controller is focused.
if (IsWebArea() &&
GetDocument()->GetFrame()->Selection().FrameIsFocusedAndActive()) {
return true;
}
Element* focused_element = GetDocument()->FocusedElement();
return focused_element && focused_element == GetElement();
}
AccessibilitySelectedState AXNodeObject::IsSelected() const {
if (!GetNode() || !IsSubWidget()) {
return kSelectedStateUndefined;
}
// The aria-selected attribute overrides automatic behaviors.
bool is_selected;
if (AriaBooleanAttribute(html_names::kAriaSelectedAttr, &is_selected)) {
return is_selected ? kSelectedStateTrue : kSelectedStateFalse;
}
// The selection should only follow the focus when the aria-selected attribute
// is marked as required or implied for this element in the ARIA specs.
// If this object can't follow the focus, then we can't say that it's selected
// nor that it's not.
if (!ui::IsSelectRequiredOrImplicit(RoleValue()))
return kSelectedStateUndefined;
if (auto* option_element = DynamicTo<HTMLOptionElement>(GetNode())) {
if (!CanSetSelectedAttribute()) {
return kSelectedStateUndefined;
}
return (option_element->Selected()) ? kSelectedStateTrue
: kSelectedStateFalse;
}
// Selection follows focus, but ONLY in single selection containers, and only
// if aria-selected was not present to override.
return IsSelectedFromFocus() ? kSelectedStateTrue : kSelectedStateFalse;
}
bool AXNodeObject::IsSelectedFromFocusSupported() const {
// The selection should only follow the focus when the aria-selected attribute
// is marked as required or implied for this element in the ARIA specs.
// If this object can't follow the focus, then we can't say that it's selected
// nor that it's not.
// TODO(crbug.com/1143483): Consider allowing more roles.
if (!ui::IsSelectRequiredOrImplicit(RoleValue()))
return false;
// Selection follows focus only when in a single selection container.
const AXObject* container = ContainerWidget();
if (!container || container->IsMultiSelectable()) {
return false;
}
// Certain properties inside the container widget mean that implicit selection
// must be turned off.
if (!AXObjectCache().IsImplicitSelectionAllowed(container)) {
return false;
}
return true;
}
// In single selection containers, selection follows focus unless aria_selected
// is set to false. This is only valid for a subset of elements.
bool AXNodeObject::IsSelectedFromFocus() const {
// A tab item can also be selected if it is associated to a focused tabpanel
// via the aria-labelledby attribute.
if (IsTabItem() && IsSelectedFromFocusSupported() && IsTabItemSelected()) {
return true;
}
// If this object is not accessibility focused, then it is not selected from
// focus.
AXObject* focused_object = AXObjectCache().FocusedObject();
if (focused_object != this &&
(!focused_object || focused_object->ActiveDescendant() != this))
return false;
return IsSelectedFromFocusSupported();
}
// Returns true if the object is marked user-select:none
bool AXNodeObject::IsNotUserSelectable() const {
if (!GetLayoutObject()) {
return false;
}
if (IsA<PseudoElement>(GetClosestElement())) {
return true;
}
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style) {
return false;
}
return (style->UsedUserSelect() == EUserSelect::kNone);
}
bool AXNodeObject::IsTabItemSelected() const {
if (!IsTabItem() || !GetLayoutObject())
return false;
if (GetNode()->IsScrollMarkerPseudoElement()) {
return To<ScrollMarkerPseudoElement>(GetNode())->IsSelected();
}
Node* node = GetNode();
if (!node || !node->IsElementNode())
return false;
// The ARIA spec says a tab item can also be selected if it is aria-labeled by
// a tabpanel that has keyboard focus inside of it, or if a tabpanel in its
// aria-controls list has KB focus inside of it.
AXObject* focused_element = AXObjectCache().FocusedObject();
if (!focused_element)
return false;
DCHECK(GetElement());
const GCedHeapVector<Member<Element>>* elements =
AXObject::ElementsFromAttributeOrInternals(GetElement(),
html_names::kAriaControlsAttr);
if (!elements) {
return false;
}
for (const auto& element : *elements) {
AXObject* tab_panel = AXObjectCache().Get(element);
// A tab item should only control tab panels.
if (!tab_panel ||
tab_panel->RoleValue() != ax::mojom::blink::Role::kTabPanel) {
continue;
}
AXObject* check_focus_element = focused_element;
// Check if the focused element is a descendant of the element controlled by
// the tab item.
while (check_focus_element) {
if (tab_panel == check_focus_element)
return true;
check_focus_element = check_focus_element->ParentObject();
}
}
return false;
}
AXRestriction AXNodeObject::Restriction() const {
Element* elem = GetElement();
if (!elem)
return kRestrictionNone;
// An <optgroup> is not exposed directly in the AX tree.
if (IsA<HTMLOptGroupElement>(elem))
return kRestrictionNone;
// According to ARIA, all elements of the base markup can be disabled.
// According to CORE-AAM, any focusable descendant of aria-disabled
// ancestor is also disabled.
if (IsDisabled())
return kRestrictionDisabled;
// Only editable fields can be marked @readonly (unlike @aria-readonly).
auto* text_area_element = DynamicTo<HTMLTextAreaElement>(*elem);
if (text_area_element && text_area_element->IsReadOnly())
return kRestrictionReadOnly;
if (const auto* input = DynamicTo<HTMLInputElement>(*elem)) {
if (input->IsTextField() && input->IsReadOnly())
return kRestrictionReadOnly;
}
// Check aria-readonly if supported by current role.
bool is_read_only;
if (SupportsARIAReadOnly() &&
AriaBooleanAttribute(html_names::kAriaReadonlyAttr, &is_read_only)) {
// ARIA overrides other readonly state markup.
return is_read_only ? kRestrictionReadOnly : kRestrictionNone;
}
// If a grid cell does not have it's own ARIA input restriction,
// fall back on parent grid's readonly state.
// See ARIA specification regarding grid/treegrid and readonly.
if (IsTableCellLikeRole()) {
AXObject* row = ParentObjectUnignored();
if (row && row->IsTableRowLikeRole()) {
AXObject* table = row->ParentObjectUnignored();
if (table && table->IsTableLikeRole() &&
(table->RoleValue() == ax::mojom::blink::Role::kGrid ||
table->RoleValue() == ax::mojom::blink::Role::kTreeGrid)) {
if (table->Restriction() == kRestrictionReadOnly)
return kRestrictionReadOnly;
}
}
}
// This is a node that is not readonly and not disabled.
return kRestrictionNone;
}
AccessibilityExpanded AXNodeObject::IsExpanded() const {
if (!SupportsARIAExpanded())
return kExpandedUndefined;
auto* element = GetElement();
if (!element)
return kExpandedUndefined;
if (RoleValue() == ax::mojom::blink::Role::kComboBoxSelect) {
DCHECK(IsA<HTMLSelectElement>(element));
bool is_expanded = To<HTMLSelectElement>(element)->PopupIsVisible();
return is_expanded ? kExpandedExpanded : kExpandedCollapsed;
}
// For button elements that act as commandFor triggers, aria-expanded may be
// set depending on the command type. This results in the same mapping as
// popovertarget, but takes precedence in the case of conflicting markup as
// the HTML spec invokers commandfor functionality first, and only
// popovertarget after, if commandfor was not executed.
if (RuntimeEnabledFeatures::HTMLCommandAttributesEnabled()) {
if (auto* button = DynamicTo<HTMLButtonElement>(element)) {
const AtomicString& action =
button->FastGetAttribute(html_names::kCommandAttr);
CommandEventType type = button->GetCommandEventType(action);
if (HTMLElement* command_for =
DynamicTo<HTMLElement>(button->commandForElement())) {
bool is_valid_popover_command =
command_for->IsValidBuiltinPopoverCommand(*button, type);
bool is_child = button->IsDescendantOrShadowDescendantOf(command_for);
// Buttons for popovers should indicate the expanded/collapsed state.
if (is_valid_popover_command && !is_child) {
return command_for->popoverOpen() ? kExpandedExpanded
: kExpandedCollapsed;
}
}
}
}
// For form controls that act as triggering elements for popovers, then set
// aria-expanded=false when the popover is hidden, and aria-expanded=true when
// it is showing.
if (auto* form_control = DynamicTo<HTMLFormControlElement>(element)) {
if (auto popover = form_control->popoverTargetElement().popover) {
if (!form_control->IsDescendantOrShadowDescendantOf(popover)) {
// Only expose expanded/collapsed if the trigger button isn't contained
// within the popover itself. E.g. a close button within the popover.
return popover->popoverOpen() ? kExpandedExpanded : kExpandedCollapsed;
}
}
}
if (IsA<HTMLSummaryElement>(*element)) {
if (element->parentNode() &&
IsA<HTMLDetailsElement>(element->parentNode())) {
return To<Element>(element->parentNode())
->FastHasAttribute(html_names::kOpenAttr)
? kExpandedExpanded
: kExpandedCollapsed;
}
}
bool expanded = false;
if (AriaBooleanAttribute(html_names::kAriaExpandedAttr, &expanded)) {
return expanded ? kExpandedExpanded : kExpandedCollapsed;
}
return kExpandedUndefined;
}
bool AXNodeObject::IsRequired() const {
auto* form_control = DynamicTo<HTMLFormControlElement>(GetNode());
if (form_control && form_control->IsRequired())
return true;
if (IsAriaAttributeTrue(html_names::kAriaRequiredAttr)) {
return true;
}
return false;
}
bool AXNodeObject::CanvasHasFallbackContent() const {
if (IsDetached())
return false;
Node* node = GetNode();
return IsA<HTMLCanvasElement>(node) && node->hasChildren();
}
int AXNodeObject::HeadingLevel() const {
// headings can be in block flow and non-block flow
Node* node = GetNode();
if (!node)
return 0;
if (RoleValue() == ax::mojom::blink::Role::kHeading) {
int32_t level;
if (AriaIntAttribute(html_names::kAriaLevelAttr, &level)) {
if (level >= 1 && level <= 9) {
return level;
}
}
}
auto* element = DynamicTo<HTMLElement>(node);
if (!element)
return 0;
if (element->HasTagName(html_names::kH1Tag))
return 1 + element->GetComputedHeadingOffset(/*max_offset=*/8);
if (element->HasTagName(html_names::kH2Tag))
return 2 + element->GetComputedHeadingOffset(/*max_offset=*/7);
if (element->HasTagName(html_names::kH3Tag))
return 3 + element->GetComputedHeadingOffset(/*max_offset=*/6);
if (element->HasTagName(html_names::kH4Tag))
return 4 + element->GetComputedHeadingOffset(/*max_offset=*/5);
if (element->HasTagName(html_names::kH5Tag))
return 5 + element->GetComputedHeadingOffset(/*max_offset=*/4);
if (element->HasTagName(html_names::kH6Tag))
return 6 + element->GetComputedHeadingOffset(/*max_offset=*/3);
if (RoleValue() == ax::mojom::blink::Role::kHeading)
return kDefaultHeadingLevel;
// TODO(accessibility) For kDisclosureTriangle, kDisclosureTriangleGrouping,
// if IsAccessibilityExposeSummaryAsHeadingEnabled(), we should expose
// a default heading level that makes sense in the context of the document.
// Will likely be easier to do on the browser side.
if (ui::IsHeading(RoleValue())) {
return 5;
}
return 0;
}
unsigned AXNodeObject::HierarchicalLevel() const {
Element* element = GetElement();
if (!element)
return 0;
int32_t level;
if (AriaIntAttribute(html_names::kAriaLevelAttr, &level)) {
if (level >= 1)
return level;
}
// Helper lambda for calculating hierarchical levels by counting ancestor
// nodes that match a target role.
auto accumulateLevel = [&](int initial_level,
ax::mojom::blink::Role target_role) {
int level = initial_level;
for (AXObject* parent = ParentObject(); parent;
parent = parent->ParentObject()) {
if (parent->RoleValue() == target_role)
level++;
}
return level;
};
switch (RoleValue()) {
case ax::mojom::blink::Role::kComment:
// Comment: level is based on counting comment ancestors until the root.
return accumulateLevel(1, ax::mojom::blink::Role::kComment);
case ax::mojom::blink::Role::kListItem:
level = accumulateLevel(0, ax::mojom::blink::Role::kList);
// When level count is 0 due to this list item not having an ancestor of
// Role::kList, not nested in list groups, this list item has a level
// of 1.
return level == 0 ? 1 : level;
case ax::mojom::blink::Role::kTabList:
return accumulateLevel(1, ax::mojom::blink::Role::kTabList);
case ax::mojom::blink::Role::kTreeItem: {
// Hierarchy leveling starts at 1, to match the aria-level spec.
// We measure tree hierarchy by the number of groups that the item is
// within.
level = 1;
for (AXObject* parent = ParentObject(); parent;
parent = parent->ParentObject()) {
ax::mojom::blink::Role parent_role = parent->RoleValue();
if (parent_role == ax::mojom::blink::Role::kGroup)
level++;
else if (parent_role == ax::mojom::blink::Role::kTree)
break;
}
return level;
}
default:
return 0;
}
}
String AXNodeObject::AutoComplete() const {
// Check cache for auto complete state.
if (AXObjectCache().GetAutofillSuggestionAvailability(AXObjectID()) ==
WebAXAutofillSuggestionAvailability::kAutocompleteAvailable) {
return "list";
}
if (IsAtomicTextField() || IsARIATextField()) {
const AtomicString& aria_auto_complete =
AriaTokenAttribute(html_names::kAriaAutocompleteAttr);
// Illegal values must be passed through, according to CORE-AAM.
if (aria_auto_complete) {
return aria_auto_complete == "none" ? String()
: aria_auto_complete.LowerASCII();
;
}
}
if (auto* input = DynamicTo<HTMLInputElement>(GetNode())) {
if (input->DataList())
return "list";
}
return String();
}
// TODO(nektar): Consider removing this method in favor of
// AXInlineTextBox::GetDocumentMarkers, or add document markers to the tree data
// instead of nodes objects.
void AXNodeObject::SerializeMarkerAttributes(ui::AXNodeData* node_data) const {
if (!GetNode() || !GetDocument() || !GetDocument()->View())
return;
auto* text_node = DynamicTo<Text>(GetNode());
if (!text_node)
return;
std::vector<int32_t> marker_types;
std::vector<int32_t> highlight_types;
std::vector<int32_t> marker_starts;
std::vector<int32_t> marker_ends;
// First use ARIA markers for spelling/grammar if available.
std::optional<DocumentMarker::MarkerType> aria_marker_type =
GetAriaSpellingOrGrammarMarker();
if (aria_marker_type) {
AXRange range = AXRange::RangeOfContents(*this);
marker_types.push_back(ToAXMarkerType(aria_marker_type.value()));
marker_starts.push_back(range.Start().TextOffset());
marker_ends.push_back(range.End().TextOffset());
}
DocumentMarkerController& marker_controller = GetDocument()->Markers();
const DocumentMarker::MarkerTypes markers_used_by_accessibility(
DocumentMarker::kSpelling | DocumentMarker::kGrammar |
DocumentMarker::kTextMatch | DocumentMarker::kActiveSuggestion |
DocumentMarker::kSuggestion | DocumentMarker::kTextFragment |
DocumentMarker::kCustomHighlight);
const DocumentMarkerVector markers =
marker_controller.MarkersFor(*text_node, markers_used_by_accessibility);
for (const DocumentMarker* marker : markers) {
if (aria_marker_type == marker->GetType())
continue;
const Position start_position(*GetNode(), marker->StartOffset());
const Position end_position(*GetNode(), marker->EndOffset());
if (!start_position.IsValidFor(*GetDocument()) ||
!end_position.IsValidFor(*GetDocument())) {
continue;
}
int32_t highlight_type =
static_cast<int32_t>(ax::mojom::blink::HighlightType::kNone);
if (marker->GetType() == DocumentMarker::kCustomHighlight) {
const auto& highlight_marker = To<CustomHighlightMarker>(*marker);
highlight_type =
ToAXHighlightType(highlight_marker.GetHighlight()->type());
}
marker_types.push_back(ToAXMarkerType(marker->GetType()));
highlight_types.push_back(static_cast<int32_t>(highlight_type));
auto start_pos = AXPosition::FromPosition(
start_position, AXObjectCache(), TextAffinity::kDownstream,
AXPositionAdjustmentBehavior::kMoveLeft);
auto end_pos = AXPosition::FromPosition(
end_position, AXObjectCache(), TextAffinity::kDownstream,
AXPositionAdjustmentBehavior::kMoveRight);
marker_starts.push_back(start_pos.TextOffset());
marker_ends.push_back(end_pos.TextOffset());
}
if (marker_types.empty())
return;
node_data->AddIntListAttribute(
ax::mojom::blink::IntListAttribute::kMarkerTypes, marker_types);
node_data->AddIntListAttribute(
ax::mojom::blink::IntListAttribute::kHighlightTypes, highlight_types);
node_data->AddIntListAttribute(
ax::mojom::blink::IntListAttribute::kMarkerStarts, marker_starts);
node_data->AddIntListAttribute(
ax::mojom::blink::IntListAttribute::kMarkerEnds, marker_ends);
}
ax::mojom::blink::ListStyle AXNodeObject::GetListStyle() const {
const LayoutObject* layout_object = GetLayoutObject();
if (!layout_object) {
return AXObject::GetListStyle();
}
const ComputedStyle* computed_style = layout_object->Style();
if (!computed_style) {
return AXObject::GetListStyle();
}
const StyleImage* style_image = computed_style->ListStyleImage();
if (style_image && !style_image->ErrorOccurred()) {
return ax::mojom::blink::ListStyle::kImage;
}
if (RuntimeEnabledFeatures::CSSAtRuleCounterStyleSpeakAsDescriptorEnabled()) {
if (!computed_style->ListStyleType()) {
return ax::mojom::blink::ListStyle::kNone;
}
if (computed_style->ListStyleType()->IsString()) {
return ax::mojom::blink::ListStyle::kOther;
}
DCHECK(computed_style->ListStyleType()->IsCounterStyle());
const CounterStyle& counter_style =
ListMarker::GetCounterStyle(*GetDocument(), *computed_style);
switch (counter_style.EffectiveSpeakAs()) {
case CounterStyleSpeakAs::kBullets: {
// See |ua_counter_style_map.cc| for predefined symbolic counter styles.
UChar symbol = counter_style.GenerateTextAlternative(0)[0];
switch (symbol) {
case 0x2022:
return ax::mojom::blink::ListStyle::kDisc;
case 0x25E6:
return ax::mojom::blink::ListStyle::kCircle;
case 0x25A0:
return ax::mojom::blink::ListStyle::kSquare;
default:
return ax::mojom::blink::ListStyle::kOther;
}
}
case CounterStyleSpeakAs::kNumbers:
return ax::mojom::blink::ListStyle::kNumeric;
case CounterStyleSpeakAs::kWords:
return ax::mojom::blink::ListStyle::kOther;
case CounterStyleSpeakAs::kAuto:
case CounterStyleSpeakAs::kReference:
NOTREACHED();
}
}
switch (ListMarker::GetListStyleCategory(*GetDocument(), *computed_style)) {
case ListMarker::ListStyleCategory::kNone:
return ax::mojom::blink::ListStyle::kNone;
case ListMarker::ListStyleCategory::kSymbol: {
const AtomicString& counter_style_name =
computed_style->ListStyleType()->GetCounterStyleName();
if (counter_style_name == keywords::kDisc) {
return ax::mojom::blink::ListStyle::kDisc;
}
if (counter_style_name == keywords::kCircle) {
return ax::mojom::blink::ListStyle::kCircle;
}
if (counter_style_name == keywords::kSquare) {
return ax::mojom::blink::ListStyle::kSquare;
}
return ax::mojom::blink::ListStyle::kOther;
}
case ListMarker::ListStyleCategory::kLanguage: {
const AtomicString& counter_style_name =
computed_style->ListStyleType()->GetCounterStyleName();
if (counter_style_name == keywords::kDecimal) {
return ax::mojom::blink::ListStyle::kNumeric;
}
if (counter_style_name == "decimal-leading-zero") {
// 'decimal-leading-zero' may be overridden by custom counter styles. We
// return kNumeric only when we are using the predefined counter style.
if (ListMarker::GetCounterStyle(*GetDocument(), *computed_style)
.IsPredefined()) {
return ax::mojom::blink::ListStyle::kNumeric;
}
}
return ax::mojom::blink::ListStyle::kOther;
}
case ListMarker::ListStyleCategory::kStaticString:
return ax::mojom::blink::ListStyle::kOther;
}
}
AXObject* AXNodeObject::InPageLinkTarget() const {
if (!IsLink() || !GetDocument())
return AXObject::InPageLinkTarget();
const Element* anchor = AnchorElement();
if (!anchor)
return AXObject::InPageLinkTarget();
KURL link_url = anchor->HrefURL();
if (!link_url.IsValid())
return AXObject::InPageLinkTarget();
KURL document_url = GetDocument()->Url();
if (!document_url.IsValid() ||
!EqualIgnoringFragmentIdentifier(document_url, link_url)) {
return AXObject::InPageLinkTarget();
}
String fragment = link_url.FragmentIdentifier().ToString();
TreeScope& tree_scope = anchor->GetTreeScope();
Node* target = tree_scope.FindAnchor(fragment);
AXObject* ax_target = AXObjectCache().Get(target);
if (!ax_target || !IsPotentialInPageLinkTarget(*ax_target->GetNode()))
return AXObject::InPageLinkTarget();
#if DCHECK_IS_ON()
// Link targets always have an element, unless it is the document itself,
// e.g. via <a href="#">.
DCHECK(ax_target->IsWebArea() || ax_target->GetElement())
<< "The link target is expected to be a document or an element: "
<< ax_target << "\n* URL fragment = " << fragment;
#endif
// Usually won't be ignored, but could be e.g. if aria-hidden.
if (ax_target->IsIgnored())
return nullptr;
return ax_target;
}
const AtomicString& AXNodeObject::EffectiveTarget() const {
// The "target" attribute defines the target browser context and is supported
// on <a>, <area>, <base>, and <form>. Valid values are: "frame_name", "self",
// "blank", "top", and "parent", where "frame_name" is the value of the "name"
// attribute on any enclosing iframe.
//
// <area> is a subclass of <a>, while <base> provides the document's base
// target that any <a>'s or any <area>'s target can override.
// `HtmlAnchorElement::GetEffectiveTarget()` will take <base> into account.
//
// <form> is out of scope, because it affects the target to which the form is
// submitted, and could also be overridden by a "formTarget" attribute on e.g.
// a form's submit button. However, screen reader users have no need to know
// to which target (browser context) a form would be submitted.
const auto* anchor = DynamicTo<HTMLAnchorElementBase>(GetNode());
if (anchor) {
const AtomicString self_value("_self");
const AtomicString& effective_target = anchor->GetEffectiveTarget();
if (effective_target != self_value) {
return anchor->GetEffectiveTarget();
}
}
return AXObject::EffectiveTarget();
}
AccessibilityOrientation AXNodeObject::Orientation() const {
const AtomicString& aria_orientation =
AriaTokenAttribute(html_names::kAriaOrientationAttr);
AccessibilityOrientation orientation = kAccessibilityOrientationUndefined;
if (EqualIgnoringASCIICase(aria_orientation, "horizontal"))
orientation = kAccessibilityOrientationHorizontal;
else if (EqualIgnoringASCIICase(aria_orientation, "vertical"))
orientation = kAccessibilityOrientationVertical;
switch (RoleValue()) {
case ax::mojom::blink::Role::kListBox:
case ax::mojom::blink::Role::kMenu:
case ax::mojom::blink::Role::kScrollBar:
case ax::mojom::blink::Role::kTree:
if (orientation == kAccessibilityOrientationUndefined)
orientation = kAccessibilityOrientationVertical;
return orientation;
case ax::mojom::blink::Role::kMenuBar:
case ax::mojom::blink::Role::kSlider:
case ax::mojom::blink::Role::kSplitter:
case ax::mojom::blink::Role::kTabList:
case ax::mojom::blink::Role::kToolbar:
if (orientation == kAccessibilityOrientationUndefined)
orientation = kAccessibilityOrientationHorizontal;
return orientation;
case ax::mojom::blink::Role::kComboBoxGrouping:
case ax::mojom::blink::Role::kComboBoxMenuButton:
case ax::mojom::blink::Role::kRadioGroup:
case ax::mojom::blink::Role::kTreeGrid:
return orientation;
default:
return AXObject::Orientation();
}
}
// According to the standard, the figcaption should only be the first or
// last child: https://html.spec.whatwg.org/#the-figcaption-element
AXObject* AXNodeObject::GetChildFigcaption() const {
AXObject* child = FirstChildIncludingIgnored();
if (!child)
return nullptr;
if (child->RoleValue() == ax::mojom::blink::Role::kFigcaption)
return child;
child = LastChildIncludingIgnored();
if (child->RoleValue() == ax::mojom::blink::Role::kFigcaption)
return child;
return nullptr;
}
AXObject::AXObjectVector AXNodeObject::RadioButtonsInGroup() const {
AXObjectVector radio_buttons;
if (!node_ || RoleValue() != ax::mojom::blink::Role::kRadioButton)
return radio_buttons;
if (auto* node_radio_button = DynamicTo<HTMLInputElement>(node_.Get())) {
HeapVector<Member<HTMLInputElement>> html_radio_buttons =
FindAllRadioButtonsWithSameName(node_radio_button);
for (HTMLInputElement* radio_button : html_radio_buttons) {
AXObject* ax_radio_button = AXObjectCache().Get(radio_button);
if (ax_radio_button)
radio_buttons.push_back(ax_radio_button);
}
return radio_buttons;
}
// If the immediate parent is a radio group, return all its children that are
// radio buttons.
AXObject* parent = ParentObjectUnignored();
if (parent && parent->RoleValue() == ax::mojom::blink::Role::kRadioGroup) {
for (AXObject* child : parent->UnignoredChildren()) {
DCHECK(child);
if (child->RoleValue() == ax::mojom::blink::Role::kRadioButton &&
child->IsIncludedInTree()) {
radio_buttons.push_back(child);
}
}
}
return radio_buttons;
}
// static
HeapVector<Member<HTMLInputElement>>
AXNodeObject::FindAllRadioButtonsWithSameName(HTMLInputElement* radio_button) {
HeapVector<Member<HTMLInputElement>> all_radio_buttons;
if (!radio_button ||
radio_button->FormControlType() != FormControlType::kInputRadio) {
return all_radio_buttons;
}
constexpr bool kTraverseForward = true;
constexpr bool kTraverseBackward = false;
HTMLInputElement* first_radio_button = radio_button;
do {
radio_button = RadioInputType::NextRadioButtonInGroup(first_radio_button,
kTraverseBackward);
if (radio_button)
first_radio_button = radio_button;
} while (radio_button);
HTMLInputElement* next_radio_button = first_radio_button;
do {
all_radio_buttons.push_back(next_radio_button);
next_radio_button = RadioInputType::NextRadioButtonInGroup(
next_radio_button, kTraverseForward);
} while (next_radio_button);
return all_radio_buttons;
}
ax::mojom::blink::WritingDirection AXNodeObject::GetTextDirection() const {
if (!GetLayoutObject())
return AXObject::GetTextDirection();
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return AXObject::GetTextDirection();
switch (style->GetWritingDirection().InlineEnd()) {
case PhysicalDirection::kRight:
return ax::mojom::blink::WritingDirection::kLtr;
case PhysicalDirection::kLeft:
return ax::mojom::blink::WritingDirection::kRtl;
case PhysicalDirection::kDown:
return ax::mojom::blink::WritingDirection::kTtb;
case PhysicalDirection::kUp:
return ax::mojom::blink::WritingDirection::kBtt;
}
NOTREACHED();
}
ax::mojom::blink::TextPosition AXNodeObject::GetTextPositionFromRole() const {
// Check for role="subscript" or role="superscript" on the element, or if
// static text, on the containing element.
AXObject* obj = nullptr;
if (RoleValue() == ax::mojom::blink::Role::kStaticText)
obj = ParentObject();
else
obj = const_cast<AXNodeObject*>(this);
if (obj->RoleValue() == ax::mojom::blink::Role::kSubscript)
return ax::mojom::blink::TextPosition::kSubscript;
if (obj->RoleValue() == ax::mojom::blink::Role::kSuperscript)
return ax::mojom::blink::TextPosition::kSuperscript;
if (!GetLayoutObject() || !GetLayoutObject()->IsInline())
return ax::mojom::blink::TextPosition::kNone;
// We could have an inline element which descends from a subscript or
// superscript.
if (auto* parent = obj->ParentObjectUnignored())
return static_cast<AXNodeObject*>(parent)->GetTextPositionFromRole();
return ax::mojom::blink::TextPosition::kNone;
}
ax::mojom::blink::TextPosition AXNodeObject::GetTextPosition() const {
if (GetNode()) {
const auto& text_position = GetTextPositionFromRole();
if (text_position != ax::mojom::blink::TextPosition::kNone)
return text_position;
}
if (!GetLayoutObject())
return AXObject::GetTextPosition();
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return AXObject::GetTextPosition();
switch (style->VerticalAlign()) {
case EVerticalAlign::kBaseline:
case EVerticalAlign::kMiddle:
case EVerticalAlign::kTextTop:
case EVerticalAlign::kTextBottom:
case EVerticalAlign::kTop:
case EVerticalAlign::kBottom:
case EVerticalAlign::kBaselineMiddle:
case EVerticalAlign::kLength:
return AXObject::GetTextPosition();
case EVerticalAlign::kSub:
return ax::mojom::blink::TextPosition::kSubscript;
case EVerticalAlign::kSuper:
return ax::mojom::blink::TextPosition::kSuperscript;
}
}
void AXNodeObject::GetTextStyleAndTextDecorationStyle(
int32_t* text_style,
ax::mojom::blink::TextDecorationStyle* text_overline_style,
ax::mojom::blink::TextDecorationStyle* text_strikethrough_style,
ax::mojom::blink::TextDecorationStyle* text_underline_style) const {
if (!GetLayoutObject()) {
AXObject::GetTextStyleAndTextDecorationStyle(
text_style, text_overline_style, text_strikethrough_style,
text_underline_style);
return;
}
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style) {
AXObject::GetTextStyleAndTextDecorationStyle(
text_style, text_overline_style, text_strikethrough_style,
text_underline_style);
return;
}
*text_style = 0;
*text_overline_style = ax::mojom::blink::TextDecorationStyle::kNone;
*text_strikethrough_style = ax::mojom::blink::TextDecorationStyle::kNone;
*text_underline_style = ax::mojom::blink::TextDecorationStyle::kNone;
if (style->GetFontWeight() == kBoldWeightValue) {
*text_style |= TextStyleFlag(ax::mojom::blink::TextStyle::kBold);
}
if (style->GetFontDescription().Style() == kItalicSlopeValue) {
*text_style |= TextStyleFlag(ax::mojom::blink::TextStyle::kItalic);
}
for (const auto& decoration : style->AppliedTextDecorations()) {
if (EnumHasFlags(decoration.Lines(), TextDecorationLine::kOverline)) {
*text_style |= TextStyleFlag(ax::mojom::blink::TextStyle::kOverline);
*text_overline_style =
TextDecorationStyleToAXTextDecorationStyle(decoration.Style());
}
if (EnumHasFlags(decoration.Lines(), TextDecorationLine::kLineThrough)) {
*text_style |= TextStyleFlag(ax::mojom::blink::TextStyle::kLineThrough);
*text_strikethrough_style =
TextDecorationStyleToAXTextDecorationStyle(decoration.Style());
}
if (EnumHasFlags(decoration.Lines(), TextDecorationLine::kUnderline)) {
*text_style |= TextStyleFlag(ax::mojom::blink::TextStyle::kUnderline);
*text_underline_style =
TextDecorationStyleToAXTextDecorationStyle(decoration.Style());
}
}
}
ax::mojom::blink::TextAlign AXNodeObject::GetTextAlign() const {
// Object attributes are not applied to text objects.
if (IsTextObject() || !GetLayoutObject())
return ax::mojom::blink::TextAlign::kNone;
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return ax::mojom::blink::TextAlign::kNone;
switch (style->GetTextAlign()) {
case ETextAlign::kLeft:
case ETextAlign::kWebkitLeft:
case ETextAlign::kStart:
return ax::mojom::blink::TextAlign::kLeft;
case ETextAlign::kRight:
case ETextAlign::kWebkitRight:
case ETextAlign::kEnd:
return ax::mojom::blink::TextAlign::kRight;
case ETextAlign::kCenter:
case ETextAlign::kWebkitCenter:
return ax::mojom::blink::TextAlign::kCenter;
case ETextAlign::kJustify:
return ax::mojom::blink::TextAlign::kJustify;
}
}
float AXNodeObject::GetTextIndent() const {
// Text-indent applies to lines or blocks, but not text.
if (IsTextObject() || !GetLayoutObject())
return 0.0f;
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return 0.0f;
const blink::LayoutBlock* layout_block =
GetLayoutObject()->InclusiveContainingBlock();
if (!layout_block)
return 0.0f;
float text_indent = layout_block->TextIndentOffset().ToFloat();
return text_indent / kCssPixelsPerMillimeter;
}
String AXNodeObject::ImageDataUrl(const gfx::Size& max_size) const {
Node* node = GetNode();
if (!node)
return String();
ImageBitmapOptions* options = ImageBitmapOptions::Create();
ImageBitmap* image_bitmap = nullptr;
if (auto* image = DynamicTo<HTMLImageElement>(node)) {
image_bitmap =
MakeGarbageCollected<ImageBitmap>(image, std::nullopt, options);
} else if (auto* canvas = DynamicTo<HTMLCanvasElement>(node)) {
image_bitmap =
MakeGarbageCollected<ImageBitmap>(canvas, std::nullopt, options);
} else if (auto* video = DynamicTo<HTMLVideoElement>(node)) {
image_bitmap =
MakeGarbageCollected<ImageBitmap>(video, std::nullopt, options);
}
if (!image_bitmap)
return String();
scoped_refptr<StaticBitmapImage> bitmap_image = image_bitmap->BitmapImage();
if (!bitmap_image)
return String();
sk_sp<SkImage> image =
bitmap_image->PaintImageForCurrentFrame().GetSwSkImage();
if (!image || image->width() <= 0 || image->height() <= 0)
return String();
// Determine the width and height of the output image, using a proportional
// scale factor such that it's no larger than |maxSize|, if |maxSize| is not
// empty. It only resizes the image to be smaller (if necessary), not
// larger.
float x_scale =
max_size.width() ? max_size.width() * 1.0 / image->width() : 1.0;
float y_scale =
max_size.height() ? max_size.height() * 1.0 / image->height() : 1.0;
float scale = std::min(x_scale, y_scale);
if (scale >= 1.0)
scale = 1.0;
int width = std::round(image->width() * scale);
int height = std::round(image->height() * scale);
// Draw the image into a bitmap in native format.
SkBitmap bitmap;
SkPixmap unscaled_pixmap;
if (scale == 1.0 && image->peekPixels(&unscaled_pixmap)) {
bitmap.installPixels(unscaled_pixmap);
} else {
bitmap.allocPixels(
SkImageInfo::MakeN32(width, height, kPremul_SkAlphaType));
SkCanvas canvas(bitmap, SkSurfaceProps{});
canvas.clear(SK_ColorTRANSPARENT);
canvas.drawImageRect(image, SkRect::MakeIWH(width, height),
SkSamplingOptions());
}
// Copy the bits into a buffer in RGBA_8888 unpremultiplied format
// for encoding.
SkImageInfo info = SkImageInfo::Make(width, height, kRGBA_8888_SkColorType,
kUnpremul_SkAlphaType);
size_t row_bytes = info.minRowBytes();
Vector<char> pixel_storage(
base::checked_cast<wtf_size_t>(info.computeByteSize(row_bytes)));
SkPixmap pixmap(info, pixel_storage.data(), row_bytes);
if (!SkImages::RasterFromBitmap(bitmap)->readPixels(pixmap, 0, 0)) {
return String();
}
// Encode as a PNG and return as a data url.
std::unique_ptr<ImageDataBuffer> buffer = ImageDataBuffer::Create(pixmap);
if (!buffer)
return String();
return buffer->ToDataURL(kMimeTypePng, 1.0);
}
const AtomicString& AXNodeObject::AccessKey() const {
auto* element = DynamicTo<Element>(GetNode());
if (!element)
return g_null_atom;
return element->FastGetAttribute(html_names::kAccesskeyAttr);
}
RGBA32 AXNodeObject::ColorValue() const {
auto* input = DynamicTo<HTMLInputElement>(GetNode());
if (!input || !IsColorWell())
return AXObject::ColorValue();
const AtomicString& type = input->getAttribute(kTypeAttr);
if (!EqualIgnoringASCIICase(type, "color"))
return AXObject::ColorValue();
// HTMLInputElement::Value always returns a string parseable by Color.
Color color;
bool success = color.SetFromString(input->Value());
DCHECK(success);
return color.Rgb();
}
RGBA32 AXNodeObject::BackgroundColor() const {
LayoutObject* layout_object = GetLayoutObject();
if (!layout_object)
return Color::kTransparent.Rgb();
if (IsA<Document>(GetNode())) {
LocalFrameView* view = DocumentFrameView();
if (view)
return view->BaseBackgroundColor().Rgb();
else
return Color::kWhite.Rgb();
}
const ComputedStyle* style = layout_object->Style();
if (!style || !style->HasBackground())
return Color::kTransparent.Rgb();
return style->VisitedDependentColor(GetCSSPropertyBackgroundColor()).Rgb();
}
RGBA32 AXNodeObject::GetColor() const {
if (!GetLayoutObject() || IsColorWell())
return AXObject::GetColor();
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return AXObject::GetColor();
Color color = style->VisitedDependentColor(GetCSSPropertyColor());
return color.Rgb();
}
const AtomicString& AXNodeObject::ComputedFontFamily() const {
if (!GetLayoutObject())
return AXObject::ComputedFontFamily();
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return AXObject::ComputedFontFamily();
const FontDescription& font_description = style->GetFontDescription();
return font_description.FirstFamily().FamilyName();
}
String AXNodeObject::FontFamilyForSerialization() const {
if (!GetLayoutObject())
return AXObject::FontFamilyForSerialization();
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return AXObject::FontFamilyForSerialization();
const SimpleFontData* primary_font = style->GetFont()->PrimaryFont();
if (!primary_font)
return AXObject::FontFamilyForSerialization();
// Note that repeatedly querying this can be expensive - only use this when
// serializing. For other comparisons consider using `ComputedFontFamily`.
return primary_font->PlatformData().FontFamilyName();
}
// Blink font size is provided in pixels.
// Platform APIs may convert to another unit (IA2 converts to points).
float AXNodeObject::FontSize() const {
if (!GetLayoutObject())
return AXObject::FontSize();
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return AXObject::FontSize();
// Font size should not be affected by scale transform or page zoom, because
// users of authoring tools may want to check that their text is formatted
// with the font size they expected.
// E.g. use SpecifiedFontSize() instead of ComputedFontSize(), and do not
// multiply by style->Scale()->Transform()->Y();
return style->SpecifiedFontSize();
}
float AXNodeObject::FontWeight() const {
if (!GetLayoutObject())
return AXObject::FontWeight();
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return AXObject::FontWeight();
return style->GetFontWeight();
}
ax::mojom::blink::AriaCurrentState AXNodeObject::GetAriaCurrentState() const {
const AtomicString& attribute_value =
AriaTokenAttribute(html_names::kAriaCurrentAttr);
if (attribute_value.IsNull()) {
return ax::mojom::blink::AriaCurrentState::kNone;
}
if (EqualIgnoringASCIICase(attribute_value, "false")) {
return ax::mojom::blink::AriaCurrentState::kFalse;
}
if (EqualIgnoringASCIICase(attribute_value, "page")) {
return ax::mojom::blink::AriaCurrentState::kPage;
}
if (EqualIgnoringASCIICase(attribute_value, "step")) {
return ax::mojom::blink::AriaCurrentState::kStep;
}
if (EqualIgnoringASCIICase(attribute_value, "location")) {
return ax::mojom::blink::AriaCurrentState::kLocation;
}
if (EqualIgnoringASCIICase(attribute_value, "date")) {
return ax::mojom::blink::AriaCurrentState::kDate;
}
if (EqualIgnoringASCIICase(attribute_value, "time")) {
return ax::mojom::blink::AriaCurrentState::kTime;
}
// An unknown value should return true.
return ax::mojom::blink::AriaCurrentState::kTrue;
}
ax::mojom::blink::InvalidState AXNodeObject::GetInvalidState() const {
// First check aria-invalid.
if (const AtomicString& attribute_value =
AriaTokenAttribute(html_names::kAriaInvalidAttr)) {
// aria-invalid="false".
if (EqualIgnoringASCIICase(attribute_value, "false")) {
return ax::mojom::blink::InvalidState::kFalse;
}
// In most cases, aria-invalid="spelling"| "grammar" are used on inline text
// elements, and are exposed via Markers() as if they are native errors.
// Therefore, they are exposed as InvalidState:kNone here in order to avoid
// exposing the state twice, and to prevent superfluous "invalid"
// announcements in some screen readers.
// On text fields, they are simply exposed as if aria-invalid="true".
if (EqualIgnoringASCIICase(attribute_value, "spelling") ||
EqualIgnoringASCIICase(attribute_value, "grammar")) {
return RoleValue() == ax::mojom::blink::Role::kTextField
? ax::mojom::blink::InvalidState::kTrue
: ax::mojom::blink::InvalidState::kNone;
}
// Any other non-empty value is considered true.
if (!attribute_value.empty()) {
return ax::mojom::blink::InvalidState::kTrue;
}
}
// Next check for native the invalid state.
if (GetElement()) {
ListedElement* form_control = ListedElement::From(*GetElement());
if (form_control) {
return IsValidFormControl(form_control)
? ax::mojom::blink::InvalidState::kFalse
: ax::mojom::blink::InvalidState::kTrue;
}
}
return AXObject::GetInvalidState();
}
bool AXNodeObject::IsValidFormControl(ListedElement* form_control) const {
// If the control is marked with a custom error, the form control is invalid.
if (form_control->CustomError())
return false;
// If the form control checks for validity, and has passed the checks,
// then consider it valid.
if (form_control->IsNotCandidateOrValid())
return true;
// The control is invalid, as far as CSS is concerned.
// However, we ignore a failed check inside of an empty required text field,
// in order to avoid redundant verbalizations (screen reader already says
// required).
if (IsAtomicTextField() && IsRequired() && GetValueForControl().length() == 0)
return true;
return false;
}
int AXNodeObject::PosInSet() const {
// A <select size=1> exposes posinset as the index of the selected option.
if (RoleValue() == ax::mojom::blink::Role::kComboBoxSelect) {
if (auto* select_element = DynamicTo<HTMLSelectElement>(*GetNode())) {
return 1 + select_element->selectedIndex();
}
}
if (SupportsARIASetSizeAndPosInSet()) {
int32_t pos_in_set;
if (AriaIntAttribute(html_names::kAriaPosinsetAttr, &pos_in_set)) {
return pos_in_set;
}
}
return 0;
}
int AXNodeObject::SetSize() const {
if (auto* select_element = DynamicTo<HTMLSelectElement>(GetNode())) {
return static_cast<int>(select_element->length());
}
if (RoleValue() == ax::mojom::blink::Role::kMenuListPopup) {
return ParentObject()->SetSize();
}
if (SupportsARIASetSizeAndPosInSet()) {
int32_t set_size;
if (AriaIntAttribute(html_names::kAriaSetsizeAttr, &set_size)) {
return set_size;
}
}
return 0;
}
bool AXNodeObject::ValueForRange(float* out_value) const {
float value_now;
if (AriaFloatAttribute(html_names::kAriaValuenowAttr, &value_now)) {
// Adjustment when the aria-valuenow is less than aria-valuemin or greater
// than the aria-valuemax value.
// See https://w3c.github.io/aria/#authorErrorDefaultValuesTable.
float min_value, max_value;
if (MinValueForRange(&min_value)) {
if (value_now < min_value) {
*out_value = min_value;
return true;
}
}
if (MaxValueForRange(&max_value)) {
if (value_now > max_value) {
*out_value = max_value;
return true;
}
}
*out_value = value_now;
return true;
}
if (IsNativeSlider() || IsNativeSpinButton()) {
*out_value = To<HTMLInputElement>(*GetNode()).valueAsNumber();
return std::isfinite(*out_value);
}
if (auto* meter = DynamicTo<HTMLMeterElement>(GetNode())) {
*out_value = meter->value();
return true;
}
// In ARIA 1.1, default values for aria-valuenow were changed as below.
// - meter: A value matching the implicit or explicitly set aria-valuemin.
// - scrollbar, slider : half way between aria-valuemin and aria-valuemax
// - separator : 50
// - spinbutton : 0
switch (RawAriaRole()) {
case ax::mojom::blink::Role::kScrollBar:
case ax::mojom::blink::Role::kSlider: {
float min_value, max_value;
if (MinValueForRange(&min_value) && MaxValueForRange(&max_value)) {
*out_value = (min_value + max_value) / 2.0f;
return true;
}
[[fallthrough]];
}
case ax::mojom::blink::Role::kSplitter: {
*out_value = 50.0f;
return true;
}
case ax::mojom::blink::Role::kMeter: {
float min_value;
if (MinValueForRange(&min_value)) {
*out_value = min_value;
return true;
}
[[fallthrough]];
}
case ax::mojom::blink::Role::kSpinButton: {
*out_value = 0.0f;
return true;
}
default:
break;
}
return false;
}
bool AXNodeObject::MaxValueForRange(float* out_value) const {
if (AriaFloatAttribute(html_names::kAriaValuemaxAttr, out_value)) {
return true;
}
if (IsNativeSlider() || IsNativeSpinButton()) {
*out_value = static_cast<float>(To<HTMLInputElement>(*GetNode()).Maximum());
return std::isfinite(*out_value);
}
if (auto* meter = DynamicTo<HTMLMeterElement>(GetNode())) {
*out_value = meter->max();
return true;
}
// In ARIA 1.1, default value of scrollbar, separator and slider
// for aria-valuemax were changed to 100. This change was made for
// progressbar in ARIA 1.2.
switch (RawAriaRole()) {
case ax::mojom::blink::Role::kMeter:
case ax::mojom::blink::Role::kProgressIndicator:
case ax::mojom::blink::Role::kScrollBar:
case ax::mojom::blink::Role::kSplitter:
case ax::mojom::blink::Role::kSlider: {
*out_value = 100.0f;
return true;
}
default:
break;
}
return false;
}
bool AXNodeObject::MinValueForRange(float* out_value) const {
if (AriaFloatAttribute(html_names::kAriaValueminAttr, out_value)) {
return true;
}
if (IsNativeSlider() || IsNativeSpinButton()) {
*out_value = static_cast<float>(To<HTMLInputElement>(*GetNode()).Minimum());
return std::isfinite(*out_value);
}
if (auto* meter = DynamicTo<HTMLMeterElement>(GetNode())) {
*out_value = meter->min();
return true;
}
// In ARIA 1.1, default value of scrollbar, separator and slider
// for aria-valuemin were changed to 0. This change was made for
// progressbar in ARIA 1.2.
switch (RawAriaRole()) {
case ax::mojom::blink::Role::kMeter:
case ax::mojom::blink::Role::kProgressIndicator:
case ax::mojom::blink::Role::kScrollBar:
case ax::mojom::blink::Role::kSplitter:
case ax::mojom::blink::Role::kSlider: {
*out_value = 0.0f;
return true;
}
default:
break;
}
return false;
}
bool AXNodeObject::StepValueForRange(float* out_value) const {
if (IsNativeSlider() || IsNativeSpinButton()) {
auto step_range =
To<HTMLInputElement>(*GetNode()).CreateStepRange(kRejectAny);
auto step = step_range.Step().ToString().ToFloat();
// Provide a step if ATs incrementing slider should move by step, otherwise
// AT will move by 5%.
// If there are too few allowed stops (< 20), incrementing/decrementing
// the slider by 5% could get stuck, and therefore the step is exposed.
// The step is also exposed if moving by 5% would cause intermittent
// behavior where sometimes the slider would alternate by 1 or 2 steps.
// Therefore the final decision is to use the step if there are
// less than stops in the slider, otherwise, move by 5%.
float max = step_range.Maximum().ToString().ToFloat();
float min = step_range.Minimum().ToString().ToFloat();
int num_stops = base::saturated_cast<int>((max - min) / step);
constexpr int kNumStopsForFivePercentRule = 40;
if (num_stops >= kNumStopsForFivePercentRule) {
// No explicit step, and the step is very small -- don't expose a step
// so that Talkback will move by 5% increments.
*out_value = 0.0f;
return false;
}
*out_value = step;
return std::isfinite(*out_value);
}
switch (RawAriaRole()) {
case ax::mojom::blink::Role::kScrollBar:
case ax::mojom::blink::Role::kSplitter:
case ax::mojom::blink::Role::kSlider: {
*out_value = 0.0f;
return true;
}
default:
break;
}
return false;
}
KURL AXNodeObject::Url() const {
if (IsLink()) // <area>, <link>, <html:a> or <svg:a>
return GetElement()->HrefURL();
if (IsWebArea()) {
DCHECK(GetDocument());
return GetDocument()->Url();
}
auto* html_image_element = DynamicTo<HTMLImageElement>(GetNode());
if (IsImage() && html_image_element) {
// Using ImageSourceURL handles both src and srcset.
String source_url = html_image_element->ImageSourceURL();
String stripped_image_source_url =
StripLeadingAndTrailingHTMLSpaces(source_url);
if (!stripped_image_source_url.empty())
return GetDocument()->CompleteURL(stripped_image_source_url);
}
if (IsInputImage())
return To<HTMLInputElement>(GetNode())->Src();
return KURL();
}
AXObject* AXNodeObject::ChooserPopup() const {
if (RuntimeEnabledFeatures::SelectAccessibilityReparentInputEnabled() ||
RuntimeEnabledFeatures::SelectAccessibilityNestedInputEnabled()) {
// The first input inside of a select filters the listbox, and therefore
// controls it.
if (auto* input = DynamicTo<HTMLInputElement>(GetNode())) {
if (input->IsTextField()) {
if (auto* select = input->FirstAncestorSelectElement()) {
if (auto* popover = select->PopoverForAppearanceBase()) {
if (auto* axobject = AXObjectCache().Get(popover)) {
return axobject;
}
}
}
}
}
}
// When color & date chooser popups are visible, they can be found in the tree
// as a group child of the <input> control itself.
switch (native_role_) {
case ax::mojom::blink::Role::kColorWell:
case ax::mojom::blink::Role::kComboBoxSelect:
case ax::mojom::blink::Role::kDate:
case ax::mojom::blink::Role::kDateTime:
case ax::mojom::blink::Role::kInputTime:
case ax::mojom::blink::Role::kTextFieldWithComboBox: {
for (const auto& child : ChildrenIncludingIgnored()) {
if (IsA<Document>(child->GetNode())) {
return child.Get();
}
}
return nullptr;
}
default:
#if DCHECK_IS_ON()
for (const auto& child : ChildrenIncludingIgnored()) {
DCHECK(!IsA<Document>(child->GetNode()) ||
!child->ParentObject()->IsVisible())
<< "Chooser popup exists for " << native_role_
<< "\n* Child: " << child
<< "\n* Child's immediate parent: " << child->ParentObject();
}
#endif
return nullptr;
}
}
String AXNodeObject::GetValueForControl() const {
AXObjectSet visited;
return GetValueForControl(visited);
}
String AXNodeObject::GetValueForControl(AXObjectSet& visited) const {
// TODO(crbug.com/1165853): Remove this method completely and compute value on
// the browser side.
Node* node = GetNode();
if (!node)
return String();
if (const auto* select_element = DynamicTo<HTMLSelectElement>(*node)) {
if (!select_element->UsesMenuList())
return String();
// In most cases, we want to return what's actually displayed inside the
// <select> element on screen, unless there is an ARIA label overriding it.
int selected_index = select_element->SelectedListIndex();
const HeapVector<Member<HTMLElement>>& list_items =
select_element->GetListItems();
if (selected_index >= 0 &&
static_cast<wtf_size_t>(selected_index) < list_items.size()) {
const AtomicString& overridden_description = AriaAttribute(
*list_items[selected_index], html_names::kAriaLabelAttr);
if (!overridden_description.IsNull())
return overridden_description;
}
// If the author replaced the button by providing their own <button> on a
// customizable select, then use the text inside that button:
// https://github.com/openui/open-ui/issues/1117
if (RuntimeEnabledFeatures::CustomizableSelectEnabled() &&
select_element->IsAppearanceBase()) {
if (auto* button = select_element->SlottedButton()) {
if (AXObject* button_object = AXObjectCache().Get(button)) {
return button_object->TextFromDescendants(visited, nullptr, false);
}
}
}
// We don't retrieve the element's value attribute on purpose. The value
// attribute might be sanitized and might be different from what is actually
// displayed inside the <select> element on screen.
return select_element->InnerElement().GetInnerTextWithoutUpdate();
}
if (IsAtomicTextField()) {
// This is an "<input type=text>" or a "<textarea>": We should not simply
// return the "value" attribute because it might be sanitized in some input
// control types, e.g. email fields. If we do that, then "selectionStart"
// and "selectionEnd" indices will not match with the text in the sanitized
// value.
String inner_text = ToTextControl(*node).InnerEditorValue();
unsigned int unmasked_text_length = inner_text.length();
// If the inner text is empty, we return a null string to let the text
// alternative algorithm continue searching for an accessible name.
if (!unmasked_text_length) {
return String();
}
if (!IsPasswordFieldAndShouldHideValue())
return inner_text;
if (!GetLayoutObject())
return inner_text;
const ComputedStyle* style = GetLayoutObject()->Style();
if (!style)
return inner_text;
UChar mask_character = 0;
switch (style->TextSecurity()) {
case ETextSecurity::kNone:
break; // Fall through to the non-password branch.
case ETextSecurity::kDisc:
mask_character = kBulletCharacter;
break;
case ETextSecurity::kCircle:
mask_character = kWhiteBulletCharacter;
break;
case ETextSecurity::kSquare:
mask_character = kBlackSquareCharacter;
break;
}
if (!mask_character)
return inner_text;
StringBuilder masked_text;
masked_text.ReserveCapacity(unmasked_text_length);
for (unsigned int i = 0; i < unmasked_text_length; ++i)
masked_text.Append(mask_character);
return masked_text.ToString();
}
if (IsRangeValueSupported()) {
return AriaAttribute(html_names::kAriaValuetextAttr).GetString();
}
// Handle other HTML input elements that aren't text controls, like date and
// time controls, by returning their value converted to text, with the
// exception of checkboxes and radio buttons (which would return "on"), and
// buttons which will return their name.
// https://html.spec.whatwg.org/C/#dom-input-value
if (const auto* input = DynamicTo<HTMLInputElement>(node)) {
if (input->FormControlType() == FormControlType::kInputFile) {
return input->FileStatusText();
}
if (input->FormControlType() != FormControlType::kInputButton &&
input->FormControlType() != FormControlType::kInputCheckbox &&
input->FormControlType() != FormControlType::kInputImage &&
input->FormControlType() != FormControlType::kInputRadio &&
input->FormControlType() != FormControlType::kInputReset &&
input->FormControlType() != FormControlType::kInputSubmit) {
return input->Value();
}
}
if (RoleValue() == ax::mojom::blink::Role::kComboBoxMenuButton) {
// An ARIA combobox can get value from inner contents.
return TextFromDescendants(visited, nullptr, false);
}
return String();
}
String AXNodeObject::SlowGetValueForControlIncludingContentEditable() const {
AXObjectSet visited;
return SlowGetValueForControlIncludingContentEditable(visited);
}
String AXNodeObject::SlowGetValueForControlIncludingContentEditable(
AXObjectSet& visited) const {
if (IsNonAtomicTextField()) {
Element* element = GetElement();
return element ? element->GetInnerTextWithoutUpdate() : String();
}
return GetValueForControl(visited);
}
ax::mojom::blink::Role AXNodeObject::RawAriaRole() const {
return aria_role_;
}
ax::mojom::blink::HasPopup AXNodeObject::HasPopup() const {
if (const AtomicString& has_popup =
AriaTokenAttribute(html_names::kAriaHaspopupAttr)) {
if (EqualIgnoringASCIICase(has_popup, "false"))
return ax::mojom::blink::HasPopup::kFalse;
if (EqualIgnoringASCIICase(has_popup, "listbox"))
return ax::mojom::blink::HasPopup::kListbox;
if (EqualIgnoringASCIICase(has_popup, "tree"))
return ax::mojom::blink::HasPopup::kTree;
if (EqualIgnoringASCIICase(has_popup, "grid"))
return ax::mojom::blink::HasPopup::kGrid;
if (EqualIgnoringASCIICase(has_popup, "dialog"))
return ax::mojom::blink::HasPopup::kDialog;
// To provide backward compatibility with ARIA 1.0 content,
// user agents MUST treat an aria-haspopup value of true
// as equivalent to a value of menu.
if (EqualIgnoringASCIICase(has_popup, "true") ||
EqualIgnoringASCIICase(has_popup, "menu"))
return ax::mojom::blink::HasPopup::kMenu;
}
// ARIA 1.1 default value of haspopup for combobox is "listbox".
if (RoleValue() == ax::mojom::blink::Role::kComboBoxMenuButton ||
RoleValue() == ax::mojom::blink::Role::kTextFieldWithComboBox) {
return ax::mojom::blink::HasPopup::kListbox;
}
if (AXObjectCache().GetAutofillSuggestionAvailability(AXObjectID()) !=
WebAXAutofillSuggestionAvailability::kNoSuggestions) {
return ax::mojom::blink::HasPopup::kMenu;
}
return AXObject::HasPopup();
}
ax::mojom::blink::IsPopup AXNodeObject::IsPopup() const {
if (IsDetached() || !GetElement()) {
return ax::mojom::blink::IsPopup::kNone;
}
const auto* html_element = DynamicTo<HTMLElement>(GetElement());
if (!html_element) {
return ax::mojom::blink::IsPopup::kNone;
}
if (RoleValue() == ax::mojom::blink::Role::kMenuListPopup) {
return ax::mojom::blink::IsPopup::kAuto;
}
switch (html_element->PopoverType()) {
case PopoverValueType::kNone:
return ax::mojom::blink::IsPopup::kNone;
case PopoverValueType::kAuto:
return ax::mojom::blink::IsPopup::kAuto;
case PopoverValueType::kHint:
return ax::mojom::blink::IsPopup::kHint;
case PopoverValueType::kManual:
return ax::mojom::blink::IsPopup::kManual;
}
}
bool AXNodeObject::IsEditableRoot() const {
const Node* node = GetNode();
if (IsDetached() || !node)
return false;
#if DCHECK_IS_ON() // Required in order to get Lifecycle().ToString()
DCHECK(GetDocument());
DCHECK_GE(GetDocument()->Lifecycle().GetState(),
DocumentLifecycle::kStyleClean)
<< "Unclean document style at lifecycle state "
<< GetDocument()->Lifecycle().ToString();
#endif // DCHECK_IS_ON()
// Catches the case where the 'contenteditable' attribute is set on an atomic
// text field (which shouldn't have any effect).
if (IsAtomicTextField())
return false;
// The DOM inside native text fields is an implementation detail that should
// not be exposed to platform accessibility APIs.
if (EnclosingTextControl(node))
return false;
if (IsRootEditableElement(*node))
return true;
// Catches the case where a contenteditable is inside another contenteditable.
// This is especially important when the two nested contenteditables have
// different attributes, e.g. "true" vs. "plaintext-only".
if (HasContentEditableAttributeSet())
return true;
return false;
}
bool AXNodeObject::HasContentEditableAttributeSet() const {
if (IsDetached() || !GetNode())
return false;
const auto* html_element = DynamicTo<HTMLElement>(GetNode());
if (!html_element)
return false;
ContentEditableType normalized_value =
html_element->contentEditableNormalized();
return normalized_value == ContentEditableType::kContentEditable ||
normalized_value == ContentEditableType::kPlaintextOnly;
}
// Returns the nearest block-level LayoutBlockFlow ancestor
static LayoutBlockFlow* GetNearestBlockFlow(LayoutObject* object) {
LayoutObject* current = object;
while (current) {
if (auto* block_flow = DynamicTo<LayoutBlockFlow>(current)) {
return block_flow;
}
current = current->Parent();
}
NOTREACHED();
}
// Returns true if |r1| and |r2| are both non-null, both inline, and are
// contained within the same LayoutBlockFlow.
static bool IsInSameBlockFlow(LayoutObject* r1, LayoutObject* r2) {
if (!r1 || !r2)
return false;
if (!r1->IsInline() || !r2->IsInline())
return false;
LayoutBlockFlow* b1 = GetNearestBlockFlow(r1);
LayoutBlockFlow* b2 = GetNearestBlockFlow(r2);
return b1 && b2 && b1 == b2;
}
//
// Modify or take an action on an object.
//
bool AXNodeObject::OnNativeSetSelectedAction(bool selected) {
auto* option = DynamicTo<HTMLOptionElement>(GetNode());
if (!option) {
return false;
}
HTMLSelectElement* select_element = option->OwnerSelectElement();
if (!select_element) {
return false;
}
if (!CanSetSelectedAttribute()) {
return false;
}
AccessibilitySelectedState is_option_selected = IsSelected();
if (is_option_selected == kSelectedStateUndefined) {
return false;
}
bool is_selected = (is_option_selected == kSelectedStateTrue) ? true : false;
if ((is_selected && selected) || (!is_selected && !selected)) {
return false;
}
select_element->SelectOptionByAccessKey(To<HTMLOptionElement>(GetNode()));
return true;
}
bool AXNodeObject::OnNativeSetValueAction(const String& string) {
base::UmaHistogramEnumeration("Accessibility.SetValue.Role", RoleValue());
if (!GetNode() || !GetNode()->IsElementNode()) {
return false;
}
const LayoutObject* layout_object = GetLayoutObject();
if (!layout_object || !layout_object->IsBoxModelObject()) {
return false;
}
auto* html_input_element = DynamicTo<HTMLInputElement>(*GetNode());
if (html_input_element && layout_object->IsTextField()) {
html_input_element->SetValue(
string, TextFieldEventBehavior::kDispatchInputAndChangeEvent);
return true;
}
if (auto* text_area_element = DynamicTo<HTMLTextAreaElement>(*GetNode())) {
DCHECK(layout_object->IsTextArea());
text_area_element->SetValue(
string, TextFieldEventBehavior::kDispatchInputAndChangeEvent);
return true;
}
if (HasContentEditableAttributeSet()) {
To<HTMLElement>(GetNode())->setInnerText(string);
return true;
}
return false;
}
//
// New AX name calculation.
//
String AXNodeObject::GetName(ax::mojom::blink::NameFrom& name_from,
AXObjectVector* name_objects) const {
String name = AXObject::GetName(name_from, name_objects);
// Fields inside a datetime control need to merge the field name with
// the name of the <input> element.
if (RoleValue() == ax::mojom::blink::Role::kSpinButton &&
DatetimeAncestor()) {
name_objects->clear();
String input_name = DatetimeAncestor()->GetName(name_from, name_objects);
if (!input_name.empty())
return name + " " + input_name;
}
// Handle ::scroll-button(*) pseudo element names.
const Element* element = GetElement();
if (element && element->IsScrollButtonPseudoElement()) {
// Prioritize alt text if available.
std::optional<String> alt_text = GetCSSAltText(element);
if (alt_text && !alt_text->empty()) {
return *alt_text;
}
// If the alt text is not available, return a "Scroll [direction]" name,
const ComputedStyle* style =
GetLayoutObject() ? GetLayoutObject()->Style() : nullptr;
if (style) {
PhysicalDirection physical;
if (element->IsScrollButtonBlockStartPseudoElement()) {
physical = style->GetWritingDirection().BlockStart();
} else if (element->IsScrollButtonBlockEndPseudoElement()) {
physical = style->GetWritingDirection().BlockEnd();
} else if (element->IsScrollButtonInlineStartPseudoElement()) {
physical = style->GetWritingDirection().InlineStart();
} else if (element->IsScrollButtonInlineEndPseudoElement()) {
physical = style->GetWritingDirection().InlineEnd();
} else {
NOTREACHED()
<< "ScrollButtonPseudoElement must be one of known directions";
}
switch (physical) {
case PhysicalDirection::kRight:
return element->GetLocale().QueryString(IDS_AX_CAROUSEL_SCROLL_RIGHT);
case PhysicalDirection::kLeft:
return element->GetLocale().QueryString(IDS_AX_CAROUSEL_SCROLL_LEFT);
case PhysicalDirection::kDown:
return element->GetLocale().QueryString(IDS_AX_CAROUSEL_SCROLL_DOWN);
case PhysicalDirection::kUp:
return element->GetLocale().QueryString(IDS_AX_CAROUSEL_SCROLL_UP);
}
}
}
// Handle ::scroll-marker names. Pick the first one that matches:
// - Use CSS alt text if one is available.
// - Use CSS content (from LayoutText descendants) if specified and
// non-empty.
// - Use scroll target's accessibility name is it has one.
if (element && element->IsScrollMarkerPseudoElement()) {
std::optional<String> alt_text = GetCSSAltText(element);
if (alt_text && !alt_text->empty()) {
return *alt_text;
}
std::optional<String> content = GetCSSContentText(element);
if (content && !content->empty()) {
return *content;
}
const AXObject* scroll_target =
AXObjectCache().Get(element->parentElement());
ax::mojom::blink::NameFrom name_source;
return scroll_target ? scroll_target->GetName(name_source, nullptr) : "";
}
return name;
}
String AXNodeObject::TextAlternative(
bool recursive,
const AXObject* aria_label_or_description_root,
AXObjectSet& visited,
ax::mojom::blink::NameFrom& name_from,
AXRelatedObjectVector* related_objects,
NameSources* name_sources) const {
// If nameSources is non-null, relatedObjects is used in filling it in, so it
// must be non-null as well.
DCHECK(!name_sources || related_objects);
bool found_text_alternative = false;
Node* node = GetNode();
name_from = ax::mojom::blink::NameFrom::kNone;
if (!node && !GetLayoutObject()) {
return String();
}
if (IsA<HTMLSlotElement>(node) && node->IsInUserAgentShadowRoot() &&
!recursive) {
// User agent slots do not have their own name, but their subtrees can
// contribute to ancestor names (where recursive == true).
return String();
}
if (GetLayoutObject()) {
std::optional<String> text_alternative = GetCSSAltText(GetElement());
if (text_alternative) {
name_from = ax::mojom::blink::NameFrom::kCssAltText;
if (name_sources) {
name_sources->push_back(NameSource(false));
name_sources->back().type = name_from;
name_sources->back().text = text_alternative.value();
}
return text_alternative.value();
}
if (GetLayoutObject()->IsBR()) {
text_alternative = String("\n");
found_text_alternative = true;
} else if (GetLayoutObject()->IsText() &&
(!recursive || !GetLayoutObject()->IsCounter())) {
auto* layout_text = To<LayoutText>(GetLayoutObject());
String visible_text = layout_text->PlainText(); // Actual rendered text.
// If no text boxes we assume this is unrendered end-of-line whitespace.
// TODO find robust way to deterministically detect end-of-line space.
if (visible_text.empty()) {
// No visible rendered text -- must be whitespace.
// Either it is useful whitespace for separating words or not.
if (layout_text->IsAllCollapsibleWhitespace()) {
if (IsIgnored()) {
return "";
}
// If no textboxes, this was whitespace at the line's end.
text_alternative = " ";
} else {
text_alternative = layout_text->TransformedText();
}
} else {
text_alternative = visible_text;
}
found_text_alternative = true;
} else if (!recursive) {
if (ListMarker* marker = ListMarker::Get(GetLayoutObject())) {
text_alternative = marker->TextAlternative(*GetLayoutObject());
found_text_alternative = true;
}
}
if (found_text_alternative) {
name_from = ax::mojom::blink::NameFrom::kContents;
if (name_sources) {
name_sources->push_back(NameSource(false));
name_sources->back().type = name_from;
name_sources->back().text = text_alternative.value();
}
// Ensure that text nodes count toward
// kMaxDescendantsForTextAlternativeComputation when calculating the name
// for their direct parent (see AXNodeObject::TextFromDescendants).
visited.insert(this);
return text_alternative.value();
}
}
// Step 2E from: http://www.w3.org/TR/accname-aam-1.1 -- value from control.
// This must occur before 2C, because 2C is not applied if 2E will be:
// 2C: "If traversal of the current node is due to recursion and the current
// node is an embedded control as defined in step 2E, ignore aria-label and
// skip to rule 2E".
// Note that 2E only applies the label is for "another widget", therefore, the
// value cannot be used to label the original control, even if aria-labelledby
// points to itself. The easiest way to check this is by testing whether this
// node has already been visited.
if (recursive && !visited.Contains(this)) {
String value_for_name = GetValueContributionToName(visited);
// TODO(accessibility): Consider using `empty` check instead of `IsNull`.
if (!value_for_name.IsNull()) {
name_from = ax::mojom::blink::NameFrom::kValue;
if (name_sources) {
name_sources->push_back(NameSource(false));
name_sources->back().type = ax::mojom::blink::NameFrom::kValue;
name_sources->back().text = value_for_name;
}
return value_for_name;
}
}
// Step 2C from: http://www.w3.org/TR/accname-aam-1.1 -- aria-label.
String text_alternative = AriaTextAlternative(
recursive, aria_label_or_description_root, visited, name_from,
related_objects, name_sources, &found_text_alternative);
if (found_text_alternative && !name_sources)
return MaybeAppendFileDescriptionToName(text_alternative);
// Step 2D from: http://www.w3.org/TR/accname-aam-1.1 -- native markup.
text_alternative =
NativeTextAlternative(visited, name_from, related_objects, name_sources,
&found_text_alternative);
// An explicitly empty native text alternative can still be overridden if a
// viable text alternative is found later in the search, so remember that it
// was explicitly empty here but don't terminate the search yet unless we
// already found something non-empty.
const bool has_explicitly_empty_native_text_alternative =
text_alternative.empty() &&
name_from == ax::mojom::blink::NameFrom::kAttributeExplicitlyEmpty;
if (!text_alternative.empty() && !name_sources) {
return MaybeAppendFileDescriptionToName(text_alternative);
}
// Step 2F / 2G from: http://www.w3.org/TR/accname-aam-1.1 -- from content.
if (ShouldIncludeContentInTextAlternative(
recursive, aria_label_or_description_root, visited)) {
name_from = ax::mojom::blink::NameFrom::kContents;
if (name_sources) {
name_sources->push_back(NameSource(found_text_alternative));
name_sources->back().type = name_from;
}
if (auto* text_node = DynamicTo<Text>(node)) {
text_alternative = text_node->data();
} else if (IsA<HTMLBRElement>(node)) {
text_alternative = String("\n");
} else {
text_alternative =
TextFromDescendants(visited, aria_label_or_description_root, false);
}
if (!text_alternative.empty()) {
if (name_sources) {
found_text_alternative = true;
name_sources->back().text = text_alternative;
} else {
return MaybeAppendFileDescriptionToName(text_alternative);
}
}
}
// Step 2I from: http://www.w3.org/TR/accname-aam-1.1
// Use the tooltip text for the name if there was no other accessible name.
// However, it does not make sense to do this if the object has a role
// that prohibits name as specified in
// https://w3c.github.io/aria/#namefromprohibited.
// Preventing the tooltip for being used in the name causes it to be used for
// the description instead.
// This complies with https://w3c.github.io/html-aam/#att-title, which says
// how to expose a title: "Either the accessible name, or the accessible
// description, or Not mapped". There's nothing in HTML-AAM that explicitly
// forbids this, and it seems reasonable for authors to use a tooltip on any
// visible element without causing an accessibility error or user problem.
// Note: if this is part of another label or description, it needs to be
// computed as a name, in order to contribute to that.
if (aria_label_or_description_root || !IsNameProhibited()) {
String resulting_text = TextAlternativeFromTooltip(
name_from, name_sources, &found_text_alternative, &text_alternative,
related_objects);
if (!resulting_text.empty()) {
if (name_sources) {
text_alternative = resulting_text;
} else {
return resulting_text;
}
}
}
String saved_text_alternative = GetSavedTextAlternativeFromNameSource(
found_text_alternative, name_from, related_objects, name_sources);
if (!saved_text_alternative.empty()) {
return saved_text_alternative;
}
if (has_explicitly_empty_native_text_alternative) {
// If the native text alternative is explicitly empty and we
// never found another text alternative, then set name_source
// to reflect the fact that there was an explicitly empty text
// alternative. This is important because an empty `alt` attribute on an
// <img> can be used to indicate that the image is presentational and should
// be ignored by ATs.
name_from = ax::mojom::blink::NameFrom::kAttributeExplicitlyEmpty;
}
return String();
}
static bool ShouldInsertSpaceBetweenObjectsIfNeeded(
AXObject* previous,
AXObject* next,
ax::mojom::blink::NameFrom last_used_name_from,
ax::mojom::blink::NameFrom name_from) {
LayoutObject* next_layout = next->GetLayoutObject();
LayoutObject* prev_layout = previous->GetLayoutObject();
// If we're going between two LayoutObjects that are in separate
// LayoutBoxes, add whitespace if it wasn't there already. Intuitively if
// you have <span>Hello</span><span>World</span>, those are part of the same
// LayoutBox so we should return "HelloWorld", but given
// <div>Hello</div><div>World</div> the strings are in separate boxes so we
// should return "Hello World".
// https://www.w3.org/TR/css-display-3/#the-display-properties
if (!IsInSameBlockFlow(next_layout, prev_layout)) {
return true;
}
// Even if we are in the same block flow, let's make sure to add whitespace
// if the layout objects define new formatting contexts for their children,
// as is the case with the inline-* family of display properties.
// So we want the following:
// <span style="display:inline-block;">Hello</span><span>World</span>
// <span style="display:inline-flex;">Hello</span><span>World</span>
// <span style="display:inline-grid;">Hello</span><span>World</span>
// <span style="display:inline-table;">Hello</span><span>World</span>
// to return "Hello World". See "inner display type" in the CSS Display 3.0
// spec: https://www.w3.org/TR/css-display-3/#the-display-properties
CHECK(next_layout);
CHECK(prev_layout);
if (next_layout->IsAtomicInlineLevel() ||
prev_layout->IsAtomicInlineLevel()) {
return true;
}
// Even if it is in the same inline block flow, if we are using a text
// alternative such as an ARIA label or HTML title, we should separate
// the strings. Doing so is consistent with what is stated in the AccName
// spec and with what is done in other user agents.
switch (last_used_name_from) {
case ax::mojom::blink::NameFrom::kNone:
case ax::mojom::blink::NameFrom::kAttributeExplicitlyEmpty:
case ax::mojom::blink::NameFrom::kContents:
case ax::mojom::blink::NameFrom::kProhibited:
case ax::mojom::blink::NameFrom::kProhibitedAndRedundant:
break;
case ax::mojom::blink::NameFrom::kAttribute:
case ax::mojom::blink::NameFrom::kCaption:
case ax::mojom::blink::NameFrom::kCssAltText:
case ax::mojom::blink::NameFrom::kInterestTarget:
case ax::mojom::blink::NameFrom::kPlaceholder:
case ax::mojom::blink::NameFrom::kRelatedElement:
case ax::mojom::blink::NameFrom::kTitle:
case ax::mojom::blink::NameFrom::kValue:
case ax::mojom::blink::NameFrom::kPopoverTarget:
return true;
}
switch (name_from) {
case ax::mojom::blink::NameFrom::kNone:
case ax::mojom::blink::NameFrom::kAttributeExplicitlyEmpty:
case ax::mojom::blink::NameFrom::kContents:
case ax::mojom::blink::NameFrom::kProhibited:
case ax::mojom::blink::NameFrom::kProhibitedAndRedundant:
break;
case ax::mojom::blink::NameFrom::kAttribute:
case ax::mojom::blink::NameFrom::kCaption:
case ax::mojom::blink::NameFrom::kCssAltText:
case ax::mojom::blink::NameFrom::kInterestTarget:
case ax::mojom::blink::NameFrom::kPlaceholder:
case ax::mojom::blink::NameFrom::kRelatedElement:
case ax::mojom::blink::NameFrom::kTitle:
case ax::mojom::blink::NameFrom::kValue:
case ax::mojom::blink::NameFrom::kPopoverTarget:
return true;
}
// According to the AccName spec, we need to separate controls from text nodes
// using a space.
if (previous->IsControl() || next->IsControl())
return true;
// When |previous| and |next| are in same inline formatting context, we
// may have block-in-inline between |previous| and |next|.
// For <div>abc<p aria-hidden=true>...</p>def</div>, we have following
// layout tree:
// LayoutBlockFlow {DIV}, children are inline
// LayoutText "abc" <= previous
// LayoutBlockFlow (anonymous) block-in-inline wrapper
// LayoutBlockFlow {P}
// ...
// LayoutText "def" <= next
// When block-in-inline disabled, layout tree is:
// LayoutBlockFlow {DIV}, children are block
// LayoutBlockFlow (anonymous)
// LayoutText "abc" <= previous
// LayoutBlockFlow (anonymous) block-in-inline wrapper
// LayoutBlockFlow {P}
// ...
// LayoutBlockFlow (anonymous)
// LayoutText "def" <= next
// See accessibility/name-calc-aria-hidden.html
for (auto* layout_object = previous->GetLayoutObject();
layout_object && layout_object != next_layout;
layout_object = layout_object->NextInPreOrder()) {
if (layout_object->IsBlockInInline())
return true;
}
return false;
}
String AXNodeObject::TextFromDescendants(
AXObjectSet& visited,
const AXObject* aria_label_or_description_root,
bool recursive) const {
if (!CanHaveChildren()) {
return recursive || !GetElement()
? String()
: GetElement()->GetInnerTextWithoutUpdate();
}
StringBuilder accumulated_text;
AXObject* previous = nullptr;
ax::mojom::blink::NameFrom last_used_name_from =
ax::mojom::blink::NameFrom::kNone;
AXObjectVector action_objects =
RelationVectorFromAria(html_names::kAriaActionsAttr);
CHECK(!NeedsToUpdateCachedValues());
const AXObjectVector& children = ChildrenIncludingIgnored();
#if AX_FAIL_FAST_BUILD()
base::AutoReset<bool> auto_reset(&is_computing_text_from_descendants_, true);
#endif
wtf_size_t num_children = children.size();
for (wtf_size_t index = 0; index < num_children; index++) {
DCHECK_EQ(children.size(), num_children);
if (index >= children.size()) {
// TODO(accessibility) Remove this condition once we solve all causes of
// the child list being altered during this loop.
break;
}
AXObject* child = children[index];
DCHECK(child);
DCHECK(!child->IsDetached()) << child;
constexpr size_t kMaxDescendantsForTextAlternativeComputation = 100;
if (visited.size() > kMaxDescendantsForTextAlternativeComputation)
break;
// Exclude nodes referenced by aria-actions.
if (action_objects.Contains(child)) {
continue;
}
if (child->IsHiddenForTextAlternativeCalculation(
aria_label_or_description_root)) {
continue;
}
ax::mojom::blink::NameFrom child_name_from =
ax::mojom::blink::NameFrom::kNone;
String result;
if (child->IsPresentational()) {
result = child->TextFromDescendants(visited,
aria_label_or_description_root, true);
} else {
result = RecursiveTextAlternative(*child, aria_label_or_description_root,
visited, child_name_from);
}
if (!result.empty() && previous && accumulated_text.length() &&
!IsHTMLSpace(accumulated_text[accumulated_text.length() - 1]) &&
!IsHTMLSpace(result[0])) {
if (ShouldInsertSpaceBetweenObjectsIfNeeded(
previous, child, last_used_name_from, child_name_from)) {
accumulated_text.Append(' ');
}
}
accumulated_text.Append(result);
// We keep track of all non-hidden children, even those whose content is
// not included, because all rendered children impact whether or not a
// space should be inserted between objects. Example: A label which has
// a single, nameless input surrounded by CSS-generated content should
// have a space separating the before and after content.
previous = child;
// We only keep track of the source of children whose content is included.
// Example: Three spans, the first with an aria-label, the second with no
// content, and the third whose name comes from content. There should be a
// space between the first and third because of the aria-label in the first.
if (!result.empty())
last_used_name_from = child_name_from;
}
return accumulated_text.ToString();
}
// static
bool AXNodeObject::IsNameFromLabelElement(HTMLElement* control) {
// This duplicates some logic from TextAlternative()/NativeTextAlternative(),
// but is necessary because IsNameFromLabelElement() needs to be called from
// ComputeIsIgnored(), which isn't allowed to call
// AXObjectCache().GetOrCreate() in random places in the tree.
if (!control)
return false;
// aria-label and aria-labelledby take precedence over <label>.
if (IsNameFromAriaAttribute(control))
return false;
// <label> will be used. It contains the control or points via <label for>.
// Based on https://www.w3.org/TR/html-aam-1.0
// 5.1/5.5 Text inputs, Other labelable Elements
auto* labels = control->labels();
return labels && labels->length();
}
// static
bool AXNodeObject::IsRedundantLabel(HTMLLabelElement* label) {
// Determine if label is redundant:
// - Labelling a checkbox or radio.
// - Text was already used to name the checkbox/radio.
// - No interesting content in the label (focusable or semantically useful)
// TODO(accessibility) Consider moving this logic to the browser side.
// TODO(accessibility) Consider this for more controls, such as textboxes.
// There isn't a clear history why this is only done for checkboxes, and not
// other controls such as textboxes. It may be because the checkbox/radio
// itself is small, so this makes a nicely sized combined click target. Most
// ATs do not already have features to combine labels and controls, e.g.
// removing redundant announcements caused by having text and named controls
// as separate objects.
HTMLInputElement* input = DynamicTo<HTMLInputElement>(label->Control());
if (!input)
return false;
if (!input->GetLayoutObject() ||
input->GetLayoutObject()->Style()->Visibility() !=
EVisibility::kVisible) {
return false;
}
if (!input->IsCheckable()) {
return false;
}
if (!IsNameFromLabelElement(input)) {
return false;
}
DCHECK_NE(input->labels()->length(), 0U);
// Look for any first child element that is not the input control itself.
// This could be important semantically.
Element* first_child = ElementTraversal::FirstChild(*label);
if (!first_child)
return true; // No element children.
if (first_child != input)
return false; // Has an element child that is not the input control.
// The first child was the input control.
// If there's another child, then it won't be the input control.
return ElementTraversal::NextSibling(*first_child) == nullptr;
}
void AXNodeObject::GetRelativeBounds(AXObject** out_container,
gfx::RectF& out_bounds_in_container,
gfx::Transform& out_container_transform,
bool* clips_children) const {
if (GetLayoutObject()) {
AXObject::GetRelativeBounds(out_container, out_bounds_in_container,
out_container_transform, clips_children);
return;
}
#if DCHECK_IS_ON()
DCHECK(!getting_bounds_) << "GetRelativeBounds reentrant: " << ToString();
base::AutoReset<bool> reentrancy_protector(&getting_bounds_, true);
#endif
*out_container = nullptr;
out_bounds_in_container = gfx::RectF();
out_container_transform.MakeIdentity();
if (RoleValue() == ax::mojom::blink::Role::kMenuListOption) {
// When a <select> is collapsed, the bounds of its options are the same as
// that of the containing <select>. Falling through will achieve this.
// TODO(accessibility): Support bounding boxes for <optgroup>. Could
// union the rect of the first and last option in it.
auto* select = To<HTMLOptionElement>(GetNode())->OwnerSelectElement();
if (auto* ax_select = AXObjectCache().Get(select)) {
if (ax_select->IsExpanded() == kExpandedExpanded) {
auto* options_bounds = AXObjectCache().GetOptionsBounds(*ax_select);
if (options_bounds) {
unsigned int index = static_cast<unsigned int>(
To<HTMLOptionElement>(GetNode())->index());
// Some <option> bounding boxes may not be sent, as a performance
// optimization. For example, only the first 1000 options may have
// bounding boxes. If no bounding box is available, then we serialize
// the option with everything except for that information.
if (index < options_bounds->size()) {
out_bounds_in_container = gfx::RectF(options_bounds->at(index));
}
return;
}
}
}
}
// First check if it has explicit bounds, for example if this element is tied
// to a canvas path. When explicit coordinates are provided, the ID of the
// explicit container element that the coordinates are relative to must be
// provided too.
if (auto canvas_bounds =
AXObjectCache().GetCanvasElementBounds(this->AXObjectID())) {
*out_container = AXObjectCache().ObjectFromAXID(canvas_bounds->second);
if (*out_container) {
out_bounds_in_container = gfx::RectF(canvas_bounds->first);
return;
}
}
Element* element = GetElement();
// If it's in a canvas but doesn't have an explicit rect, or has display:
// contents set, get the bounding rect of its children.
if ((GetNode()->parentElement() &&
GetNode()->parentElement()->IsInCanvasSubtree()) ||
(element && element->HasDisplayContentsStyle())) {
Vector<gfx::RectF> rects;
for (Node& child : NodeTraversal::ChildrenOf(*GetNode())) {
if (child.IsHTMLElement()) {
if (AXObject* obj = AXObjectCache().Get(&child)) {
AXObject* container;
gfx::RectF bounds;
obj->GetRelativeBounds(&container, bounds, out_container_transform,
clips_children);
if (container) {
*out_container = container;
rects.push_back(bounds);
}
}
}
}
if (*out_container) {
for (auto& rect : rects)
out_bounds_in_container.Union(rect);
return;
}
}
// If this object doesn't have an explicit element rect or computable from its
// children, for now, let's return the position of the ancestor that does have
// a position, and make it the width of that parent, and about the height of a
// line of text, so that it's clear the object is a child of the parent.
for (AXObject* position_provider = ParentObject(); position_provider;
position_provider = position_provider->ParentObject()) {
if (position_provider->GetLayoutObject()) {
position_provider->GetRelativeBounds(
out_container, out_bounds_in_container, out_container_transform,
clips_children);
if (*out_container) {
out_bounds_in_container.set_size(
gfx::SizeF(out_bounds_in_container.width(),
std::min(10.0f, out_bounds_in_container.height())));
}
break;
}
}
}
bool AXNodeObject::HasValidHTMLTableStructureAndLayout() const {
// Is it a visible <table> with a table-like role and layout?
if (!IsTableLikeRole() || !GetLayoutObject() ||
!GetLayoutObject()->IsTable() || !IsA<HTMLTableElement>(GetNode()))
return false;
// Check for any invalid children, as far as W3C table validity is concerned.
// * If no invalid children exist, this will be considered a valid table,
// and AddTableChildren() can be used to add the children in rendered order.
// * If any invalid children exist, this table will be considered invalid.
// In that case the children will still be added via AddNodeChildren(),
// so that no content is lost.
// See comments in AddTableChildren() for more information about valid tables.
auto* table = To<HTMLTableElement>(GetNode());
auto* thead = table->tHead();
auto* tfoot = table->tFoot();
for (Node* node = LayoutTreeBuilderTraversal::FirstChild(*GetElement()); node;
node = LayoutTreeBuilderTraversal::NextSibling(*node)) {
if (Element* child = DynamicTo<Element>(node)) {
if (child == thead || child == tfoot) {
// Only 1 thead and 1 tfoot are allowed.
continue;
}
if (IsA<HTMLTableSectionElement>(child) &&
child->HasTagName(html_names::kTbodyTag)) {
// Multiple <tbody>s are valid, but only 1 thead or tfoot.
continue;
}
if (!child->GetLayoutObject() &&
child->HasTagName(html_names::kColgroupTag)) {
continue;
}
if (IsA<HTMLTableCaptionElement>(child) && child == table->caption()) {
continue; // Only one caption is valid.
}
} else if (!node->GetLayoutObject()) {
continue;
}
return false;
}
return true;
}
void AXNodeObject::AddTableChildren() {
// Add the caption (if any) and table sections in the visible order.
//
// Implementation notes:
//
// * In a valid table, there is always at least one section child DOM node.
// For example, if the HTML of the web page includes <tr>s as direct
// children of a <table>, Blink will insert a <tbody> as a child of the
// table, and parent of the <tr> elements.
//
// * Rendered order can differ from DOM order:
// The valid DOM order of <table> children is specified here:
// https://html.spec.whatwg.org/multipage/tables.html#the-table-element,
// "... optionally a caption element, followed by zero or more
// colgroup elements, followed optionally by a thead element, followed by
// either zero or more tbody elements or one or more tr elements, followed
// optionally by a tfoot element"
// However, even if the DOM children occur in an incorrect order, Blink
// automatically renders them as if they were in the correct order.
// The following code ensures that the children are added to the AX tree in
// the same order as Blink renders them.
DCHECK(HasValidHTMLTableStructureAndLayout());
auto* html_table_element = To<HTMLTableElement>(GetNode());
AddNodeChild(html_table_element->caption());
AddNodeChild(html_table_element->tHead());
for (Node* node : *html_table_element->tBodies())
AddNodeChild(node);
AddNodeChild(html_table_element->tFoot());
}
int AXNodeObject::TextOffsetInFormattingContext(int offset) const {
DCHECK_GE(offset, 0);
if (IsDetached())
return 0;
// When a node has the first-letter CSS style applied to it, it is split into
// two parts (two branches) in the layout tree. The "first-letter part"
// contains its first letter and any surrounding Punctuation. The "remaining
// part" contains the rest of the text.
//
// We need to ensure that we retrieve the correct layout object: either the
// one for the "first-letter part" or the one for the "remaining part",
// depending of the value of |offset|.
const LayoutObject* layout_obj =
GetNode() ? AssociatedLayoutObjectOf(*GetNode(), offset)
: GetLayoutObject();
if (!layout_obj)
return AXObject::TextOffsetInFormattingContext(offset);
// We support calculating the text offset from the start of the formatting
// contexts of the following layout objects, provided that they are at
// inline-level, (display=inline) or "display=inline-block":
//
// (Note that in the following examples, the paragraph is the formatting
// context.
//
// Layout replaced, e.g. <p><img></p>.
// Layout inline with a layout text child, e.g. <p><a href="#">link</a></p>.
// Layout block flow, e.g. <p><b style="display: inline-block;"></b></p>.
// Layout text, e.g. <p>Hello</p>.
// Layout br (subclass of layout text), e.g. <p><br></p>.
if (layout_obj->IsLayoutInline()) {
// The OffsetMapping class doesn't map layout inline objects to their text
// mappings because such an operation could be ambiguous. An inline object
// may have another inline object inside it. For example,
// <span><span>Inner</span outer</span>. We need to recursively retrieve the
// first layout text or layout replaced child so that any potential
// ambiguity would be removed.
const AXObject* first_child = FirstChildIncludingIgnored();
return first_child ? first_child->TextOffsetInFormattingContext(offset)
: offset;
}
// TODO(crbug.com/567964): LayoutObject::IsAtomicInlineLevel() also includes
// block-level replaced elements. We need to explicitly exclude them via
// LayoutObject::IsInline().
const bool is_atomic_inline_level =
layout_obj->IsInline() && layout_obj->IsAtomicInlineLevel();
if (!is_atomic_inline_level && !layout_obj->IsText()) {
// Not in a formatting context in which text offsets are meaningful.
return AXObject::TextOffsetInFormattingContext(offset);
}
// TODO(crbug.com/1149171): NGInlineOffsetMappingBuilder does not properly
// compute offset mappings for empty LayoutText objects. Other text objects
// (such as some list markers) are not affected.
if (const LayoutText* layout_text = DynamicTo<LayoutText>(layout_obj)) {
if (layout_text->HasEmptyText()) {
return AXObject::TextOffsetInFormattingContext(offset);
}
}
LayoutBlockFlow* formatting_context =
OffsetMapping::GetInlineFormattingContextOf(*layout_obj);
if (!formatting_context || formatting_context == layout_obj)
return AXObject::TextOffsetInFormattingContext(offset);
// If "formatting_context" is not a Layout NG object, the offset mappings will
// be computed on demand and cached.
const OffsetMapping* inline_offset_mapping =
InlineNode::GetOffsetMapping(formatting_context);
if (!inline_offset_mapping)
return AXObject::TextOffsetInFormattingContext(offset);
const base::span<const OffsetMappingUnit> mapping_units =
inline_offset_mapping->GetMappingUnitsForLayoutObject(*layout_obj);
if (mapping_units.empty())
return AXObject::TextOffsetInFormattingContext(offset);
return static_cast<int>(mapping_units.front().TextContentStart()) + offset;
}
//
// Inline text boxes.
//
void AXNodeObject::LoadInlineTextBoxes() {
#if DCHECK_IS_ON()
DCHECK(GetDocument()->Lifecycle().GetState() >=
DocumentLifecycle::kLayoutClean)
<< "Unclean document at lifecycle "
<< GetDocument()->Lifecycle().ToString();
#endif
std::queue<AXID> work_queue;
work_queue.push(AXObjectID());
while (!work_queue.empty()) {
AXObject* work_obj = AXObjectCache().ObjectFromAXID(work_queue.front());
work_queue.pop();
if (!work_obj || !work_obj->IsIncludedInTree()) {
continue;
}
if (CanHaveInlineTextBoxChildren(work_obj)) {
if (work_obj->CachedChildrenIncludingIgnored().empty()) {
// We only need to add inline textbox children if they aren't present.
// Although some platforms (e.g. Android), load inline text boxes
// on subtrees that may later be stale, once they are stale, the old
// inline text boxes are cleared because SetNeedsToUpdateChildren()
// calls ClearChildren().
work_obj->LoadInlineTextBoxesHelper();
}
} else {
for (const auto& child : work_obj->ChildrenIncludingIgnored())
work_queue.push(child->AXObjectID());
}
}
// If the work was deferred via ChildrenChanged(), update accessibility
// to force that work to be performed now.
if (!AXObjectCache().lifecycle().StateAllowsImmediateTreeUpdates()) {
AXObjectCache().UpdateAXForAllDocuments();
}
}
void AXNodeObject::LoadInlineTextBoxesHelper() {
// The inline textbox children start empty.
DCHECK(CachedChildrenIncludingIgnored().empty());
#if defined(REDUCE_AX_INLINE_TEXTBOXES)
// Keep inline text box children up-to-date for this object in the future.
// This is only necessary on Android, which tries to skip inline text boxes
// for most objects.
SetAlwaysLoadInlineTextBoxes(true);
#endif
if (AXObjectCache().lifecycle().StateAllowsImmediateTreeUpdates()) {
// Can only add new objects while processing deferred events.
if (::features::IsAccessibilityBlockFlowIteratorEnabled()) {
AddInlineTextBoxChildrenWithBlockFlowIterator();
} else {
AddInlineTextBoxChildren();
}
// Avoid adding these children twice.
SetNeedsToUpdateChildren(false);
// If inline text box children were added, mark the node dirty so that the
// results are serialized.
if (!CachedChildrenIncludingIgnored().empty()) {
AXObjectCache().AddDirtyObjectToSerializationQueue(
this, ax::mojom::blink::EventFrom::kNone,
ax::mojom::blink::Action::kNone, {});
}
} else {
// Wait until processing deferred events.
AXObjectCache().ChildrenChanged(this);
}
}
void AXNodeObject::AddInlineTextBoxChildrenWithBlockFlowIterator() {
CHECK(GetDocument());
CHECK(ShouldLoadInlineTextBoxes());
CHECK(GetLayoutObject());
GetLayoutObject()->CheckIsNotDestroyed();
CHECK(GetLayoutObject()->IsText()) << GetLayoutObject() << " " << this;
CHECK(!GetLayoutObject()->NeedsLayout());
CHECK(AXObjectCache().lifecycle().StateAllowsImmediateTreeUpdates())
<< AXObjectCache();
AXBlockFlowIterator it(this);
while (it.Next()) {
AXObject* box =
AXObjectCache().GetOrCreate(it.CurrentFragmentIndex(), this);
if (!box) {
return;
}
children_.push_back(box);
}
}
void AXNodeObject::AddInlineTextBoxChildren() {
CHECK(GetDocument());
CHECK(ShouldLoadInlineTextBoxes());
CHECK(GetLayoutObject());
GetLayoutObject()->CheckIsNotDestroyed();
CHECK(GetLayoutObject()->IsText()) << GetLayoutObject() << " " << this;
CHECK(!GetLayoutObject()->NeedsLayout());
CHECK(AXObjectCache().GetAXMode().has_mode(ui::AXMode::kInlineTextBoxes));
CHECK(!AXObjectCache().GetAXMode().HasFilterFlags(
ui::AXMode::kFormsAndLabelsOnly))
<< "Form controls mode should not have inline text boxes turned on.";
CHECK(AXObjectCache().lifecycle().StateAllowsImmediateTreeUpdates())
<< AXObjectCache();
auto* layout_text = To<LayoutText>(GetLayoutObject());
for (auto* box = layout_text->FirstAbstractInlineTextBox(); box;
box = box->NextInlineTextBox()) {
AXObject* ax_box = AXObjectCache().GetOrCreate(box, this);
if (!ax_box) {
continue;
}
children_.push_back(ax_box);
}
}
void AXNodeObject::AddValidationMessageChild() {
DCHECK(IsWebArea()) << "Validation message must be child of root";
// First child requirement enables easy checking to see if a children changed
// event is needed in AXObjectCacheImpl::ValidationMessageObjectIfInvalid().
DCHECK_EQ(children_.size(), 0U)
<< "Validation message must be the first child";
AddChildAndCheckIncluded(AXObjectCache().ValidationMessageObjectIfInvalid());
}
void AXNodeObject::AddImageMapChildren() {
HTMLMapElement* map = GetMapForImage(GetNode());
if (!map)
return;
HTMLImageElement* curr_image_element = DynamicTo<HTMLImageElement>(GetNode());
DCHECK(curr_image_element);
DCHECK(curr_image_element->IsLink());
DCHECK(
!curr_image_element->FastGetAttribute(html_names::kUsemapAttr).empty());
// Even though several images can point to the same map via usemap, only
// use one reported via HTMLImageMapElement::ImageElement(), which is always
// the first image in the DOM that matches the #usemap, even if there are
// changes to the DOM. Only allow map children for the primary image.
// This avoids two problems:
// 1. Focusing the same area but in a different image scrolls the page to
// the first image that uses that map. Safari does the same thing, and
// Firefox does something similar (but seems to prefer the last image).
// 2. When an object has multiple parents, serialization errors occur.
// While allowed in the spec, using multiple images with the same map is not
// handled well in browsers (problem #1), and serializer support for multiple
// parents of the same area children is messy.
// Get the primary image, which is the first image using this map.
HTMLImageElement* primary_image_element = map->ImageElement();
// Is this the primary image for this map?
if (primary_image_element != curr_image_element) {
return;
}
// Yes, this is the primary image.
// Add the children to |this|.
Node* child = LayoutTreeBuilderTraversal::FirstChild(*map);
while (child) {
AddChildAndCheckIncluded(AXObjectCache().GetOrCreate(child, this));
child = LayoutTreeBuilderTraversal::NextSibling(*child);
}
}
void AXNodeObject::AddPopupChildren() {
if (AXObjectCache().IsForSnapshot()) {
// The snapshotter is unaware of the popup document.
return;
}
auto* html_select_element = DynamicTo<HTMLSelectElement>(GetNode());
if (html_select_element) {
if (html_select_element->UsesMenuList()) {
AddChildAndCheckIncluded(html_select_element->PopupRootAXObject());
}
return;
}
auto* html_input_element = DynamicTo<HTMLInputElement>(GetNode());
if (html_input_element) {
AddChildAndCheckIncluded(html_input_element->PopupRootAXObject());
}
}
void AXNodeObject::AddPseudoElementChildrenFromLayoutTree() {
// Children are added this way only for pseudo-element subtrees.
// See AXObject::ShouldUseLayoutObjectTraversalForChildren().
if (!IsVisible() || !GetLayoutObject()) {
DCHECK(GetNode());
DCHECK(GetNode()->IsPseudoElement());
return; // Can't add children for hidden or display-locked pseudo elements.
}
LayoutObject* child = GetLayoutObject()->SlowFirstChild();
while (child) {
// All added pseudo element descendants are included in the tree.
if (AXObject* ax_child = AXObjectCache().GetOrCreate(child, this)) {
DCHECK(AXObjectCacheImpl::IsRelevantPseudoElementDescendant(*child));
AddChildAndCheckIncluded(ax_child);
}
child = child->NextSibling();
}
}
void AXNodeObject::AddNodeChildren() {
if (!node_)
return;
// Ignore DOM children of frame/iframe: they do not act as fallbacks and
// are never part of layout.
if (IsA<HTMLFrameElementBase>(GetNode()))
return;
// If node has reading flow children, then we should reading-flow order.
// Note that this is only used for the case where the element is a
// reading-flow container, and not for the case where the element is a
// reading-flow item.
HeapVector<Member<Node>> reading_flow_children;
if (Element* element = GetElement()) {
reading_flow_children = element->ReadingFlowChildren();
}
if (!reading_flow_children.empty()) {
HeapHashSet<Member<Node>> ax_children_added;
// Add reading flow siblings in order.
for (Node* reading_flow_item : reading_flow_children) {
if (IsAddedOnlyViaSpecialTraversal(reading_flow_item)) {
continue;
}
if (ax_children_added.insert(reading_flow_item).is_new_entry) {
AddNodeChild(reading_flow_item);
}
}
#if DCHECK_IS_ON()
// At this point, the number of AXObject children added should equal the
// number of LayoutTreeBuilderTraversal children.
size_t num_layout_tree_children = 0;
for (Node* child = LayoutTreeBuilderTraversal::FirstChild(*node_); child;
child = LayoutTreeBuilderTraversal::NextSibling(*child)) {
if (IsAddedOnlyViaSpecialTraversal(child)) {
continue;
}
DCHECK(ax_children_added.Contains(child));
++num_layout_tree_children;
}
DCHECK_EQ(ax_children_added.size(), num_layout_tree_children);
#endif
} else {
for (Node* child = LayoutTreeBuilderTraversal::FirstChild(*node_); child;
child = LayoutTreeBuilderTraversal::NextSibling(*child)) {
if (IsAddedOnlyViaSpecialTraversal(child)) {
continue;
}
AddNodeChild(child);
}
}
}
void AXNodeObject::AddSelectChildren() {
auto* select = DynamicTo<HTMLSelectElement>(GetNode());
if (RuntimeEnabledFeatures::SelectAccessibilityReparentInputEnabled() &&
select) {
if (auto* input = select->FirstDescendantTextInput()) {
// Reparent the first descendant <input> element of this <select> to be
// adjacent to the listbox in the a11y tree.
AddNodeChild(input);
}
}
AddNodeChildren();
}
void AXNodeObject::AddOwnedChildren() {
AXObjectVector owned_children;
AXObjectCache().ValidatedAriaOwnedChildren(this, owned_children);
DCHECK(owned_children.size() == 0 || AXRelationCache::IsValidOwner(this))
<< "This object is not allowed to use aria-owns, but it is.\n"
<< this;
// Always include owned children.
for (const auto& owned_child : owned_children) {
DCHECK(owned_child->GetNode());
DCHECK(AXRelationCache::IsValidOwnedChild(*owned_child->GetNode()))
<< "This object is not allowed to be owned, but it is.\n"
<< owned_child;
AddChildAndCheckIncluded(owned_child, true);
}
}
void AXNodeObject::AddChildrenImpl() {
#define CHECK_ATTACHED() \
if (IsDetached()) { \
NOTREACHED() << "Detached adding children: " << this; \
}
CHECK(NeedsToUpdateChildren());
CHECK(CanHaveChildren());
if (ShouldLoadInlineTextBoxes() && HasLayoutText(this)) {
if (::features::IsAccessibilityBlockFlowIteratorEnabled()) {
AddInlineTextBoxChildrenWithBlockFlowIterator();
} else {
AddInlineTextBoxChildren();
}
CHECK_ATTACHED();
return;
}
if (IsA<HTMLImageElement>(GetNode())) {
AddImageMapChildren();
CHECK_ATTACHED();
return;
}
// If validation message exists, always make it the first child of the root,
// to enable easy checking of whether it's a known child of the root.
if (IsWebArea())
AddValidationMessageChild();
CHECK_ATTACHED();
if (IsA<HTMLSelectElement>(GetNode())) {
AddSelectChildren();
} else if (HasValidHTMLTableStructureAndLayout()) {
AddTableChildren();
} else if (GetNode() && GetNode()->IsScrollMarkerGroupPseudoElement()) {
AddScrollMarkerGroupChildren();
} else if (ShouldUseLayoutObjectTraversalForChildren()) {
AddPseudoElementChildrenFromLayoutTree();
} else {
AddNodeChildren();
}
CHECK_ATTACHED();
AddPopupChildren();
CHECK_ATTACHED();
AddOwnedChildren();
CHECK_ATTACHED();
}
void AXNodeObject::AddScrollMarkerGroupChildren() {
DCHECK(GetNode() && GetNode()->IsScrollMarkerGroupPseudoElement());
if (!IsVisible() || !GetLayoutObject()) {
DCHECK(GetNode());
DCHECK(GetNode()->IsPseudoElement());
// Can't add children for hidden or display-locked pseudo elements.
return;
}
// In the DOM tree, a carousel looks like the following
// Scroller
// Item
// ::scroll-marker
// ::scroll-marker-group
//
// The following is the corresponding layout tree:
// Scroller
// Item
// ::scroll-marker-group
// Anonymous layout object
// ::scroll-marker
//
// The desired AX tree is the following:
// Scroller
// Item
// ::scroll-marker-group
// ::scroll-marker
//
// So far, we added items as they appeared in the Layout tree, with the
// exception that we pruned ::scroll-markers any time we saw them (see
// IsAddedOnlyViaSpecialTraversal). Now, we've reached ::scroll-marker-group.
// From here, we use the layout object walk skipping any anonymous layout
// objects. In fact, we only add ::scroll-markers. When this function is done,
// we should have our desired AX tree.
//
LayoutObject* child = GetLayoutObject()->SlowFirstChild();
while (child) {
DCHECK(
child->IsAnonymous() ||
(child->GetNode() && child->GetNode()->IsScrollMarkerPseudoElement()));
if (child->GetNode() && child->GetNode()->IsScrollMarkerPseudoElement()) {
AddNodeChild(child->GetNode());
}
// Iterate the whole subtree staying within the ::scroll-marker-group.
child = child->NextInPreOrder(GetLayoutObject());
}
}
void AXNodeObject::AddChildren() {
#if DCHECK_IS_ON()
DCHECK(!IsDetached());
// If the need to add more children in addition to existing children arises,
// childrenChanged should have been called, which leads to children_dirty_
// being true, then UpdateChildrenIfNecessary() clears the children before
// calling AddChildren().
DCHECK(children_.empty()) << "\nParent still has " << children_.size()
<< " children before adding:" << "\nParent is "
<< this << "\nFirst child is " << children_[0];
#endif
#if AX_FAIL_FAST_BUILD()
SANITIZER_CHECK(!is_computing_text_from_descendants_)
<< "Should not attempt to simultaneously compute text from descendants "
"and add children on: "
<< this;
SANITIZER_CHECK(!is_adding_children_) << " Reentering method on " << this;
base::AutoReset<bool> reentrancy_protector(&is_adding_children_, true);
#endif
AddChildrenImpl();
SetNeedsToUpdateChildren(false);
#if DCHECK_IS_ON()
// All added children must be attached.
for (const auto& child : children_) {
DCHECK(!child->IsDetached()) << "A brand new child was detached.\n"
<< child << "\n ... of parent " << this;
}
#endif
}
// Add non-owned children that are backed with a DOM node.
void AXNodeObject::AddNodeChild(Node* node) {
if (!node)
return;
if (Element* element = DynamicTo<Element>(node);
element && element->HasScrollButtonOrMarkerGroupPseudos()) {
VectorOf<Node> children = UnpackScrollerWithSiblingControls(element);
for (auto child : children) {
AddNodeChildImpl(child.Get());
}
} else {
AddNodeChildImpl(node);
}
}
void AXNodeObject::AddNodeChildImpl(Node* node) {
CHECK(node);
AXObject* ax_child = AXObjectCache().Get(node);
CHECK(!ax_child || !ax_child->IsDetached());
// Should not have another parent unless owned.
if (AXObjectCache().IsAriaOwned(ax_child))
return; // Do not add owned children to their natural parent.
AXObject* ax_cached_parent =
ax_child ? ax_child->ParentObjectIfPresent() : nullptr;
if (!ax_child) {
ax_child =
AXObjectCache().CreateAndInit(node, node->GetLayoutObject(), this);
if (!ax_child) {
return;
}
CHECK(!ax_child->IsDetached());
}
AddChild(ax_child);
// If we are adding an included child, check to see that it didn't have a
// different previous parent, because that indicates something strange is
// happening -- we shouldn't be stealing AXObjects from other parents here.
bool did_add_child_as_included =
children_.size() && children_[children_.size() - 1] == ax_child;
if (did_add_child_as_included && ax_cached_parent) {
CHECK(ax_child->IsIncludedInTree());
DUMP_WILL_BE_CHECK(ax_cached_parent->AXObjectID() == AXObjectID())
<< "Newly added child shouldn't have a different preexisting parent:"
<< "\nChild = " << ax_child << "\nNew parent = " << this
<< "\nPreexisting parent = " << ax_cached_parent;
}
}
#if DCHECK_IS_ON()
void AXNodeObject::CheckValidChild(AXObject* child) {
DCHECK(!child->IsDetached()) << "Cannot add a detached child.\n" << child;
Node* child_node = child->GetNode();
// <area> children should only be added via AddImageMapChildren(), as the
// descendants of an <image usemap> -- never alone or as children of a <map>.
if (IsA<HTMLAreaElement>(child_node)) {
AXObject* ancestor = this;
while (ancestor && !IsA<HTMLImageElement>(ancestor->GetNode()))
ancestor = ancestor->ParentObject();
DCHECK(ancestor && IsA<HTMLImageElement>(ancestor->GetNode()))
<< "Area elements can only be added by image parents: " << child
<< " had a parent of " << this;
}
DCHECK(!IsA<HTMLFrameElementBase>(GetNode()) ||
IsA<Document>(child->GetNode()))
<< "Cannot have a non-document child of a frame or iframe."
<< "\nChild: " << child << "\nParent: " << child->ParentObject();
}
#endif
void AXNodeObject::AddChild(AXObject* child, bool is_from_aria_owns) {
if (!child)
return;
#if DCHECK_IS_ON()
CheckValidChild(child);
#endif
unsigned int index = children_.size();
InsertChild(child, index, is_from_aria_owns);
}
void AXNodeObject::AddChildAndCheckIncluded(AXObject* child,
bool is_from_aria_owns) {
if (!child)
return;
DCHECK(child->CachedIsIncludedInTree());
AddChild(child, is_from_aria_owns);
}
void AXNodeObject::InsertChild(AXObject* child,
unsigned index,
bool is_from_aria_owns) {
if (!child)
return;
DCHECK(CanHaveChildren());
DCHECK(!child->IsDetached()) << "Cannot add a detached child: " << child;
// Enforce expected aria-owns status:
// - Don't add a non-aria-owned child when called from AddOwnedChildren().
// - Don't add an aria-owned child to its natural parent, because it will
// already be the child of the element with aria-owns.
DCHECK_EQ(AXObjectCache().IsAriaOwned(child), is_from_aria_owns);
// Set the parent:
// - For a new object it will have already been set.
// - For a reused, older object, it may need to be changed to a new parent.
child->SetParent(this);
if (ChildrenNeedToUpdateCachedValues()) {
child->InvalidateCachedValues(TreeUpdateReason::kChildInserted);
}
// Update cached values preemptively, but don't allow children changed to be
// called on the parent if the ignored state changes, as we are already
// recomputing children and don't want to recurse.
child->UpdateCachedAttributeValuesIfNeeded(
/*notify_parent_of_ignored_changes*/ false);
if (!child->IsIncludedInTree()) {
DCHECK(!is_from_aria_owns) << "Owned elements must be in tree: " << child
<< "\nRecompute included in tree: "
<< child->ComputeIsIgnoredButIncludedInTree();
// Get the ignored child's children and add to children of ancestor
// included in tree. This will recurse if necessary, skipping levels of
// unignored descendants as it goes.
const auto& children = child->ChildrenIncludingIgnored();
wtf_size_t length = children.size();
int new_index = index;
for (wtf_size_t i = 0; i < length; ++i) {
if (children[i]->IsDetached()) {
NOTREACHED(base::NotFatalUntil::M140)
<< "Cannot add a detached child: " << "\n* Child: " << children[i]
<< "\n* Parent: " << child << "\n* Grandparent: " << this;
continue;
}
// If the child was owned, it will be added elsewhere as a direct
// child of the object owning it.
if (!AXObjectCache().IsAriaOwned(children[i]))
children_.insert(new_index++, children[i]);
}
} else {
children_.insert(index, child);
}
}
bool AXNodeObject::CanHaveChildren() const {
DCHECK(!IsDetached());
// A child tree has been stitched onto this node, hiding its usual subtree.
if (AXObjectCache().GetAXObjectChildAXTreeID(AXObjectID())) {
return false;
}
// Notes:
// * Native text fields expose any children they might have, complying
// with browser-side expectations that editable controls have children
// containing the actual text content.
// * ARIA roles with childrenPresentational:true in the ARIA spec expose
// their contents to the browser side, allowing platforms to decide whether
// to make them a leaf, ensuring that focusable content cannot be hidden,
// and improving stability in Blink.
bool result = !GetElement() || AXObject::CanHaveChildren(*GetElement());
switch (native_role_) {
case ax::mojom::blink::Role::kListBoxOption:
if (RuntimeEnabledFeatures::CustomizableSelectEnabled()) {
// When CustomizableSelect is enabled, then options are allowed to have
// children as per the new content model.
break;
}
[[fallthrough]];
case ax::mojom::blink::Role::kCheckBox:
case ax::mojom::blink::Role::kMenuItem:
case ax::mojom::blink::Role::kMenuItemCheckBox:
case ax::mojom::blink::Role::kMenuItemRadio:
case ax::mojom::blink::Role::kProgressIndicator:
case ax::mojom::blink::Role::kRadioButton:
case ax::mojom::blink::Role::kScrollBar:
case ax::mojom::blink::Role::kSlider:
case ax::mojom::blink::Role::kSplitter:
case ax::mojom::blink::Role::kSwitch:
case ax::mojom::blink::Role::kTab:
DCHECK(!result) << "Expected to disallow children for:" << "\n* Node: "
<< GetNode() << "\n* Layout Object: " << GetLayoutObject()
<< "\n* Native role: " << native_role_
<< "\n* Aria role: " << RawAriaRole();
break;
case ax::mojom::blink::Role::kComboBoxSelect:
case ax::mojom::blink::Role::kPopUpButton:
case ax::mojom::blink::Role::kStaticText:
// Note: these can have AXInlineTextBox children, but when adding them, we
// also check AXObjectCache().InlineTextBoxAccessibilityEnabled().
DCHECK(result) << "Expected to allow children for " << GetElement()
<< " on role " << native_role_;
break;
default:
break;
}
return result;
}
//
// Properties of the object's owning document or page.
//
double AXNodeObject::EstimatedLoadingProgress() const {
if (!GetDocument())
return 0;
if (IsLoaded())
return 1.0;
if (LocalFrame* frame = GetDocument()->GetFrame())
return frame->Loader().Progress().EstimatedProgress();
return 0;
}
//
// DOM and Render tree access.
//
Element* AXNodeObject::ActionElement() const {
const AXObject* current = this;
if (blink::IsA<blink::Document>(current->GetNode()))
return nullptr; // Do not expose action element for document.
// In general, we look an action element up only for AXObjects that have a
// backing Element. We make an exception for text nodes and pseudo elements
// because we also want these to expose a default action when any of their
// ancestors is clickable. We have found Windows ATs relying on this behavior
// (see https://crbug.com/1382034).
DCHECK(current->GetElement() || current->IsTextObject() ||
current->ShouldUseLayoutObjectTraversalForChildren());
while (current) {
// Handles clicks or is a textfield and is not a disabled form control.
if (current->IsClickable()) {
Element* click_element = current->GetElement();
DCHECK(click_element) << "Only elements are clickable";
// Only return if the click element is a DOM ancestor as well, because
// the click handler won't propagate down via aria-owns.
if (!GetNode() || click_element->contains(GetNode()))
return click_element;
return nullptr;
}
current = current->ParentObject();
}
return nullptr;
}
Element* AXNodeObject::AnchorElement() const {
// Search up the DOM tree for an anchor. This can be anything that has the
// linked state, such as an HTMLAnchorElement or role=link/doc-backlink.
const AXObject* current = this;
while (current) {
if (current->IsLink()) {
if (!current->GetElement()) {
// TODO(crbug.com/1524124): Investigate and fix why this gets hit.
DUMP_WILL_BE_NOTREACHED()
<< "An AXObject* that is a link should always have an element.\n"
<< this << "\n"
<< current;
}
return current->GetElement();
}
current = current->ParentObject();
}
return nullptr;
}
Document* AXNodeObject::GetDocument() const {
if (GetNode()) {
return &GetNode()->GetDocument();
}
if (GetLayoutObject()) {
return &GetLayoutObject()->GetDocument();
}
return nullptr;
}
LayoutObject* AXNodeObject::GetLayoutObject() const {
return layout_object_;
}
bool AXNodeObject::OnNativeBlurAction() {
Document* document = GetDocument();
Node* node = GetNode();
if (!document || !node) {
return false;
}
// An AXObject's node will always be of type `Element`, `Document` or
// `Text`. If the object we're currently on is associated with the currently
// focused element or the document object, we want to clear the focus.
// Otherwise, no modification is needed.
Element* element = GetElement();
if (element) {
element->blur();
return true;
}
if (IsA<Document>(GetNode())) {
document->ClearFocusedElement();
return true;
}
return false;
}
bool AXNodeObject::OnNativeFocusAction() {
Document* document = GetDocument();
Node* node = GetNode();
if (!document || !node)
return false;
if (!CanSetFocusAttribute())
return false;
if (IsWebArea()) {
// If another Frame has focused content (e.g. nested iframe), then we
// need to clear focus for the other Document Frame.
// Here we set the focused element via the FocusController so that the
// other Frame loses focus, and the target Document Element gains focus.
// This fixes a scenario with Narrator Item Navigation when the user
// navigates from the outer UI to the document when the last focused
// element was within a nested iframe before leaving the document frame.
if (Page* page = document->GetPage()) {
page->GetFocusController().SetFocusedElement(document->documentElement(),
document->GetFrame());
} else {
document->ClearFocusedElement();
}
return true;
}
Element* element = GetElement();
if (!element) {
document->ClearFocusedElement();
return true;
}
#if BUILDFLAG(IS_ANDROID)
// If this node is already the currently focused node, then calling
// focus() won't do anything. That is a problem when focus is removed
// from the webpage to chrome, and then returns. In these cases, we need
// to do what keyboard and mouse focus do, which is reset focus first.
if (document->FocusedElement() == element) {
document->ClearFocusedElement();
// Calling ClearFocusedElement could result in changes to the document,
// like this AXObject becoming detached.
if (IsDetached()) {
return false;
}
}
#endif
element->Focus(FocusParams(FocusTrigger::kUserGesture));
// Calling NotifyUserActivation here allows the browser to activate features
// that need user activation, such as showing an autofill suggestion.
LocalFrame::NotifyUserActivation(
document->GetFrame(),
mojom::blink::UserActivationNotificationType::kInteraction);
return true;
}
bool AXNodeObject::OnNativeIncrementAction() {
LocalFrame* frame = GetDocument() ? GetDocument()->GetFrame() : nullptr;
LocalFrame::NotifyUserActivation(
frame, mojom::blink::UserActivationNotificationType::kInteraction);
AlterSliderOrSpinButtonValue(true);
return true;
}
bool AXNodeObject::OnNativeDecrementAction() {
LocalFrame* frame = GetDocument() ? GetDocument()->GetFrame() : nullptr;
LocalFrame::NotifyUserActivation(
frame, mojom::blink::UserActivationNotificationType::kInteraction);
AlterSliderOrSpinButtonValue(false);
return true;
}
bool AXNodeObject::OnNativeSetSequentialFocusNavigationStartingPointAction() {
if (!GetNode())
return false;
Document* document = GetDocument();
document->ClearFocusedElement();
document->SetSequentialFocusNavigationStartingPoint(GetNode());
return true;
}
void AXNodeObject::SelectedOptions(AXObjectVector& options) const {
if (auto* select = DynamicTo<HTMLSelectElement>(GetNode())) {
for (auto* const option : *select->selectedOptions()) {
AXObject* ax_option = AXObjectCache().Get(option);
if (ax_option)
options.push_back(ax_option);
}
return;
}
const AXObjectVector& children = ChildrenIncludingIgnored();
if (RoleValue() == ax::mojom::blink::Role::kComboBoxGrouping ||
RoleValue() == ax::mojom::blink::Role::kComboBoxMenuButton) {
for (const auto& obj : children) {
if (obj->RoleValue() == ax::mojom::blink::Role::kListBox) {
obj->SelectedOptions(options);
return;
}
}
}
for (const auto& obj : children) {
if (obj->IsSelected() == kSelectedStateTrue)
options.push_back(obj);
}
}
//
// Notifications that this object may have changed.
//
void AXNodeObject::HandleAriaExpandedChanged() {
// Find if a parent of this object should handle aria-expanded changes.
AXObject* container_parent = ParentObject();
while (container_parent) {
bool found_parent = false;
switch (container_parent->RoleValue()) {
case ax::mojom::blink::Role::kLayoutTable:
case ax::mojom::blink::Role::kTree:
case ax::mojom::blink::Role::kTreeGrid:
case ax::mojom::blink::Role::kGrid:
case ax::mojom::blink::Role::kTable:
found_parent = true;
break;
default:
break;
}
if (found_parent)
break;
container_parent = container_parent->ParentObject();
}
// Post that the row count changed.
if (container_parent) {
AXObjectCache().PostNotification(container_parent,
ax::mojom::blink::Event::kRowCountChanged);
}
// Post that the specific row either collapsed or expanded.
AccessibilityExpanded expanded = IsExpanded();
if (!expanded)
return;
if (RoleValue() == ax::mojom::blink::Role::kRow ||
RoleValue() == ax::mojom::blink::Role::kTreeItem) {
ax::mojom::blink::Event notification =
ax::mojom::blink::Event::kRowExpanded;
if (expanded == kExpandedCollapsed)
notification = ax::mojom::blink::Event::kRowCollapsed;
AXObjectCache().PostNotification(this, notification);
} else {
AXObjectCache().PostNotification(this,
ax::mojom::blink::Event::kExpandedChanged);
}
}
void AXNodeObject::HandleActiveDescendantChanged() {
if (!GetLayoutObject() || !GetNode() || !GetDocument())
return;
Node* focused_node = GetDocument()->FocusedElement();
if (focused_node == GetNode()) {
AXObject* active_descendant = ActiveDescendant();
if (active_descendant) {
if (active_descendant->IsSelectedFromFocus()) {
// In single selection containers, selection follows focus, so a
// selection changed event must be fired. This ensures the AT is
// notified that the selected state has changed, so that it does not
// read "unselected" as the user navigates through the items.
AXObjectCache().HandleAriaSelectedChangedWithCleanLayout(
active_descendant->GetNode());
} else if (active_descendant->RoleValue() ==
ax::mojom::blink::Role::kRow) {
// Active descendant rows must be marked dirty because that can make
// them gain accessible name from contents
// (see AXObject::SupportsNameFromContents).
AXObjectCache().MarkAXObjectDirtyWithCleanLayout(active_descendant);
}
}
// Mark this node dirty. AXEventGenerator will automatically infer
// that the active descendant changed.
AXObjectCache().MarkAXObjectDirtyWithCleanLayout(this);
}
}
AXObject::AXObjectVector AXNodeObject::ErrorMessage() const {
if (GetInvalidState() == ax::mojom::blink::InvalidState::kFalse)
return AXObjectVector();
AXObjectVector aria_error_messages =
RelationVectorFromAria(html_names::kAriaErrormessageAttr);
if (aria_error_messages.size() > 0) {
return aria_error_messages;
}
AXObjectVector html_error_messages = ErrorMessageFromHTML();
if (html_error_messages.size() > 0) {
return html_error_messages;
}
return AXObjectVector();
}
AXObject::AXObjectVector AXNodeObject::RelationVectorFromAria(
const QualifiedName& attr_name) const {
Element* el = GetElement();
if (!el) {
return AXObjectVector();
}
const GCedHeapVector<Member<Element>>* elements_from_attribute =
ElementsFromAttributeOrInternals(el, attr_name);
if (!elements_from_attribute) {
return AXObjectVector();
}
AXObjectVector objects;
for (Element* element : *elements_from_attribute) {
AXObject* obj = AXObjectCache().Get(element);
if (obj && !obj->IsIgnored()) {
objects.push_back(obj);
}
}
return objects;
}
AXObject::AXObjectVector AXNodeObject::ErrorMessageFromHTML() const {
// This can only be visible for a focused
// control. Corollary: if there is a visible validationMessage alert box, then
// it is related to the current focus.
if (this != AXObjectCache().FocusedObject()) {
return AXObjectVector();
}
AXObject* native_error_message =
AXObjectCache().ValidationMessageObjectIfInvalid();
if (native_error_message && !native_error_message->IsDetached()) {
CHECK_GE(native_error_message->IndexInParent(), 0);
return AXObjectVector({native_error_message});
}
return AXObjectVector();
}
String AXNodeObject::TextAlternativeFromTooltip(
ax::mojom::blink::NameFrom& name_from,
NameSources* name_sources,
bool* found_text_alternative,
String* text_alternative,
AXRelatedObjectVector* related_objects) const {
if (!GetElement()) {
return String();
}
name_from = ax::mojom::blink::NameFrom::kTitle;
const AtomicString& title = GetElement()->FastGetAttribute(kTitleAttr);
String title_text = TextAlternativeFromTitleAttribute(
title, name_from, name_sources, found_text_alternative);
// Do not use if empty or if redundant with inner text.
if (!title_text.empty()) {
*text_alternative = title_text;
return title_text;
}
// First try for interest target, then for hint popover.
// TODO(accessibility) Consider only using interest target.
AXObject* popover_ax_object = nullptr;
if (RuntimeEnabledFeatures::HTMLInterestTargetAttributeEnabled(
GetElement()->GetDocument().GetExecutionContext())) {
popover_ax_object =
AXObjectCache().Get(GetElement()->InterestTargetElement());
}
if (popover_ax_object) {
DCHECK(RuntimeEnabledFeatures::HTMLInterestTargetAttributeEnabled(
GetElement()->GetDocument().GetExecutionContext()));
name_from = ax::mojom::blink::NameFrom::kInterestTarget;
} else {
auto* form_control = DynamicTo<HTMLFormControlElement>(GetElement());
if (!form_control) {
return String();
}
auto popover_target = form_control->popoverTargetElement();
if (!popover_target.popover ||
popover_target.popover->PopoverType() != PopoverValueType::kHint) {
return String();
}
popover_ax_object = AXObjectCache().Get(popover_target.popover);
name_from = ax::mojom::blink::NameFrom::kPopoverTarget;
}
if (name_sources) {
name_sources->push_back(
NameSource(*found_text_alternative, html_names::kPopovertargetAttr));
name_sources->back().type = name_from;
}
// Hint popovers and interest targets are used for text if and only if all of
// the contents are plain, e.g. have no interesting semantic or interactive
// elements. Otherwise, the hint will be exposed via the kDetails
// relationship. The motivation for this is that by reusing the simple
// mechanism of titles, screen reader users can easily access the information
// of plain hints without having to navigate to it, making the content more
// accessible. However, in the case of rich hints, a kDetails relationship is
// required to ensure that users are able to access and interact with the hint
// as they can navigate to it using commands.
if (!popover_ax_object || !popover_ax_object->IsPlainContent()) {
return String();
}
AXObjectSet visited;
String popover_text =
RecursiveTextAlternative(*popover_ax_object, popover_ax_object, visited);
// Do not use if redundant with inner text.
if (popover_text.StripWhiteSpace() ==
GetElement()->GetInnerTextWithoutUpdate().StripWhiteSpace()) {
return String();
}
*text_alternative = popover_text;
if (related_objects) {
related_objects->push_back(MakeGarbageCollected<NameSourceRelatedObject>(
popover_ax_object, popover_text));
}
if (name_sources) {
NameSource& source = name_sources->back();
source.related_objects = *related_objects;
source.text = *text_alternative;
*found_text_alternative = true;
}
return popover_text;
}
String AXNodeObject::TextAlternativeFromTitleAttribute(
const AtomicString& title,
ax::mojom::blink::NameFrom& name_from,
NameSources* name_sources,
bool* found_text_alternative) const {
DCHECK(GetElement());
String text_alternative;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative, kTitleAttr));
name_sources->back().type = name_from;
}
name_from = ax::mojom::blink::NameFrom::kTitle;
if (!title.IsNull() &&
String(title).StripWhiteSpace() !=
GetElement()->GetInnerTextWithoutUpdate().StripWhiteSpace()) {
text_alternative = title;
if (name_sources) {
NameSource& source = name_sources->back();
source.attribute_value = title;
source.attribute_value = title;
source.text = text_alternative;
*found_text_alternative = true;
}
}
return text_alternative;
}
// Based on
// https://www.w3.org/TR/html-aam-1.0/#accessible-name-and-description-computation
String AXNodeObject::NativeTextAlternative(
AXObjectSet& visited,
ax::mojom::blink::NameFrom& name_from,
AXRelatedObjectVector* related_objects,
NameSources* name_sources,
bool* found_text_alternative) const {
if (!GetNode())
return String();
// If nameSources is non-null, relatedObjects is used in filling it in, so it
// must be non-null as well.
if (name_sources)
DCHECK(related_objects);
String text_alternative;
AXRelatedObjectVector local_related_objects;
if (auto* option_element = DynamicTo<HTMLOptionElement>(GetNode())) {
if (option_element->HasOneTextChild()) {
// Use the DisplayLabel() method if there are no interesting children.
// If there are interesting children, fall through and compute the name
// from contents rather, so that descendant markup is respected.
name_from = ax::mojom::blink::NameFrom::kContents;
text_alternative = option_element->DisplayLabel();
if (!text_alternative.empty()) {
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative));
name_sources->back().type = name_from;
name_sources->back().text = text_alternative;
*found_text_alternative = true;
}
return text_alternative;
}
}
}
if (auto* opt_group_element = DynamicTo<HTMLOptGroupElement>(GetNode())) {
name_from = ax::mojom::blink::NameFrom::kAttribute;
text_alternative = opt_group_element->GroupLabelText();
if (!text_alternative.empty()) {
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative));
name_sources->back().type = name_from;
name_sources->back().text = text_alternative;
*found_text_alternative = true;
}
return text_alternative;
}
}
// 5.1/5.5 Text inputs, Other labelable Elements
// If you change this logic, update AXNodeObject::IsNameFromLabelElement, too.
auto* html_element = DynamicTo<HTMLElement>(GetNode());
if (html_element && html_element->IsLabelable()) {
name_from = ax::mojom::blink::NameFrom::kRelatedElement;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative));
name_sources->back().type = name_from;
name_sources->back().native_source = kAXTextFromNativeHTMLLabel;
}
LabelsNodeList* labels = nullptr;
if (AXObjectCache().MayHaveHTMLLabel(*html_element))
labels = html_element->labels();
if (labels && labels->length() > 0) {
HeapVector<Member<Element>> label_elements;
for (unsigned label_index = 0; label_index < labels->length();
++label_index) {
Element* label = labels->item(label_index);
if (name_sources) {
if (!label->FastGetAttribute(html_names::kForAttr).empty() &&
label->FastGetAttribute(html_names::kForAttr) ==
html_element->GetIdAttribute()) {
name_sources->back().native_source = kAXTextFromNativeHTMLLabelFor;
} else {
name_sources->back().native_source =
kAXTextFromNativeHTMLLabelWrapped;
}
}
label_elements.push_back(label);
}
text_alternative =
TextFromElements(false, visited, label_elements, related_objects);
if (!text_alternative.IsNull()) {
*found_text_alternative = true;
if (name_sources) {
NameSource& source = name_sources->back();
source.related_objects = *related_objects;
source.text = text_alternative;
} else {
return text_alternative.StripWhiteSpace();
}
} else if (name_sources) {
name_sources->back().invalid = true;
}
}
}
// 5.2 input type="button", input type="submit" and input type="reset"
const auto* input_element = DynamicTo<HTMLInputElement>(GetNode());
if (input_element && input_element->IsTextButton()) {
// value attribute.
name_from = ax::mojom::blink::NameFrom::kValue;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative, kValueAttr));
name_sources->back().type = name_from;
}
String value = input_element->Value();
if (!value.IsNull()) {
text_alternative = value;
if (name_sources) {
NameSource& source = name_sources->back();
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
// Get default value if object is not laid out.
// If object is laid out, it will have a layout object for the label.
if (!GetLayoutObject()) {
String default_label = input_element->ValueOrDefaultLabel();
if (value.IsNull() && !default_label.IsNull()) {
// default label
name_from = ax::mojom::blink::NameFrom::kContents;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative));
name_sources->back().type = name_from;
}
text_alternative = default_label;
if (name_sources) {
NameSource& source = name_sources->back();
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
}
return text_alternative;
}
// 5.3 input type="image"
if (input_element &&
input_element->getAttribute(kTypeAttr) == input_type_names::kImage) {
// alt attr
const AtomicString& alt = input_element->getAttribute(kAltAttr);
const bool is_empty = alt.empty() && !alt.IsNull();
name_from = is_empty ? ax::mojom::blink::NameFrom::kAttributeExplicitlyEmpty
: ax::mojom::blink::NameFrom::kAttribute;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative, kAltAttr));
name_sources->back().type = name_from;
}
if (!alt.empty()) {
text_alternative = alt;
if (name_sources) {
NameSource& source = name_sources->back();
source.attribute_value = alt;
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
// value attribute.
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative, kValueAttr));
name_sources->back().type = name_from;
}
name_from = ax::mojom::blink::NameFrom::kAttribute;
String value = input_element->Value();
if (!value.IsNull()) {
text_alternative = value;
if (name_sources) {
NameSource& source = name_sources->back();
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
// title attr or popover
String resulting_text = TextAlternativeFromTooltip(
name_from, name_sources, found_text_alternative, &text_alternative,
related_objects);
if (!resulting_text.empty()) {
if (name_sources) {
text_alternative = resulting_text;
} else {
return resulting_text;
}
}
// localised default value ("Submit")
name_from = ax::mojom::blink::NameFrom::kValue;
text_alternative =
input_element->GetLocale().QueryString(IDS_FORM_SUBMIT_LABEL);
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative, kTypeAttr));
NameSource& source = name_sources->back();
source.attribute_value = input_element->getAttribute(kTypeAttr);
source.type = name_from;
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
return text_alternative;
}
// <input type="file">
if (input_element &&
input_element->FormControlType() == FormControlType::kInputFile) {
// Append label of inner shadow root button + value attribute.
name_from = ax::mojom::blink::NameFrom::kContents;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative, kValueAttr));
name_sources->back().type = name_from;
}
if (ShadowRoot* shadow_root = input_element->UserAgentShadowRoot()) {
text_alternative =
To<HTMLInputElement>(shadow_root->firstElementChild())->Value();
if (name_sources) {
NameSource& source = name_sources->back();
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
}
// 5.1 Text inputs - step 3 (placeholder attribute)
if (html_element && html_element->IsTextControl()) {
// title attr
String resulting_text = TextAlternativeFromTooltip(
name_from, name_sources, found_text_alternative, &text_alternative,
related_objects);
if (!resulting_text.empty()) {
if (name_sources) {
text_alternative = resulting_text;
} else {
return resulting_text;
}
}
name_from = ax::mojom::blink::NameFrom::kPlaceholder;
if (name_sources) {
name_sources->push_back(
NameSource(*found_text_alternative, html_names::kPlaceholderAttr));
NameSource& source = name_sources->back();
source.type = name_from;
}
const String placeholder = PlaceholderFromNativeAttribute();
if (!placeholder.empty()) {
text_alternative = placeholder;
if (name_sources) {
NameSource& source = name_sources->back();
source.text = text_alternative;
source.attribute_value =
html_element->FastGetAttribute(html_names::kPlaceholderAttr);
*found_text_alternative = true;
} else {
return text_alternative;
}
}
}
// Also check for aria-placeholder.
if (IsTextField()) {
name_from = ax::mojom::blink::NameFrom::kPlaceholder;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative,
html_names::kAriaPlaceholderAttr));
NameSource& source = name_sources->back();
source.type = name_from;
}
const AtomicString& aria_placeholder =
AriaAttribute(html_names::kAriaPlaceholderAttr);
if (!aria_placeholder.empty()) {
text_alternative = aria_placeholder;
if (name_sources) {
NameSource& source = name_sources->back();
source.text = text_alternative;
source.attribute_value = aria_placeholder;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
return text_alternative;
}
// 5.8 img or area Element
if (IsA<HTMLImageElement>(GetNode()) || IsA<HTMLAreaElement>(GetNode())) {
// alt
const AtomicString& alt = GetElement()->FastGetAttribute(kAltAttr);
const bool is_empty = alt.empty() && !alt.IsNull();
name_from = is_empty ? ax::mojom::blink::NameFrom::kAttributeExplicitlyEmpty
: ax::mojom::blink::NameFrom::kAttribute;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative, kAltAttr));
name_sources->back().type = name_from;
}
if (!alt.empty()) {
text_alternative = alt;
if (name_sources) {
NameSource& source = name_sources->back();
source.attribute_value = alt;
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
return text_alternative;
}
// 5.9 table Element
if (auto* table_element = DynamicTo<HTMLTableElement>(GetNode())) {
// caption
name_from = ax::mojom::blink::NameFrom::kCaption;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative));
name_sources->back().type = name_from;
name_sources->back().native_source = kAXTextFromNativeHTMLTableCaption;
}
HTMLTableCaptionElement* caption = table_element->caption();
if (caption) {
AXObject* caption_ax_object = AXObjectCache().Get(caption);
if (caption_ax_object) {
text_alternative =
RecursiveTextAlternative(*caption_ax_object, nullptr, visited);
if (related_objects) {
local_related_objects.push_back(
MakeGarbageCollected<NameSourceRelatedObject>(caption_ax_object,
text_alternative));
*related_objects = local_related_objects;
local_related_objects.clear();
}
if (name_sources) {
NameSource& source = name_sources->back();
source.related_objects = *related_objects;
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
}
// summary
name_from = ax::mojom::blink::NameFrom::kAttribute;
if (name_sources) {
name_sources->push_back(
NameSource(*found_text_alternative, html_names::kSummaryAttr));
name_sources->back().type = name_from;
}
const AtomicString& summary =
GetElement()->FastGetAttribute(html_names::kSummaryAttr);
if (!summary.IsNull()) {
text_alternative = summary;
if (name_sources) {
NameSource& source = name_sources->back();
source.attribute_value = summary;
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
return text_alternative;
}
// Per SVG AAM 1.0's modifications to 2D of this algorithm.
if (GetNode()->IsSVGElement()) {
name_from = ax::mojom::blink::NameFrom::kRelatedElement;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative));
name_sources->back().type = name_from;
name_sources->back().native_source = kAXTextFromNativeTitleElement;
}
auto* container_node = To<ContainerNode>(GetNode());
Element* title = ElementTraversal::FirstChild(
*container_node, HasTagName(svg_names::kTitleTag));
if (title) {
// TODO(accessibility): In most cases <desc> and <title> can
// participate in the recursive text alternative calculation. However
// when the <desc> or <title> is the child of a <use>,
// |AXObjectCache::GetOrCreate| will fail when
// |AXObject::ComputeNonARIAParent| returns null because the <use>
// element's subtree isn't visited by LayoutTreeBuilderTraversal. In
// addition, while aria-label and other text alternative sources are
// are technically valid on SVG <desc> and <title>, it is not clear if
// user agents must expose their values. Therefore until we hear
// otherwise, just use the inner text. See
// https://github.com/w3c/svgwg/issues/867
text_alternative = title->GetInnerTextWithoutUpdate();
if (!text_alternative.empty()) {
if (name_sources) {
NameSource& source = name_sources->back();
source.text = text_alternative;
source.related_objects = *related_objects;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
}
// The SVG-AAM says that the xlink:title participates as a name source
// for links.
if (IsA<SVGAElement>(GetNode())) {
name_from = ax::mojom::blink::NameFrom::kAttribute;
if (name_sources) {
name_sources->push_back(
NameSource(*found_text_alternative, xlink_names::kTitleAttr));
name_sources->back().type = name_from;
}
const AtomicString& title_attr =
DynamicTo<Element>(GetNode())->FastGetAttribute(
xlink_names::kTitleAttr);
if (!title_attr.empty()) {
text_alternative = title_attr;
if (name_sources) {
NameSource& source = name_sources->back();
source.text = text_alternative;
source.attribute_value = title_attr;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
}
}
// Fieldset / legend.
if (auto* html_field_set_element =
DynamicTo<HTMLFieldSetElement>(GetNode())) {
name_from = ax::mojom::blink::NameFrom::kRelatedElement;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative));
name_sources->back().type = name_from;
name_sources->back().native_source = kAXTextFromNativeHTMLLegend;
}
HTMLElement* legend = html_field_set_element->Legend();
if (legend) {
AXObject* legend_ax_object = AXObjectCache().Get(legend);
// Avoid an infinite loop
if (legend_ax_object && !visited.Contains(legend_ax_object)) {
text_alternative =
RecursiveTextAlternative(*legend_ax_object, nullptr, visited);
if (related_objects) {
local_related_objects.push_back(
MakeGarbageCollected<NameSourceRelatedObject>(legend_ax_object,
text_alternative));
*related_objects = local_related_objects;
local_related_objects.clear();
}
if (name_sources) {
NameSource& source = name_sources->back();
source.related_objects = *related_objects;
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
}
}
// Document.
if (Document* document = DynamicTo<Document>(GetNode())) {
if (document) {
name_from = ax::mojom::blink::NameFrom::kAttribute;
if (name_sources) {
name_sources->push_back(
NameSource(found_text_alternative, html_names::kAriaLabelAttr));
name_sources->back().type = name_from;
}
if (Element* document_element = document->documentElement()) {
const AtomicString& aria_label =
AriaAttribute(*document_element, html_names::kAriaLabelAttr);
if (!aria_label.empty()) {
text_alternative = aria_label;
if (name_sources) {
NameSource& source = name_sources->back();
source.text = text_alternative;
source.attribute_value = aria_label;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
}
text_alternative = document->title();
bool is_empty_title_element =
text_alternative.empty() && document->TitleElement();
if (is_empty_title_element)
name_from = ax::mojom::blink::NameFrom::kAttributeExplicitlyEmpty;
else
name_from = ax::mojom::blink::NameFrom::kRelatedElement;
if (name_sources) {
name_sources->push_back(NameSource(*found_text_alternative));
NameSource& source = name_sources->back();
source.type = name_from;
source.native_source = kAXTextFromNativeTitleElement;
source.text = text_alternative;
*found_text_alternative = true;
} else {
return text_alternative;
}
}
}
return text_alternative;
}
// static
String AXNodeObject::GetSavedTextAlternativeFromNameSource(
bool found_text_alternative,
ax::mojom::NameFrom& name_from,
AXRelatedObjectVector* related_objects,
NameSources* name_sources) {
name_from = ax::mojom::blink::NameFrom::kNone;
if (!name_sources || !found_text_alternative) {
return String();
}
for (NameSource& name_source : *name_sources) {
if (name_source.text.empty() || name_source.superseded) {
continue;
}
name_from = name_source.type;
if (!name_source.related_objects.empty()) {
*related_objects = name_source.related_objects;
}
return name_source.text;
}
return String();
}
// This is not part of the spec, but we think it's a worthy addition: if the
// labelled input is of type="file", we append the chosen file name to it. We do
// this because this type of input is actually exposed as a button, and buttons
// may not have a "value" field. An unlabelled input is manager later in this
// function, it's named with the default text in the button, 'Choose File', plus
// the file name.
String AXNodeObject::MaybeAppendFileDescriptionToName(
const String& name) const {
const auto* input_element = DynamicTo<HTMLInputElement>(GetNode());
if (!input_element ||
input_element->FormControlType() != FormControlType::kInputFile) {
return name;
}
String displayed_file_path = GetValueForControl();
if (!displayed_file_path.empty()) {
if (GetTextDirection() == ax::mojom::blink::WritingDirection::kRtl)
return name + " :" + displayed_file_path;
else
return name + ": " + displayed_file_path;
}
return name;
}
bool AXNodeObject::ShouldIncludeContentInTextAlternative(
bool recursive,
const AXObject* aria_label_or_description_root,
AXObjectSet& visited) const {
if (!aria_label_or_description_root &&
!SupportsNameFromContents(recursive, /*consider_focus*/ true)) {
return false;
}
// Avoid option descendent text.
if (IsA<HTMLSelectElement>(GetNode())) {
return false;
}
// A textfield's name should not include its value (see crbug.com/352665697),
// unless aria-labelledby explicitly references its own content.
//
// Example from aria-labelledby-on-input.html:
// <input id="time" value="10" aria-labelledby="message time unit"/>
//
// When determining the name for the <input>, we parse the list of IDs in
// aria-labelledby. When "time" is reached, aria_label_or_description_root
// points to the element we are naming (the <input>) and 'this' refers to the
// element we are currently traversing, which is the element with id="time"
// (so, aria_label_or_description_root == this). In this case, since the
// author explicitly included the input id, the value of the input should be
// included in the name.
if (IsTextField() && aria_label_or_description_root != this) {
return false;
}
return true;
}
String AXNodeObject::Description(
ax::mojom::blink::NameFrom name_from,
ax::mojom::blink::DescriptionFrom& description_from,
AXObjectVector* description_objects) const {
AXRelatedObjectVector related_objects;
String result =
Description(name_from, description_from, nullptr, &related_objects);
if (description_objects) {
description_objects->clear();
for (NameSourceRelatedObject* related_object : related_objects)
description_objects->push_back(related_object->object);
}
result = result.SimplifyWhiteSpace(IsHTMLSpace<UChar>);
if (RoleValue() == ax::mojom::blink::Role::kSpinButton &&
DatetimeAncestor()) {
// Fields inside a datetime control need to merge the field description
// with the description of the <input> element.
const AXObject* datetime_ancestor = DatetimeAncestor();
ax::mojom::blink::NameFrom datetime_ancestor_name_from;
datetime_ancestor->GetName(datetime_ancestor_name_from, nullptr);
if (description_objects)
description_objects->clear();
String ancestor_description = DatetimeAncestor()->Description(
datetime_ancestor_name_from, description_from, description_objects);
if (!result.empty() && !ancestor_description.empty())
return result + " " + ancestor_description;
if (!ancestor_description.empty())
return ancestor_description;
}
return result;
}
// Based on
// http://rawgit.com/w3c/aria/master/html-aam/html-aam.html#accessible-name-and-description-calculation
String AXNodeObject::Description(
ax::mojom::blink::NameFrom name_from,
ax::mojom::blink::DescriptionFrom& description_from,
DescriptionSources* description_sources,
AXRelatedObjectVector* related_objects) const {
// If descriptionSources is non-null, relatedObjects is used in filling it in,
// so it must be non-null as well.
// Important: create a DescriptionSource for every *potential* description
// source, even if it ends up not being present.
// When adding a new description_from type:
// * Also add it to AXValueNativeSourceType here:
// blink/public/devtools_protocol/browser_protocol.pdl
// * Update InspectorTypeBuilderHelper to map the new enum to
// the browser_protocol enum in NativeSourceType():
// blink/renderer/modules/accessibility/inspector_type_builder_helper.cc
// * Update devtools_frontend to add a new string for the new type of
// description. See AXNativeSourceTypes at:
// devtools-frontend/src/front_end/accessibility/AccessibilityStrings.js
if (description_sources)
DCHECK(related_objects);
if (!GetNode())
return String();
String description;
bool found_description = false;
description_from = ax::mojom::blink::DescriptionFrom::kRelatedElement;
if (description_sources) {
description_sources->push_back(
DescriptionSource(found_description, html_names::kAriaDescribedbyAttr));
description_sources->back().type = description_from;
}
// aria-describedby overrides any other accessible description, from:
// http://rawgit.com/w3c/aria/master/html-aam/html-aam.html
Element* element = GetElement();
if (!element)
return String();
const GCedHeapVector<Member<Element>>* elements_from_attribute =
ElementsFromAttributeOrInternals(element,
html_names::kAriaDescribedbyAttr);
if (elements_from_attribute) {
// TODO(meredithl): Determine description sources when |aria_describedby| is
// the empty string, in order to make devtools work with attr-associated
// elements.
if (description_sources) {
description_sources->back().attribute_value =
AriaAttribute(html_names::kAriaDescribedbyAttr);
}
AXObjectSet visited;
description = TextFromElements(true, visited, *elements_from_attribute,
related_objects);
if (!description.IsNull()) {
if (description_sources) {
DescriptionSource& source = description_sources->back();
source.type = description_from;
source.related_objects = *related_objects;
source.text = description;
found_description = true;
} else {
return description;
}
} else if (description_sources) {
description_sources->back().invalid = true;
}
}
// aria-description overrides any HTML-based accessible description,
// but not aria-describedby.
const AtomicString& aria_desc =
AriaAttribute(html_names::kAriaDescriptionAttr);
if (aria_desc) {
description_from = ax::mojom::blink::DescriptionFrom::kAriaDescription;
description = aria_desc;
if (description_sources) {
found_description = true;
description_sources->back().text = description;
} else {
return description;
}
}
// SVG-AAM specifies additional description sources when ARIA sources have not
// been found. https://w3c.github.io/svg-aam/#mapping_additional_nd
if (IsA<SVGElement>(GetNode())) {
String svg_description = SVGDescription(
name_from, description_from, description_sources, related_objects);
if (!svg_description.empty()) {
return svg_description;
}
}
const auto* input_element = DynamicTo<HTMLInputElement>(GetNode());
// value, 5.2.2 from: https://www.w3.org/TR/html-aam-1.0/
if (name_from != ax::mojom::blink::NameFrom::kValue && input_element &&
input_element->IsTextButton()) {
description_from = ax::mojom::blink::DescriptionFrom::kButtonLabel;
if (description_sources) {
description_sources->push_back(
DescriptionSource(found_description, kValueAttr));
description_sources->back().type = description_from;
}
String value = input_element->Value();
if (!value.IsNull()) {
description = value;
if (description_sources) {
DescriptionSource& source = description_sources->back();
source.text = description;
found_description = true;
} else {
return description;
}
}
}
if (RoleValue() == ax::mojom::blink::Role::kRuby) {
description_from = ax::mojom::blink::DescriptionFrom::kRubyAnnotation;
if (description_sources) {
description_sources->push_back(DescriptionSource(found_description));
description_sources->back().type = description_from;
description_sources->back().native_source =
kAXTextFromNativeHTMLRubyAnnotation;
}
AXObject* ruby_annotation_ax_object = nullptr;
for (const auto& child : children_) {
if (child->RoleValue() == ax::mojom::blink::Role::kRubyAnnotation &&
child->GetNode() &&
child->GetNode()->HasTagName(html_names::kRtTag)) {
ruby_annotation_ax_object = child;
break;
}
}
if (ruby_annotation_ax_object) {
AXObjectSet visited;
description =
RecursiveTextAlternative(*ruby_annotation_ax_object, this, visited);
if (related_objects) {
related_objects->push_back(
MakeGarbageCollected<NameSourceRelatedObject>(
ruby_annotation_ax_object, description));
}
if (description_sources) {
DescriptionSource& source = description_sources->back();
source.related_objects = *related_objects;
source.text = description;
found_description = true;
} else {
return description;
}
}
}
// table caption, 5.9.2 from: https://www.w3.org/TR/html-aam-1.0/
auto* table_element = DynamicTo<HTMLTableElement>(element);
if (name_from != ax::mojom::blink::NameFrom::kCaption && table_element) {
description_from = ax::mojom::blink::DescriptionFrom::kTableCaption;
if (description_sources) {
description_sources->push_back(DescriptionSource(found_description));
description_sources->back().type = description_from;
description_sources->back().native_source =
kAXTextFromNativeHTMLTableCaption;
}
HTMLTableCaptionElement* caption = table_element->caption();
if (caption) {
AXObject* caption_ax_object = AXObjectCache().Get(caption);
if (caption_ax_object) {
AXObjectSet visited;
description =
RecursiveTextAlternative(*caption_ax_object, nullptr, visited);
if (related_objects) {
related_objects->push_back(
MakeGarbageCollected<NameSourceRelatedObject>(caption_ax_object,
description));
}
if (description_sources) {
DescriptionSource& source = description_sources->back();
source.related_objects = *related_objects;
source.text = description;
found_description = true;
} else {
return description;
}
}
}
}
// summary, 5.8.2 from: https://www.w3.org/TR/html-aam-1.0/
if (name_from != ax::mojom::blink::NameFrom::kContents &&
IsA<HTMLSummaryElement>(GetNode())) {
description_from = ax::mojom::blink::DescriptionFrom::kSummary;
if (description_sources) {
description_sources->push_back(DescriptionSource(found_description));
description_sources->back().type = description_from;
}
AXObjectSet visited;
description = TextFromDescendants(visited, nullptr, false);
if (!description.empty()) {
if (description_sources) {
found_description = true;
description_sources->back().text = description;
} else {
return description;
}
}
}
// title attribute, from: https://www.w3.org/TR/html-aam-1.0/
if (name_from != ax::mojom::blink::NameFrom::kTitle) {
description_from = ax::mojom::blink::DescriptionFrom::kTitle;
if (description_sources) {
description_sources->push_back(
DescriptionSource(found_description, kTitleAttr));
description_sources->back().type = description_from;
}
const AtomicString& title = element->FastGetAttribute(kTitleAttr);
if (!title.empty() &&
String(title).StripWhiteSpace() !=
element->GetInnerTextWithoutUpdate().StripWhiteSpace()) {
description = title;
if (description_sources) {
found_description = true;
description_sources->back().text = description;
} else {
return description;
}
}
}
// For form controls that act as interest target triggering elements, use
// the target for a description if it only contains plain contents.
if (RuntimeEnabledFeatures::HTMLInterestTargetAttributeEnabled(
element->GetDocument().GetExecutionContext()) &&
name_from != ax::mojom::blink::NameFrom::kInterestTarget) {
if (Element* interest_target = element->InterestTargetElement()) {
DCHECK(RuntimeEnabledFeatures::HTMLInterestTargetAttributeEnabled(
element->GetDocument().GetExecutionContext()));
description_from = ax::mojom::blink::DescriptionFrom::kInterestTarget;
if (description_sources) {
description_sources->push_back(DescriptionSource(
found_description, html_names::kInteresttargetAttr));
description_sources->back().type = description_from;
}
AXObject* interest_ax_object = AXObjectCache().Get(interest_target);
if (interest_ax_object && interest_ax_object->IsPlainContent()) {
AXObjectSet visited;
description = RecursiveTextAlternative(*interest_ax_object,
interest_ax_object, visited);
if (related_objects) {
related_objects->push_back(
MakeGarbageCollected<NameSourceRelatedObject>(interest_ax_object,
description));
}
if (description_sources) {
DescriptionSource& source = description_sources->back();
source.related_objects = *related_objects;
source.text = description;
found_description = true;
} else {
return description;
}
}
}
}
// For form controls that act as triggering elements for popovers of type
// kHint, then set aria-describedby to the popover.
if (name_from != ax::mojom::blink::NameFrom::kPopoverTarget) {
if (auto* form_control = DynamicTo<HTMLFormControlElement>(element)) {
auto popover_target = form_control->popoverTargetElement();
if (popover_target.popover &&
popover_target.popover->PopoverType() == PopoverValueType::kHint) {
description_from = ax::mojom::blink::DescriptionFrom::kPopoverTarget;
if (description_sources) {
description_sources->push_back(DescriptionSource(
found_description, html_names::kPopovertargetAttr));
description_sources->back().type = description_from;
}
AXObject* popover_ax_object =
AXObjectCache().Get(popover_target.popover);
if (popover_ax_object && popover_ax_object->IsPlainContent()) {
AXObjectSet visited;
description = RecursiveTextAlternative(*popover_ax_object,
popover_ax_object, visited);
if (related_objects) {
related_objects->push_back(
MakeGarbageCollected<NameSourceRelatedObject>(popover_ax_object,
description));
}
if (description_sources) {
DescriptionSource& source = description_sources->back();
source.related_objects = *related_objects;
source.text = description;
found_description = true;
} else {
return description;
}
}
}
}
}
// There was a name, but it is prohibited for this role. Move to description.
if (name_from == ax::mojom::blink::NameFrom::kProhibited) {
description_from = ax::mojom::blink::DescriptionFrom::kProhibitedNameRepair;
ax::mojom::blink::NameFrom orig_name_from_without_prohibited;
HeapHashSet<Member<const AXObject>> visited;
description = TextAlternative(false, nullptr, visited,
orig_name_from_without_prohibited,
related_objects, nullptr);
DCHECK(!description.empty());
if (description_sources) {
description_sources->push_back(DescriptionSource(found_description));
DescriptionSource& source = description_sources->back();
source.type = description_from;
source.related_objects = *related_objects;
source.text = description;
found_description = true;
} else {
return description;
}
}
description_from = ax::mojom::blink::DescriptionFrom::kNone;
if (found_description) {
DCHECK(description_sources)
<< "Should only reach here if description_sources are tracked";
// Use the first non-null description.
// TODO(accessibility) Why do we need to check superceded if that will
// always be the first one?
for (DescriptionSource& description_source : *description_sources) {
if (!description_source.text.IsNull() && !description_source.superseded) {
description_from = description_source.type;
if (!description_source.related_objects.empty())
*related_objects = description_source.related_objects;
return description_source.text;
}
}
}
return String();
}
String AXNodeObject::SVGDescription(
ax::mojom::blink::NameFrom name_from,
ax::mojom::blink::DescriptionFrom& description_from,
DescriptionSources* description_sources,
AXRelatedObjectVector* related_objects) const {
DCHECK(IsA<SVGElement>(GetNode()));
String description;
bool found_description = false;
Element* element = GetElement();
description_from = ax::mojom::blink::DescriptionFrom::kSvgDescElement;
if (description_sources) {
description_sources->push_back(DescriptionSource(found_description));
description_sources->back().type = description_from;
description_sources->back().native_source = kAXTextFromNativeSVGDescElement;
}
if (Element* desc = ElementTraversal::FirstChild(
*element, HasTagName(svg_names::kDescTag))) {
// TODO(accessibility): In most cases <desc> and <title> can participate in
// the recursive text alternative calculation. However when the <desc> or
// <title> is the child of a <use>, |AXObjectCache::GetOrCreate| will fail
// when |AXObject::ComputeNonARIAParent| returns null because the <use>
// element's subtree isn't visited by LayoutTreeBuilderTraversal. In
// addition, while aria-label and other text alternative sources are are
// technically valid on SVG <desc> and <title>, it is not clear if user
// agents must expose their values. Therefore until we hear otherwise, just
// use the inner text. See https://github.com/w3c/svgwg/issues/867
description = desc->GetInnerTextWithoutUpdate();
if (!description.empty()) {
if (description_sources) {
DescriptionSource& source = description_sources->back();
source.related_objects = *related_objects;
source.text = description;
found_description = true;
} else {
return description;
}
}
}
// If we haven't found a description source yet and the title is present,
// SVG-AAM states to use the <title> if ARIA label attributes are used to
// provide the accessible name.
if (IsNameFromAriaAttribute(element)) {
description_from = ax::mojom::blink::DescriptionFrom::kTitle;
if (description_sources) {
description_sources->push_back(DescriptionSource(found_description));
description_sources->back().type = description_from;
description_sources->back().native_source = kAXTextFromNativeTitleElement;
}
if (Element* title = ElementTraversal::FirstChild(
*element, HasTagName(svg_names::kTitleTag))) {
// TODO(accessibility): In most cases <desc> and <title> can participate
// in the recursive text alternative calculation. However when the <desc>
// or <title> is the child of a <use>, |AXObjectCache::GetOrCreate| will
// fail when |AXObject::ComputeNonARIAParent| returns null because the
// <use> element's subtree isn't visited by LayoutTreeBuilderTraversal. In
// addition, while aria-label and other text alternative sources are are
// technically valid on SVG <desc> and <title>, it is not clear if user
// agents must expose their values. Therefore until we hear otherwise,
// just use the inner text. See https://github.com/w3c/svgwg/issues/867
description = title->GetInnerTextWithoutUpdate();
if (!description.empty()) {
if (description_sources) {
DescriptionSource& source = description_sources->back();
source.related_objects = *related_objects;
source.text = description;
found_description = true;
} else {
return description;
}
}
}
}
// In the case of an SVG <a>, the last description source is the xlink:title
// attribute, if it didn't serve as the name source.
if (IsA<SVGAElement>(GetNode()) &&
name_from != ax::mojom::blink::NameFrom::kAttribute) {
description_from = ax::mojom::blink::DescriptionFrom::kTitle;
const AtomicString& title_attr =
DynamicTo<Element>(GetNode())->FastGetAttribute(
xlink_names::kTitleAttr);
if (!title_attr.empty()) {
description = title_attr;
if (description_sources) {
found_description = true;
description_sources->back().text = description;
} else {
return description;
}
}
}
return String();
}
String AXNodeObject::Placeholder(ax::mojom::blink::NameFrom name_from) const {
if (name_from == ax::mojom::blink::NameFrom::kPlaceholder)
return String();
Node* node = GetNode();
if (!node || !node->IsHTMLElement())
return String();
String native_placeholder = PlaceholderFromNativeAttribute();
if (!native_placeholder.empty())
return native_placeholder;
const AtomicString& aria_placeholder =
AriaAttribute(html_names::kAriaPlaceholderAttr);
if (!aria_placeholder.empty())
return aria_placeholder;
return String();
}
String AXNodeObject::Title(ax::mojom::blink::NameFrom name_from) const {
if (name_from == ax::mojom::blink::NameFrom::kTitle)
return String(); // Already exposed the title in the name field.
return GetTitle(GetElement());
}
String AXNodeObject::PlaceholderFromNativeAttribute() const {
Node* node = GetNode();
if (!node || !blink::IsTextControl(*node))
return String();
return ToTextControl(node)->StrippedPlaceholder();
}
String AXNodeObject::GetValueContributionToName(AXObjectSet& visited) const {
if (IsTextField())
return SlowGetValueForControlIncludingContentEditable();
if (IsRangeValueSupported()) {
const AtomicString& aria_valuetext =
AriaAttribute(html_names::kAriaValuetextAttr);
if (aria_valuetext) {
return aria_valuetext.GetString();
}
float value;
if (ValueForRange(&value))
return String::Number(value);
}
// "If the embedded control has role combobox or listbox, return the text
// alternative of the chosen option."
if (UseNameFromSelectedOption()) {
AXObjectVector selected_options;
SelectedOptions(selected_options);
if (selected_options.size() == 0) {
// Per https://www.w3.org/TR/wai-aria/#combobox, a combobox gets its
// value in the following way:
// "If the combobox element is a host language element that provides a
// value, such as an HTML input element, the value of the combobox is the
// value of that element. Otherwise, the value of the combobox is
// represented by its descendant elements and can be determined using the
// same method used to compute the name of a button from its descendant
// content."
//
// Section 2C of the accname computation steps for the combobox/listbox
// case (https://w3c.github.io/accname/#comp_embedded_control) only
// mentions getting the text alternative from the chosen option, which
// doesn't precisely fit for combobox, but a clarification is coming; see
// https://github.com/w3c/accname/issues/232 and
// https://github.com/w3c/accname/issues/200.
return SlowGetValueForControlIncludingContentEditable(visited);
} else {
StringBuilder accumulated_text;
for (const auto& child : selected_options) {
if (visited.insert(child).is_new_entry) {
if (accumulated_text.length()) {
accumulated_text.Append(" ");
}
accumulated_text.Append(child->ComputedName());
}
}
return accumulated_text.ToString();
}
}
return String();
}
bool AXNodeObject::UseNameFromSelectedOption() const {
// Assumes that the node was reached via recursion in the name calculation.
switch (RoleValue()) {
// Step 2E from: http://www.w3.org/TR/accname-aam-1.1
case ax::mojom::blink::Role::kComboBoxGrouping:
case ax::mojom::blink::Role::kComboBoxMenuButton:
case ax::mojom::blink::Role::kComboBoxSelect:
case ax::mojom::blink::Role::kListBox:
return true;
default:
return false;
}
}
ScrollableArea* AXNodeObject::GetScrollableAreaIfScrollable() const {
if (IsA<Document>(GetNode())) {
return DocumentFrameView()->LayoutViewport();
}
if (auto* box = DynamicTo<LayoutBox>(GetLayoutObject())) {
PaintLayerScrollableArea* scrollable_area = box->GetScrollableArea();
if (scrollable_area && scrollable_area->HasOverflow()) {
return scrollable_area;
}
}
return nullptr;
}
AXObject* AXNodeObject::AccessibilityHitTest(const gfx::Point& point) const {
// Must be called for the document's root or a popup's root.
if (!IsA<Document>(GetNode())) {
return nullptr;
}
CHECK(GetLayoutObject());
// Must be called with lifecycle >= pre-paint clean
DCHECK_GE(GetDocument()->Lifecycle().GetState(),
DocumentLifecycle::kPrePaintClean);
DCHECK(GetLayoutObject()->IsLayoutView());
PaintLayer* layer = To<LayoutBox>(GetLayoutObject())->Layer();
DCHECK(layer);
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
HitTestLocation location(point);
HitTestResult hit_test_result = HitTestResult(request, location);
layer->HitTest(location, hit_test_result, PhysicalRect(InfiniteIntRect()));
Node* node = hit_test_result.InnerNode();
if (!node) {
return nullptr;
}
if (auto* area = DynamicTo<HTMLAreaElement>(node)) {
return AccessibilityImageMapHitTest(area, point);
}
if (auto* option = DynamicTo<HTMLOptionElement>(node)) {
node = option->OwnerSelectElement();
if (!node) {
return nullptr;
}
}
// If |node| is in a user-agent shadow tree, reassign it as the host to hide
// details in the shadow tree. Previously this was implemented by using
// Retargeting (https://dom.spec.whatwg.org/#retarget), but this caused
// elements inside regular shadow DOMs to be ignored by screen reader. See
// crbug.com/1111800 and crbug.com/1048959.
const TreeScope& tree_scope = node->GetTreeScope();
if (auto* shadow_root = DynamicTo<ShadowRoot>(tree_scope.RootNode())) {
if (shadow_root->IsUserAgent()) {
node = &shadow_root->host();
}
}
LayoutObject* obj = node->GetLayoutObject();
AXObject* result = AXObjectCache().Get(obj);
if (!result) {
return nullptr;
}
// Allow the element to perform any hit-testing it might need to do to reach
// non-layout children.
result = result->ElementAccessibilityHitTest(point);
while (result && result->IsIgnored()) {
CHECK(!result->IsDetached());
// If this element is the label of a control, a hit test should return the
// control. The label is ignored because it's already reflected in the name.
if (auto* label = DynamicTo<HTMLLabelElement>(result->GetNode())) {
if (HTMLElement* control = label->Control()) {
if (AXObject* ax_control = AXObjectCache().Get(control)) {
result = ax_control;
break;
}
}
}
result = result->ParentObject();
}
return result->IsIncludedInTree() ? result
: result->ParentObjectIncludedInTree();
}
AXObject* AXNodeObject::AccessibilityImageMapHitTest(
HTMLAreaElement* area,
const gfx::Point& point) const {
if (!area) {
return nullptr;
}
AXObject* parent = AXObjectCache().Get(area->ImageElement());
if (!parent) {
return nullptr;
}
PhysicalOffset physical_point(point);
for (const auto& child : parent->ChildrenIncludingIgnored()) {
if (child->GetBoundsInFrameCoordinates().Contains(physical_point)) {
return child.Get();
}
}
return nullptr;
}
AXObject* AXNodeObject::GetFirstInlineBlockOrDeepestInlineAXChildInLayoutTree(
AXObject* start_object,
bool first) const {
if (!start_object) {
return nullptr;
}
// Return the deepest last child that is included.
// Uses LayoutTreeBuildTraversaler to get children, in order to avoid getting
// children unconnected to the line, e.g. via aria-owns. Doing this first also
// avoids the issue that |start_object| may not be included in the tree.
AXObject* result = start_object;
Node* current_node = start_object->GetNode();
while (current_node) {
// If we find a node that is inline-block, we want to return it rather than
// getting the deepest child for that. This is because these are now always
// being included in the tree and the Next/PreviousOnLine could be set on
// the inline-block element. We exclude list markers since those technically
// fulfill the inline-block condition.
AXObject* ax_object = start_object->AXObjectCache().Get(current_node);
if (ax_object && ax_object->IsIncludedInTree() &&
!current_node->IsMarkerPseudoElement()) {
if (ax_object->GetLayoutObject() &&
ax_object->GetLayoutObject()->IsInline() &&
ax_object->GetLayoutObject()->IsAtomicInlineLevel()) {
return ax_object;
}
}
current_node = first ? LayoutTreeBuilderTraversal::FirstChild(*current_node)
: LayoutTreeBuilderTraversal::LastChild(*current_node);
if (!current_node) {
break;
}
AXObject* tentative_child = start_object->AXObjectCache().Get(current_node);
if (tentative_child && tentative_child->IsIncludedInTree()) {
result = tentative_child;
}
}
// Have reached the end of LayoutTreeBuilderTraversal. From here on, traverse
// AXObjects to get deepest descendant of pseudo element or static text,
// such as an AXInlineTextBox.
// Relevant static text or pseudo element is always included.
if (!result->IsIncludedInTree()) {
return nullptr;
}
// Already a leaf: return current result.
if (!result->ChildCountIncludingIgnored()) {
return result;
}
// Get deepest AXObject descendant.
return first ? result->DeepestFirstChildIncludingIgnored()
: result->DeepestLastChildIncludingIgnored();
}
void AXNodeObject::MaybeResetCache() const {
uint64_t generation = AXObjectCache().GenerationalCacheId();
if (!generational_cache_) {
generational_cache_ = MakeGarbageCollected<GenerationalCache>();
}
DCHECK(AXObjectCache().IsFrozen());
if (generation != generational_cache_->generation) {
generational_cache_->generation = generation;
generational_cache_->next_on_line = nullptr;
generational_cache_->previous_on_line = nullptr;
} else {
#if DCHECK_IS_ON()
// AXObjects cannot be detached while the tree is frozen.
// These are sanity checks. Limited to DCHECK enabled builds due to
// potential performance impact with to the sheer volume of calls.
if (AXObject* next = generational_cache_->next_on_line) {
CHECK(!next->IsDetached());
}
if (AXObject* previous = generational_cache_->previous_on_line) {
CHECK(!previous->IsDetached());
}
#endif
}
}
void AXNodeObject::GenerationalCache::Trace(Visitor* visitor) const {
visitor->Trace(next_on_line);
visitor->Trace(previous_on_line);
}
AXObject* AXNodeObject::SetNextOnLine(AXObject* next_on_line) const {
CHECK(generational_cache_) << "Must call MaybeResetCache ahead of this call";
generational_cache_->next_on_line = next_on_line;
return next_on_line;
}
AXObject* AXNodeObject::SetPreviousOnLine(AXObject* previous_on_line) const {
CHECK(generational_cache_) << "Must call MaybeResetCache ahead of this call";
generational_cache_->previous_on_line = previous_on_line;
return previous_on_line;
}
AXObject* AXNodeObject::NextOnLine() const {
// If this is the last object on the line, nullptr is returned. Otherwise, all
// inline AXNodeObjects, regardless of role and tree depth, are connected to
// the next inline text box on the same line. If there is no inline text box,
// they are connected to the next leaf AXObject.
DCHECK(!IsDetached());
MaybeResetCache();
if (generational_cache_->next_on_line) {
return generational_cache_->next_on_line;
}
const LayoutObject* layout_object = GetLayoutObject();
if (!layout_object) {
return SetNextOnLine(nullptr);
}
if (!AXObjectCache().IsFrozen() ||
!AXObjectCache().HasCachedDataForNodesOnLine()) {
// TODO(crbug.com/372084397): Solve race condition for web AX API and frozen
// states of accessibility lifecycle.
// Not all serialization data comes from the regular flow (see
// third_party/blink/renderer/modules/accessibility/ax_object_cache_lifecycle.h).
// Some serialization requests come through a special test API (see
// third_party/blink/public/web/web_ax_object.h), which requires us to force
// the data to be computed in case it is not computed yet.
AXObjectCache().ComputeNodesOnLine(layout_object);
}
if (DisplayLockUtilities::LockedAncestorPreventingPaint(*layout_object)) {
return SetNextOnLine(nullptr);
}
if (const auto* list_marker =
GetListMarker(*layout_object, ParentObjectIfPresent())) {
// A list marker should be followed by a list item on the same line.
// Note that pseudo content is always included in the tree, so
// NextSiblingIncludingIgnored() will succeed.
auto* ax_list_marker = AXObjectCache().Get(list_marker);
if (ax_list_marker && ax_list_marker->IsIncludedInTree()) {
return SetNextOnLine(
GetFirstInlineBlockOrDeepestInlineAXChildInLayoutTree(
ax_list_marker->NextSiblingIncludingIgnored(), true));
}
return SetNextOnLine(nullptr);
}
if (!ShouldUseLayoutNG(*layout_object)) {
return SetNextOnLine(nullptr);
}
if (!layout_object->IsInLayoutNGInlineFormattingContext()) {
return SetNextOnLine(nullptr);
}
// Obtain the next LayoutObject that is in the same line, which was previously
// computed in `AXObjectCacheImpl::ComputeNodesOnLine()`. If one does not
// exist, move to children and Repeate the process.
// If a LayoutObject is found, in the next loop we compute if it has an
// AXObject that is included in the tree. If so, connect them.
const LayoutObject* next_layout_object = nullptr;
while (layout_object) {
next_layout_object = AXObjectCache().CachedNextOnLine(layout_object);
if (next_layout_object) {
break;
}
const auto* child = layout_object->SlowLastChild();
if (!child) {
break;
}
layout_object = child;
}
while (next_layout_object) {
AXObject* result = AXObjectCache().Get(next_layout_object);
// We want to continue searching for the next inline leaf if the
// current one is inert or aria-hidden.
// We don't necessarily want to keep searching in the case of any ignored
// node, because we anticipate that there might be scenarios where a
// descendant of the ignored node is not ignored and would be returned by
// the call to `GetFirstInlineBlockOrDeepestInlineAXChildInLayoutTree`
bool should_keep_looking =
result ? result->IsInert() || result->IsAriaHidden() : false;
result =
GetFirstInlineBlockOrDeepestInlineAXChildInLayoutTree(result, true);
if (result && !should_keep_looking) {
return SetNextOnLine(result);
}
if (!should_keep_looking) {
break;
}
next_layout_object = AXObjectCache().CachedNextOnLine(next_layout_object);
}
return SetNextOnLine(nullptr);
}
AXObject* AXNodeObject::PreviousOnLine() const {
// If this is the first object on the line, nullptr is returned. Otherwise,
// all inline AXNodeObjects, regardless of role and tree depth, are connected
// to the previous inline text box on the same line. If there is no inline
// text box, they are connected to the previous leaf AXObject.
DCHECK(!IsDetached());
MaybeResetCache();
if (generational_cache_->previous_on_line) {
return generational_cache_->previous_on_line;
}
const LayoutObject* layout_object = GetLayoutObject();
if (!layout_object) {
return SetPreviousOnLine(nullptr);
}
if (!AXObjectCache().IsFrozen() ||
!AXObjectCache().HasCachedDataForNodesOnLine()) {
// See AXNodeObject::NextOnLine() for reasoning of this call.
AXObjectCache().ComputeNodesOnLine(layout_object);
}
if (!ShouldUseLayoutNG(*layout_object)) {
return SetPreviousOnLine(nullptr);
}
if (DisplayLockUtilities::LockedAncestorPreventingPaint(*layout_object)) {
return SetPreviousOnLine(nullptr);
}
AXObject* previous_sibling =
IsIncludedInTree() ? PreviousSiblingIncludingIgnored() : nullptr;
if (previous_sibling && previous_sibling->GetLayoutObject() &&
previous_sibling->GetLayoutObject()->IsLayoutOutsideListMarker()) {
// A list item should be preceded by a list marker on the same line.
return SetPreviousOnLine(
GetFirstInlineBlockOrDeepestInlineAXChildInLayoutTree(previous_sibling,
false));
}
if (layout_object->IsLayoutOutsideListMarker() ||
!layout_object->IsInLayoutNGInlineFormattingContext()) {
return SetPreviousOnLine(nullptr);
}
// Obtain the previous LayoutObject that is in the same line, which was
// previously computed in `AXObjectCacheImpl::ComputeNodesOnLine()`. If one
// does not exist, move to children and repeate the process. If a LayoutObject
// is found, in the next loop we compute if it has an AXObject that is
// included in the tree. If so, connect them.
const LayoutObject* previous_layout_object = nullptr;
while (layout_object) {
previous_layout_object =
AXObjectCache().CachedPreviousOnLine(layout_object);
if (previous_layout_object) {
break;
}
const auto* child = layout_object->SlowFirstChild();
if (!child) {
break;
}
layout_object = child;
}
while (previous_layout_object) {
AXObject* result = AXObjectCache().Get(previous_layout_object);
// We want to continue searching for the next inline leaf if the
// current one is inert or aria-hidden.
// We don't necessarily want to keep searching in the case of any ignored
// node, because we anticipate that there might be scenarios where a
// descendant of the ignored node is not ignored and would be returned by
// the call to `GetFirstInlineBlockOrDeepestInlineAXChildInLayoutTree`
bool should_keep_looking =
result ? result->IsInert() || result->IsAriaHidden() : false;
result =
GetFirstInlineBlockOrDeepestInlineAXChildInLayoutTree(result, false);
if (result && !should_keep_looking) {
return SetPreviousOnLine(result);
}
// We want to continue searching for the previous inline leaf if the
// current one is inert.
if (!should_keep_looking) {
break;
}
previous_layout_object =
AXObjectCache().CachedPreviousOnLine(previous_layout_object);
}
return SetPreviousOnLine(nullptr);
}
void AXNodeObject::HandleAutofillSuggestionAvailabilityChanged(
WebAXAutofillSuggestionAvailability suggestion_availability) {
if (GetLayoutObject()) {
// Autofill suggestion availability is stored in AXObjectCache.
AXObjectCache().SetAutofillSuggestionAvailability(AXObjectID(),
suggestion_availability);
}
}
void AXNodeObject::GetWordBoundaries(Vector<int>& word_starts,
Vector<int>& word_ends) const {
if (!GetLayoutObject() || !GetLayoutObject()->IsListMarker()) {
return;
}
String text_alternative;
if (ListMarker* marker = ListMarker::Get(GetLayoutObject())) {
text_alternative = marker->TextAlternative(*GetLayoutObject());
}
if (text_alternative.ContainsOnlyWhitespaceOrEmpty()) {
return;
}
Vector<AbstractInlineTextBox::WordBoundaries> boundaries;
AbstractInlineTextBox::GetWordBoundariesForText(boundaries, text_alternative);
word_starts.reserve(boundaries.size());
word_ends.reserve(boundaries.size());
for (const auto& boundary : boundaries) {
word_starts.push_back(boundary.start_index);
word_ends.push_back(boundary.end_index);
}
}
void AXNodeObject::Trace(Visitor* visitor) const {
visitor->Trace(node_);
visitor->Trace(layout_object_);
visitor->Trace(generational_cache_);
AXObject::Trace(visitor);
}
} // namespace blink
|