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
|
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "ui/accessibility/platform/ax_platform_node_cocoa.h"
#import <Cocoa/Cocoa.h>
#include <Foundation/Foundation.h>
#include "base/apple/foundation_util.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/mac/mac_util.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/no_destructor.h"
#include "base/strings/sys_string_conversions.h"
#include "base/trace_event/trace_event.h"
#include "skia/ext/skia_utils_mac.h"
#include "ui/accessibility/accessibility_features.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_range.h"
#include "ui/accessibility/ax_role_properties.h"
#include "ui/accessibility/platform/ax_platform_node_mac.h"
#include "ui/accessibility/platform/ax_private_attributes_mac.h"
#include "ui/accessibility/platform/ax_private_roles_mac.h"
#include "ui/accessibility/platform/ax_utils_mac.h"
#include "ui/accessibility/platform/child_iterator.h"
#include "ui/base/l10n/l10n_util.h"
#import "ui/gfx/mac/coordinate_conversion.h"
#include "ui/strings/grit/ax_strings.h"
using AXRange = ui::AXPlatformNodeDelegate::AXRange;
// Not defined in current versions of library, but may be in the future:
#define NSAccessibilityChildrenInNavigationOrderAttribute \
@"AXChildrenInNavigationOrder"
@interface AXAnnouncementSpec ()
@property(nonatomic, strong) NSString* announcement;
@property(nonatomic, strong) NSWindow* window;
@property(nonatomic, assign) BOOL polite;
@end
@implementation AXAnnouncementSpec
@synthesize announcement = _announcement;
@synthesize window = _window;
@synthesize polite = _polite;
@end
namespace {
// Same length as web content/WebKit.
int kLiveRegionDebounceMillis = 20;
using RoleMap = std::map<ax::mojom::Role, NSString*>;
using EventMap = std::map<ax::mojom::Event, NSString*>;
RoleMap BuildSubroleMap() {
const RoleMap::value_type subroles[] = {
{ax::mojom::Role::kAlert, @"AXApplicationAlert"},
{ax::mojom::Role::kAlertDialog, @"AXApplicationAlertDialog"},
{ax::mojom::Role::kApplication, @"AXWebApplication"},
{ax::mojom::Role::kArticle, @"AXDocumentArticle"},
{ax::mojom::Role::kBanner, @"AXLandmarkBanner"},
{ax::mojom::Role::kCode, @"AXCodeStyleGroup"},
{ax::mojom::Role::kComplementary, @"AXLandmarkComplementary"},
{ax::mojom::Role::kContentDeletion, @"AXDeleteStyleGroup"},
{ax::mojom::Role::kContentInsertion, @"AXInsertStyleGroup"},
{ax::mojom::Role::kContentInfo, @"AXLandmarkContentInfo"},
{ax::mojom::Role::kDefinition, @"AXDefinition"},
{ax::mojom::Role::kDialog, @"AXApplicationDialog"},
{ax::mojom::Role::kDocument, @"AXDocument"},
{ax::mojom::Role::kEmphasis, @"AXEmphasisStyleGroup"},
{ax::mojom::Role::kFeed, @"AXApplicationGroup"},
{ax::mojom::Role::kFooter, @"AXLandmarkContentInfo"},
{ax::mojom::Role::kForm, @"AXLandmarkForm"},
{ax::mojom::Role::kGraphicsDocument, @"AXDocument"},
{ax::mojom::Role::kGroup, @"AXApplicationGroup"},
{ax::mojom::Role::kHeader, @"AXLandmarkBanner"},
{ax::mojom::Role::kLog, @"AXApplicationLog"},
{ax::mojom::Role::kMain, @"AXLandmarkMain"},
{ax::mojom::Role::kMarquee, @"AXApplicationMarquee"},
// https://w3c.github.io/mathml-aam/#mathml-element-mappings
{ax::mojom::Role::kMath, @"AXDocumentMath"},
{ax::mojom::Role::kMathMLFraction, @"AXMathFraction"},
{ax::mojom::Role::kMathMLIdentifier, @"AXMathIdentifier"},
{ax::mojom::Role::kMathMLMath, @"AXDocumentMath"},
{ax::mojom::Role::kMathMLMultiscripts, @"AXMathMultiscript"},
{ax::mojom::Role::kMathMLNoneScript, @"AXMathRow"},
{ax::mojom::Role::kMathMLNumber, @"AXMathNumber"},
{ax::mojom::Role::kMathMLOperator, @"AXMathOperator"},
{ax::mojom::Role::kMathMLOver, @"AXMathUnderOver"},
{ax::mojom::Role::kMathMLPrescriptDelimiter, @"AXMathRow"},
{ax::mojom::Role::kMathMLRoot, @"AXMathRoot"},
{ax::mojom::Role::kMathMLRow, @"AXMathRow"},
{ax::mojom::Role::kMathMLSquareRoot, @"AXMathSquareRoot"},
{ax::mojom::Role::kMathMLSub, @"AXMathSubscriptSuperscript"},
{ax::mojom::Role::kMathMLSubSup, @"AXMathSubscriptSuperscript"},
{ax::mojom::Role::kMathMLSup, @"AXMathSubscriptSuperscript"},
{ax::mojom::Role::kMathMLTable, @"AXMathTable"},
{ax::mojom::Role::kMathMLTableCell, @"AXMathTableCell"},
{ax::mojom::Role::kMathMLTableRow, @"AXMathTableRow"},
{ax::mojom::Role::kMathMLText, @"AXMathText"},
{ax::mojom::Role::kMathMLUnder, @"AXMathUnderOver"},
{ax::mojom::Role::kMathMLUnderOver, @"AXMathUnderOver"},
{ax::mojom::Role::kMeter, @"AXMeter"},
{ax::mojom::Role::kNavigation, @"AXLandmarkNavigation"},
{ax::mojom::Role::kNote, @"AXDocumentNote"},
{ax::mojom::Role::kRegion, @"AXLandmarkRegion"},
{ax::mojom::Role::kSearch, @"AXLandmarkSearch"},
{ax::mojom::Role::kSearchBox, @"AXSearchField"},
{ax::mojom::Role::kSectionFooter, @"AXSectionFooter"},
{ax::mojom::Role::kSectionHeader, @"AXSectionHeader"},
{ax::mojom::Role::kStatus, @"AXApplicationStatus"},
{ax::mojom::Role::kStrong, @"AXStrongStyleGroup"},
{ax::mojom::Role::kSubscript, @"AXSubscriptStyleGroup"},
{ax::mojom::Role::kSuperscript, @"AXSuperscriptStyleGroup"},
{ax::mojom::Role::kSwitch, @"AXSwitch"},
{ax::mojom::Role::kTab, @"AXTabButton"},
{ax::mojom::Role::kTabPanel, @"AXTabPanel"},
{ax::mojom::Role::kTerm, @"AXTerm"},
{ax::mojom::Role::kTime, @"AXTimeGroup"},
{ax::mojom::Role::kTimer, @"AXApplicationTimer"},
{ax::mojom::Role::kToggleButton, @"AXToggleButton"},
{ax::mojom::Role::kTooltip, @"AXUserInterfaceTooltip"},
{ax::mojom::Role::kTreeItem, NSAccessibilityOutlineRowSubrole},
};
return RoleMap(begin(subroles), end(subroles));
}
EventMap BuildEventMap() {
const EventMap::value_type events[] = {
{ax::mojom::Event::kCheckedStateChanged,
NSAccessibilityValueChangedNotification},
{ax::mojom::Event::kFocus,
NSAccessibilityFocusedUIElementChangedNotification},
{ax::mojom::Event::kFocusContext,
NSAccessibilityFocusedUIElementChangedNotification},
// Do not map kMenuStart/End to the Mac's opened/closed notifications.
// kMenuStart/End are fired at the start/end of menu interaction on the
// container of the menu; not the menu itself. All newly-opened/closed
// menus should fire kMenuPopupStart/End. See SubmenuView::ShowAt and
// SubmenuView::Hide.
{ax::mojom::Event::kMenuPopupStart, (NSString*)kAXMenuOpenedNotification},
{ax::mojom::Event::kMenuPopupEnd, (NSString*)kAXMenuClosedNotification},
{ax::mojom::Event::kTextChanged, NSAccessibilityTitleChangedNotification},
{ax::mojom::Event::kValueChanged,
NSAccessibilityValueChangedNotification},
{ax::mojom::Event::kTextSelectionChanged,
NSAccessibilitySelectedTextChangedNotification},
// TODO(patricialor): Add more events.
};
return EventMap(begin(events), end(events));
}
// Builds the pairings of accessibility actions and their Cocoa equivalents.
ui::CocoaActionList BuildActionList() {
const ui::CocoaActionList::value_type entries[] = {
// NSAccessibilityPressAction must come first in this list.
{ax::mojom::Action::kDoDefault, NSAccessibilityPressAction},
{ax::mojom::Action::kDecrement, NSAccessibilityDecrementAction},
{ax::mojom::Action::kIncrement, NSAccessibilityIncrementAction},
{ax::mojom::Action::kShowContextMenu, NSAccessibilityShowMenuAction},
};
return ui::CocoaActionList(begin(entries), end(entries));
}
// Returns a static vector of pairings of accessibility actions and their Cocoa
// equivalents.
const ui::CocoaActionList& GetCocoaActionList() {
static const base::NoDestructor<ui::CocoaActionList> action_list(
BuildActionList());
return *action_list;
}
void PostAnnouncementNotification(NSString* announcement,
NSWindow* window,
bool is_polite) {
NSAccessibilityPriorityLevel priority =
is_polite ? NSAccessibilityPriorityMedium : NSAccessibilityPriorityHigh;
NSDictionary* notification_info = @{
NSAccessibilityAnnouncementKey : announcement,
NSAccessibilityPriorityKey : @(priority)
};
// On Mojave, announcements from an inactive window aren't spoken.
NSAccessibilityPostNotificationWithUserInfo(
window, NSAccessibilityAnnouncementRequestedNotification,
notification_info);
}
// Returns true if |action| should be added implicitly for |data|.
bool HasImplicitAction(const ui::AXPlatformNodeBase& node,
ax::mojom::Action action) {
// TODO integrate the method into AXNodeData, see crrev.com/c/6115619
// for details.
switch (action) {
case ax::mojom::Action::kDoDefault:
return node.GetData().IsClickable();
case ax::mojom::Action::kDecrement:
case ax::mojom::Action::kIncrement:
return node.GetRole() == ax::mojom::Role::kSlider ||
node.GetRole() == ax::mojom::Role::kSpinButton;
default:
return false;
}
}
// For roles that show a menu for the default action, ensure "show menu" also
// appears in available actions, but only if that's not already used for a
// context menu. It will be mapped back to the default action when performed.
bool AlsoUseShowMenuActionForDefaultAction(const ui::AXPlatformNodeBase& node) {
return HasImplicitAction(node, ax::mojom::Action::kDoDefault) &&
!node.HasAction(ax::mojom::Action::kShowContextMenu) &&
(node.GetRole() == ax::mojom::Role::kPopUpButton ||
node.GetRole() == ax::mojom::Role::kComboBoxSelect);
}
// Check whether |selector| is an accessibility setter. This is a heuristic but
// seems to be a pretty good one.
bool IsAXSetter(SEL selector) {
return [NSStringFromSelector(selector) hasPrefix:@"setAccessibility"];
}
void CollectAncestorRoles(
const ui::AXNode& node,
std::map<ui::AXNodeID, std::set<ax::mojom::Role>>& out_ancestor_roles) {
if (out_ancestor_roles.contains(node.id()))
return;
out_ancestor_roles[node.id()] = {node.GetRole()};
if (!node.GetParent())
return;
CollectAncestorRoles(*node.GetParent(), out_ancestor_roles);
out_ancestor_roles[node.id()].insert(
out_ancestor_roles[node.GetParent()->id()].begin(),
out_ancestor_roles[node.GetParent()->id()].end());
}
} // namespace
namespace ui {
const ui::CocoaActionList& GetCocoaActionListForTesting() {
return GetCocoaActionList();
}
} // namespace ui
@interface AXPlatformNodeCocoa (Private)
// Helper function for string attributes that don't require extra processing.
- (NSString*)getStringAttribute:(ax::mojom::StringAttribute)attribute;
// Returns AXValue, or nil if AXValue isn't an NSString.
- (NSString*)getAXValueAsString;
// Returns the native wrapper for the given node id.
- (AXPlatformNodeCocoa*)fromNodeID:(ui::AXNodeID)id;
// Returns true if this object is an image.
- (BOOL)isImage;
@end
@implementation AXPlatformNodeCocoa {
// This field is not a raw_ptr<> because it requires @property rewrite.
RAW_PTR_EXCLUSION ui::AXPlatformNodeBase* _node; // Weak. Retains us.
AXAnnouncementSpec* __strong _pendingAnnouncement;
}
@synthesize node = _node;
// Required for AXCustomContentProvider, which defines the property.
@synthesize accessibilityCustomContent = _accessibilityCustomContent;
// The new NSAccessibility API is method-based, but the old NSAccessibility
// is attribute-based. For every method, there is a corresponding attribute.
// This function returns the map between the methods and the attributes
// for purposes of migrating to the new API.
+ (NSDictionary*)newAccessibilityAPIMethodToAttributeMap {
static NSDictionary* dict = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dict = @{
@"accessibilityCellForColumn:row:" :
NSAccessibilityCellForColumnAndRowParameterizedAttribute,
@"accessibilityChildrenInNavigationOrder" :
NSAccessibilityChildrenInNavigationOrderAttribute,
@"accessibilityColumns" : NSAccessibilityColumnsAttribute,
@"accessibilityColumnCount" : NSAccessibilityColumnCountAttribute,
@"accessibilityColumnIndexRange" :
NSAccessibilityColumnIndexRangeAttribute,
@"accessibilityDisclosedByRow" : NSAccessibilityDisclosedByRowAttribute,
@"accessibilityDisclosedRows" : NSAccessibilityDisclosedRowsAttribute,
@"accessibilityDisclosureLevel" : NSAccessibilityDisclosureLevelAttribute,
@"accessibilityHeader" : NSAccessibilityHeaderAttribute,
@"accessibilityHorizontalScrollBar" :
NSAccessibilityHorizontalScrollBarAttribute,
@"accessibilityIndex" : NSAccessibilityIndexAttribute,
@"accessibilityLinkedUIElements" :
NSAccessibilityLinkedUIElementsAttribute,
@"accessibilityRowCount" : NSAccessibilityRowCountAttribute,
@"accessibilityRowHeaderUIElements" :
NSAccessibilityRowHeaderUIElementsAttribute,
@"accessibilityRowIndexRange" : NSAccessibilityRowIndexRangeAttribute,
@"accessibilitySortDirection" : NSAccessibilitySortDirectionAttribute,
@"accessibilitySplitters" : NSAccessibilitySplittersAttribute,
@"accessibilityTabs" : NSAccessibilityTabsAttribute,
@"accessibilityToolbarButton" : NSAccessibilityToolbarButtonAttribute,
@"accessibilityVerticalScrollBar" :
NSAccessibilityVerticalScrollBarAttribute,
@"accessibilityVisibleColumns" : NSAccessibilityVisibleColumnsAttribute,
@"accessibilityVisibleCells" : NSAccessibilityVisibleCellsAttribute,
@"accessibilityVisibleRows" : NSAccessibilityVisibleRowsAttribute,
@"isAccessibilityDisclosed" : NSAccessibilityDisclosingAttribute,
@"isAccessibilityExpanded" : NSAccessibilityExpandedAttribute,
@"isAccessibilityFocused" : NSAccessibilityFocusedAttribute,
};
});
return dict;
}
// Similar to newAccessibilityAPIMethodToAttributeMap but for actions.
+ (NSDictionary*)newAccessibilityAPIMethodToActionMap {
static NSDictionary* dict = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dict = @{
@"accessibilityPerformConfirm" : NSAccessibilityConfirmAction,
@"accessibilityPerformPress" : NSAccessibilityPressAction,
@"accessibilityPerformShowMenu" : NSAccessibilityShowMenuAction,
@"accessibilityPerformDecrement" : NSAccessibilityDecrementAction,
@"accessibilityPerformIncrement" : NSAccessibilityIncrementAction,
};
});
return dict;
}
// Returns the set of attributes available through the new Cocoa
// accessibility API.
+ (NSSet<NSString*>*)attributesAvailableThroughNewAccessibilityAPI {
static NSSet<NSString*>* set = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
set = [NSSet<NSString*>
setWithArray:[[self newAccessibilityAPIMethodToAttributeMap]
allValues]];
});
return set;
}
// Returns the set of actions available through the new Cocoa
// accessibility API.
+ (NSSet<NSString*>*)actionsAvailableThroughNewAccessibilityAPI {
static NSSet<NSString*>* set = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
set = [NSSet<NSString*>
setWithArray:[[self newAccessibilityAPIMethodToActionMap] allValues]];
});
return set;
}
// Returns YES if `attribute` is available through a method implemented for
// the new accessibility API.
+ (BOOL)isAttributeAvailableThroughNewAccessibilityAPI:(NSString*)attribute {
if (features::IsMacAccessibilityAPIMigrationEnabled()) {
return [[self attributesAvailableThroughNewAccessibilityAPI]
containsObject:attribute];
}
return NO;
}
// Returns YES if `action` is available through a method implemented for
// the new accessibility API.
+ (BOOL)isActionAvailableThroughNewAccessibilityAPI:(NSString*)action {
if (features::IsMacAccessibilityAPIMigrationEnabled()) {
return [[self actionsAvailableThroughNewAccessibilityAPI]
containsObject:action];
}
return NO;
}
// Returns the set of methods implemented to support the new Cocoa
// accessibility API corresponding to old API attributes.
+ (NSSet<NSString*>*)newAccessibilityAPIMethods {
static NSSet<NSString*>* set = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
set = [NSSet<NSString*>
setWithArray:[[self newAccessibilityAPIMethodToAttributeMap] allKeys]];
});
return set;
}
// Returns YES if `method` has been implemented in the transition to the new
// accessibility API.
+ (BOOL)isMethodImplementedForNewAccessibilityAPI:(NSString*)method {
if (features::IsMacAccessibilityAPIMigrationEnabled()) {
return [[self newAccessibilityAPIMethods] containsObject:method];
}
return NO;
}
// Returns true if `method` has been implemented in the transition to the new
// accessibility API, and is supported by this node (based on its role).
- (BOOL)supportsNewAccessibilityAPIMethod:(NSString*)method {
if (!_node) {
return NO;
}
// Check whether the corresponding attribute is supported for this node.
NSString* attribute = [[[self class] newAccessibilityAPIMethodToAttributeMap]
objectForKey:method];
if (attribute) {
NSArray* attributeNames = [self internalAccessibilityAttributeNames];
if ([attributeNames containsObject:attribute]) {
return YES;
}
attributeNames = [self internalAccessibilityParameterizedAttributeNames];
return [attributeNames containsObject:attribute];
}
// Check whether the corresponding action is supported for this node.
NSString* action =
[[[self class] newAccessibilityAPIMethodToActionMap] objectForKey:method];
if (action) {
NSArray* actionNames = [self internalAccessibilityActionNames];
return [actionNames containsObject:action];
}
return NO;
}
- (BOOL)conditionallyRespondsToSelector:(SEL)selector {
static base::NoDestructor<std::unordered_set<SEL>> methodSelectorsForActions({
@selector(accessibilityPerformPress),
@selector(accessibilityPerformDecrement),
@selector(accessibilityPerformIncrement),
@selector(accessibilityPerformShowMenu),
@selector(accessibilityPerformConfirm)
});
static base::NoDestructor<std::unordered_set<SEL>>
methodSelectorsForParameterizedAttributes({
@selector(accessibilityCellForColumn:row:),
@selector(accessibilityRangeForIndex:),
@selector(accessibilityRangeForLine:),
@selector(accessibilityRangeForPosition:),
});
// See if the method is permitted by checking its corresponding parameterized
// attribute counterpart.
if (methodSelectorsForParameterizedAttributes->find(selector) !=
methodSelectorsForParameterizedAttributes->end()) {
NSString* selectorString = NSStringFromSelector(selector);
NSString* attribute =
[[AXPlatformNodeCocoa newAccessibilityAPIMethodToAttributeMap]
objectForKey:selectorString];
NSArray* attributes =
[self internalAccessibilityParameterizedAttributeNames];
if (![attributes containsObject:attribute]) {
return NO;
}
}
// See if the method is permitted by checking its corresponding action
// counterpart.
if (methodSelectorsForActions->find(selector) !=
methodSelectorsForActions->end()) {
NSString* selectorString = NSStringFromSelector(selector);
NSString* action =
[[AXPlatformNodeCocoa newAccessibilityAPIMethodToActionMap]
objectForKey:selectorString];
NSArray* actions = [self internalAccessibilityActionNames];
if (![actions containsObject:action]) {
return NO;
}
}
return YES;
}
- (BOOL)respondsToSelector:(SEL)selector {
// If we're in old-accessibility-API mode, disable methods that we've added
// to support the new API.
if (!features::IsMacAccessibilityAPIMigrationEnabled()) {
static base::NoDestructor<std::unordered_set<SEL>>
newAccessibilityAPISelectors;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSSet<NSString*>* methodNames =
[AXPlatformNodeCocoa newAccessibilityAPIMethods];
for (NSString* methodName in methodNames) {
SEL methodSelector = NSSelectorFromString(methodName);
newAccessibilityAPISelectors->insert(methodSelector);
}
});
if (newAccessibilityAPISelectors->find(selector) !=
newAccessibilityAPISelectors->end()) {
return NO;
}
} else {
// The following deprecated selectors had existing new-API implementations
// that are expected to continue to work independent of the flag. For any
// such API, ensure the corresponding old API is not available when the flag
// is enabled.
static base::NoDestructor<std::unordered_set<SEL>> deprecatedSelectors({
@selector(AXInsertionPointLineNumber), @selector(AXNumberOfCharacters),
@selector(AXPlaceholderValue), @selector(AXSelectedText),
@selector(AXSelectedTextRange), @selector(AXVisibleCharacterRange)
});
if (deprecatedSelectors->find(selector) != deprecatedSelectors->end()) {
return NO;
}
}
// Do not respond to the method if it's not supported by the node.
if (![self conditionallyRespondsToSelector:selector]) {
return NO;
}
return [super respondsToSelector:selector];
}
- (ui::AXPlatformNodeDelegate*)nodeDelegate {
return _node ? _node->GetDelegate() : nil;
}
- (BOOL)instanceActive {
return _node != nullptr;
}
- (BOOL)isIncludedInPlatformTree {
// TODO(accessibility): Do we really need to have invisible objects in
// the platform tree?
return [self instanceActive] &&
![[self AXRole] isEqualToString:NSAccessibilityUnknownRole] &&
!_node->IsInvisibleOrIgnored();
}
- (id)titleUIElement {
// True only if it's a control, if there's a single label, and the label has
// nonempty text.
// VoiceOver ignores TitleUIElement if the element isn't a control.
if (!ui::IsControl(_node->GetRole()))
return nil;
if (!_node->HasNameFromOtherElement())
return nil;
std::vector<int32_t> labelledby_ids =
_node->GetIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds);
if (labelledby_ids.size() != 1)
return nil;
ui::AXPlatformNode* label =
_node->GetDelegate()->GetFromNodeID(labelledby_ids[0]);
if (!label)
return nil;
// No title UI element if the label's name is empty.
std::string labelName = label->GetDelegate()->GetName();
if (labelName.empty())
return nil;
// In the case where we have a radio button or a checked box, no title UI
// element. This goes against Apple's documentation for AXTitleUIElement,
// but is consistent with Safari+Voiceover behavior.
// See crbug.com/1430419
ax::mojom::Role role = _node->GetRole();
if (ui::IsRadio(role) || ui::IsCheckBox(role))
return nil;
return label->GetNativeViewAccessible().Get();
}
- (BOOL)isNameFromLabel {
// Image annotations are not visible text, so they should be exposed
// as a description and not a title.
switch (_node->GetData().GetImageAnnotationStatus()) {
case ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation:
case ax::mojom::ImageAnnotationStatus::kAnnotationPending:
case ax::mojom::ImageAnnotationStatus::kAnnotationEmpty:
case ax::mojom::ImageAnnotationStatus::kAnnotationAdult:
case ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed:
case ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded:
return true;
case ax::mojom::ImageAnnotationStatus::kNone:
case ax::mojom::ImageAnnotationStatus::kWillNotAnnotateDueToScheme:
case ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation:
case ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation:
break;
}
// No label for windows or native dialogs.
ax::mojom::Role role = _node->GetRole();
if (ui::IsWindow(role) || (ui::IsDialog(role) && !_node->IsWebContent())) {
return false;
}
// VoiceOver computes the wrong description for a link.
if (ui::IsLink(role))
return true;
// If a radiobutton or checkbox has a single label, we are consistent
// with Safari+Voiceover and expose it via AccessibilityLabel.
// Note: Safari+Voiceover is inconsistent with Apple's documentation,
// which suggests this should be exposed via AXTitleUIElement. See
// crbug.com/1430419
if (ui::IsRadio(role) || ui::IsCheckBox(role)) {
std::vector<int32_t> labelledby_ids =
_node->GetIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds);
if (labelledby_ids.size() == 1) {
ui::AXPlatformNode* label =
_node->GetDelegate()->GetFromNodeID(labelledby_ids[0]);
if (label) {
// No title UI element if the label's name is empty.
std::string labelName = label->GetDelegate()->GetName();
if (!labelName.empty())
return true;
}
}
}
// VoiceOver will not read the label of these roles unless it is
// exposed in the description instead of the title.
switch (role) {
case ax::mojom::Role::kGenericContainer:
case ax::mojom::Role::kGroup:
case ax::mojom::Role::kRadioGroup:
case ax::mojom::Role::kTabPanel:
return true;
default:
break;
}
// On macOS, the accessible name of an object is exposed as its title if it
// comes from visible text, and as its description otherwise, but never both.
//
// Note: a placeholder is often visible text, but since it aids in data entry
// it is similar to accessibilityValue, and thus cannot be exposed either in
// accessibilityTitle or in accessibilityLabel.
ax::mojom::NameFrom nameFrom = _node->GetNameFrom();
if (nameFrom == ax::mojom::NameFrom::kCaption ||
nameFrom == ax::mojom::NameFrom::kContents ||
nameFrom == ax::mojom::NameFrom::kPlaceholder ||
nameFrom == ax::mojom::NameFrom::kRelatedElement ||
nameFrom == ax::mojom::NameFrom::kValue) {
return false;
}
return true;
}
- (NSArray*)uiElementsForAttribute:(ax::mojom::IntListAttribute)attribute {
NSMutableArray* elements = [NSMutableArray array];
ui::AXPlatformNodeDelegate* delegate = [self nodeDelegate];
if (!delegate) {
return elements;
}
const std::vector<int32_t>& attributeValues =
delegate->GetIntListAttribute(attribute);
for (auto& attributeValue : attributeValues) {
ui::AXPlatformNode* node = delegate->GetFromNodeID(attributeValue);
if (node) {
[elements addObject:node->GetNativeViewAccessible().Get()];
}
}
return elements;
}
- (void)getTreeItemDescendantNodeIds:(std::vector<int32_t>*)treeItemIds {
for (auto childDelegateIterator = [self nodeDelegate]->ChildrenBegin();
*childDelegateIterator != *[self nodeDelegate]->ChildrenEnd();
++(*childDelegateIterator)) {
ui::AXPlatformNodeDelegate* childDelegate = childDelegateIterator->get();
if (childDelegate->GetRole() == ax::mojom::Role::kTreeItem) {
treeItemIds->push_back(childDelegate->GetId());
}
gfx::NativeViewAccessible child = childDelegate->GetNativeViewAccessible();
AXPlatformNodeCocoa* childCocoa =
base::apple::ObjCCastStrict<AXPlatformNodeCocoa>(child.Get());
[childCocoa getTreeItemDescendantNodeIds:treeItemIds];
}
}
+ (NSString*)nativeRoleFromAXRole:(ax::mojom::Role)role {
switch (role) {
case ax::mojom::Role::kAbbr:
case ax::mojom::Role::kAlert:
case ax::mojom::Role::kAlertDialog:
case ax::mojom::Role::kApplication:
case ax::mojom::Role::kArticle:
case ax::mojom::Role::kAudio:
case ax::mojom::Role::kBanner:
case ax::mojom::Role::kBlockquote:
case ax::mojom::Role::kCaption:
case ax::mojom::Role::kClient:
case ax::mojom::Role::kCode:
case ax::mojom::Role::kComment:
case ax::mojom::Role::kComplementary:
case ax::mojom::Role::kContentDeletion:
case ax::mojom::Role::kContentInsertion:
case ax::mojom::Role::kContentInfo:
case ax::mojom::Role::kDefinition:
case ax::mojom::Role::kDesktop:
case ax::mojom::Role::kDialog:
case ax::mojom::Role::kDetails:
case ax::mojom::Role::kDocAbstract:
case ax::mojom::Role::kDocAcknowledgments:
case ax::mojom::Role::kDocAfterword:
case ax::mojom::Role::kDocAppendix:
case ax::mojom::Role::kDocBiblioEntry:
case ax::mojom::Role::kDocBibliography:
case ax::mojom::Role::kDocChapter:
case ax::mojom::Role::kDocColophon:
case ax::mojom::Role::kDocConclusion:
case ax::mojom::Role::kDocCredit:
case ax::mojom::Role::kDocCredits:
case ax::mojom::Role::kDocDedication:
case ax::mojom::Role::kDocEndnote:
case ax::mojom::Role::kDocEndnotes:
case ax::mojom::Role::kDocEpigraph:
case ax::mojom::Role::kDocEpilogue:
case ax::mojom::Role::kDocErrata:
case ax::mojom::Role::kDocExample:
case ax::mojom::Role::kDocFootnote:
case ax::mojom::Role::kDocForeword:
case ax::mojom::Role::kDocGlossary:
case ax::mojom::Role::kDocIndex:
case ax::mojom::Role::kDocIntroduction:
case ax::mojom::Role::kDocNotice:
case ax::mojom::Role::kDocPageFooter:
case ax::mojom::Role::kDocPageHeader:
case ax::mojom::Role::kDocPageList:
case ax::mojom::Role::kDocPart:
case ax::mojom::Role::kDocPreface:
case ax::mojom::Role::kDocPrologue:
case ax::mojom::Role::kDocPullquote:
case ax::mojom::Role::kDocQna:
case ax::mojom::Role::kDocTip:
case ax::mojom::Role::kDocToc:
case ax::mojom::Role::kDocument:
case ax::mojom::Role::kEmbeddedObject:
case ax::mojom::Role::kEmphasis:
case ax::mojom::Role::kFeed:
case ax::mojom::Role::kFigcaption:
case ax::mojom::Role::kFigure:
case ax::mojom::Role::kFooter:
case ax::mojom::Role::kForm:
case ax::mojom::Role::kGenericContainer:
case ax::mojom::Role::kGraphicsDocument:
case ax::mojom::Role::kGraphicsObject:
case ax::mojom::Role::kGroup:
case ax::mojom::Role::kHeader:
case ax::mojom::Role::kIframe:
case ax::mojom::Role::kIframePresentational:
case ax::mojom::Role::kLabelText:
case ax::mojom::Role::kLayoutTable:
case ax::mojom::Role::kLayoutTableCell:
case ax::mojom::Role::kLayoutTableRow:
case ax::mojom::Role::kLegend:
case ax::mojom::Role::kLineBreak:
case ax::mojom::Role::kListItem:
case ax::mojom::Role::kLog:
case ax::mojom::Role::kMain:
case ax::mojom::Role::kMark:
case ax::mojom::Role::kMarquee:
case ax::mojom::Role::kMath:
case ax::mojom::Role::kMathMLFraction:
case ax::mojom::Role::kMathMLIdentifier:
case ax::mojom::Role::kMathMLMath:
case ax::mojom::Role::kMathMLMultiscripts:
case ax::mojom::Role::kMathMLNoneScript:
case ax::mojom::Role::kMathMLNumber:
case ax::mojom::Role::kMathMLOperator:
case ax::mojom::Role::kMathMLOver:
case ax::mojom::Role::kMathMLPrescriptDelimiter:
case ax::mojom::Role::kMathMLRoot:
case ax::mojom::Role::kMathMLRow:
case ax::mojom::Role::kMathMLSquareRoot:
case ax::mojom::Role::kMathMLStringLiteral:
case ax::mojom::Role::kMathMLSub:
case ax::mojom::Role::kMathMLSubSup:
case ax::mojom::Role::kMathMLSup:
case ax::mojom::Role::kMathMLTable:
case ax::mojom::Role::kMathMLTableCell:
case ax::mojom::Role::kMathMLTableRow:
case ax::mojom::Role::kMathMLText:
case ax::mojom::Role::kMathMLUnder:
case ax::mojom::Role::kMathMLUnderOver:
case ax::mojom::Role::kNavigation:
case ax::mojom::Role::kNone:
case ax::mojom::Role::kNote:
case ax::mojom::Role::kPane:
case ax::mojom::Role::kParagraph:
case ax::mojom::Role::kPdfRoot:
case ax::mojom::Role::kPluginObject:
case ax::mojom::Role::kRegion:
case ax::mojom::Role::kRowGroup:
case ax::mojom::Role::kRuby:
case ax::mojom::Role::kSearch:
case ax::mojom::Role::kSection:
case ax::mojom::Role::kSectionFooter:
case ax::mojom::Role::kSectionHeader:
case ax::mojom::Role::kSectionWithoutName:
case ax::mojom::Role::kStatus:
case ax::mojom::Role::kSubscript:
case ax::mojom::Role::kSuggestion:
case ax::mojom::Role::kSuperscript:
return NSAccessibilityGroupRole;
case ax::mojom::Role::kSvgRoot:
return NSAccessibilityImageRole;
case ax::mojom::Role::kStrong:
case ax::mojom::Role::kTableHeaderContainer:
case ax::mojom::Role::kTabPanel:
case ax::mojom::Role::kTerm:
case ax::mojom::Role::kTime:
case ax::mojom::Role::kTimer:
case ax::mojom::Role::kTooltip:
case ax::mojom::Role::kVideo:
case ax::mojom::Role::kWebView:
return NSAccessibilityGroupRole;
case ax::mojom::Role::kButton:
return NSAccessibilityButtonRole;
case ax::mojom::Role::kCanvas:
return NSAccessibilityImageRole;
case ax::mojom::Role::kCaret:
return NSAccessibilityUnknownRole;
case ax::mojom::Role::kCell:
return @"AXCell";
case ax::mojom::Role::kCheckBox:
return NSAccessibilityCheckBoxRole;
case ax::mojom::Role::kColorWell:
return NSAccessibilityColorWellRole;
case ax::mojom::Role::kColumn:
return NSAccessibilityColumnRole;
case ax::mojom::Role::kColumnHeader:
return @"AXCell";
case ax::mojom::Role::kComboBoxGrouping:
return NSAccessibilityComboBoxRole;
case ax::mojom::Role::kComboBoxMenuButton:
return NSAccessibilityComboBoxRole;
case ax::mojom::Role::kComboBoxSelect:
// TODO(crbug.com/40864556): Can this be NSAccessibilityComboBoxRole?
return NSAccessibilityPopUpButtonRole;
case ax::mojom::Role::kDate:
return @"AXDateField";
case ax::mojom::Role::kDateTime:
return @"AXDateField";
case ax::mojom::Role::kDescriptionList:
return NSAccessibilityListRole;
case ax::mojom::Role::kDisclosureTriangle:
case ax::mojom::Role::kDisclosureTriangleGrouped:
// If Mac supports AXExpandedChanged event with
// NSAccessibilityDisclosureTriangleRole, We should update
// ax::mojom::Role::kDisclosureTriangle mapping to
// NSAccessibilityDisclosureTriangleRole. http://crbug.com/558324
return features::IsAccessibilityExposeSummaryAsHeadingEnabled()
? NSAccessibilityDisclosureTriangleRole
: NSAccessibilityButtonRole;
case ax::mojom::Role::kDocBackLink:
case ax::mojom::Role::kDocBiblioRef:
case ax::mojom::Role::kDocGlossRef:
case ax::mojom::Role::kDocNoteRef:
return NSAccessibilityLinkRole;
case ax::mojom::Role::kDocCover:
return NSAccessibilityImageRole;
case ax::mojom::Role::kDocPageBreak:
return NSAccessibilitySplitterRole;
case ax::mojom::Role::kDocSubtitle:
return @"AXHeading";
case ax::mojom::Role::kGraphicsSymbol:
return NSAccessibilityImageRole;
case ax::mojom::Role::kGrid:
// Should be NSAccessibilityGridRole but VoiceOver treating it like
// a list as of 10.12.6, so following WebKit and using table role:
// crbug.com/753925
return NSAccessibilityTableRole;
case ax::mojom::Role::kGridCell:
return @"AXCell";
case ax::mojom::Role::kHeading:
return @"AXHeading";
case ax::mojom::Role::kImage:
return NSAccessibilityImageRole;
case ax::mojom::Role::kImeCandidate:
return NSAccessibilityUnknownRole;
case ax::mojom::Role::kInlineTextBox:
return NSAccessibilityStaticTextRole;
case ax::mojom::Role::kInputTime:
return @"AXTimeField";
case ax::mojom::Role::kKeyboard:
return NSAccessibilityUnknownRole;
case ax::mojom::Role::kLink:
return NSAccessibilityLinkRole;
case ax::mojom::Role::kList:
return NSAccessibilityListRole;
case ax::mojom::Role::kListBox:
return NSAccessibilityListRole;
case ax::mojom::Role::kListBoxOption:
return NSAccessibilityStaticTextRole;
case ax::mojom::Role::kListGrid:
return NSAccessibilityTableRole;
case ax::mojom::Role::kListMarker:
return @"AXListMarker";
case ax::mojom::Role::kMenu:
return NSAccessibilityMenuRole;
case ax::mojom::Role::kMenuBar:
return NSAccessibilityMenuBarRole;
case ax::mojom::Role::kMenuItem:
return NSAccessibilityMenuItemRole;
case ax::mojom::Role::kMenuItemCheckBox:
return NSAccessibilityMenuItemRole;
case ax::mojom::Role::kMenuItemRadio:
return NSAccessibilityMenuItemRole;
case ax::mojom::Role::kMenuListOption:
return NSAccessibilityMenuItemRole;
case ax::mojom::Role::kMenuListPopup:
return NSAccessibilityMenuRole;
case ax::mojom::Role::kMeter:
return NSAccessibilityLevelIndicatorRole;
case ax::mojom::Role::kPdfActionableHighlight:
return NSAccessibilityButtonRole;
case ax::mojom::Role::kPopUpButton:
return NSAccessibilityPopUpButtonRole;
case ax::mojom::Role::kProgressIndicator:
return NSAccessibilityProgressIndicatorRole;
case ax::mojom::Role::kRadioButton:
return NSAccessibilityRadioButtonRole;
case ax::mojom::Role::kRadioGroup:
return NSAccessibilityRadioGroupRole;
case ax::mojom::Role::kRootWebArea:
return NSAccessibilityWebAreaRole;
case ax::mojom::Role::kRow:
return NSAccessibilityRowRole;
case ax::mojom::Role::kRowHeader:
return @"AXCell";
case ax::mojom::Role::kRubyAnnotation:
return NSAccessibilityUnknownRole;
case ax::mojom::Role::kScrollBar:
return NSAccessibilityScrollBarRole;
case ax::mojom::Role::kScrollView:
return NSAccessibilityScrollAreaRole;
case ax::mojom::Role::kSearchBox:
return NSAccessibilityTextFieldRole;
case ax::mojom::Role::kSlider:
return NSAccessibilitySliderRole;
case ax::mojom::Role::kSpinButton:
return NSAccessibilityIncrementorRole;
case ax::mojom::Role::kSplitter:
return NSAccessibilitySplitterRole;
case ax::mojom::Role::kStaticText:
return NSAccessibilityStaticTextRole;
case ax::mojom::Role::kSwitch:
return NSAccessibilityCheckBoxRole;
case ax::mojom::Role::kTab:
return NSAccessibilityRadioButtonRole;
case ax::mojom::Role::kTable:
return NSAccessibilityTableRole;
case ax::mojom::Role::kTabList:
return NSAccessibilityTabGroupRole;
case ax::mojom::Role::kTextField:
return NSAccessibilityTextFieldRole;
case ax::mojom::Role::kTextFieldWithComboBox:
return NSAccessibilityComboBoxRole;
case ax::mojom::Role::kTitleBar:
return NSAccessibilityStaticTextRole;
case ax::mojom::Role::kToggleButton:
return NSAccessibilityCheckBoxRole;
case ax::mojom::Role::kToolbar:
return NSAccessibilityToolbarRole;
case ax::mojom::Role::kTree:
return NSAccessibilityOutlineRole;
case ax::mojom::Role::kTreeGrid:
return NSAccessibilityTableRole;
case ax::mojom::Role::kTreeItem:
return NSAccessibilityRowRole;
case ax::mojom::Role::kUnknown:
return NSAccessibilityUnknownRole;
case ax::mojom::Role::kWindow:
// Use the group role as the BrowserNativeWidgetWindow already provides
// a kWindow role, and having extra window roles, which are treated
// specially by screen readers, can break their ability to find the
// content window. See http://crbug.com/875843 for more information.
return NSAccessibilityGroupRole;
case ax::mojom::Role::kDescriptionListTermDeprecated:
case ax::mojom::Role::kDescriptionListDetailDeprecated:
case ax::mojom::Role::kDirectoryDeprecated:
case ax::mojom::Role::kPreDeprecated:
case ax::mojom::Role::kPortalDeprecated:
NOTREACHED();
}
}
+ (NSString*)nativeSubroleFromAXRole:(ax::mojom::Role)role {
static const base::NoDestructor<RoleMap> subrole_map(BuildSubroleMap());
RoleMap::const_iterator it = subrole_map->find(role);
return it != subrole_map->end() ? it->second : nil;
}
+ (NSString*)nativeNotificationFromAXEvent:(ax::mojom::Event)event {
static const base::NoDestructor<EventMap> event_map(BuildEventMap());
EventMap::const_iterator it = event_map->find(event);
return it != event_map->end() ? it->second : nil;
}
- (instancetype)initWithNode:(ui::AXPlatformNodeBase*)node {
if ((self = [super init])) {
_node = node;
}
return self;
}
- (void)detachAndNotifyDestroyed:(BOOL)shouldNotify {
if (!_node)
return;
_node = nil;
if (shouldNotify) {
NSAccessibilityPostNotification(
self, NSAccessibilityUIElementDestroyedNotification);
}
}
- (NSRect)boundsInScreen {
if (!_node) {
return NSZeroRect;
}
return gfx::ScreenRectToNSRect(_node->GetDelegate()->GetBoundsRect(
ui::AXCoordinateSystem::kScreenDIPs, ui::AXClippingBehavior::kClipped));
}
- (NSString*)getStringAttribute:(ax::mojom::StringAttribute)attribute {
std::string attributeValue;
if (_node->GetStringAttribute(attribute, &attributeValue))
return base::SysUTF8ToNSString(attributeValue);
return nil;
}
- (NSString*)getAXValueAsString {
id value = [self AXValue];
return [value isKindOfClass:[NSString class]] ? value : nil;
}
- (ax::mojom::Role)internalRole {
if ([self instanceActive]) {
ax::mojom::Role role = static_cast<ax::mojom::Role>(_node->GetRole());
// Make sure to use Role::kPopupButton instead of Role::kButton for all
// values of kHasPopup. This is normally already true, but the default
// implementation does not use kPopupButton if aria-haspopup="dialog".
if (role == ax::mojom::Role::kButton &&
_node->HasIntAttribute(ax::mojom::IntAttribute::kHasPopup)) {
return ax::mojom::Role::kPopUpButton;
}
return role;
}
return ax::mojom::Role::kUnknown;
}
- (BOOL)hasAction:(ax::mojom::Action)action {
return _node->HasAction(action) || HasImplicitAction(*_node, action);
}
- (BOOL)performAction:(ax::mojom::Action)action {
if (![self hasAction:action]) {
return NO;
}
ui::AXActionData data;
data.action = action;
_node->GetDelegate()->AccessibilityPerformAction(data);
return YES;
}
- (AXPlatformNodeCocoa*)fromNodeID:(ui::AXNodeID)id {
ui::AXPlatformNode* cell = _node->GetDelegate()->GetFromNodeID(id);
if (cell) {
return base::apple::ObjCCast<AXPlatformNodeCocoa>(
cell->GetNativeViewAccessible().Get());
}
return nil;
}
- (BOOL)isImage {
bool has_image_semantics =
ui::IsImage(_node->GetRole()) &&
!_node->GetBoolAttribute(ax::mojom::BoolAttribute::kCanvasHasFallback) &&
!_node->GetChildCount() &&
_node->GetNameFrom() != ax::mojom::NameFrom::kAttributeExplicitlyEmpty;
#if DCHECK_IS_ON()
bool is_native_image =
[[self accessibilityRole] isEqualToString:NSAccessibilityImageRole];
DCHECK_EQ(is_native_image, has_image_semantics)
<< "\nPresence/lack of native image role do not match the expected "
"internal semantics:"
<< "\n* Chrome role: " << ui::ToString(_node->GetRole())
<< "\n* NSAccessibility role: " << [self accessibilityRole]
<< "\n* AXNode: " << *_node;
#endif
return has_image_semantics;
}
- (void)addTextAnnotationsIn:(const AXRange*)axRange
to:(NSMutableAttributedString*)attributedString {
int anchorStartOffset = 0;
std::map<ui::AXNodeID, std::set<ax::mojom::Role>> ancestor_roles;
[attributedString beginEditing];
for (const AXRange& leafTextRange : *axRange) {
DCHECK(!leafTextRange.IsNull());
DCHECK_EQ(leafTextRange.anchor()->GetAnchor(),
leafTextRange.focus()->GetAnchor())
<< "An anchor range should only span a single object.";
int leafTextLength = leafTextRange.GetText().length();
NSRange leafRange = NSMakeRange(anchorStartOffset, leafTextLength);
// As we iterate over the attributed string's string using leaf ranges,
// double check that the next leaf string actually matches the text in the
// attributed string. If it doesn't, the leaf text is "extra" text that's
// not included in the attributed string.
if (leafRange.location >= attributedString.length ||
base::SysNSStringToUTF16([attributedString.string
substringWithRange:leafRange]) != leafTextRange.GetText()) {
continue;
}
ui::AXNode* anchor = leafTextRange.focus()->GetAnchor();
DCHECK(anchor) << "A non-null position should have a non-null anchor node.";
// Add misspelling information
const std::vector<int32_t>& markerTypes =
anchor->GetIntListAttribute(ax::mojom::IntListAttribute::kMarkerTypes);
const std::vector<int>& markerStarts =
anchor->GetIntListAttribute(ax::mojom::IntListAttribute::kMarkerStarts);
const std::vector<int>& markerEnds =
anchor->GetIntListAttribute(ax::mojom::IntListAttribute::kMarkerEnds);
DCHECK_EQ(markerTypes.size(), markerStarts.size());
DCHECK_EQ(markerTypes.size(), markerEnds.size());
for (size_t i = 0; i < markerTypes.size(); ++i) {
if (!(markerTypes[i] &
static_cast<int32_t>(ax::mojom::MarkerType::kSpelling))) {
continue;
}
int misspellingStart = anchorStartOffset + markerStarts[i];
int misspellingEnd = anchorStartOffset + markerEnds[i];
int misspellingLength = misspellingEnd - misspellingStart;
DCHECK_LE(static_cast<unsigned long>(misspellingEnd),
[attributedString length]);
DCHECK_GT(misspellingLength, 0);
[attributedString
addAttribute:NSAccessibilityMarkedMisspelledTextAttribute
value:@YES
range:NSMakeRange(misspellingStart, misspellingLength)];
}
CollectAncestorRoles(*anchor, ancestor_roles);
// Add annotation information
if (ancestor_roles[anchor->id()].contains(ax::mojom::Role::kMark)) {
[attributedString addAttribute:@"AXHighlight" value:@YES range:leafRange];
}
if (ancestor_roles[anchor->id()].contains(ax::mojom::Role::kSuggestion)) {
[attributedString addAttribute:@"AXIsSuggestion"
value:@YES
range:leafRange];
}
if (ancestor_roles[anchor->id()].contains(
ax::mojom::Role::kContentDeletion)) {
[attributedString addAttribute:@"AXIsSuggestedDeletion"
value:@YES
range:leafRange];
}
if (ancestor_roles[anchor->id()].contains(
ax::mojom::Role::kContentInsertion)) {
[attributedString addAttribute:@"AXIsSuggestedInsertion"
value:@YES
range:leafRange];
}
ui::AXTextAttributes text_attrs =
leafTextRange.anchor()->GetTextAttributes();
NSMutableDictionary* fontAttributes = [NSMutableDictionary dictionary];
// TODO(crbug.com/41456329): Implement NSAccessibilityFontFamilyKey.
// TODO(crbug.com/41456329): Implement NSAccessibilityFontNameKey.
// TODO(crbug.com/41456329): Implement NSAccessibilityVisibleNameKey.
if (text_attrs.font_size != ui::AXTextAttributes::kUnsetValue) {
fontAttributes[NSAccessibilityFontSizeKey] = @(text_attrs.font_size);
}
if (text_attrs.HasTextStyle(ax::mojom::TextStyle::kBold)) {
fontAttributes[@"AXFontBold"] = @YES;
}
if (text_attrs.HasTextStyle(ax::mojom::TextStyle::kItalic)) {
fontAttributes[@"AXFontItalic"] = @YES;
}
[attributedString addAttribute:NSAccessibilityFontTextAttribute
value:fontAttributes
range:leafRange];
if (text_attrs.color != ui::AXTextAttributes::kUnsetValue) {
[attributedString addAttribute:NSAccessibilityForegroundColorTextAttribute
value:(__bridge id)skia::SkColorToSRGBNSColor(
SkColor(text_attrs.color))
.CGColor
range:leafRange];
} else {
[attributedString
removeAttribute:NSAccessibilityForegroundColorTextAttribute
range:leafRange];
}
if (text_attrs.background_color != ui::AXTextAttributes::kUnsetValue) {
[attributedString addAttribute:NSAccessibilityBackgroundColorTextAttribute
value:(__bridge id)skia::SkColorToSRGBNSColor(
SkColor(text_attrs.background_color))
.CGColor
range:leafRange];
} else {
[attributedString
removeAttribute:NSAccessibilityBackgroundColorTextAttribute
range:leafRange];
}
// TODO(crbug.com/41456329): Implement
// NSAccessibilitySuperscriptTextAttribute.
// TODO(crbug.com/41456329): Implement NSAccessibilityShadowTextAttribute.
if (text_attrs.underline_style != ui::AXTextAttributes::kUnsetValue) {
[attributedString addAttribute:NSAccessibilityUnderlineTextAttribute
value:@YES
range:leafRange];
} else {
[attributedString removeAttribute:NSAccessibilityUnderlineTextAttribute
range:leafRange];
}
// TODO(crbug.com/41456329): Implement
// NSAccessibilityUnderlineColorTextAttribute.
if (text_attrs.strikethrough_style != ui::AXTextAttributes::kUnsetValue) {
[attributedString addAttribute:NSAccessibilityStrikethroughTextAttribute
value:@YES
range:leafRange];
} else {
[attributedString
removeAttribute:NSAccessibilityStrikethroughTextAttribute
range:leafRange];
}
// TODO(crbug.com/41456329): Implement
// NSAccessibilityStrikethroughColorTextAttribute.
// TODO(crbug.com/41456329): Implement NSAccessibilityLinkTextAttribute.
// TODO(crbug.com/41456329): Implement
// NSAccessibilityAutocorrectedTextAttribute.
anchorStartOffset += leafTextLength;
}
[attributedString endEditing];
}
- (BOOL)descriptionIsFromAriaDescription {
ax::mojom::DescriptionFrom descFrom = static_cast<ax::mojom::DescriptionFrom>(
_node->GetIntAttribute(ax::mojom::IntAttribute::kDescriptionFrom));
return descFrom == ax::mojom::DescriptionFrom::kAriaDescription ||
descFrom == ax::mojom::DescriptionFrom::kRelatedElement;
}
- (NSString*)getName {
return base::SysUTF8ToNSString(_node->GetName());
}
- (AXAnnouncementSpec*)announcementForEvent:(ax::mojom::Event)eventType {
// Only alerts and live region changes should be announced.
DCHECK(eventType == ax::mojom::Event::kAlert ||
eventType == ax::mojom::Event::kLiveRegionChanged);
std::string liveStatus =
_node->GetStringAttribute(ax::mojom::StringAttribute::kLiveStatus);
// If live status is explicitly set to off, don't announce.
if (liveStatus == "off") {
return nil;
}
NSString* name = [self getName];
NSString* announcementText =
name.length > 0 ? name
: base::SysUTF16ToNSString(_node->GetTextContentUTF16());
if (announcementText.length == 0) {
return nil;
}
const std::string& description =
_node->GetStringAttribute(ax::mojom::StringAttribute::kDescription);
if (!description.empty()) {
// Concatenating name and description, with a newline in between to create a
// pause to avoid treating the concatenation as a single sentence.
announcementText =
[NSString stringWithFormat:@"%@\n%@", announcementText,
base::SysUTF8ToNSString(description)];
}
AXAnnouncementSpec* spec = [[AXAnnouncementSpec alloc] init];
spec.announcement = announcementText;
spec.window = [self AXWindow];
spec.polite = liveStatus != "assertive";
return spec;
}
- (void)scheduleLiveRegionAnnouncement:(AXAnnouncementSpec*)announcement {
if (_pendingAnnouncement) {
// An announcement is already in flight, so just reset the contents. This is
// threadsafe because the dispatch is on the main queue.
_pendingAnnouncement = announcement;
return;
}
_pendingAnnouncement = announcement;
dispatch_after(
kLiveRegionDebounceMillis * NSEC_PER_MSEC, dispatch_get_main_queue(), ^{
if (!self->_pendingAnnouncement) {
return;
}
PostAnnouncementNotification(self->_pendingAnnouncement.announcement,
self->_pendingAnnouncement.window,
self->_pendingAnnouncement.polite);
self->_pendingAnnouncement = nil;
});
}
//
// NSAccessibility legacy informal protocol implementation (deprecated).
// https://developer.apple.com/documentation/appkit/deprecated_symbols/nsaccessibility
//
- (BOOL)accessibilityIsIgnored {
return ![self isAccessibilityElement];
}
- (id)accessibilityHitTest:(NSPoint)point {
if (!NSPointInRect(point, self.boundsInScreen)) {
return nil;
}
for (id child in [[self accessibilityChildren] reverseObjectEnumerator]) {
if (!NSPointInRect(point, [child accessibilityFrame]))
continue;
if (id foundChild = [child accessibilityHitTest:point])
return foundChild;
}
// Hit self, but not any child.
return NSAccessibilityUnignoredAncestor(self);
}
- (BOOL)accessibilityNotifiesWhenDestroyed {
return YES;
}
- (id)accessibilityFocusedUIElement {
return _node ? _node->GetDelegate()->GetFocus().Get() : nil;
}
// This function and accessibilityPerformAction:, while deprecated, are a) still
// called by AppKit internally and b) not implemented by NSAccessibilityElement,
// so this class needs its own implementations.
- (NSArray*)accessibilityActionNames {
TRACE_EVENT1("accessibility", "AXPlatformNodeCocoa::accessibilityActionNames",
"role=", ui::ToString([self internalRole]));
// Exclude actions available through the new accessibility API.
NSMutableArray* actions = [self internalAccessibilityActionNames];
if (features::IsMacAccessibilityAPIMigrationEnabled()) {
[actions
filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(
id evaluatedObject,
NSDictionary* bindings) {
return ![[[self class] actionsAvailableThroughNewAccessibilityAPI]
containsObject:evaluatedObject];
}]];
}
return actions;
}
- (NSMutableArray*)internalAccessibilityActionNames {
if (![self instanceActive]) {
return [NSMutableArray array];
}
NSMutableArray* axActions = [NSMutableArray array];
const ui::CocoaActionList& action_list = GetCocoaActionList();
// VoiceOver expects the "press" action to be first. Note that some roles
// should be given a press action implicitly.
DCHECK([action_list[0].second isEqualToString:NSAccessibilityPressAction]);
for (const auto& item : action_list) {
if ((_node->HasAction(item.first) ||
HasImplicitAction(*_node, item.first))) {
[axActions addObject:item.second];
}
}
if (AlsoUseShowMenuActionForDefaultAction(*_node))
[axActions addObject:NSAccessibilityShowMenuAction];
return axActions;
}
// This API is deprecated.
- (void)accessibilityPerformAction:(NSString*)action {
// Actions are performed asynchronously, so it's always possible for an object
// to change its mind after previously reporting an action as available.
if (![[self accessibilityActionNames] containsObject:action]) {
return;
}
ui::AXActionData data;
if ([action isEqualToString:NSAccessibilityShowMenuAction] &&
AlsoUseShowMenuActionForDefaultAction(*_node)) {
data.action = ax::mojom::Action::kDoDefault;
} else {
for (const ui::CocoaActionList::value_type& entry : GetCocoaActionList()) {
if ([action isEqualToString:entry.second]) {
data.action = entry.first;
break;
}
}
}
// Note ui::AX_ACTIONs which are just overwriting an accessibility attribute
// are already implemented in -accessibilitySetValue:forAttribute:, so ignore
// those here.
if (data.action != ax::mojom::Action::kNone)
_node->GetDelegate()->AccessibilityPerformAction(data);
}
- (BOOL)accessibilityPerformPress {
if (![self instanceActive]) {
return NO;
}
return [self performAction:ax::mojom::Action::kDoDefault];
}
- (BOOL)accessibilityPerformShowMenu {
if (![self instanceActive]) {
return NO;
}
if (AlsoUseShowMenuActionForDefaultAction(*_node)) {
return [self accessibilityPerformPress];
}
if ([self performAction:ax::mojom::Action::kShowContextMenu]) {
return YES;
}
return NO;
}
- (BOOL)accessibilityPerformDecrement {
if (![self instanceActive]) {
return NO;
}
return [self performAction:ax::mojom::Action::kDecrement];
}
- (BOOL)accessibilityPerformIncrement {
if (![self instanceActive]) {
return NO;
}
return [self performAction:ax::mojom::Action::kIncrement];
}
- (BOOL)accessibilityPerformConfirm {
// Placeholder for the future. Needs to implement Return press key action.
return NO;
}
- (NSMutableArray*)internalAccessibilityAttributeNames {
if (!_node)
return [NSMutableArray array];
// These attributes are required on all accessibility objects.
NSArray* const kAllRoleAttributes = @[
NSAccessibilityBlockQuoteLevelAttribute, NSAccessibilityChildrenAttribute,
NSAccessibilityDOMClassList, NSAccessibilityDOMIdentifierAttribute,
NSAccessibilityDescriptionAttribute, NSAccessibilityElementBusyAttribute,
NSAccessibilityParentAttribute, NSAccessibilityPositionAttribute,
NSAccessibilityRoleAttribute, NSAccessibilitySizeAttribute,
NSAccessibilitySelectedAttribute, NSAccessibilitySizeAttribute,
NSAccessibilitySubroleAttribute,
// Title is required for most elements. Cocoa asks for the value even if it
// is omitted here, but won't present it to accessibility APIs without this.
NSAccessibilityTitleAttribute,
// Attributes which are not required, but are general to all roles.
NSAccessibilityRoleDescriptionAttribute, NSAccessibilityEnabledAttribute,
NSAccessibilityFocusedAttribute, NSAccessibilityHelpAttribute,
NSAccessibilityTopLevelUIElementAttribute, NSAccessibilityVisitedAttribute,
NSAccessibilityWindowAttribute, NSAccessibilityChromeAXNodeIdAttribute
];
// Attributes required for user-editable controls.
NSArray* const kValueAttributes = @[ NSAccessibilityValueAttribute ];
// Attributes required for unprotected textfields and labels.
NSArray* const kUnprotectedTextAttributes = @[
NSAccessibilityInsertionPointLineNumberAttribute,
NSAccessibilityNumberOfCharactersAttribute,
NSAccessibilitySelectedTextAttribute,
NSAccessibilitySelectedTextRangeAttribute,
NSAccessibilityVisibleCharacterRangeAttribute
];
// Required for all text, including protected textfields.
NSString* const kTextAttributes = NSAccessibilityPlaceholderValueAttribute;
NSMutableArray* axAttributes =
[NSMutableArray arrayWithArray:kAllRoleAttributes];
ax::mojom::Role role = _node->GetRole();
switch (role) {
case ax::mojom::Role::kTextField:
case ax::mojom::Role::kTextFieldWithComboBox:
[axAttributes addObject:NSAccessibilityOwnsAttribute];
break;
case ax::mojom::Role::kStaticText:
[axAttributes addObject:kTextAttributes];
if (!_node->HasState(ax::mojom::State::kProtected))
[axAttributes addObjectsFromArray:kUnprotectedTextAttributes];
[[fallthrough]];
case ax::mojom::Role::kCheckBox:
case ax::mojom::Role::kComboBoxMenuButton:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kMenuItemRadio:
case ax::mojom::Role::kRadioButton:
case ax::mojom::Role::kSearchBox:
case ax::mojom::Role::kSlider:
case ax::mojom::Role::kToggleButton:
[axAttributes addObjectsFromArray:kValueAttributes];
break;
case ax::mojom::Role::kMathMLFraction:
[axAttributes addObjectsFromArray:@[
NSAccessibilityMathFractionNumeratorAttribute,
NSAccessibilityMathFractionDenominatorAttribute
]];
break;
case ax::mojom::Role::kMathMLSquareRoot:
[axAttributes addObject:NSAccessibilityMathRootRadicandAttribute];
break;
case ax::mojom::Role::kMathMLRoot:
[axAttributes addObjectsFromArray:@[
NSAccessibilityMathRootRadicandAttribute,
NSAccessibilityMathRootIndexAttribute
]];
break;
case ax::mojom::Role::kMathMLSub:
[axAttributes addObjectsFromArray:@[
NSAccessibilityMathBaseAttribute, NSAccessibilityMathSubscriptAttribute
]];
break;
case ax::mojom::Role::kMathMLSup:
[axAttributes addObjectsFromArray:@[
NSAccessibilityMathBaseAttribute,
NSAccessibilityMathSuperscriptAttribute
]];
break;
case ax::mojom::Role::kMathMLSubSup:
[axAttributes addObjectsFromArray:@[
NSAccessibilityMathBaseAttribute, NSAccessibilityMathSubscriptAttribute,
NSAccessibilityMathSuperscriptAttribute
]];
break;
case ax::mojom::Role::kMathMLUnder:
[axAttributes addObjectsFromArray:@[
NSAccessibilityMathBaseAttribute, NSAccessibilityMathUnderAttribute
]];
break;
case ax::mojom::Role::kMathMLOver:
[axAttributes addObjectsFromArray:@[
NSAccessibilityMathBaseAttribute, NSAccessibilityMathOverAttribute
]];
break;
case ax::mojom::Role::kMathMLUnderOver:
[axAttributes addObjectsFromArray:@[
NSAccessibilityMathBaseAttribute, NSAccessibilityMathUnderAttribute,
NSAccessibilityMathOverAttribute
]];
break;
case ax::mojom::Role::kMathMLMultiscripts:
[axAttributes addObjectsFromArray:@[
NSAccessibilityMathBaseAttribute,
NSAccessibilityMathPostscriptsAttribute,
NSAccessibilityMathPrescriptsAttribute
]];
break;
// TODO(tapted): Add additional attributes based on role.
default:
break;
}
if (ui::IsMenuItem(role))
[axAttributes addObject:@"AXMenuItemMarkChar"];
if (ui::IsItemLike(role))
[axAttributes addObjectsFromArray:@[ @"AXARIAPosInSet", @"AXARIASetSize" ]];
if (ui::IsSetLike(role))
[axAttributes addObject:@"AXARIASetSize"];
if ([[self accessibilityRole] isEqualToString:NSAccessibilityWebAreaRole]) {
[axAttributes addObjectsFromArray:@[
NSAccessibilityLoadedAttribute, NSAccessibilityLoadingProgressAttribute
]];
}
// Caret navigation and text selection attributes.
if (!ui::IsPlatformDocument(_node->GetRole())) {
[axAttributes addObject:NSAccessibilityFocusableAncestorAttribute];
if (_node->HasState(ax::mojom::State::kEditable)) {
[axAttributes addObjectsFromArray:@[
NSAccessibilityEditableAncestorAttribute,
NSAccessibilityHighestEditableAncestorAttribute
]];
}
}
// Live regions.
if (_node->HasStringAttribute(ax::mojom::StringAttribute::kLiveStatus))
[axAttributes addObject:NSAccessibilityARIALiveAttribute];
if (_node->HasStringAttribute(ax::mojom::StringAttribute::kLiveRelevant))
[axAttributes addObject:NSAccessibilityARIARelevantAttribute];
if (_node->HasBoolAttribute(ax::mojom::BoolAttribute::kLiveAtomic))
[axAttributes addObject:NSAccessibilityARIAAtomicAttribute];
if (_node->HasBoolAttribute(ax::mojom::BoolAttribute::kBusy))
[axAttributes addObject:NSAccessibilityARIABusyAttribute];
if (_node->HasIntAttribute(ax::mojom::IntAttribute::kAriaCurrentState))
[axAttributes addObject:NSAccessibilityARIACurrentAttribute];
// Control element.
if (ui::IsControl(role)) {
[axAttributes addObjectsFromArray:@[
NSAccessibilityAccessKeyAttribute,
NSAccessibilityInvalidAttribute,
]];
}
// Autocomplete.
if (_node->HasStringAttribute(ax::mojom::StringAttribute::kAutoComplete))
[axAttributes addObject:NSAccessibilityAutocompleteValueAttribute];
// AriaBrailleLabel.
if (_node->HasStringAttribute(ax::mojom::StringAttribute::kAriaBrailleLabel))
[axAttributes addObject:NSAccessibilityBrailleLabelAttribute];
// AriaBrailleRoleDescription.
if (_node->HasStringAttribute(
ax::mojom::StringAttribute::kAriaBrailleRoleDescription))
[axAttributes addObject:NSAccessibilityBrailleRoleDescription];
// Details.
if (_node->HasIntListAttribute(ax::mojom::IntListAttribute::kDetailsIds)) {
[axAttributes addObject:NSAccessibilityDetailsElementsAttribute];
}
// Error messages.
if (_node->HasIntListAttribute(
ax::mojom::IntListAttribute::kErrormessageIds)) {
[axAttributes addObject:NSAccessibilityErrorMessageElementsAttribute];
}
if (ui::SupportsRequired(role)) {
[axAttributes addObject:NSAccessibilityRequiredAttribute];
}
// Url: add the url attribute only if the object has a valid url.
if ([self accessibilityURL])
[axAttributes addObject:NSAccessibilityURLAttribute];
// Table and grid.
if (ui::IsTableLike(role)) {
[axAttributes addObjectsFromArray:@[
NSAccessibilityColumnHeaderUIElementsAttribute,
NSAccessibilityARIAColumnCountAttribute,
NSAccessibilityARIARowCountAttribute,
]];
}
if (ui::IsCellOrTableHeader(role)) {
[axAttributes addObjectsFromArray:@[
NSAccessibilityARIAColumnIndexAttribute,
NSAccessibilityARIARowIndexAttribute,
]];
}
if (ui::IsCellOrTableHeader(role) && role != ax::mojom::Role::kColumnHeader) {
[axAttributes addObject:NSAccessibilityColumnHeaderUIElementsAttribute];
}
// Tree and grid (Outline role in Mac accessibility)
if (ui::IsGridLike(role))
[axAttributes addObject:NSAccessibilitySelectedRowsAttribute];
// Popup
if (_node->HasIntAttribute(ax::mojom::IntAttribute::kHasPopup)) {
[axAttributes addObjectsFromArray:@[
NSAccessibilityHasPopupAttribute, NSAccessibilityPopupValueAttribute
]];
}
// KeyShortcuts
if (_node->HasStringAttribute(ax::mojom::StringAttribute::kKeyShortcuts))
[axAttributes addObject:NSAccessibilityKeyShortcutsValueAttribute];
// TitleUIElement
if ([self titleUIElement])
[axAttributes addObject:NSAccessibilityTitleUIElementAttribute];
return axAttributes;
}
// This API is deprecated.
// This method, while deprecated, is still called internally by AppKit.
- (NSArray*)accessibilityAttributeNames {
TRACE_EVENT1("accessibility",
"AXPlatformNodeCocoa::accessibilityAttributeNames",
"role=", ui::ToString([self internalRole]));
// Exclude attributes available through the new accessibility API.
NSMutableArray* attributes = [self internalAccessibilityAttributeNames];
if (features::IsMacAccessibilityAPIMigrationEnabled()) {
[attributes
filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(
id evaluatedObject,
NSDictionary* bindings) {
return ![[[self class] attributesAvailableThroughNewAccessibilityAPI]
containsObject:evaluatedObject];
}]];
}
return attributes;
}
- (NSArray*)accessibilityParameterizedAttributeNames {
TRACE_EVENT1("accessibility",
"AXPlatformNodeCocoa::accessibilityParameterizedAttributeNames",
"role=", ui::ToString([self internalRole]));
// Exclude attributes available through the new accessibility API.
NSMutableArray* attributes =
[self internalAccessibilityParameterizedAttributeNames];
if (features::IsMacAccessibilityAPIMigrationEnabled()) {
[attributes
filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(
id evaluatedObject,
NSDictionary* bindings) {
return ![[[self class] attributesAvailableThroughNewAccessibilityAPI]
containsObject:evaluatedObject];
}]];
}
return attributes;
}
- (NSMutableArray*)internalAccessibilityParameterizedAttributeNames {
if (![self instanceActive]) {
return [NSMutableArray array];
}
// General attributes.
NSMutableArray* attributeNames = [NSMutableArray
arrayWithObjects:
NSAccessibilityAttributedStringForTextMarkerRangeParameterizedAttribute,
nil];
if (_node->HasState(ax::mojom::State::kEditable)) {
[attributeNames addObjectsFromArray:@[
NSAccessibilityAttributedStringForRangeParameterizedAttribute
]];
}
return attributeNames;
}
// This API is deprecated.
// Despite its deprecation, the AppKit internally calls this function sometimes
// in unclear circumstances. It is implemented in terms of the new a11y API
// here.
- (void)accessibilitySetValue:(id)value forAttribute:(NSString*)attribute {
if (!_node)
return;
if ([[self class] isAttributeAvailableThroughNewAccessibilityAPI:attribute]) {
return;
}
if ([attribute isEqualToString:NSAccessibilityValueAttribute]) {
[self setAccessibilityValue:value];
} else if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute]) {
[self setAccessibilitySelectedText:base::apple::ObjCCastStrict<NSString>(
value)];
} else if ([attribute
isEqualToString:NSAccessibilitySelectedTextRangeAttribute]) {
[self
setAccessibilitySelectedTextRange:base::apple::ObjCCastStrict<NSValue>(
value)
.rangeValue];
} else if ([attribute isEqualToString:NSAccessibilityFocusedAttribute]) {
[self setAccessibilityFocused:base::apple::ObjCCastStrict<NSNumber>(value)
.boolValue];
}
}
// This method, while deprecated, is still called internally by AppKit.
- (id)accessibilityAttributeValue:(NSString*)attribute {
if (!_node)
return nil; // Return nil when detached. Even for ax::mojom::Role.
if ([[self class] isAttributeAvailableThroughNewAccessibilityAPI:attribute]) {
// TODO(crbug.com/376723178): We should be able to add a NOTREACHED()
// here, but at the moment, test infrastructure still directly calls this
// api endpoint.
return nil;
}
SEL selector = NSSelectorFromString(attribute);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
if ([self respondsToSelector:selector])
return [self performSelector:selector];
#pragma clang diagnostic pop
return nil;
}
- (id)accessibilityAttributeValue:(NSString*)attribute
forParameter:(id)parameter {
if (!_node)
return nil;
if ([[self class] isAttributeAvailableThroughNewAccessibilityAPI:attribute]) {
// TODO(crbug.com/376723178): We should be able to add a NOTREACHED()
// here, but at the moment, test infrastructure still directly calls this
// api endpoint.
return nil;
}
SEL selector = NSSelectorFromString([attribute stringByAppendingString:@":"]);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
if ([self respondsToSelector:selector])
return [self performSelector:selector withObject:parameter];
#pragma clang diagnostic pop
return nil;
}
//
// End of legacy deprecated NSAccessibility informal protocol.
//
// NSAccessibility (key-based) attributes. Order them according to
// NSAccessibilityConstants.h, or see https://crbug.com/678898.
- (NSString*)AXAccessKey {
if (![self instanceActive])
return nil;
return [self getStringAttribute:ax::mojom::StringAttribute::kAccessKey];
}
- (NSNumber*)AXARIAAtomic {
if (![self instanceActive])
return nil;
return @(_node->GetBoolAttribute(ax::mojom::BoolAttribute::kLiveAtomic));
}
- (NSNumber*)AXARIABusy {
if (![self instanceActive])
return nil;
return @(_node->GetBoolAttribute(ax::mojom::BoolAttribute::kBusy));
}
- (NSString*)AXARIACurrent {
if (![self instanceActive])
return nil;
int ariaCurrent;
if (!_node->GetIntAttribute(ax::mojom::IntAttribute::kAriaCurrentState,
&ariaCurrent))
return nil;
switch (static_cast<ax::mojom::AriaCurrentState>(ariaCurrent)) {
case ax::mojom::AriaCurrentState::kNone:
NOTREACHED();
case ax::mojom::AriaCurrentState::kFalse:
return @"false";
case ax::mojom::AriaCurrentState::kTrue:
return @"true";
case ax::mojom::AriaCurrentState::kPage:
return @"page";
case ax::mojom::AriaCurrentState::kStep:
return @"step";
case ax::mojom::AriaCurrentState::kLocation:
return @"location";
case ax::mojom::AriaCurrentState::kDate:
return @"date";
case ax::mojom::AriaCurrentState::kTime:
return @"time";
}
NOTREACHED();
}
- (NSNumber*)AXARIAColumnCount {
if (![self instanceActive])
return nil;
std::optional<int> ariaColCount =
_node->GetDelegate()->GetTableAriaColCount();
if (!ariaColCount)
return nil;
return @(*ariaColCount);
}
- (NSNumber*)AXARIAColumnIndex {
if (![self instanceActive])
return nil;
std::optional<int> ariaColIndex =
_node->GetDelegate()->GetTableCellAriaColIndex();
if (!ariaColIndex)
return nil;
return @(*ariaColIndex);
}
- (NSString*)AXARIALive {
if (![self instanceActive])
return nil;
return [self getStringAttribute:ax::mojom::StringAttribute::kLiveStatus];
}
- (NSString*)AXARIARelevant {
if (![self instanceActive])
return nil;
return [self getStringAttribute:ax::mojom::StringAttribute::kLiveRelevant];
}
- (NSNumber*)AXARIARowCount {
if (![self instanceActive])
return nil;
std::optional<int> ariaRowCount =
_node->GetDelegate()->GetTableAriaRowCount();
if (!ariaRowCount)
return nil;
return @(*ariaRowCount);
}
- (NSNumber*)AXARIARowIndex {
if (![self instanceActive])
return nil;
std::optional<int> ariaRowIndex =
_node->GetDelegate()->GetTableCellAriaRowIndex();
if (!ariaRowIndex)
return nil;
return @(*ariaRowIndex);
}
- (NSString*)AXAutocompleteValue {
if (![self instanceActive])
return nil;
return [self getStringAttribute:ax::mojom::StringAttribute::kAutoComplete];
}
- (NSString*)AXBrailleLabel {
if (![self instanceActive])
return nil;
return
[self getStringAttribute:ax::mojom::StringAttribute::kAriaBrailleLabel];
}
- (NSString*)AXBrailleRoleDescription {
if (![self instanceActive])
return nil;
return [self getStringAttribute:ax::mojom::StringAttribute::
kAriaBrailleRoleDescription];
}
- (id)AXBlockQuoteLevel {
if (![self instanceActive])
return nil;
// This is for the number of ancestors that are a <blockquote>, including
// self, useful for tracking replies to replies etc. in an email.
int level = 0;
for (ui::AXPlatformNodeBase* ancestor = _node; ancestor;
ancestor = ancestor->GetPlatformParent()) {
// Do not cross document boundaries.
if (ui::IsPlatformDocument(ancestor->GetRole()))
break;
if (ancestor->GetRole() == ax::mojom::Role::kBlockquote)
++level;
}
return @(level);
}
- (NSArray*)AXColumnHeaderUIElements {
return [self accessibilityColumnHeaderUIElements];
}
- (NSArray*)AXDetailsElements {
if (![self instanceActive])
return nil;
NSMutableArray* elements = [NSMutableArray array];
for (ui::AXNodeID id :
_node->GetIntListAttribute(ax::mojom::IntListAttribute::kDetailsIds)) {
AXPlatformNodeCocoa* node = [self fromNodeID:id];
if (node)
[elements addObject:node];
}
return elements.count ? elements : nil;
}
- (NSArray*)AXDOMClassList {
if (![self instanceActive])
return nil;
NSMutableArray* ret = [NSMutableArray array];
std::string classes;
if (_node->GetStringAttribute(ax::mojom::StringAttribute::kClassName,
&classes)) {
std::vector<std::string> split_classes = base::SplitString(
classes, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
for (const auto& className : split_classes)
[ret addObject:(base::SysUTF8ToNSString(className))];
}
return ret;
}
- (NSString*)AXDOMIdentifier {
if (![self instanceActive])
return nil;
std::string id;
if (_node->GetStringAttribute(ax::mojom::StringAttribute::kHtmlId, &id)) {
return base::SysUTF8ToNSString(id);
}
return @"";
}
- (id)AXEditableAncestor {
if (![self instanceActive])
return nil;
ui::AXPlatformNodeBase* text_field_ancestor =
_node->GetPlatformTextFieldAncestor();
if (text_field_ancestor)
return text_field_ancestor->GetNativeViewAccessible().Get();
return nil;
}
- (NSNumber*)AXElementBusy {
if (![self instanceActive])
return nil;
return @(_node->GetBoolAttribute(ax::mojom::BoolAttribute::kBusy));
}
- (NSArray*)AXErrorMessageElements {
if (![self instanceActive]) {
return nil;
}
NSMutableArray* elements = [NSMutableArray array];
for (ui::AXNodeID id : _node->GetIntListAttribute(
ax::mojom::IntListAttribute::kErrormessageIds)) {
AXPlatformNodeCocoa* node = [self fromNodeID:id];
if (node) {
[elements addObject:node];
}
}
return elements.count ? elements : nil;
}
- (NSNumber*)AXGrabbed {
return @NO;
}
- (NSNumber*)AXHasPopup {
if (![self instanceActive])
return nil;
return @(_node->HasIntAttribute(ax::mojom::IntAttribute::kHasPopup));
}
- (id)AXHighestEditableAncestor {
if (![self instanceActive])
return nil;
AXPlatformNodeCocoa* highestEditableAncestor = [self AXEditableAncestor];
while (highestEditableAncestor) {
AXPlatformNodeCocoa* ancestorParent = [highestEditableAncestor AXParent];
if (!ancestorParent || ![ancestorParent isKindOfClass:[self class]])
break;
AXPlatformNodeCocoa* higherAncestor = [ancestorParent AXEditableAncestor];
if (!higherAncestor)
break;
highestEditableAncestor = higherAncestor;
}
return highestEditableAncestor;
}
- (NSString*)AXInvalid {
if (![self instanceActive])
return nil;
switch (_node->GetData().GetInvalidState()) {
case ax::mojom::InvalidState::kNone:
case ax::mojom::InvalidState::kFalse:
return @"false";
case ax::mojom::InvalidState::kTrue:
return @"true";
}
}
- (NSNumber*)AXIsMultiSelectable {
if (![self instanceActive])
return nil;
return @(_node->HasState(ax::mojom::State::kMultiselectable));
}
- (NSString*)AXKeyShortcutsValue {
if (![self instanceActive])
return nil;
return [self getStringAttribute:ax::mojom::StringAttribute::kKeyShortcuts];
}
- (NSNumber*)AXLoaded {
if (![self instanceActive])
return nil;
return @(_node->GetDelegate()->GetTreeData().loaded);
}
- (NSNumber*)AXLoadingProgress {
if (![self instanceActive])
return nil;
double doubleValue = _node->GetDelegate()->GetTreeData().loading_progress;
return @(doubleValue);
}
- (id)AXOwns {
if (![self instanceActive])
return nil;
ui::AXPlatformNodeBase* activeDescendant = _node->GetActiveDescendant();
if (!activeDescendant)
return nil;
ui::AXPlatformNodeBase* container = activeDescendant->GetSelectionContainer();
if (!container)
return nil;
return @[ container->GetNativeViewAccessible().Get() ];
}
- (NSString*)AXPopupValue {
if (![self instanceActive])
return nil;
int hasPopup = _node->GetIntAttribute(ax::mojom::IntAttribute::kHasPopup);
switch (static_cast<ax::mojom::HasPopup>(hasPopup)) {
case ax::mojom::HasPopup::kFalse:
return @"false";
case ax::mojom::HasPopup::kTrue:
return @"true";
case ax::mojom::HasPopup::kMenu:
return @"menu";
case ax::mojom::HasPopup::kListbox:
return @"listbox";
case ax::mojom::HasPopup::kTree:
return @"tree";
case ax::mojom::HasPopup::kGrid:
return @"grid";
case ax::mojom::HasPopup::kDialog:
return @"dialog";
}
}
- (NSNumber*)AXRequired {
return [self isAccessibilityRequired] ? @YES : @NO;
}
- (NSString*)AXRole {
if (!_node)
return nil;
return [[self class] nativeRoleFromAXRole:_node->GetRole()];
}
- (NSString*)AXRoleDescription {
return [self accessibilityRoleDescription];
}
- (NSNumber*)AXSelected {
return [self accessibilitySelected];
}
- (NSArray*)AXSelectedRows {
return [self accessibilitySelectedRows];
}
- (NSString*)AXSubrole {
ax::mojom::Role role = _node->GetRole();
switch (role) {
case ax::mojom::Role::kTextField:
if (_node->HasState(ax::mojom::State::kProtected))
return NSAccessibilitySecureTextFieldSubrole;
break;
default:
break;
}
return [AXPlatformNodeCocoa nativeSubroleFromAXRole:role];
}
- (NSURL*)AXURL {
return [self accessibilityURL];
}
- (NSNumber*)AXVisited {
if (![self instanceActive])
return nil;
return @(_node->HasState(ax::mojom::State::kVisited));
}
- (NSString*)AXHelp {
if (![self instanceActive]) {
return nil;
}
// ARIA descriptions are returned as AXCustomContent (see
// -accessibilityCustomContent below), so if the description is from ARIA,
// don't provide it as AXHelp, and return nothing.
if ([self descriptionIsFromAriaDescription]) {
return nil;
}
// Otherwise, it's a non-ARIA description, which is returned as AXHelp.
return [self getStringAttribute:ax::mojom::StringAttribute::kDescription];
}
- (id)AXValue {
ax::mojom::Role role = _node->GetRole();
if (role == ax::mojom::Role::kTab)
return [self AXSelected];
if (ui::IsNameExposedInAXValueForRole(role))
return [self getName];
if (_node->IsPlatformCheckable()) {
// Mixed checkbox state not currently supported in views, but could be.
// See browser_accessibility_cocoa.mm for details.
const auto checkedState = static_cast<ax::mojom::CheckedState>(
_node->GetIntAttribute(ax::mojom::IntAttribute::kCheckedState));
return checkedState == ax::mojom::CheckedState::kTrue ? @1 : @0;
}
return base::SysUTF16ToNSString(_node->GetValueForControl());
}
- (NSNumber*)AXEnabled {
return
@(_node->GetData().GetRestriction() != ax::mojom::Restriction::kDisabled);
}
- (BOOL)isAccessibilityExpanded {
// Keep logic consistent with `-[BrowserAccessibilityCocoa expanded]`
if (![self instanceActive]) {
return NO;
}
return _node->HasState(ax::mojom::State::kExpanded);
}
- (NSNumber*)AXFocused {
return @([self isAccessibilityFocused]);
}
- (BOOL)isAccessibilityFocused {
if (![self instanceActive]) {
return NO;
}
return _node->GetDelegate()->GetFocus() == _node->GetNativeViewAccessible();
}
- (id)AXFocusableAncestor {
if (![self instanceActive])
return nil;
ui::AXPlatformNodeBase* ancestor = _node;
for (; ancestor; ancestor = ancestor->GetPlatformParent()) {
// Do not cross document boundaries.
if (ui::IsPlatformDocument(ancestor->GetRole()))
return nil;
if (ancestor->IsFocusable())
break;
}
// The assignment to ancestor may be null.
if (!ancestor)
return nil;
return ancestor->GetNativeViewAccessible().Get();
}
- (id)AXParent {
if (!_node)
return nil;
return NSAccessibilityUnignoredAncestor(_node->GetParent().Get());
}
- (NSArray*)accessibilityChildren {
if (!_node)
return @[];
int count = _node->GetChildCount();
NSMutableArray* children = [NSMutableArray arrayWithCapacity:count];
for (auto child_iterator_ptr = _node->GetDelegate()->ChildrenBegin();
*child_iterator_ptr != *_node->GetDelegate()->ChildrenEnd();
++(*child_iterator_ptr)) {
ui::AXPlatformNodeDelegate* child = child_iterator_ptr->get();
if (child && child->IsInvisibleOrIgnored()) {
[children
addObjectsFromArray:[child_iterator_ptr->GetNativeViewAccessible()
.Get() accessibilityChildren]];
} else {
[children addObject:child_iterator_ptr->GetNativeViewAccessible().Get()];
}
}
return NSAccessibilityUnignoredChildren(children);
}
- (NSArray*)accessibilityChildrenInNavigationOrder {
// We follow Webkit's implementation here.
return [self accessibilityChildren];
}
- (id)AXWindow {
return _node->GetDelegate()->GetNSWindow().Get();
}
- (id)AXTopLevelUIElement {
return [self AXWindow];
}
- (NSValue*)AXPosition {
return [NSValue valueWithPoint:self.boundsInScreen.origin];
}
- (NSValue*)AXSize {
return [NSValue valueWithSize:self.boundsInScreen.size];
}
- (NSString*)AXTitle {
return [self accessibilityTitle];
}
- (id)AXTitleUIElement {
return [self accessibilityTitleUIElement];
}
- (NSString*)AXDescription {
return [self accessibilityLabel];
}
// Misc attributes.
- (NSString*)AXPlaceholderValue {
if (![self instanceActive]) {
return nil;
}
if (_node->GetNameFrom() == ax::mojom::NameFrom::kPlaceholder) {
return [self getName];
}
return [self getStringAttribute:ax::mojom::StringAttribute::kPlaceholder];
}
- (NSString*)AXMenuItemMarkChar {
if (!ui::IsMenuItem(_node->GetRole()))
return nil;
const auto checkedState = static_cast<ax::mojom::CheckedState>(
_node->GetIntAttribute(ax::mojom::IntAttribute::kCheckedState));
if (checkedState == ax::mojom::CheckedState::kTrue) {
return @"\u2713"; // "check mark"
}
return @"";
}
- (NSNumber*)AXARIAPosInSet {
if (![self instanceActive])
return nil;
std::optional<int> posInSet = _node->GetPosInSet();
if (!posInSet)
return nil;
return @(*posInSet);
}
- (NSNumber*)AXARIASetSize {
if (![self instanceActive])
return nil;
std::optional<int> setSize = _node->GetSetSize();
if (!setSize)
return nil;
return @(*setSize);
}
// Text-specific attributes.
// LINT.IfChange
- (NSString*)AXSelectedText {
NSRange selectedTextRange = [[self AXSelectedTextRange] rangeValue];
return [[self getAXValueAsString] substringWithRange:selectedTextRange];
}
// LINT.ThenChange(accessibilitySelectedText)
// LINT.IfChange
- (NSValue*)AXSelectedTextRange {
int start = 0, end = 0;
if (_node->IsAtomicTextField() &&
_node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, &start) &&
_node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, &end)) {
// NSRange cannot represent the direction the text was selected in.
return
[NSValue valueWithRange:{static_cast<NSUInteger>(std::min(start, end)),
static_cast<NSUInteger>(abs(end - start))}];
}
return [NSValue valueWithRange:NSMakeRange(0, 0)];
}
// LINT.ThenChange(accessibilitySelectedTextRange)
// LINT.IfChange
- (NSNumber*)AXNumberOfCharacters {
return @([[self getAXValueAsString] length]);
}
// LINT.ThenChange(accessibilityNumberOfCharacters)
// LINT.IfChange
- (NSValue*)AXVisibleCharacterRange {
return [NSValue valueWithRange:{0, [[self getAXValueAsString] length]}];
}
// LINT.ThenChange(accessibilityVisibleCharacterRange)
// LINT.IfChange
- (NSNumber*)AXInsertionPointLineNumber {
// TODO: multiline is not supported on views.
return @0;
}
// LINT.ThenChange(accessibilityInsertionPointLineNumber)
// Parameterized text-specific attributes.
- (id)AXRangeForLine:(id)parameter {
NSNumber* lineNumber = base::apple::ObjCCast<NSNumber>(parameter);
if (!lineNumber) {
return nil;
}
int lineIndex = [lineNumber intValue];
if (lineIndex != 0) {
return nil;
}
return [NSValue valueWithRange:[self accessibilityRangeForLine:lineIndex]];
}
- (id)AXStringForRange:(id)parameter {
if (![parameter isKindOfClass:[NSValue class]] ||
(0 != UNSAFE_TODO(strcmp([parameter objCType], @encode(NSRange))))) {
return nil;
}
return [self accessibilityStringForRange:[parameter rangeValue]];
}
- (id)AXRangeForPosition:(id)parameter {
NSValue* positionValue = base::apple::ObjCCast<NSValue>(parameter);
if (!positionValue) {
return nil;
}
NSPoint point = [positionValue pointValue];
return [NSValue valueWithRange:[self accessibilityRangeForPosition:point]];
}
- (id)AXRangeForIndex:(id)parameter {
NSNumber* indexNumber = base::apple::ObjCCast<NSNumber>(parameter);
if (!indexNumber) {
return nil;
}
NSInteger index = [indexNumber intValue];
return [NSValue valueWithRange:[self accessibilityRangeForIndex:index]];
}
- (id)AXBoundsForRange:(id)parameter {
// TODO(tapted): Provide an accessor on AXPlatformNodeDelegate to obtain this
// from ui::TextInputClient::GetCompositionCharacterBounds().
NOTIMPLEMENTED();
return nil;
}
- (id)AXRTFForRange:(id)parameter {
NOTIMPLEMENTED();
return nil;
}
- (id)AXStyleRangeForIndex:(id)parameter {
NSNumber* indexNumber = base::apple::ObjCCast<NSNumber>(parameter);
if (!indexNumber) {
return nil;
}
return [NSValue
valueWithRange:[self accessibilityStyleRangeForIndex:[indexNumber
intValue]]];
}
- (id)AXAttributedStringForRange:(id)parameter {
if (![parameter isKindOfClass:[NSValue class]])
return nil;
// TODO(crbug.com/41456329): Finish implementation.
// Currently, we only decorate the attributed string with misspelling
// information.
// TODO(tapted): views::WordLookupClient has a way to obtain the actual
// decorations, and BridgedContentView has a conversion function that creates
// an NSAttributedString. Refactor things so they can be used here.
NSRange range = [(NSValue*)parameter rangeValue];
std::u16string textContent = _node->GetTextContentUTF16();
if (NSMaxRange(range) > textContent.length())
return nil;
// We potentially need to add text attributes to the whole text content
// because a spelling mistake might start or end outside the given range.
NSMutableAttributedString* attributedTextContent =
[[NSMutableAttributedString alloc]
initWithString:base::SysUTF16ToNSString(textContent)];
if (!_node->IsText()) {
AXRange axRange(_node->GetDelegate()->CreateTextPositionAt(0),
_node->GetDelegate()->CreateTextPositionAt(
static_cast<int>(textContent.length())));
[self addTextAnnotationsIn:&axRange to:attributedTextContent];
}
return [attributedTextContent attributedSubstringFromRange:range];
}
- (NSAttributedString*)AXAttributedStringForTextMarkerRange:(id)markerRange {
AXRange axRange = ui::AXTextMarkerRangeToAXRange(markerRange);
if (axRange.IsNull())
return nil;
NSString* text = base::SysUTF16ToNSString(axRange.GetText());
if (text.length == 0) {
return nil;
}
NSMutableAttributedString* attributedText =
[[NSMutableAttributedString alloc] initWithString:text];
// Currently, we only decorate the attributed string with misspelling
// and annotation information.
[self addTextAnnotationsIn:&axRange to:attributedText];
return attributedText;
}
- (NSString*)ChromeAXNodeId {
return [@(_node->GetNodeId()) stringValue];
}
- (NSString*)description {
return [NSString stringWithFormat:@"%@ - %@ (%@)", [super description],
[self accessibilityTitle], [self AXRole]];
}
//
// End of key-based attributes.
//
//
// NSAccessibility protocol.
// https://developer.apple.com/documentation/appkit/nsaccessibilityprotocol
//
// These methods appear to be the minimum needed to avoid AppKit refusing to
// handle the element or crashing internally. Most of the remaining old API
// methods (the ones from NSObject) are implemented in terms of the new
// NSAccessibility methods.
//
// TODO(crbug.com/41115917): Does this class need to implement the various
// accessibilityPerformFoo methods, or are the stub implementations from
// NSAccessibilityElement sufficient?
// NSAccessibility: Configuring Accessibility.
- (BOOL)isAccessibilityElement {
if (![self instanceActive])
return NO;
return (![[[self class] nativeRoleFromAXRole:_node->GetRole()]
isEqualToString:NSAccessibilityUnknownRole] &&
!_node->GetDelegate()->IsIgnored());
}
- (BOOL)isAccessibilityEnabled {
if (!_node)
return NO;
return _node->GetData().GetRestriction() != ax::mojom::Restriction::kDisabled;
}
- (NSRect)accessibilityFrame {
return [self boundsInScreen];
}
- (NSString*)accessibilityHelp {
return [self AXHelp];
}
- (NSString*)accessibilityLabel {
if (![self instanceActive])
return nil;
// macOS wants static text exposed in AXValue.
if (ui::IsNameExposedInAXValueForRole([self internalRole]))
return @"";
// If we're exposing the title in TitleUIElement, don't also redundantly
// expose it in accessibilityLabel.
if ([self titleUIElement])
return @"";
if (![self isNameFromLabel])
return @"";
std::string name = _node->GetName();
if (!name.empty())
return base::SysUTF8ToNSString(name);
// Given an image where there's no other title, return the base part
// of the filename as the description.
if ([self isImage]) {
std::string url;
if (_node->GetStringAttribute(ax::mojom::StringAttribute::kUrl, &url)) {
// Given a url like http://foo.com/bar/baz.png, just return the
// base name, e.g., "baz.png".
size_t leftIndex = url.rfind('/');
std::string basename =
leftIndex != std::string::npos ? url.substr(leftIndex) : url;
return base::SysUTF8ToNSString(basename);
}
}
return @"";
}
// LINT.IfChange(accessibilityLinkedUIElements)
- (NSArray*)accessibilityLinkedUIElements {
if (![self instanceActive]) {
return nil;
}
ui::AXPlatformNodeDelegate* delegate = [self nodeDelegate];
if (!delegate) {
return nil;
}
NSMutableArray* elements = [[NSMutableArray alloc] init];
[elements
addObjectsFromArray:[self uiElementsForAttribute:
ax::mojom::IntListAttribute::kControlsIds]];
[elements
addObjectsFromArray:[self uiElementsForAttribute:
ax::mojom::IntListAttribute::kFlowtoIds]];
int targetId;
if (delegate->GetIntAttribute(ax::mojom::IntAttribute::kInPageLinkTargetId,
&targetId)) {
ui::AXPlatformNode* target = delegate->GetFromNodeID(targetId);
if (target) {
[elements addObject:target->GetNativeViewAccessible().Get()];
}
}
[elements
addObjectsFromArray:[self
uiElementsForAttribute:
ax::mojom::IntListAttribute::kRadioGroupIds]];
return elements;
}
// LINT.ThenChange(ui/accessibility/platform/browser_accessibility_cocoa.mm:accessibilityLinkedUIElements)
- (NSString*)accessibilityTitle {
if (![self instanceActive])
return nil;
if (ui::IsNameExposedInAXValueForRole(_node->GetRole()))
return @"";
if ([self isNameFromLabel])
return @"";
// If we're exposing the title in TitleUIElement, don't also redundantly
// expose it in AXDescription.
if ([self titleUIElement])
return @"";
ax::mojom::NameFrom nameFrom = _node->GetNameFrom();
// The accessible name, which is exposed via accessibilityTitle, should not
// contain any placeholder text because an HTML or an ARIA placeholder refers
// to a sample value that is usually found in a text field and is used to aid
// the user in data entry. It is similar to a replacement for the value
// attribute, not the title.
if (nameFrom == ax::mojom::NameFrom::kPlaceholder)
return @"";
// Cell titles are empty if they came from content.
if (nameFrom == ax::mojom::NameFrom::kContents) {
NSString* role = [self accessibilityRole];
if ([role isEqualToString:NSAccessibilityCellRole])
return @"";
}
return [self getName];
}
- (id)accessibilityValue {
return [self AXValue];
}
- (void)setAccessibilityValue:(id)value {
if (!_node) {
return;
}
ui::AXActionData data;
data.action = _node->GetRole() == ax::mojom::Role::kTab
? ax::mojom::Action::kSetSelection
: ax::mojom::Action::kSetValue;
if ([value isKindOfClass:[NSString class]]) {
data.value = base::SysNSStringToUTF8(value);
} else if ([value isKindOfClass:[NSValue class]]) {
// TODO(crbug.com/41115917): Is this case actually needed? The
// NSObject accessibility implementation supported this, but can it actually
// occur?
NSRange range = [value rangeValue];
data.anchor_offset = range.location;
data.focus_offset = NSMaxRange(range);
}
_node->GetDelegate()->AccessibilityPerformAction(data);
}
- (BOOL)isAccessibilitySelectorAllowed:(SEL)selector {
TRACE_EVENT1(
"accessibility", "AXPlatformNodeCocoa::isAccessibilitySelectorAllowed",
"selector=", base::SysNSStringToUTF8(NSStringFromSelector(selector)));
if (!_node) {
return NO;
}
if (selector == @selector(setAccessibilityFocused:)) {
return _node->IsFocusable();
}
if (selector == @selector(setAccessibilityValue:)) {
switch (_node->GetRole()) {
case ax::mojom::Role::kSlider:
// When VoiceOver performs an increment/decrement action, it immediately
// calls upon success of the action the selector setAccessibilityValue
// on the slider that was just updated. The value passed to this
// function is always equals to 5% of the slider's value range, so
// actually setting that value to our slider would:
// 1. render the increment/decrement action performed a moment before
// useless as it would override the modified value;
// 2. make the slider value stuck in place, at 5% of its range.
//
// I haven't found much on the topic online, so the following is at best
// a conjecture: I believe that VoiceOver "suggests" us to
// increment/decrement the value by 5%. There might be a setting I'm not
// aware of that allows the VO users to modify this value by a different
// one, which would allow them to always increment/decrement sliders by
// the same amount on all apps.
//
// However, in Chromium, we handle the increment and decrement actions
// on the blink side and the step value is computed over there. That
// way, the experience for changing the value of a slider by increments
// is the same for all different inputs: whether it's the keyboard arrow
// keys, an AT, etc.
//
// TL;DR: setAccessibilityValue, when called on sliders, is breaking our
// increment and decrement AX actions, so don't allow it.
return NO;
case ax::mojom::Role::kTab:
// Tabs use the radio button role on Mac, so they are selected by
// calling setSelected on an individual tab, rather than by setting the
// selected element on the tabstrip as a whole.
return !_node->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected);
default:
break;
}
}
// Don't allow calling AX setters on disabled elements.
// TODO(crbug.com/41301942): Once the underlying bug in
// views::Textfield::SetSelectionRange() described in that bug is fixed,
// remove the check here when the selector is setAccessibilitySelectedText*;
// right now, this check serves to prevent accessibility clients from trying
// to set the selection range, which won't work because of 692362.
if (_node->GetDelegate() && _node->GetDelegate()->IsReadOnlyOrDisabled() &&
IsAXSetter(selector)) {
return NO;
}
NSString* selectorString = NSStringFromSelector(selector);
if ([[self class] isMethodImplementedForNewAccessibilityAPI:selectorString] &&
![self supportsNewAccessibilityAPIMethod:selectorString]) {
return NO;
}
// TODO(crbug.com/41115917): What about role-specific selectors?
return [super isAccessibilitySelectorAllowed:selector];
}
// NSAccessibility: Determining Relationships.
- (NSArray*)AXChildren {
return [self accessibilityChildren];
}
- (id)accessibilityParent {
return [self AXParent];
}
// NSAccessibility: Assigning Roles.
- (BOOL)isAccessibilityRequired {
TRACE_EVENT1("accessibility", "accessibilityRequired",
"role=", ui::ToString([self internalRole]));
if (![self instanceActive]) {
return NO;
}
return _node->HasState(ax::mojom::State::kRequired);
}
- (NSAccessibilityRole)accessibilityRole {
return [self AXRole];
}
- (NSAccessibilitySubrole)accessibilitySubrole {
return [self AXSubrole];
}
- (NSString*)accessibilityRoleDescription {
TRACE_EVENT1("accessibility", "accessibilityRoleDescription",
"role=", ui::ToString([self internalRole]));
if (![self instanceActive]) {
return nil;
}
// Image annotations.
if (_node->GetData().GetImageAnnotationStatus() ==
ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation ||
_node->GetData().GetImageAnnotationStatus() ==
ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation) {
return base::SysUTF16ToNSString(
_node->GetDelegate()->GetLocalizedRoleDescriptionForUnlabeledImage());
}
// ARIA role description.
std::string roleDescription;
if (_node->GetStringAttribute(ax::mojom::StringAttribute::kRoleDescription,
&roleDescription)) {
return [base::SysUTF8ToNSString(_node->GetStringAttribute(
ax::mojom::StringAttribute::kRoleDescription)) lowercaseString];
}
NSString* role = [self accessibilityRole];
switch ([self internalRole]) {
case ax::mojom::Role::kColorWell: // Use platform's "color well"
case ax::mojom::Role::kImage: // Default: IDS_AX_ROLE_GRAPHIC
case ax::mojom::Role::kInputTime: // Use platform's "time field"
case ax::mojom::Role::kMeter: // Use platform's "level indicator"
case ax::mojom::Role::kPopUpButton: // Use platform's "popup button"
case ax::mojom::Role::kTabList: // Use platform's "tab group"
case ax::mojom::Role::kTree: // Use platform's "outline"
case ax::mojom::Role::kTreeItem: // Use platform's "outline row"
break;
case ax::mojom::Role::kHeader: // Default: IDS_AX_ROLE_HEADER
return l10n_util::GetNSString(IDS_AX_ROLE_BANNER);
case ax::mojom::Role::kRootWebArea: {
if ([role isEqualToString:NSAccessibilityWebAreaRole]) {
return l10n_util::GetNSString(IDS_AX_ROLE_WEB_AREA);
}
// Preserve platform default of "group" in the case of the child
// of a presentational <iframe> which has the internal role of
// kRootWebArea.
break;
}
default: {
std::u16string result =
_node->GetDelegate()->GetLocalizedStringForRoleDescription();
if (!result.empty()) {
return base::SysUTF16ToNSString(result);
}
}
}
return NSAccessibilityRoleDescription(role, [self accessibilitySubrole]);
}
// NSAccessibility: Configuring Table and Outline Views.
- (NSArray*)accessibilitySelectedRows {
if (![self instanceActive]) {
return nil;
}
NSArray* rows = [self accessibilityRows];
// accessibilityRows returns an empty array unless instanceActive does,
// not exist, so we do not need to check if rows is nil at this time.
NSMutableArray* selectedRows = [NSMutableArray array];
for (id row in rows) {
if ([[row accessibilitySelected] boolValue]) {
[selectedRows addObject:row];
}
}
return selectedRows;
}
- (NSArray*)accessibilityColumnHeaderUIElements {
if (![self instanceActive]) {
return nil;
}
ui::AXPlatformNodeDelegate* delegate = _node->GetDelegate();
NSMutableArray* ret = [NSMutableArray array];
// If this is a table, return all column headers.
ax::mojom::Role role = _node->GetRole();
if (ui::IsTableLike(role)) {
for (ui::AXNodeID id : delegate->GetColHeaderNodeIds()) {
AXPlatformNodeCocoa* colheader = [self fromNodeID:id];
if (colheader) {
[ret addObject:colheader];
}
}
return [ret count] ? ret : nil;
}
// Otherwise if this is a cell or a header cell, return the column headers for
// it.
if (!ui::IsCellOrTableHeader(role)) {
return nil;
}
ui::AXPlatformNodeBase* table = _node->GetTable();
if (!table) {
return nil;
}
std::optional<int> column = delegate->GetTableCellColIndex();
if (!column) {
return nil;
}
ui::AXPlatformNodeDelegate* tableDelegate = table->GetDelegate();
for (ui::AXNodeID id : tableDelegate->GetColHeaderNodeIds(*column)) {
AXPlatformNodeCocoa* colheader = [self fromNodeID:id];
if (colheader) {
[ret addObject:colheader];
}
}
return [ret count] ? ret : nil;
}
- (id)accessibilityHeader {
// Keep logic consistent with `-[BrowserAccessibilityCocoa header]`
if (![self instanceActive]) {
return nil;
}
if (ui::IsTableLike(_node->GetRole())) {
ui::AXPlatformNodeDelegate* delegate = _node->GetDelegate();
// The table header container is a special node in the accessibility tree
// only used on macOS. It has all of the table headers as its children, even
// though those cells are also children of rows in the table. Internally
// this is implemented using `AXTableInfo` and `indirect_child_ids` with the
// result retrievable via `AXNode::GetExtraMacNodes()`.
const std::vector<raw_ptr<ui::AXNode, VectorExperimental>>* nodes =
delegate->node()->GetExtraMacNodes();
if (nodes && !nodes->empty()) {
ui::AXNode* lastChild = nodes->back();
if (lastChild->GetRole() == ax::mojom::Role::kTableHeaderContainer) {
// TODO(crbug.com/363275809): This works for `BrowserAccessibilityCocoa`
// nodes but will otherwise fail with `-fromNodeID` returning nil. This
// is due to the fact that `BrowserAccessibilityMac` ensures that the
// internal "extra Mac nodes" are included in the platform accessibility
// tree. See `BrowserAccessibilityMac::PlatformChildCount` and
// `BrowserAccessibilityMac::PlatformGetChild` as examples.
return [self fromNodeID:lastChild->id()];
}
}
return nil;
}
int headerElementId = -1;
if ([self internalRole] == ax::mojom::Role::kColumn) {
_node->GetIntAttribute(ax::mojom::IntAttribute::kTableColumnHeaderId,
&headerElementId);
} else if ([self internalRole] == ax::mojom::Role::kRow) {
_node->GetIntAttribute(ax::mojom::IntAttribute::kTableRowHeaderId,
&headerElementId);
}
return headerElementId > 0 ? [self fromNodeID:headerElementId] : nil;
}
- (NSInteger)accessibilityColumnCount {
if (![self instanceActive]) {
return NSNotFound;
}
if (!ui::IsTableLike(_node->GetRole())) {
return NSNotFound;
}
ui::AXPlatformNodeDelegate* delegate = _node->GetDelegate();
std::optional<int> count = delegate->GetTableColCount();
if (count.has_value()) {
return *count;
}
return -1;
}
- (NSInteger)accessibilityRowCount {
if (![self instanceActive]) {
return NSNotFound;
}
if (!ui::IsTableLike(_node->GetRole())) {
return NSNotFound;
}
ui::AXPlatformNodeDelegate* delegate = _node->GetDelegate();
std::optional<int> count = delegate->GetTableRowCount();
if (count.has_value()) {
return *count;
}
return -1;
}
// LINT.IfChange(accessibilityRowHeaderUIElements)
- (NSArray*)accessibilityRowHeaderUIElements {
if (![self instanceActive]) {
return nil;
}
ax::mojom::Role role = [self internalRole];
bool isCellOrTableHeader = ui::IsCellOrTableHeader(role);
bool isTableLike = ui::IsTableLike(role);
if (!isTableLike && !isCellOrTableHeader) {
return nil;
}
ui::AXPlatformNodeDelegate* delegate = [self nodeDelegate];
gfx::NativeViewAccessible table = delegate->GetTableAncestor();
if (!table) {
return nil;
}
ui::AXPlatformNode* tableNode =
ui::AXPlatformNode::FromNativeViewAccessible(table);
if (!tableNode) {
return nil;
}
ui::AXPlatformNodeDelegate* tableDelegate = tableNode->GetDelegate();
// A table with no row headers.
if (isTableLike && !tableDelegate->GetTableRowCount().has_value()) {
return nil;
}
NSMutableArray* rowHeaders = [[NSMutableArray alloc] init];
if (isTableLike) {
// Return the table's row headers.
std::set<int32_t> headerIds;
int numberOfRows = tableDelegate->GetTableRowCount().value();
// Rows can have more than one row header cell. Also, we apparently need
// to guard against duplicate row header ids. Storing in a set dedups.
for (int i = 0; i < numberOfRows; i++) {
std::vector<int32_t> rowHeaderIds = tableDelegate->GetRowHeaderNodeIds(i);
for (int32_t rowHeaderId : rowHeaderIds) {
headerIds.insert(rowHeaderId);
}
}
for (int32_t headerId : headerIds) {
ui::AXPlatformNode* cellNode = tableDelegate->GetFromNodeID(headerId);
if (cellNode) {
[rowHeaders addObject:cellNode->GetNativeViewAccessible().Get()];
}
}
} else {
// Otherwise this is a cell, return the row headers for this cell.
for (int32_t nodeId : delegate->GetRowHeaderNodeIds()) {
ui::AXPlatformNode* cellNode = delegate->GetFromNodeID(nodeId);
if (cellNode) {
[rowHeaders addObject:cellNode->GetNativeViewAccessible().Get()];
}
}
}
return [rowHeaders count] ? rowHeaders : nil;
}
// LINT.ThenChange(ui/accessibility/platform/browser_accessibility_cocoa.mm:accessibilityRowHeaderUIElements)
// LINT.IfChange(accessibilityColumns)
- (NSArray*)accessibilityColumns {
if (![self instanceActive]) {
return nil;
}
NSMutableArray* columns = [[NSMutableArray alloc] init];
for (AXPlatformNodeCocoa* child in [self accessibilityChildren]) {
if ([[child accessibilityRole] isEqualToString:NSAccessibilityColumnRole]) {
[columns addObject:child];
}
}
return columns;
}
// LINT.ThenChange(ui/accessibility/platform/browser_accessibility_cocoa.mm:accessibilityColumns)
- (NSArray*)accessibilityRows {
if (![self instanceActive]) {
return nil;
}
ui::AXPlatformNodeDelegate* delegate = [self nodeDelegate];
if (!delegate) {
return nil;
}
NSMutableArray* rows = [[NSMutableArray alloc] init];
ax::mojom::Role role = [self internalRole];
std::vector<int32_t> nodeIds;
if (role == ax::mojom::Role::kTree) {
[self getTreeItemDescendantNodeIds:&nodeIds];
} else if (ui::IsTableLike(role)) {
nodeIds = delegate->GetRowNodeIds();
} else if (role == ax::mojom::Role::kColumn) {
// Rows attribute for a column is the list of all the elements in that
// column at each row.
nodeIds = delegate->GetIntListAttribute(
ax::mojom::IntListAttribute::kIndirectChildIds);
}
for (int32_t nodeId : nodeIds) {
ui::AXPlatformNode* rowNode = delegate->GetFromNodeID(nodeId);
if (rowNode) {
[rows addObject:rowNode->GetNativeViewAccessible().Get()];
}
}
return rows;
}
- (NSAccessibilitySortDirection)accessibilitySortDirection {
// Keep logic consistent with `-[BrowserAccessibilityCocoa sortDirection]`
if (![self instanceActive]) {
return NSAccessibilitySortDirectionUnknown;
}
// If this object should not support `accessibilitySortDirection`, treat
// the sort direction as unknown regardless of what's in the `AXNodeData`.
if ([self internalRole] != ax::mojom::Role::kRowHeader &&
[self internalRole] != ax::mojom::Role::kColumnHeader) {
return NSAccessibilitySortDirectionUnknown;
}
// The Core-AAM states that `aria-sort=none` is "not mapped".
int sortDirection;
if (!_node->GetIntAttribute(ax::mojom::IntAttribute::kSortDirection,
&sortDirection) ||
static_cast<ax::mojom::SortDirection>(sortDirection) ==
ax::mojom::SortDirection::kUnsorted) {
return NSAccessibilitySortDirectionUnknown;
}
switch (static_cast<ax::mojom::SortDirection>(sortDirection)) {
case ax::mojom::SortDirection::kAscending:
return NSAccessibilitySortDirectionAscending;
case ax::mojom::SortDirection::kDescending:
return NSAccessibilitySortDirectionDescending;
case ax::mojom::SortDirection::kOther:
return NSAccessibilitySortDirectionUnknown;
default:
NOTREACHED();
}
}
- (id)accessibilityDisclosedByRow {
if (![self instanceActive]) {
return nil;
}
// The row that contains this row.
// It should be the same as the first parent that is a treeitem.
return nil;
}
- (id)accessibilityDisclosedRows {
if (![self instanceActive]) {
return nil;
}
// The rows that are considered inside this row.
return nil;
}
- (NSInteger)accessibilityDisclosureLevel {
if (![self instanceActive]) {
return 0;
}
ax::mojom::Role role = [self internalRole];
if (role == ax::mojom::Role::kRow || role == ax::mojom::Role::kTreeItem ||
role == ax::mojom::Role::kHeading) {
int level =
_node->GetIntAttribute(ax::mojom::IntAttribute::kHierarchicalLevel);
// Mac disclosureLevel is 0-based, but web levels are 1-based.
if (level > 0) {
level--;
}
return level;
}
return 0;
}
- (BOOL)isAccessibilityDisclosed {
if (![self instanceActive]) {
return NO;
}
if ([self internalRole] == ax::mojom::Role::kTreeItem) {
return _node->HasState(ax::mojom::State::kExpanded);
}
return NO;
}
// NSAccessibility: Setting the Focus.
- (void)setAccessibilityFocused:(BOOL)isFocused {
if (!_node)
return;
ui::AXActionData data;
data.action =
isFocused ? ax::mojom::Action::kFocus : ax::mojom::Action::kBlur;
_node->GetDelegate()->AccessibilityPerformAction(data);
}
- (NSNumber*)treeItemRowIndex {
// TODO(crbug.com/363275809): `-[BrowserAccessibilityCocoa treeItemRowIndex]`
// and related logic such as `-[BrowswerAccessibilityCocoa findRowIndex]`
// should be moved here unless doing so has some impact on view tree items.
return nil;
}
- (NSInteger)accessibilityIndex {
// Keep logic consistent with `-[BrowserAccessibilityCocoa index]`
if (![self instanceActive]) {
return NSNotFound;
}
if ([self internalRole] == ax::mojom::Role::kTreeItem) {
return [[self treeItemRowIndex] integerValue];
} else if ([self internalRole] == ax::mojom::Role::kColumn) {
DCHECK(_node);
std::optional<int> col_index =
_node->GetDelegate()->node()->GetTableColColIndex();
if (col_index.has_value()) {
return *col_index;
}
} else if ([self internalRole] == ax::mojom::Role::kRow) {
DCHECK(_node);
std::optional<int> row_index =
_node->GetDelegate()->node()->GetTableRowRowIndex();
if (row_index.has_value()) {
return *row_index;
}
}
return NSNotFound;
}
// NSAccessibility: Configuring Text Elements.
// These are all "required" methods, although in practice the ones that are left
// NOTIMPLEMENTED() seem to not be called anywhere (and were NOTIMPLEMENTED in
// the old API as well).
// LINT.IfChange
- (NSInteger)accessibilityInsertionPointLineNumber {
if (![self instanceActive]) {
return NSNotFound;
}
// TODO(crbug.com/363275809): According to the comment in the old API code,
// "multiline is not supported on views." If that is no longer the case, we
// need an implementation here. Also the old API code in `AXPlatformNodeCocoa`
// doesn't do any of the work done in by `BrowserAccessibilityCocoa`.
return 0;
}
// LINT.ThenChange(AXInsertionPointLineNumber)
// LINT.IfChange
- (NSInteger)accessibilityNumberOfCharacters {
if (![self instanceActive]) {
return 0;
}
return [[self getAXValueAsString] length];
}
// LINT.ThenChange(AXNumberOfCharacters)
- (NSString*)accessibilityPlaceholderValue {
if (![self instanceActive])
return nil;
if (_node->GetNameFrom() == ax::mojom::NameFrom::kPlaceholder)
return [self getName];
return [self getStringAttribute:ax::mojom::StringAttribute::kPlaceholder];
}
// LINT.IfChange
- (NSString*)accessibilitySelectedText {
if (![self instanceActive]) {
return nil;
}
NSRange selectedTextRange = [self accessibilitySelectedTextRange];
return [[self getAXValueAsString] substringWithRange:selectedTextRange];
}
// LINT.ThenChange(AXSelectedText)
- (void)setAccessibilitySelectedText:(NSString*)text {
if (!_node) {
return;
}
ui::AXActionData data;
data.action = ax::mojom::Action::kReplaceSelectedText;
data.value = base::SysNSStringToUTF8(text);
_node->GetDelegate()->AccessibilityPerformAction(data);
}
// LINT.IfChange
- (NSRange)accessibilitySelectedTextRange {
if (![self instanceActive]) {
return NSMakeRange(0, 0);
}
int start = 0, end = 0;
if (_node->IsAtomicTextField() &&
_node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart, &start) &&
_node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd, &end)) {
// NSRange cannot represent the direction the text was selected in.
return NSMakeRange(static_cast<NSUInteger>(std::min(start, end)),
static_cast<NSUInteger>(abs(end - start)));
}
return NSMakeRange(0, 0);
}
// LINT.ThenChange(AXSelectedTextRange)
- (void)setAccessibilitySelectedTextRange:(NSRange)range {
if (!_node) {
return;
}
ui::AXActionData data;
data.action = ax::mojom::Action::kSetSelection;
data.anchor_offset = range.location;
data.anchor_node_id = _node->GetData().id;
data.focus_offset = NSMaxRange(range);
data.focus_node_id = _node->GetData().id;
_node->GetDelegate()->AccessibilityPerformAction(data);
}
- (NSArray*)accessibilitySelectedTextRanges {
if (!_node)
return nil;
return @[ [self AXSelectedTextRange] ];
}
// LINT.IfChange
- (NSRange)accessibilityVisibleCharacterRange {
if (![self instanceActive]) {
return NSMakeRange(0, 0);
}
return NSMakeRange(0, [[self getAXValueAsString] length]);
}
// LINT.ThenChange(AXVisibleCharacterRange)
- (NSString*)accessibilityStringForRange:(NSRange)range {
if (![self instanceActive]) {
return nil;
}
return [[self getAXValueAsString] substringWithRange:range];
}
- (NSInteger)accessibilityLineForIndex:(NSInteger)index {
// TODO: multiline is not supported on views.
return 0;
}
- (NSAttributedString*)accessibilityAttributedStringForRange:(NSRange)range {
if (!_node)
return nil;
return [self AXAttributedStringForRange:[NSValue valueWithRange:range]];
}
- (id)AXLineForIndex:(id)parameter {
NSNumber* lineNumber = base::apple::ObjCCast<NSNumber>(parameter);
if (!lineNumber) {
return nil;
}
return @([self accessibilityLineForIndex:[lineNumber intValue]]);
}
- (NSRange)accessibilityRangeForIndex:(NSInteger)index {
NOTIMPLEMENTED();
return NSMakeRange(0, 0);
}
- (NSRange)accessibilityStyleRangeForIndex:(NSInteger)index {
if (![self instanceActive]) {
return NSMakeRange(0, 0);
}
// TODO(crbug.com/41456329): Implement this for real.
return NSMakeRange(0, [self accessibilityNumberOfCharacters]);
}
- (NSRange)accessibilityRangeForLine:(NSInteger)line {
if (![self instanceActive]) {
return NSMakeRange(0, 0);
}
return NSMakeRange(0, [[self getAXValueAsString] length]);
}
- (NSRange)accessibilityRangeForPosition:(NSPoint)point {
// TODO(tapted): Hit-test [parameter pointValue] and return an NSRange.
NOTIMPLEMENTED();
return NSMakeRange(0, 0);
}
// NSAccessibility: setting content and values.
- (NSNumber*)accessibilitySelected {
if (![self instanceActive])
return nil;
return @(_node->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected));
}
- (NSURL*)accessibilityURL {
TRACE_EVENT1("accessibility", "accessibilityURL",
"role=", ui::ToString([self internalRole]));
if (![self instanceActive])
return nil;
std::string url;
if ([[self accessibilityRole] isEqualToString:NSAccessibilityWebAreaRole])
url = _node->GetDelegate()->GetTreeData().url;
else
url = _node->GetStringAttribute(ax::mojom::StringAttribute::kUrl);
if (url.empty())
return nil;
return [NSURL URLWithString:(base::SysUTF8ToNSString(url))];
}
// LINT.IfChange(accessibilityTabs)
- (id)accessibilityTabs {
if (![self instanceActive]) {
return nil;
}
NSMutableArray* tabSubtree = [[NSMutableArray alloc] init];
if ([self internalRole] == ax::mojom::Role::kTab) {
[tabSubtree addObject:self];
}
for (AXPlatformNodeCocoa* child in [self accessibilityChildren]) {
NSArray* tabChildren = [child accessibilityTabs];
if ([tabChildren count] > 0) {
[tabSubtree addObjectsFromArray:tabChildren];
}
}
return tabSubtree;
}
// LINT.ThenChange(ui/accessibility/platform/browser_accessibility_cocoa.mm:accessibilityTabs)
- (id)accessibilitySplitters {
// Chromium windows do not have NSSplitViews or anything similar.
return nil;
}
- (id)accessibilityToolbarButton {
// Chromium windows do not have a toolbar button.
return nil;
}
- (id)accessibilityScrollBar:(ax::mojom::State)state {
if (![self instanceActive]) {
return nil;
}
// TODO(crbug.com/363275809): For this to work for `ScrollView`, `ScrollView`
// should add `kControlsIds` on its horizontal and vertical scrollbars.
std::vector<ui::AXPlatformNode*> targets =
_node->GetDelegate()->GetSourceNodesForReverseRelations(
ax::mojom::IntListAttribute::kControlsIds);
for (auto target : targets) {
if (auto* delegate = target->GetDelegate()) {
if (delegate->GetRole() == ax::mojom::Role::kScrollBar &&
delegate->HasState(state)) {
return target->GetNativeViewAccessible().Get();
}
}
}
return nil;
}
- (id)accessibilityHorizontalScrollBar {
return [self accessibilityScrollBar:ax::mojom::State::kHorizontal];
}
- (id)accessibilityVerticalScrollBar {
return [self accessibilityScrollBar:ax::mojom::State::kVertical];
}
// NSAccessibility: configuring linkage elements.
- (id)accessibilityTitleUIElement {
if (![self instanceActive])
return nil;
return [self titleUIElement];
}
// LINT.IfChange(accessibilityCellForColumn)
- (id)accessibilityCellForColumn:(NSInteger)column row:(NSInteger)row {
if (![self instanceActive] || ![self nodeDelegate]) {
return nil;
}
if (!ui::IsTableLike([self internalRole])) {
return nil;
}
std::optional<int32_t> cellId = [self nodeDelegate]->GetCellId(row, column);
if (!cellId) {
return nil;
}
ui::AXPlatformNode* cell = [self nodeDelegate]->GetFromNodeID(*cellId);
if (!cell) {
return nil;
}
return cell->GetNativeViewAccessible().Get();
}
// LINT.ThenChange(ui/accessibility/platform/browser_accessibility_cocoa.mm:accessibilityCellForColumn)
- (NSRange)accessibilityColumnIndexRange {
if (![self instanceActive] || ![self nodeDelegate]) {
return NSMakeRange(0, 0);
}
std::optional<int> column = [self nodeDelegate]->GetTableCellColIndex();
std::optional<int> columnSpan = [self nodeDelegate]->GetTableCellColSpan();
if (column && columnSpan) {
return NSMakeRange(*column, *columnSpan);
}
return NSMakeRange(0, 0);
}
- (NSRange)accessibilityRowIndexRange {
if (![self instanceActive] || ![self nodeDelegate]) {
return NSMakeRange(0, 0);
}
std::optional<int> row = [self nodeDelegate]->GetTableCellRowIndex();
std::optional<int> rowSpan = [self nodeDelegate]->GetTableCellRowSpan();
if (row && rowSpan) {
return NSMakeRange(*row, *rowSpan);
}
return NSMakeRange(0, 0);
}
// LINT.IfChange(accessibilityVisibleColumns)
- (NSArray*)accessibilityVisibleColumns {
if (![self instanceActive]) {
return nil;
}
NSMutableArray* columns = [[NSMutableArray alloc] init];
for (AXPlatformNodeCocoa* child in [self accessibilityChildren]) {
if ([[child accessibilityRole] isEqualToString:NSAccessibilityColumnRole]) {
[columns addObject:child];
}
}
return columns;
}
// LINT.ThenChange(ui/accessibility/platform/browser_accessibility_cocoa.mm:accessibilityVisibleColumns)
// LINT.IfChange(accessibilityVisibleCells)
- (NSArray*)accessibilityVisibleCells {
if (![self instanceActive]) {
return nil;
}
ui::AXPlatformNodeDelegate* table = [self nodeDelegate];
if (!table) {
return nil;
}
NSMutableArray* cells = [[NSMutableArray alloc] init];
for (int32_t id : table->GetTableUniqueCellIds()) {
ui::AXPlatformNode* cell = table->GetFromNodeID(id);
if (cell) {
[cells addObject:cell->GetNativeViewAccessible().Get()];
}
}
return cells;
}
// LINT.ThenChange(ui/accessibility/platform/browser_accessibility_cocoa.mm:accessibilityVisibleCells)
// LINT.IfChange(accessibilityVisibleRows)
- (NSArray*)accessibilityVisibleRows {
return [self accessibilityRows];
}
// LINT.ThenChange(ui/accessibility/platform/browser_accessibility_cocoa.mm:accessibilityVisibleRows)
//
// End of NSAccessibility protocol.
//
//
// AXCustomContentProvider
// https://developer.apple.com/documentation/accessibility/axcustomcontentprovider/3600104-accessibilitycustomcontent
//
- (NSArray*)accessibilityCustomContent {
if (![self instanceActive]) {
return nil;
}
// Only descriptions originating from ARIA are returned as custom content.
// (Non-ARIA descriptions are returned as AXHelp.)
if (![self descriptionIsFromAriaDescription]) {
return nil;
}
NSString* description =
[self getStringAttribute:ax::mojom::StringAttribute::kDescription];
AXCustomContent* contentItem =
[AXCustomContent customContentWithLabel:@"description" value:description];
// A custom content importance of high causes it to be spoken
// automatically, rather than "More content available".
contentItem.importance = AXCustomContentImportanceHigh;
return @[ contentItem ];
}
// MathML attributes.
// TODO(crbug.com/40673555): The MathML aam considers only in-flow children.
// TODO(crbug.com/40673555): When/if it is needed to expose this for other a11y
// APIs, then some of the logic below should probably be moved to the
// platform-independent classes.
- (id)AXMathFractionNumerator {
if (![self instanceActive] ||
_node->GetRole() != ax::mojom::Role::kMathMLFraction) {
return nil;
}
NSArray* children = [self accessibilityChildren];
if ([children count] >= 1)
return children[0];
return nil;
}
- (id)AXMathFractionDenominator {
if (![self instanceActive] ||
_node->GetRole() != ax::mojom::Role::kMathMLFraction) {
return nil;
}
NSArray* children = [self accessibilityChildren];
if ([children count] >= 2)
return children[1];
return nil;
}
- (id)AXMathRootRadicand {
if (![self instanceActive] ||
!(_node->GetRole() == ax::mojom::Role::kMathMLRoot ||
_node->GetRole() == ax::mojom::Role::kMathMLSquareRoot)) {
return nil;
}
NSArray* children = [self accessibilityChildren];
if (_node->GetRole() == ax::mojom::Role::kMathMLRoot) {
if ([children count] >= 1)
return [NSArray arrayWithObjects:children[0], nil];
return nil;
}
return children;
}
- (id)AXMathRootIndex {
if (![self instanceActive] ||
_node->GetRole() != ax::mojom::Role::kMathMLRoot) {
return nil;
}
NSArray* children = [self accessibilityChildren];
if ([children count] >= 2)
return children[1];
return nil;
}
- (id)AXMathBase {
if (![self instanceActive] ||
!(_node->GetRole() == ax::mojom::Role::kMathMLSub ||
_node->GetRole() == ax::mojom::Role::kMathMLSup ||
_node->GetRole() == ax::mojom::Role::kMathMLSubSup ||
_node->GetRole() == ax::mojom::Role::kMathMLUnder ||
_node->GetRole() == ax::mojom::Role::kMathMLOver ||
_node->GetRole() == ax::mojom::Role::kMathMLUnderOver ||
_node->GetRole() == ax::mojom::Role::kMathMLMultiscripts)) {
return nil;
}
NSArray* children = [self accessibilityChildren];
if ([children count] >= 1)
return children[0];
return nil;
}
- (id)AXMathUnder {
if (![self instanceActive] ||
!(_node->GetRole() == ax::mojom::Role::kMathMLUnder ||
_node->GetRole() == ax::mojom::Role::kMathMLUnderOver)) {
return nil;
}
NSArray* children = [self accessibilityChildren];
if ([children count] >= 2)
return children[1];
return nil;
}
- (id)AXMathOver {
if (![self instanceActive] ||
!(_node->GetRole() == ax::mojom::Role::kMathMLOver ||
_node->GetRole() == ax::mojom::Role::kMathMLUnderOver)) {
return nil;
}
NSArray* children = [self accessibilityChildren];
if (_node->GetRole() == ax::mojom::Role::kMathMLOver &&
[children count] >= 2) {
return children[1];
}
if (_node->GetRole() == ax::mojom::Role::kMathMLUnderOver &&
[children count] >= 3) {
return children[2];
}
return nil;
}
- (id)AXMathSubscript {
if (![self instanceActive] ||
!(_node->GetRole() == ax::mojom::Role::kMathMLSub ||
_node->GetRole() == ax::mojom::Role::kMathMLSubSup)) {
return nil;
}
NSArray* children = [self accessibilityChildren];
if ([children count] >= 2)
return children[1];
return nil;
}
- (id)AXMathSuperscript {
if (![self instanceActive] ||
!(_node->GetRole() == ax::mojom::Role::kMathMLSup ||
_node->GetRole() == ax::mojom::Role::kMathMLSubSup)) {
return nil;
}
NSArray* children = [self accessibilityChildren];
if (_node->GetRole() == ax::mojom::Role::kMathMLSup &&
[children count] >= 2) {
return children[1];
}
if (_node->GetRole() == ax::mojom::Role::kMathMLSubSup &&
[children count] >= 3) {
return children[2];
}
return nil;
}
namespace {
NSDictionary* CreateMathSubSupScriptsPair(AXPlatformNodeCocoa* subscript,
AXPlatformNodeCocoa* superscript) {
NSMutableDictionary* dictionary = [NSMutableDictionary dictionary];
if (subscript) {
dictionary[NSAccessibilityMathSubscriptAttribute] = subscript;
}
if (superscript) {
dictionary[NSAccessibilityMathSuperscriptAttribute] = superscript;
}
return dictionary;
}
} // namespace
- (NSArray*)AXMathPostscripts {
if (![self instanceActive] ||
_node->GetRole() != ax::mojom::Role::kMathMLMultiscripts)
return nil;
NSMutableArray* ret = [NSMutableArray array];
bool foundBaseElement = false;
AXPlatformNodeCocoa* subscript = nullptr;
for (AXPlatformNodeCocoa* child in [self accessibilityChildren]) {
if ([child internalRole] == ax::mojom::Role::kMathMLPrescriptDelimiter)
break;
if (!foundBaseElement) {
foundBaseElement = true;
continue;
}
if (!subscript) {
subscript = child;
continue;
}
AXPlatformNodeCocoa* superscript = child;
[ret addObject:CreateMathSubSupScriptsPair(subscript, superscript)];
subscript = nullptr;
}
return [ret count] ? ret : nil;
}
- (NSArray*)AXMathPrescripts {
if (![self instanceActive] ||
_node->GetRole() != ax::mojom::Role::kMathMLMultiscripts)
return nil;
NSMutableArray* ret = [NSMutableArray array];
bool foundPrescriptDelimiter = false;
AXPlatformNodeCocoa* subscript = nullptr;
for (AXPlatformNodeCocoa* child in [self accessibilityChildren]) {
if (!foundPrescriptDelimiter) {
foundPrescriptDelimiter =
([child internalRole] == ax::mojom::Role::kMathMLPrescriptDelimiter);
continue;
}
if (!subscript) {
subscript = child;
continue;
}
AXPlatformNodeCocoa* superscript = child;
[ret addObject:CreateMathSubSupScriptsPair(subscript, superscript)];
subscript = nullptr;
}
return [ret count] ? ret : nil;
}
@end
|