1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "TextInputHandler.h"
#include <Foundation/Foundation.h>
#include <Foundation/NSObjCRuntime.h>
#include "mozilla/Logging.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/MacStringHelpers.h"
#include "mozilla/MiscEvents.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/StaticPrefs_intl.h"
#include "mozilla/StaticPrefs_widget.h"
#include "mozilla/glean/WidgetCocoaMetrics.h"
#include "mozilla/TextEventDispatcher.h"
#include "mozilla/TextEvents.h"
#include "mozilla/ToString.h"
#include "nsCocoaWindow.h"
#include "nsObjCExceptions.h"
#include "nsBidiUtils.h"
#include "nsToolkit.h"
#include "nsCocoaUtils.h"
#include "WidgetUtils.h"
#include "nsPrintfCString.h"
using namespace mozilla;
using namespace mozilla::widget;
// For collecting other people's log, tell them `MOZ_LOG=IMEHandler:4,sync`
// rather than `MOZ_LOG=IMEHandler:5,sync` since using `5` may create too
// big file.
// Therefore you shouldn't use `LogLevel::Verbose` for logging usual behavior.
mozilla::LazyLogModule gIMELog("IMEHandler");
// For collecting other people's log, tell them `MOZ_LOG=KeyboardHandler:4,sync`
// rather than `MOZ_LOG=KeyboardHandler:5,sync` since using `5` may create too
// big file.
// Therefore you shouldn't use `LogLevel::Verbose` for logging usual behavior.
mozilla::LazyLogModule gKeyLog("KeyboardHandler");
// The behavior of `TextInputHandler` class is important both for logging
// keyboard handler and IME handler. Therefore, the behavior is logged when
// either `IMEHandler` or `KeyboardHandler` is set to `MOZ_LOG`. Therefore,
// you may not need to tell people
// `MOZ_LOG=IMEHandler:4,KeyboardHandler:4,sync`.
#define MOZ_LOG_KEY_OR_IME(aLogLevel, aArgs) \
MOZ_LOG(MOZ_LOG_TEST(gIMELog, aLogLevel) ? gIMELog : gKeyLog, aLogLevel, \
aArgs)
static const char* GetKeyNameForNativeKeyCode(unsigned short aNativeKeyCode) {
switch (aNativeKeyCode) {
case kVK_Escape:
return "Escape";
case kVK_RightCommand:
return "Right-Command";
case kVK_Command:
return "Command";
case kVK_Shift:
return "Shift";
case kVK_CapsLock:
return "CapsLock";
case kVK_Option:
return "Option";
case kVK_Control:
return "Control";
case kVK_RightShift:
return "Right-Shift";
case kVK_RightOption:
return "Right-Option";
case kVK_RightControl:
return "Right-Control";
case kVK_ANSI_KeypadClear:
return "Clear";
case kVK_F1:
return "F1";
case kVK_F2:
return "F2";
case kVK_F3:
return "F3";
case kVK_F4:
return "F4";
case kVK_F5:
return "F5";
case kVK_F6:
return "F6";
case kVK_F7:
return "F7";
case kVK_F8:
return "F8";
case kVK_F9:
return "F9";
case kVK_F10:
return "F10";
case kVK_F11:
return "F11";
case kVK_F12:
return "F12";
case kVK_F13:
return "F13/PrintScreen";
case kVK_F14:
return "F14/ScrollLock";
case kVK_F15:
return "F15/Pause";
case kVK_ANSI_Keypad0:
return "NumPad-0";
case kVK_ANSI_Keypad1:
return "NumPad-1";
case kVK_ANSI_Keypad2:
return "NumPad-2";
case kVK_ANSI_Keypad3:
return "NumPad-3";
case kVK_ANSI_Keypad4:
return "NumPad-4";
case kVK_ANSI_Keypad5:
return "NumPad-5";
case kVK_ANSI_Keypad6:
return "NumPad-6";
case kVK_ANSI_Keypad7:
return "NumPad-7";
case kVK_ANSI_Keypad8:
return "NumPad-8";
case kVK_ANSI_Keypad9:
return "NumPad-9";
case kVK_ANSI_KeypadMultiply:
return "NumPad-*";
case kVK_ANSI_KeypadPlus:
return "NumPad-+";
case kVK_ANSI_KeypadMinus:
return "NumPad--";
case kVK_ANSI_KeypadDecimal:
return "NumPad-.";
case kVK_ANSI_KeypadDivide:
return "NumPad-/";
case kVK_ANSI_KeypadEquals:
return "NumPad-=";
case kVK_ANSI_KeypadEnter:
return "NumPad-Enter";
case kVK_Return:
return "Return";
case kVK_Powerbook_KeypadEnter:
return "NumPad-EnterOnPowerBook";
case kVK_PC_Insert:
return "Insert/Help";
case kVK_PC_Delete:
return "Delete";
case kVK_Tab:
return "Tab";
case kVK_PC_Backspace:
return "Backspace";
case kVK_Home:
return "Home";
case kVK_End:
return "End";
case kVK_PageUp:
return "PageUp";
case kVK_PageDown:
return "PageDown";
case kVK_LeftArrow:
return "LeftArrow";
case kVK_RightArrow:
return "RightArrow";
case kVK_UpArrow:
return "UpArrow";
case kVK_DownArrow:
return "DownArrow";
case kVK_PC_ContextMenu:
return "ContextMenu";
case kVK_Function:
return "Function";
case kVK_VolumeUp:
return "VolumeUp";
case kVK_VolumeDown:
return "VolumeDown";
case kVK_Mute:
return "Mute";
case kVK_ISO_Section:
return "ISO_Section";
case kVK_JIS_Yen:
return "JIS_Yen";
case kVK_JIS_Underscore:
return "JIS_Underscore";
case kVK_JIS_KeypadComma:
return "JIS_KeypadComma";
case kVK_JIS_Eisu:
return "JIS_Eisu";
case kVK_JIS_Kana:
return "JIS_Kana";
case kVK_ANSI_A:
return "A";
case kVK_ANSI_B:
return "B";
case kVK_ANSI_C:
return "C";
case kVK_ANSI_D:
return "D";
case kVK_ANSI_E:
return "E";
case kVK_ANSI_F:
return "F";
case kVK_ANSI_G:
return "G";
case kVK_ANSI_H:
return "H";
case kVK_ANSI_I:
return "I";
case kVK_ANSI_J:
return "J";
case kVK_ANSI_K:
return "K";
case kVK_ANSI_L:
return "L";
case kVK_ANSI_M:
return "M";
case kVK_ANSI_N:
return "N";
case kVK_ANSI_O:
return "O";
case kVK_ANSI_P:
return "P";
case kVK_ANSI_Q:
return "Q";
case kVK_ANSI_R:
return "R";
case kVK_ANSI_S:
return "S";
case kVK_ANSI_T:
return "T";
case kVK_ANSI_U:
return "U";
case kVK_ANSI_V:
return "V";
case kVK_ANSI_W:
return "W";
case kVK_ANSI_X:
return "X";
case kVK_ANSI_Y:
return "Y";
case kVK_ANSI_Z:
return "Z";
case kVK_ANSI_1:
return "1";
case kVK_ANSI_2:
return "2";
case kVK_ANSI_3:
return "3";
case kVK_ANSI_4:
return "4";
case kVK_ANSI_5:
return "5";
case kVK_ANSI_6:
return "6";
case kVK_ANSI_7:
return "7";
case kVK_ANSI_8:
return "8";
case kVK_ANSI_9:
return "9";
case kVK_ANSI_0:
return "0";
case kVK_ANSI_Equal:
return "Equal";
case kVK_ANSI_Minus:
return "Minus";
case kVK_ANSI_RightBracket:
return "RightBracket";
case kVK_ANSI_LeftBracket:
return "LeftBracket";
case kVK_ANSI_Quote:
return "Quote";
case kVK_ANSI_Semicolon:
return "Semicolon";
case kVK_ANSI_Backslash:
return "Backslash";
case kVK_ANSI_Comma:
return "Comma";
case kVK_ANSI_Slash:
return "Slash";
case kVK_ANSI_Period:
return "Period";
case kVK_ANSI_Grave:
return "Grave";
default:
return "undefined";
}
}
static const char* GetCharacters(const nsAString& aString) {
if (aString.IsEmpty()) {
return "";
}
nsAutoString escapedStr;
for (uint32_t i = 0; i < aString.Length(); i++) {
char16_t ch = aString.CharAt(i);
if (ch < 0x20) {
nsPrintfCString utf8str("(U+%04X)", ch);
escapedStr += NS_ConvertUTF8toUTF16(utf8str);
} else if (ch <= 0x7E) {
escapedStr += ch;
} else {
nsPrintfCString utf8str("(U+%04X)", ch);
escapedStr += ch;
escapedStr += NS_ConvertUTF8toUTF16(utf8str);
}
}
// the result will be freed automatically by cocoa.
NSString* result = XPCOMStringToNSString(escapedStr);
return [result UTF8String];
}
static const char* GetCharacters(const NSString* aString) {
nsAutoString str;
CopyNSStringToXPCOMString(aString, str);
return GetCharacters(str);
}
static const char* GetCharacters(const CFStringRef aString) {
const NSString* str = reinterpret_cast<const NSString*>(aString);
return GetCharacters(str);
}
static const char* GetNativeKeyEventType(NSEvent* aNativeEvent) {
switch ([aNativeEvent type]) {
case NSEventTypeKeyDown:
return "NSEventTypeKeyDown";
case NSEventTypeKeyUp:
return "NSEventTypeKeyUp";
case NSEventTypeFlagsChanged:
return "NSEventTypeFlagsChanged";
default:
return "not key event";
}
}
static const char* GetGeckoKeyEventType(const WidgetEvent& aEvent) {
switch (aEvent.mMessage) {
case eKeyDown:
return "eKeyDown";
case eKeyUp:
return "eKeyUp";
case eKeyPress:
return "eKeyPress";
default:
return "not key event";
}
}
static const char* GetWindowLevelName(NSInteger aWindowLevel) {
switch (aWindowLevel) {
case kCGBaseWindowLevelKey:
return "kCGBaseWindowLevelKey (NSNormalWindowLevel)";
case kCGMinimumWindowLevelKey:
return "kCGMinimumWindowLevelKey";
case kCGDesktopWindowLevelKey:
return "kCGDesktopWindowLevelKey";
case kCGBackstopMenuLevelKey:
return "kCGBackstopMenuLevelKey";
case kCGNormalWindowLevelKey:
return "kCGNormalWindowLevelKey";
case kCGFloatingWindowLevelKey:
return "kCGFloatingWindowLevelKey (NSFloatingWindowLevel)";
case kCGTornOffMenuWindowLevelKey:
return "kCGTornOffMenuWindowLevelKey (NSSubmenuWindowLevel, "
"NSTornOffMenuWindowLevel)";
case kCGDockWindowLevelKey:
return "kCGDockWindowLevelKey (NSDockWindowLevel)";
case kCGMainMenuWindowLevelKey:
return "kCGMainMenuWindowLevelKey (NSMainMenuWindowLevel)";
case kCGStatusWindowLevelKey:
return "kCGStatusWindowLevelKey (NSStatusWindowLevel)";
case kCGModalPanelWindowLevelKey:
return "kCGModalPanelWindowLevelKey (NSModalPanelWindowLevel)";
case kCGPopUpMenuWindowLevelKey:
return "kCGPopUpMenuWindowLevelKey (NSPopUpMenuWindowLevel)";
case kCGDraggingWindowLevelKey:
return "kCGDraggingWindowLevelKey";
case kCGScreenSaverWindowLevelKey:
return "kCGScreenSaverWindowLevelKey (NSScreenSaverWindowLevel)";
case kCGMaximumWindowLevelKey:
return "kCGMaximumWindowLevelKey";
case kCGOverlayWindowLevelKey:
return "kCGOverlayWindowLevelKey";
case kCGHelpWindowLevelKey:
return "kCGHelpWindowLevelKey";
case kCGUtilityWindowLevelKey:
return "kCGUtilityWindowLevelKey";
case kCGDesktopIconWindowLevelKey:
return "kCGDesktopIconWindowLevelKey";
case kCGCursorWindowLevelKey:
return "kCGCursorWindowLevelKey";
case kCGNumberOfWindowLevelKeys:
return "kCGNumberOfWindowLevelKeys";
default:
return "unknown window level";
}
}
static bool IsControlChar(uint32_t aCharCode) {
return aCharCode < ' ' || aCharCode == 0x7F;
}
static std::ostream& operator<<(std::ostream& aStream, const NSRange& aRange) {
aStream << "{ location=";
if (aRange.location == NSNotFound) {
aStream << "NSNotFound";
} else {
aStream << aRange.location;
}
aStream << ", length=" << aRange.length << " }";
return aStream;
}
static uint32_t gHandlerInstanceCount = 0;
static void EnsureToLogAllKeyboardLayoutsAndIMEs() {
static bool sDone = false;
if (!sDone) {
sDone = true;
TextInputHandler::DebugPrintAllKeyboardLayouts();
IMEInputHandler::DebugPrintAllIMEModes();
}
}
inline NSRange MakeNSRangeFrom(
const Maybe<OffsetAndData<uint32_t>>& aOffsetAndData) {
if (aOffsetAndData.isNothing()) {
return NSMakeRange(NSNotFound, 0);
}
return NSMakeRange(aOffsetAndData->StartOffset(), aOffsetAndData->Length());
}
#pragma mark -
/******************************************************************************
*
* TISInputSourceWrapper implementation
*
******************************************************************************/
TISInputSourceWrapper* TISInputSourceWrapper::sCurrentInputSource = nullptr;
// static
TISInputSourceWrapper& TISInputSourceWrapper::CurrentInputSource() {
if (!sCurrentInputSource) {
sCurrentInputSource = new TISInputSourceWrapper();
}
if (!sCurrentInputSource->IsInitializedByCurrentInputSource()) {
sCurrentInputSource->InitByCurrentInputSource();
}
return *sCurrentInputSource;
}
// static
void TISInputSourceWrapper::Shutdown() {
if (!sCurrentInputSource) {
return;
}
sCurrentInputSource->Clear();
delete sCurrentInputSource;
sCurrentInputSource = nullptr;
}
bool TISInputSourceWrapper::TranslateToString(UInt32 aKeyCode,
UInt32 aModifiers, UInt32 aKbType,
nsAString& aStr) {
aStr.Truncate();
const UCKeyboardLayout* UCKey = GetUCKeyboardLayout();
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::TranslateToString, aKeyCode=0x%X, "
"aModifiers=0x%X, aKbType=0x%X UCKey=%p\n "
"Shift: %s, Ctrl: %s, Opt: %s, Cmd: %s, CapsLock: %s, NumLock: %s",
this, static_cast<unsigned int>(aKeyCode),
static_cast<unsigned int>(aModifiers),
static_cast<unsigned int>(aKbType), UCKey,
OnOrOff(aModifiers & shiftKey), OnOrOff(aModifiers & controlKey),
OnOrOff(aModifiers & optionKey), OnOrOff(aModifiers & cmdKey),
OnOrOff(aModifiers & alphaLock),
OnOrOff(aModifiers & kEventKeyModifierNumLockMask)));
NS_ENSURE_TRUE(UCKey, false);
UInt32 deadKeyState = 0;
UniCharCount len;
UniChar chars[5];
OSStatus err = ::UCKeyTranslate(
UCKey, aKeyCode, kUCKeyActionDown, aModifiers >> 8, aKbType,
kUCKeyTranslateNoDeadKeysMask, &deadKeyState, 5, &len, chars);
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::TranslateToString, err=0x%X, len=%zu",
this, static_cast<int>(err), len));
NS_ENSURE_TRUE(err == noErr, false);
if (len == 0) {
return true;
}
if (!aStr.SetLength(len, fallible)) {
return false;
}
NS_ASSERTION(sizeof(char16_t) == sizeof(UniChar),
"size of char16_t and size of UniChar are different");
memcpy(aStr.BeginWriting(), chars, len * sizeof(char16_t));
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::TranslateToString, aStr=\"%s\"", this,
NS_ConvertUTF16toUTF8(aStr).get()));
return true;
}
uint32_t TISInputSourceWrapper::TranslateToChar(UInt32 aKeyCode,
UInt32 aModifiers,
UInt32 aKbType) {
nsAutoString str;
if (!TranslateToString(aKeyCode, aModifiers, aKbType, str) ||
str.Length() != 1) {
return 0;
}
return static_cast<uint32_t>(str.CharAt(0));
}
bool TISInputSourceWrapper::IsDeadKey(NSEvent* aNativeKeyEvent) {
if ([[aNativeKeyEvent characters] length]) {
return false;
}
// Assume that if the control key, command key or Fn key is pressed, it's not
// a dead key.
NSUInteger cocoaState = [aNativeKeyEvent modifierFlags];
if (cocoaState & (NSEventModifierFlagControl | NSEventModifierFlagCommand |
NSEventModifierFlagFunction)) {
return false;
}
UInt32 nativeKeyCode = [aNativeKeyEvent keyCode];
switch (nativeKeyCode) {
case kVK_ANSI_A:
case kVK_ANSI_B:
case kVK_ANSI_C:
case kVK_ANSI_D:
case kVK_ANSI_E:
case kVK_ANSI_F:
case kVK_ANSI_G:
case kVK_ANSI_H:
case kVK_ANSI_I:
case kVK_ANSI_J:
case kVK_ANSI_K:
case kVK_ANSI_L:
case kVK_ANSI_M:
case kVK_ANSI_N:
case kVK_ANSI_O:
case kVK_ANSI_P:
case kVK_ANSI_Q:
case kVK_ANSI_R:
case kVK_ANSI_S:
case kVK_ANSI_T:
case kVK_ANSI_U:
case kVK_ANSI_V:
case kVK_ANSI_W:
case kVK_ANSI_X:
case kVK_ANSI_Y:
case kVK_ANSI_Z:
case kVK_ANSI_1:
case kVK_ANSI_2:
case kVK_ANSI_3:
case kVK_ANSI_4:
case kVK_ANSI_5:
case kVK_ANSI_6:
case kVK_ANSI_7:
case kVK_ANSI_8:
case kVK_ANSI_9:
case kVK_ANSI_0:
case kVK_ANSI_Equal:
case kVK_ANSI_Minus:
case kVK_ANSI_RightBracket:
case kVK_ANSI_LeftBracket:
case kVK_ANSI_Quote:
case kVK_ANSI_Semicolon:
case kVK_ANSI_Backslash:
case kVK_ANSI_Comma:
case kVK_ANSI_Slash:
case kVK_ANSI_Period:
case kVK_ANSI_Grave:
case kVK_JIS_Yen:
case kVK_JIS_Underscore:
break;
default:
// Let's assume that dead key can be only a printable key in standard
// position.
return false;
}
// If TranslateToChar() returns non-zero value, that means that
// the key may input a character with different dead key state.
UInt32 kbType = GetKbdType();
UInt32 carbonState = nsCocoaUtils::ConvertToCarbonModifier(cocoaState);
return IsDeadKey(nativeKeyCode, carbonState, kbType);
}
bool TISInputSourceWrapper::IsDeadKey(UInt32 aKeyCode, UInt32 aModifiers,
UInt32 aKbType) {
const UCKeyboardLayout* UCKey = GetUCKeyboardLayout();
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::IsDeadKey, aKeyCode=0x%X, "
"aModifiers=0x%X, aKbType=0x%X UCKey=%p\n "
"Shift: %s, Ctrl: %s, Opt: %s, Cmd: %s, CapsLock: %s, NumLock: %s",
this, static_cast<unsigned int>(aKeyCode),
static_cast<unsigned int>(aModifiers),
static_cast<unsigned int>(aKbType), UCKey,
OnOrOff(aModifiers & shiftKey), OnOrOff(aModifiers & controlKey),
OnOrOff(aModifiers & optionKey), OnOrOff(aModifiers & cmdKey),
OnOrOff(aModifiers & alphaLock),
OnOrOff(aModifiers & kEventKeyModifierNumLockMask)));
if (NS_WARN_IF(!UCKey)) {
return false;
}
UInt32 deadKeyState = 0;
UniCharCount len;
UniChar chars[5];
OSStatus err =
::UCKeyTranslate(UCKey, aKeyCode, kUCKeyActionDown, aModifiers >> 8,
aKbType, 0, &deadKeyState, 5, &len, chars);
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::IsDeadKey, err=0x%X, "
"len=%zu, deadKeyState=%u",
this, static_cast<int>(err), len, deadKeyState));
if (NS_WARN_IF(err != noErr)) {
return false;
}
return deadKeyState != 0;
}
void TISInputSourceWrapper::InitByInputSourceID(const char* aID) {
Clear();
if (!aID) return;
CFStringRef idstr = ::CFStringCreateWithCString(kCFAllocatorDefault, aID,
kCFStringEncodingASCII);
InitByInputSourceID(idstr);
::CFRelease(idstr);
}
void TISInputSourceWrapper::InitByInputSourceID(const nsString& aID) {
Clear();
if (aID.IsEmpty()) return;
CFStringRef idstr = ::CFStringCreateWithCharacters(
kCFAllocatorDefault, reinterpret_cast<const UniChar*>(aID.get()),
aID.Length());
InitByInputSourceID(idstr);
::CFRelease(idstr);
}
void TISInputSourceWrapper::InitByInputSourceID(const CFStringRef aID) {
Clear();
if (!aID) return;
const void* keys[] = {kTISPropertyInputSourceID};
const void* values[] = {aID};
CFDictionaryRef filter =
::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL);
NS_ASSERTION(filter, "failed to create the filter");
mInputSourceList = ::TISCreateInputSourceList(filter, true);
::CFRelease(filter);
if (::CFArrayGetCount(mInputSourceList) > 0) {
mInputSource = static_cast<TISInputSourceRef>(
const_cast<void*>(::CFArrayGetValueAtIndex(mInputSourceList, 0)));
if (IsKeyboardLayout()) {
mKeyboardLayout = mInputSource;
}
}
}
void TISInputSourceWrapper::InitByLayoutID(SInt32 aLayoutID,
bool aOverrideKeyboard) {
// NOTE: Doument new layout IDs in TextInputHandler.h when you add ones.
switch (aLayoutID) {
case 0:
InitByInputSourceID("com.apple.keylayout.US");
break;
case 1:
InitByInputSourceID("com.apple.keylayout.Greek");
break;
case 2:
InitByInputSourceID("com.apple.keylayout.German");
break;
case 3:
InitByInputSourceID("com.apple.keylayout.Swedish-Pro");
break;
case 4:
InitByInputSourceID("com.apple.keylayout.DVORAK-QWERTYCMD");
break;
case 5:
InitByInputSourceID("com.apple.keylayout.Thai");
break;
case 6:
InitByInputSourceID("com.apple.keylayout.Arabic");
break;
case 7:
InitByInputSourceID("com.apple.keylayout.ArabicPC");
break;
case 8:
InitByInputSourceID("com.apple.keylayout.French");
break;
case 9:
InitByInputSourceID("com.apple.keylayout.Hebrew");
break;
case 10:
InitByInputSourceID("com.apple.keylayout.Lithuanian");
break;
case 11:
InitByInputSourceID("com.apple.keylayout.Norwegian");
break;
case 12:
InitByInputSourceID("com.apple.keylayout.Spanish");
break;
case 13:
InitByInputSourceID("com.apple.keylayout.French-PC");
break;
default:
Clear();
break;
}
mOverrideKeyboard = aOverrideKeyboard;
}
void TISInputSourceWrapper::InitByCurrentInputSource() {
Clear();
mInputSource = ::TISCopyCurrentKeyboardInputSource();
mKeyboardLayout = ::TISCopyInputMethodKeyboardLayoutOverride();
if (!mKeyboardLayout) {
mKeyboardLayout = ::TISCopyCurrentKeyboardLayoutInputSource();
}
// If this causes composition, the current keyboard layout may input non-ASCII
// characters such as Japanese Kana characters or Hangul characters.
// However, we need to set ASCII characters to DOM key events for consistency
// with other platforms.
if (IsOpenedIMEMode()) {
TISInputSourceWrapper tis(mKeyboardLayout);
if (!tis.IsASCIICapable()) {
mKeyboardLayout = ::TISCopyCurrentASCIICapableKeyboardLayoutInputSource();
}
}
}
void TISInputSourceWrapper::InitByCurrentKeyboardLayout() {
Clear();
mInputSource = ::TISCopyCurrentKeyboardLayoutInputSource();
mKeyboardLayout = mInputSource;
}
void TISInputSourceWrapper::InitByCurrentASCIICapableInputSource() {
Clear();
mInputSource = ::TISCopyCurrentASCIICapableKeyboardInputSource();
mKeyboardLayout = ::TISCopyInputMethodKeyboardLayoutOverride();
if (mKeyboardLayout) {
TISInputSourceWrapper tis(mKeyboardLayout);
if (!tis.IsASCIICapable()) {
mKeyboardLayout = nullptr;
}
}
if (!mKeyboardLayout) {
mKeyboardLayout = ::TISCopyCurrentASCIICapableKeyboardLayoutInputSource();
}
}
void TISInputSourceWrapper::InitByCurrentASCIICapableKeyboardLayout() {
Clear();
mInputSource = ::TISCopyCurrentASCIICapableKeyboardLayoutInputSource();
mKeyboardLayout = mInputSource;
}
void TISInputSourceWrapper::InitByCurrentInputMethodKeyboardLayoutOverride() {
Clear();
mInputSource = ::TISCopyInputMethodKeyboardLayoutOverride();
mKeyboardLayout = mInputSource;
}
void TISInputSourceWrapper::InitByTISInputSourceRef(
TISInputSourceRef aInputSource) {
Clear();
mInputSource = aInputSource;
if (IsKeyboardLayout()) {
mKeyboardLayout = mInputSource;
}
}
void TISInputSourceWrapper::InitByLanguage(CFStringRef aLanguage) {
Clear();
mInputSource = ::TISCopyInputSourceForLanguage(aLanguage);
if (IsKeyboardLayout()) {
mKeyboardLayout = mInputSource;
}
}
const UCKeyboardLayout* TISInputSourceWrapper::GetUCKeyboardLayout() {
NS_ENSURE_TRUE(mKeyboardLayout, nullptr);
if (mUCKeyboardLayout) {
return mUCKeyboardLayout;
}
CFDataRef uchr = static_cast<CFDataRef>(::TISGetInputSourceProperty(
mKeyboardLayout, kTISPropertyUnicodeKeyLayoutData));
// We should be always able to get the layout here.
NS_ENSURE_TRUE(uchr, nullptr);
mUCKeyboardLayout =
reinterpret_cast<const UCKeyboardLayout*>(CFDataGetBytePtr(uchr));
return mUCKeyboardLayout;
}
bool TISInputSourceWrapper::GetBoolProperty(const CFStringRef aKey) {
CFBooleanRef ret = static_cast<CFBooleanRef>(
::TISGetInputSourceProperty(mInputSource, aKey));
return ::CFBooleanGetValue(ret);
}
bool TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey,
CFStringRef& aStr) {
aStr =
static_cast<CFStringRef>(::TISGetInputSourceProperty(mInputSource, aKey));
return aStr != nullptr;
}
bool TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey,
nsAString& aStr) {
CFStringRef str;
GetStringProperty(aKey, str);
CopyNSStringToXPCOMString((const NSString*)str, aStr);
return !aStr.IsEmpty();
}
bool TISInputSourceWrapper::IsOpenedIMEMode() {
NS_ENSURE_TRUE(mInputSource, false);
if (!IsIMEMode()) return false;
return !IsASCIICapable();
}
bool TISInputSourceWrapper::IsIMEMode() {
NS_ENSURE_TRUE(mInputSource, false);
CFStringRef str;
GetInputSourceType(str);
NS_ENSURE_TRUE(str, false);
return ::CFStringCompare(kTISTypeKeyboardInputMode, str, 0) ==
kCFCompareEqualTo;
}
bool TISInputSourceWrapper::IsKeyboardLayout() {
NS_ENSURE_TRUE(mInputSource, false);
CFStringRef str;
GetInputSourceType(str);
NS_ENSURE_TRUE(str, false);
return ::CFStringCompare(kTISTypeKeyboardLayout, str, 0) == kCFCompareEqualTo;
}
bool TISInputSourceWrapper::GetLanguageList(CFArrayRef& aLanguageList) {
NS_ENSURE_TRUE(mInputSource, false);
aLanguageList = static_cast<CFArrayRef>(::TISGetInputSourceProperty(
mInputSource, kTISPropertyInputSourceLanguages));
return aLanguageList != nullptr;
}
bool TISInputSourceWrapper::GetPrimaryLanguage(CFStringRef& aPrimaryLanguage) {
NS_ENSURE_TRUE(mInputSource, false);
CFArrayRef langList;
NS_ENSURE_TRUE(GetLanguageList(langList), false);
if (::CFArrayGetCount(langList) == 0) return false;
aPrimaryLanguage =
static_cast<CFStringRef>(::CFArrayGetValueAtIndex(langList, 0));
return aPrimaryLanguage != nullptr;
}
bool TISInputSourceWrapper::GetPrimaryLanguage(nsAString& aPrimaryLanguage) {
NS_ENSURE_TRUE(mInputSource, false);
CFStringRef primaryLanguage;
NS_ENSURE_TRUE(GetPrimaryLanguage(primaryLanguage), false);
CopyNSStringToXPCOMString((const NSString*)primaryLanguage, aPrimaryLanguage);
return !aPrimaryLanguage.IsEmpty();
}
bool TISInputSourceWrapper::IsForRTLLanguage() {
if (mIsRTL < 0) {
// Get the input character of the 'A' key of ANSI keyboard layout.
nsAutoString str;
bool ret = TranslateToString(kVK_ANSI_A, 0, eKbdType_ANSI, str);
NS_ENSURE_TRUE(ret, ret);
char16_t ch = str.IsEmpty() ? char16_t(0) : str.CharAt(0);
mIsRTL = UTF16_CODE_UNIT_IS_BIDI(ch);
}
return mIsRTL != 0;
}
bool TISInputSourceWrapper::IsForJapaneseLanguage() {
nsAutoString lang;
GetPrimaryLanguage(lang);
return lang.EqualsLiteral("ja");
}
bool TISInputSourceWrapper::IsInitializedByCurrentInputSource() {
return mInputSource == ::TISCopyCurrentKeyboardInputSource();
}
void TISInputSourceWrapper::Select() {
if (!mInputSource) return;
::TISSelectInputSource(mInputSource);
}
void TISInputSourceWrapper::Clear() {
// Clear() is always called when TISInputSourceWrappper is created.
EnsureToLogAllKeyboardLayoutsAndIMEs();
if (mInputSourceList) {
::CFRelease(mInputSourceList);
}
mInputSourceList = nullptr;
mInputSource = nullptr;
mKeyboardLayout = nullptr;
mIsRTL = -1;
mUCKeyboardLayout = nullptr;
mOverrideKeyboard = false;
}
bool TISInputSourceWrapper::IsPrintableKeyEvent(
NSEvent* aNativeKeyEvent) const {
UInt32 nativeKeyCode = [aNativeKeyEvent keyCode];
bool isPrintableKey = !TextInputHandler::IsSpecialGeckoKey(nativeKeyCode);
if (isPrintableKey && [aNativeKeyEvent type] != NSEventTypeKeyDown &&
[aNativeKeyEvent type] != NSEventTypeKeyUp) {
NS_WARNING("Why would a printable key not be an NSEventTypeKeyDown or "
"NSEventTypeKeyUp event?");
isPrintableKey = false;
}
return isPrintableKey;
}
UInt32 TISInputSourceWrapper::GetKbdType() const {
// If a keyboard layout override is set, we also need to force the keyboard
// type to something ANSI to avoid test failures on machines with JIS
// keyboards (since the pair of keyboard layout and physical keyboard type
// form the actual key layout). This assumes that the test setting the
// override was written assuming an ANSI keyboard.
return mOverrideKeyboard ? eKbdType_ANSI : ::LMGetKbdType();
}
void TISInputSourceWrapper::ComputeInsertStringForCharCode(
NSEvent* aNativeKeyEvent, const WidgetKeyboardEvent& aKeyEvent,
const nsAString* aInsertString, nsAString& aResult) {
if (aInsertString) {
// If the caller expects that the aInsertString will be input, we shouldn't
// change it.
aResult = *aInsertString;
} else if (IsPrintableKeyEvent(aNativeKeyEvent)) {
// If IME is open, [aNativeKeyEvent characters] may be a character
// which will be appended to the composition string. However, especially,
// while IME is disabled, most users and developers expect the key event
// works as IME closed. So, we should compute the aResult with
// the ASCII capable keyboard layout.
// NOTE: Such keyboard layouts typically change the layout to its ASCII
// capable layout when Command key is pressed. And we don't worry
// when Control key is pressed too because it causes inputting
// control characters.
// Additionally, if the key event doesn't input any text, the event may be
// dead key event. In this case, the charCode value should be the dead
// character.
UInt32 nativeKeyCode = [aNativeKeyEvent keyCode];
if ((!aKeyEvent.IsMeta() && !aKeyEvent.IsControl() && IsOpenedIMEMode()) ||
![[aNativeKeyEvent characters] length]) {
UInt32 state = nsCocoaUtils::ConvertToCarbonModifier(
[aNativeKeyEvent modifierFlags]);
uint32_t ch = TranslateToChar(nativeKeyCode, state, GetKbdType());
if (ch) {
aResult = ch;
}
} else {
// If the caller isn't sure what string will be input, let's use
// characters of NSEvent.
CopyNSStringToXPCOMString([aNativeKeyEvent characters], aResult);
}
// If control key is pressed and the eventChars is a non-printable control
// character, we should convert it to ASCII alphabet.
if (aKeyEvent.IsControl() && !aResult.IsEmpty() &&
aResult[0] <= char16_t(26)) {
aResult = (aKeyEvent.IsShift() ^ aKeyEvent.IsCapsLocked())
? static_cast<char16_t>(aResult[0] + ('A' - 1))
: static_cast<char16_t>(aResult[0] + ('a' - 1));
}
// If Meta key is pressed, it may cause to switch the keyboard layout like
// Arabic, Russian, Hebrew, Greek and Dvorak-QWERTY.
else if (aKeyEvent.IsMeta() &&
!(aKeyEvent.IsControl() || aKeyEvent.IsAlt())) {
UInt32 kbType = GetKbdType();
UInt32 numLockState =
aKeyEvent.IsNumLocked() ? kEventKeyModifierNumLockMask : 0;
UInt32 capsLockState = aKeyEvent.IsCapsLocked() ? alphaLock : 0;
UInt32 shiftState = aKeyEvent.IsShift() ? shiftKey : 0;
uint32_t uncmdedChar =
TranslateToChar(nativeKeyCode, numLockState, kbType);
uint32_t cmdedChar =
TranslateToChar(nativeKeyCode, cmdKey | numLockState, kbType);
// If we can make a good guess at the characters that the user would
// expect this key combination to produce (with and without Shift) then
// use those characters. This also corrects for CapsLock.
uint32_t ch = 0;
if (uncmdedChar == cmdedChar) {
// The characters produced with Command seem similar to those without
// Command.
ch = TranslateToChar(nativeKeyCode,
shiftState | capsLockState | numLockState, kbType);
} else {
TISInputSourceWrapper USLayout("com.apple.keylayout.US");
uint32_t uncmdedUSChar =
USLayout.TranslateToChar(nativeKeyCode, numLockState, kbType);
// If it looks like characters from US keyboard layout when Command key
// is pressed, we should compute a character in the layout.
if (uncmdedUSChar == cmdedChar) {
ch = USLayout.TranslateToChar(
nativeKeyCode, shiftState | capsLockState | numLockState, kbType);
}
}
// If there is a more preferred character for the commanded key event,
// we should use it.
if (ch) {
aResult = ch;
}
}
}
// Remove control characters which shouldn't be inputted on editor.
// XXX Currently, we don't find any cases inserting control characters with
// printable character. So, just checking first character is enough.
if (!aResult.IsEmpty() && IsControlChar(aResult[0])) {
aResult.Truncate();
}
}
void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent,
WidgetKeyboardEvent& aKeyEvent,
bool aIsProcessedByIME,
const nsAString* aInsertString) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_ASSERT(!aIsProcessedByIME || aKeyEvent.mMessage != eKeyPress,
"eKeyPress event should not be marked as proccessed by IME");
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::InitKeyEvent, aNativeKeyEvent=%p, "
"aKeyEvent.mMessage=%s, aProcessedByIME=%s, aInsertString=%p, "
"IsOpenedIMEMode()=%s",
this, aNativeKeyEvent, GetGeckoKeyEventType(aKeyEvent),
TrueOrFalse(aIsProcessedByIME), aInsertString,
TrueOrFalse(IsOpenedIMEMode())));
if (NS_WARN_IF(!aNativeKeyEvent)) {
return;
}
nsCocoaUtils::InitInputEvent(aKeyEvent, aNativeKeyEvent);
// This is used only while dispatching the event (which is a synchronous
// call), so there is no need to retain and release this data.
aKeyEvent.mNativeKeyEvent = aNativeKeyEvent;
aKeyEvent.mRefPoint = LayoutDeviceIntPoint(0, 0);
UInt32 kbType = GetKbdType();
UInt32 nativeKeyCode = [aNativeKeyEvent keyCode];
// macOS handles dead key as IME. If the key is first key press of dead
// key, we should use KEY_NAME_INDEX_Dead for first (dead) key event.
// So, if aIsProcessedByIME is true, it may be dead key. Let's check
// if current key event is a dead key's keydown event.
bool isProcessedByIME =
aIsProcessedByIME &&
!TISInputSourceWrapper::CurrentInputSource().IsDeadKey(aNativeKeyEvent);
aKeyEvent.mKeyCode =
isProcessedByIME
? NS_VK_PROCESSKEY
: ComputeGeckoKeyCode(nativeKeyCode, kbType, aKeyEvent.IsMeta());
switch (nativeKeyCode) {
case kVK_Command:
case kVK_Shift:
case kVK_Option:
case kVK_Control:
aKeyEvent.mLocation = eKeyLocationLeft;
break;
case kVK_RightCommand:
case kVK_RightShift:
case kVK_RightOption:
case kVK_RightControl:
aKeyEvent.mLocation = eKeyLocationRight;
break;
case kVK_ANSI_Keypad0:
case kVK_ANSI_Keypad1:
case kVK_ANSI_Keypad2:
case kVK_ANSI_Keypad3:
case kVK_ANSI_Keypad4:
case kVK_ANSI_Keypad5:
case kVK_ANSI_Keypad6:
case kVK_ANSI_Keypad7:
case kVK_ANSI_Keypad8:
case kVK_ANSI_Keypad9:
case kVK_ANSI_KeypadMultiply:
case kVK_ANSI_KeypadPlus:
case kVK_ANSI_KeypadMinus:
case kVK_ANSI_KeypadDecimal:
case kVK_ANSI_KeypadDivide:
case kVK_ANSI_KeypadEquals:
case kVK_ANSI_KeypadEnter:
case kVK_JIS_KeypadComma:
case kVK_Powerbook_KeypadEnter:
aKeyEvent.mLocation = eKeyLocationNumpad;
break;
default:
aKeyEvent.mLocation = eKeyLocationStandard;
break;
}
aKeyEvent.mIsRepeat = ([aNativeKeyEvent type] == NSEventTypeKeyDown)
? [aNativeKeyEvent isARepeat]
: false;
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::InitKeyEvent, "
"shift=%s, ctrl=%s, alt=%s, meta=%s",
this, OnOrOff(aKeyEvent.IsShift()), OnOrOff(aKeyEvent.IsControl()),
OnOrOff(aKeyEvent.IsAlt()), OnOrOff(aKeyEvent.IsMeta())));
if (isProcessedByIME) {
aKeyEvent.mKeyNameIndex = KEY_NAME_INDEX_Process;
} else if (IsPrintableKeyEvent(aNativeKeyEvent)) {
aKeyEvent.mKeyNameIndex = KEY_NAME_INDEX_USE_STRING;
// If insertText calls this method, let's use the string.
if (aInsertString && !aInsertString->IsEmpty() &&
!IsControlChar((*aInsertString)[0])) {
aKeyEvent.mKeyValue = *aInsertString;
}
// If meta key is pressed, the printable key layout may be switched from
// non-ASCII capable layout to ASCII capable, or from Dvorak to QWERTY.
// KeyboardEvent.key value should be the switched layout's character.
else if (aKeyEvent.IsMeta()) {
CopyNSStringToXPCOMString([aNativeKeyEvent characters],
aKeyEvent.mKeyValue);
}
// If control key is pressed, some keys may produce printable character via
// [aNativeKeyEvent characters]. Otherwise, translate input character of
// the key without control key.
else if (aKeyEvent.IsControl()) {
NSUInteger cocoaState =
[aNativeKeyEvent modifierFlags] & ~NSEventModifierFlagControl;
UInt32 carbonState = nsCocoaUtils::ConvertToCarbonModifier(cocoaState);
if (IsDeadKey(nativeKeyCode, carbonState, kbType)) {
aKeyEvent.mKeyNameIndex = KEY_NAME_INDEX_Dead;
} else {
aKeyEvent.mKeyValue =
TranslateToChar(nativeKeyCode, carbonState, kbType);
if (!aKeyEvent.mKeyValue.IsEmpty() &&
IsControlChar(aKeyEvent.mKeyValue[0])) {
// Don't expose control character to the web.
aKeyEvent.mKeyValue.Truncate();
}
}
}
// Otherwise, KeyboardEvent.key expose
// [aNativeKeyEvent characters] value. However, if IME is open and the
// keyboard layout isn't ASCII capable, exposing the non-ASCII character
// doesn't match with other platform's behavior. For the compatibility
// with other platform's Gecko, we need to set a translated character.
else if (IsOpenedIMEMode()) {
UInt32 state = nsCocoaUtils::ConvertToCarbonModifier(
[aNativeKeyEvent modifierFlags]);
aKeyEvent.mKeyValue = TranslateToChar(nativeKeyCode, state, kbType);
} else {
CopyNSStringToXPCOMString([aNativeKeyEvent characters],
aKeyEvent.mKeyValue);
// If the key value is empty, the event may be a dead key event.
// If TranslateToChar() returns non-zero value, that means that
// the key may input a character with different dead key state.
if (aKeyEvent.mKeyValue.IsEmpty()) {
NSUInteger cocoaState = [aNativeKeyEvent modifierFlags];
UInt32 carbonState = nsCocoaUtils::ConvertToCarbonModifier(cocoaState);
if (TranslateToChar(nativeKeyCode, carbonState, kbType)) {
aKeyEvent.mKeyNameIndex = KEY_NAME_INDEX_Dead;
}
}
}
// Last resort. If .key value becomes empty string, we should use
// charactersIgnoringModifiers, if it's available.
if (aKeyEvent.mKeyNameIndex == KEY_NAME_INDEX_USE_STRING &&
(aKeyEvent.mKeyValue.IsEmpty() ||
IsControlChar(aKeyEvent.mKeyValue[0]))) {
CopyNSStringToXPCOMString([aNativeKeyEvent charactersIgnoringModifiers],
aKeyEvent.mKeyValue);
// But don't expose it if it's a control character.
if (!aKeyEvent.mKeyValue.IsEmpty() &&
IsControlChar(aKeyEvent.mKeyValue[0])) {
aKeyEvent.mKeyValue.Truncate();
}
}
} else {
// Compute the key for non-printable keys and some special printable keys.
aKeyEvent.mKeyNameIndex = ComputeGeckoKeyNameIndex(nativeKeyCode);
}
aKeyEvent.mCodeNameIndex = ComputeGeckoCodeNameIndex(nativeKeyCode, kbType);
MOZ_ASSERT(aKeyEvent.mCodeNameIndex != CODE_NAME_INDEX_USE_STRING);
NS_OBJC_END_TRY_IGNORE_BLOCK
}
void TISInputSourceWrapper::WillDispatchKeyboardEvent(
NSEvent* aNativeKeyEvent, const nsAString* aInsertString,
uint32_t aIndexOfKeypress, WidgetKeyboardEvent& aKeyEvent) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
// Nothing to do here if the native key event is neither NSEventTypeKeyDown
// nor NSEventTypeKeyUp because accessing [aNativeKeyEvent characters] causes
// throwing an exception.
if ([aNativeKeyEvent type] != NSEventTypeKeyDown &&
[aNativeKeyEvent type] != NSEventTypeKeyUp) {
return;
}
UInt32 kbType = GetKbdType();
if (MOZ_LOG_TEST(gKeyLog, LogLevel::Info)) {
nsAutoString chars;
CopyNSStringToXPCOMString([aNativeKeyEvent characters], chars);
NS_ConvertUTF16toUTF8 utf8Chars(chars);
char16_t uniChar = static_cast<char16_t>(aKeyEvent.mCharCode);
MOZ_LOG(
gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, "
"aNativeKeyEvent=%p, aInsertString=%p (\"%s\"), "
"aIndexOfKeypress=%u, [aNativeKeyEvent characters]=\"%s\", "
"aKeyEvent={ mMessage=%s, mCharCode=0x%X(%s) }, kbType=0x%X, "
"IsOpenedIMEMode()=%s",
this, aNativeKeyEvent, aInsertString,
aInsertString ? GetCharacters(*aInsertString) : "", aIndexOfKeypress,
GetCharacters([aNativeKeyEvent characters]),
GetGeckoKeyEventType(aKeyEvent), aKeyEvent.mCharCode,
uniChar ? NS_ConvertUTF16toUTF8(&uniChar, 1).get() : "",
static_cast<unsigned int>(kbType), TrueOrFalse(IsOpenedIMEMode())));
}
nsAutoString insertStringForCharCode;
ComputeInsertStringForCharCode(aNativeKeyEvent, aKeyEvent, aInsertString,
insertStringForCharCode);
// The mCharCode was set from mKeyValue. However, for example, when Ctrl key
// is pressed, its value should indicate an ASCII character for backward
// compatibility rather than inputting character without the modifiers.
// Therefore, we need to modify mCharCode value here.
uint32_t charCode = 0;
if (aIndexOfKeypress < insertStringForCharCode.Length()) {
charCode = insertStringForCharCode[aIndexOfKeypress];
}
aKeyEvent.SetCharCode(charCode);
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, "
"aKeyEvent.mKeyCode=0x%X, aKeyEvent.mCharCode=0x%X",
this, aKeyEvent.mKeyCode, aKeyEvent.mCharCode));
// If aInsertString is not nullptr (it means InsertText() is called)
// and it acutally inputs a character, we don't need to append alternative
// charCode values since such keyboard event shouldn't be handled as
// a shortcut key.
if (aInsertString && charCode) {
return;
}
TISInputSourceWrapper USLayout("com.apple.keylayout.US");
bool isRomanKeyboardLayout = IsASCIICapable();
UInt32 key = [aNativeKeyEvent keyCode];
// Caps lock and num lock modifier state:
UInt32 lockState = 0;
if ([aNativeKeyEvent modifierFlags] & NSEventModifierFlagCapsLock) {
lockState |= alphaLock;
}
if ([aNativeKeyEvent modifierFlags] & NSEventModifierFlagNumericPad) {
lockState |= kEventKeyModifierNumLockMask;
}
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, "
"isRomanKeyboardLayout=%s, kbType=0x%X, key=0x%X",
this, TrueOrFalse(isRomanKeyboardLayout),
static_cast<unsigned int>(kbType), static_cast<unsigned int>(key)));
nsString str;
// normal chars
uint32_t unshiftedChar = TranslateToChar(key, lockState, kbType);
UInt32 shiftLockMod = shiftKey | lockState;
uint32_t shiftedChar = TranslateToChar(key, shiftLockMod, kbType);
// characters generated with Cmd key
// XXX we should remove CapsLock state, which changes characters from
// Latin to Cyrillic with Russian layout on 10.4 only when Cmd key
// is pressed.
UInt32 numState = (lockState & ~alphaLock); // only num lock state
uint32_t uncmdedChar = TranslateToChar(key, numState, kbType);
UInt32 shiftNumMod = numState | shiftKey;
uint32_t uncmdedShiftChar = TranslateToChar(key, shiftNumMod, kbType);
uint32_t uncmdedUSChar = USLayout.TranslateToChar(key, numState, kbType);
UInt32 cmdNumMod = cmdKey | numState;
uint32_t cmdedChar = TranslateToChar(key, cmdNumMod, kbType);
UInt32 cmdShiftNumMod = shiftKey | cmdNumMod;
uint32_t cmdedShiftChar = TranslateToChar(key, cmdShiftNumMod, kbType);
// Is the keyboard layout changed by Cmd key?
// E.g., Arabic, Russian, Hebrew, Greek and Dvorak-QWERTY.
bool isCmdSwitchLayout = uncmdedChar != cmdedChar;
// Is the keyboard layout for Latin, but Cmd key switches the layout?
// I.e., Dvorak-QWERTY
bool isDvorakQWERTY = isCmdSwitchLayout && isRomanKeyboardLayout;
// If the current keyboard is not Dvorak-QWERTY or Cmd is not pressed,
// we should append unshiftedChar and shiftedChar for handling the
// normal characters. These are the characters that the user is most
// likely to associate with this key.
if ((unshiftedChar || shiftedChar) &&
(!aKeyEvent.IsMeta() || !isDvorakQWERTY)) {
AlternativeCharCode altCharCodes(unshiftedChar, shiftedChar);
aKeyEvent.mAlternativeCharCodes.AppendElement(altCharCodes);
}
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, "
"aKeyEvent.isMeta=%s, isDvorakQWERTY=%s, "
"unshiftedChar=U+%X, shiftedChar=U+%X",
this, OnOrOff(aKeyEvent.IsMeta()), TrueOrFalse(isDvorakQWERTY),
unshiftedChar, shiftedChar));
// Most keyboard layouts provide the same characters in the NSEvents
// with Command+Shift as with Command. However, with Command+Shift we
// want the character on the second level. e.g. With a US QWERTY
// layout, we want "?" when the "/","?" key is pressed with
// Command+Shift.
// On a German layout, the OS gives us '/' with Cmd+Shift+SS(eszett)
// even though Cmd+SS is 'SS' and Shift+'SS' is '?'. This '/' seems
// like a hack to make the Cmd+"?" event look the same as the Cmd+"?"
// event on a US keyboard. The user thinks they are typing Cmd+"?", so
// we'll prefer the "?" character, replacing mCharCode with shiftedChar
// when Shift is pressed. However, in case there is a layout where the
// character unique to Cmd+Shift is the character that the user expects,
// we'll send it as an alternative char.
bool hasCmdShiftOnlyChar =
cmdedChar != cmdedShiftChar && uncmdedShiftChar != cmdedShiftChar;
uint32_t originalCmdedShiftChar = cmdedShiftChar;
// If we can make a good guess at the characters that the user would
// expect this key combination to produce (with and without Shift) then
// use those characters. This also corrects for CapsLock, which was
// ignored above.
if (!isCmdSwitchLayout) {
// The characters produced with Command seem similar to those without
// Command.
if (unshiftedChar) {
cmdedChar = unshiftedChar;
}
if (shiftedChar) {
cmdedShiftChar = shiftedChar;
}
} else if (uncmdedUSChar == cmdedChar) {
// It looks like characters from a US layout are provided when Command
// is down.
uint32_t ch = USLayout.TranslateToChar(key, lockState, kbType);
if (ch) {
cmdedChar = ch;
}
ch = USLayout.TranslateToChar(key, shiftLockMod, kbType);
if (ch) {
cmdedShiftChar = ch;
}
}
// If the current keyboard layout is switched by the Cmd key,
// we should append cmdedChar and shiftedCmdChar that are
// Latin char for the key.
// If the keyboard layout is Dvorak-QWERTY, we should append them only when
// command key is pressed because when command key isn't pressed, uncmded
// chars have been appended already.
if ((cmdedChar || cmdedShiftChar) && isCmdSwitchLayout &&
(aKeyEvent.IsMeta() || !isDvorakQWERTY)) {
AlternativeCharCode altCharCodes(cmdedChar, cmdedShiftChar);
aKeyEvent.mAlternativeCharCodes.AppendElement(altCharCodes);
}
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, "
"hasCmdShiftOnlyChar=%s, isCmdSwitchLayout=%s, isDvorakQWERTY=%s, "
"cmdedChar=U+%X, cmdedShiftChar=U+%X",
this, TrueOrFalse(hasCmdShiftOnlyChar), TrueOrFalse(isDvorakQWERTY),
TrueOrFalse(isDvorakQWERTY), cmdedChar, cmdedShiftChar));
// Special case for 'SS' key of German layout. See the comment of
// hasCmdShiftOnlyChar definition for the detail.
if (hasCmdShiftOnlyChar && originalCmdedShiftChar) {
AlternativeCharCode altCharCodes(0, originalCmdedShiftChar);
aKeyEvent.mAlternativeCharCodes.AppendElement(altCharCodes);
}
MOZ_LOG(gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, "
"hasCmdShiftOnlyChar=%s, originalCmdedShiftChar=U+%X",
this, TrueOrFalse(hasCmdShiftOnlyChar), originalCmdedShiftChar));
NS_OBJC_END_TRY_IGNORE_BLOCK
}
uint32_t TISInputSourceWrapper::ComputeGeckoKeyCode(UInt32 aNativeKeyCode,
UInt32 aKbType,
bool aCmdIsPressed) {
MOZ_LOG(
gKeyLog, LogLevel::Info,
("%p TISInputSourceWrapper::ComputeGeckoKeyCode, aNativeKeyCode=0x%X, "
"aKbType=0x%X, aCmdIsPressed=%s, IsOpenedIMEMode()=%s, "
"IsASCIICapable()=%s",
this, static_cast<unsigned int>(aNativeKeyCode),
static_cast<unsigned int>(aKbType), TrueOrFalse(aCmdIsPressed),
TrueOrFalse(IsOpenedIMEMode()), TrueOrFalse(IsASCIICapable())));
switch (aNativeKeyCode) {
case kVK_Space:
return NS_VK_SPACE;
case kVK_Escape:
return NS_VK_ESCAPE;
// modifiers
case kVK_RightCommand:
case kVK_Command:
return NS_VK_META;
case kVK_RightShift:
case kVK_Shift:
return NS_VK_SHIFT;
case kVK_CapsLock:
return NS_VK_CAPS_LOCK;
case kVK_RightControl:
case kVK_Control:
return NS_VK_CONTROL;
case kVK_RightOption:
case kVK_Option:
return NS_VK_ALT;
case kVK_ANSI_KeypadClear:
return NS_VK_CLEAR;
// function keys
case kVK_F1:
return NS_VK_F1;
case kVK_F2:
return NS_VK_F2;
case kVK_F3:
return NS_VK_F3;
case kVK_F4:
return NS_VK_F4;
case kVK_F5:
return NS_VK_F5;
case kVK_F6:
return NS_VK_F6;
case kVK_F7:
return NS_VK_F7;
case kVK_F8:
return NS_VK_F8;
case kVK_F9:
return NS_VK_F9;
case kVK_F10:
return NS_VK_F10;
case kVK_F11:
return NS_VK_F11;
case kVK_F12:
return NS_VK_F12;
// case kVK_F13: return NS_VK_F13; // clash with the 3 below
// case kVK_F14: return NS_VK_F14;
// case kVK_F15: return NS_VK_F15;
case kVK_F16:
return NS_VK_F16;
case kVK_F17:
return NS_VK_F17;
case kVK_F18:
return NS_VK_F18;
case kVK_F19:
return NS_VK_F19;
case kVK_PC_Pause:
return NS_VK_PAUSE;
case kVK_PC_ScrollLock:
return NS_VK_SCROLL_LOCK;
case kVK_PC_PrintScreen:
return NS_VK_PRINTSCREEN;
// keypad
case kVK_ANSI_Keypad0:
return NS_VK_NUMPAD0;
case kVK_ANSI_Keypad1:
return NS_VK_NUMPAD1;
case kVK_ANSI_Keypad2:
return NS_VK_NUMPAD2;
case kVK_ANSI_Keypad3:
return NS_VK_NUMPAD3;
case kVK_ANSI_Keypad4:
return NS_VK_NUMPAD4;
case kVK_ANSI_Keypad5:
return NS_VK_NUMPAD5;
case kVK_ANSI_Keypad6:
return NS_VK_NUMPAD6;
case kVK_ANSI_Keypad7:
return NS_VK_NUMPAD7;
case kVK_ANSI_Keypad8:
return NS_VK_NUMPAD8;
case kVK_ANSI_Keypad9:
return NS_VK_NUMPAD9;
case kVK_ANSI_KeypadMultiply:
return NS_VK_MULTIPLY;
case kVK_ANSI_KeypadPlus:
return NS_VK_ADD;
case kVK_ANSI_KeypadMinus:
return NS_VK_SUBTRACT;
case kVK_ANSI_KeypadDecimal:
return NS_VK_DECIMAL;
case kVK_ANSI_KeypadDivide:
return NS_VK_DIVIDE;
case kVK_JIS_KeypadComma:
return NS_VK_SEPARATOR;
// IME keys
case kVK_JIS_Eisu:
return NS_VK_EISU;
case kVK_JIS_Kana:
return NS_VK_KANA;
// these may clash with forward delete and help
case kVK_PC_Insert:
return NS_VK_INSERT;
case kVK_PC_Delete:
return NS_VK_DELETE;
case kVK_PC_Backspace:
return NS_VK_BACK;
case kVK_Tab:
return NS_VK_TAB;
case kVK_Home:
return NS_VK_HOME;
case kVK_End:
return NS_VK_END;
case kVK_PageUp:
return NS_VK_PAGE_UP;
case kVK_PageDown:
return NS_VK_PAGE_DOWN;
case kVK_LeftArrow:
return NS_VK_LEFT;
case kVK_RightArrow:
return NS_VK_RIGHT;
case kVK_UpArrow:
return NS_VK_UP;
case kVK_DownArrow:
return NS_VK_DOWN;
case kVK_PC_ContextMenu:
return NS_VK_CONTEXT_MENU;
case kVK_ANSI_1:
return NS_VK_1;
case kVK_ANSI_2:
return NS_VK_2;
case kVK_ANSI_3:
return NS_VK_3;
case kVK_ANSI_4:
return NS_VK_4;
case kVK_ANSI_5:
return NS_VK_5;
case kVK_ANSI_6:
return NS_VK_6;
case kVK_ANSI_7:
return NS_VK_7;
case kVK_ANSI_8:
return NS_VK_8;
case kVK_ANSI_9:
return NS_VK_9;
case kVK_ANSI_0:
return NS_VK_0;
case kVK_ANSI_KeypadEnter:
case kVK_Return:
case kVK_Powerbook_KeypadEnter:
return NS_VK_RETURN;
}
// If Cmd key is pressed, that causes switching keyboard layout temporarily.
// E.g., Dvorak-QWERTY. Therefore, if Cmd key is pressed, we should honor it.
UInt32 modifiers = aCmdIsPressed ? cmdKey : 0;
uint32_t charCode = TranslateToChar(aNativeKeyCode, modifiers, aKbType);
// Special case for Mac. Mac inputs Yen sign (U+00A5) directly instead of
// Back slash (U+005C). We should return NS_VK_BACK_SLASH for compatibility
// with other platforms.
// XXX How about Won sign (U+20A9) which has same problem as Yen sign?
if (charCode == 0x00A5) {
return NS_VK_BACK_SLASH;
}
uint32_t keyCode = WidgetUtils::ComputeKeyCodeFromChar(charCode);
if (keyCode) {
return keyCode;
}
// If the unshifed char isn't an ASCII character, use shifted char.
charCode = TranslateToChar(aNativeKeyCode, modifiers | shiftKey, aKbType);
keyCode = WidgetUtils::ComputeKeyCodeFromChar(charCode);
if (keyCode) {
return keyCode;
}
if (!IsASCIICapable()) {
// Retry with ASCII capable keyboard layout.
TISInputSourceWrapper currentKeyboardLayout;
currentKeyboardLayout.InitByCurrentASCIICapableKeyboardLayout();
NS_ENSURE_TRUE(mInputSource != currentKeyboardLayout.mInputSource, 0);
keyCode = currentKeyboardLayout.ComputeGeckoKeyCode(aNativeKeyCode, aKbType,
aCmdIsPressed);
// We've returned 0 for long time if keyCode isn't for an alphabet keys or
// a numeric key even in alternative ASCII capable keyboard layout because
// we decided that we should avoid setting same keyCode value to 2 or
// more keys since active keyboard layout may have a key to input the
// punctuation with different key. However, setting keyCode to 0 makes
// some web applications which are aware of neither KeyboardEvent.key nor
// KeyboardEvent.code not work with Firefox when user selects non-ASCII
// capable keyboard layout such as Russian and Thai. So, if alternative
// ASCII capable keyboard layout has keyCode value for the key, we should
// use it. In other words, this behavior does that non-ASCII capable
// keyboard layout overrides some keys' keyCode value only if the key
// produces ASCII character by itself or with Shift key.
if (keyCode) {
return keyCode;
}
}
// Otherwise, let's decide keyCode value from the native virtual keycode
// value on major keyboard layout.
CodeNameIndex code = ComputeGeckoCodeNameIndex(aNativeKeyCode, aKbType);
return WidgetKeyboardEvent::GetFallbackKeyCodeOfPunctuationKey(code);
}
// static
KeyNameIndex TISInputSourceWrapper::ComputeGeckoKeyNameIndex(
UInt32 aNativeKeyCode) {
// NOTE:
// When unsupported keys like Convert, Nonconvert of Japanese keyboard is
// pressed:
// on 10.6.x, 'A' key event is fired (and also actually 'a' is inserted).
// on 10.7.x, Nothing happens.
// on 10.8.x, Nothing happens.
// on 10.9.x, FlagsChanged event is fired with keyCode 0xFF.
switch (aNativeKeyCode) {
#define NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, aKeyNameIndex) \
case aNativeKey: \
return aKeyNameIndex;
#include "NativeKeyToDOMKeyName.h"
#undef NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX
default:
return KEY_NAME_INDEX_Unidentified;
}
}
// static
CodeNameIndex TISInputSourceWrapper::ComputeGeckoCodeNameIndex(
UInt32 aNativeKeyCode, UInt32 aKbType) {
// macOS swaps native key code between Backquote key and IntlBackslash key
// only when the keyboard type is ISO. Let's treat the key code after
// swapping them here because Chromium does so only when computing .code
// value.
if (::KBGetLayoutType(aKbType) == kKeyboardISO) {
if (aNativeKeyCode == kVK_ISO_Section) {
aNativeKeyCode = kVK_ANSI_Grave;
} else if (aNativeKeyCode == kVK_ANSI_Grave) {
aNativeKeyCode = kVK_ISO_Section;
}
}
switch (aNativeKeyCode) {
#define NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX(aNativeKey, aCodeNameIndex) \
case aNativeKey: \
return aCodeNameIndex;
#include "NativeKeyToDOMCodeName.h"
#undef NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX
default:
return CODE_NAME_INDEX_UNKNOWN;
}
}
#pragma mark -
/******************************************************************************
*
* TextInputHandler implementation (static methods)
*
******************************************************************************/
NSUInteger TextInputHandler::sLastModifierState = 0;
// static
CFArrayRef TextInputHandler::CreateAllKeyboardLayoutList() {
const void* keys[] = {kTISPropertyInputSourceType};
const void* values[] = {kTISTypeKeyboardLayout};
CFDictionaryRef filter =
::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL);
NS_ASSERTION(filter, "failed to create the filter");
CFArrayRef list = ::TISCreateInputSourceList(filter, true);
::CFRelease(filter);
return list;
}
// static
void TextInputHandler::DebugPrintAllKeyboardLayouts() {
if (MOZ_LOG_TEST(gKeyLog, LogLevel::Info)) {
CFArrayRef list = CreateAllKeyboardLayoutList();
MOZ_LOG(gKeyLog, LogLevel::Info, ("Keyboard layout configuration:"));
CFIndex idx = ::CFArrayGetCount(list);
TISInputSourceWrapper tis;
for (CFIndex i = 0; i < idx; ++i) {
TISInputSourceRef inputSource = static_cast<TISInputSourceRef>(
const_cast<void*>(::CFArrayGetValueAtIndex(list, i)));
tis.InitByTISInputSourceRef(inputSource);
nsAutoString name, isid;
tis.GetLocalizedName(name);
tis.GetInputSourceID(isid);
MOZ_LOG(gKeyLog, LogLevel::Info,
(" %s\t<%s>%s%s\n", NS_ConvertUTF16toUTF8(name).get(),
NS_ConvertUTF16toUTF8(isid).get(),
tis.IsASCIICapable() ? "" : "\t(Isn't ASCII capable)",
tis.IsKeyboardLayout() && tis.GetUCKeyboardLayout()
? ""
: "\t(uchr is NOT AVAILABLE)"));
}
::CFRelease(list);
}
}
#pragma mark -
/******************************************************************************
*
* TextInputHandler implementation
*
******************************************************************************/
TextInputHandler::TextInputHandler(nsCocoaWindow* aWidget,
NSView<mozView>* aNativeView)
: IMEInputHandler(aWidget, aNativeView) {
EnsureToLogAllKeyboardLayoutsAndIMEs();
[mView installTextInputHandler:this];
}
TextInputHandler::~TextInputHandler() { [mView uninstallTextInputHandler]; }
bool TextInputHandler::HandleKeyDownEvent(NSEvent* aNativeEvent,
uint32_t aUniqueId) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
if (Destroyed()) {
MOZ_LOG_KEY_OR_IME(LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, "
"widget has been already destroyed",
this));
return false;
}
// Insert empty line to the log for easier to read.
MOZ_LOG_KEY_OR_IME(LogLevel::Info, (""));
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, aNativeEvent=%p, "
"type=%s, keyCode=%u (0x%X), modifierFlags=0x%lX, characters=\"%s\", "
"charactersIgnoringModifiers=\"%s\"",
this, aNativeEvent, GetNativeKeyEventType(aNativeEvent),
[aNativeEvent keyCode], [aNativeEvent keyCode],
static_cast<unsigned long>([aNativeEvent modifierFlags]),
GetCharacters([aNativeEvent characters]),
GetCharacters([aNativeEvent charactersIgnoringModifiers])));
// We should hide the mouse cursor until the next mousemove, unless we aren't
// dealing with editable content or the Command key was pressed. We hide the
// mouse cursor even if the key event will be handled by IME (i.e., even
// without dispatching eKeyPress events).
if (IsEditableContent() &&
!([aNativeEvent modifierFlags] & NSEventModifierFlagCommand)) {
[NSCursor setHiddenUntilMouseMoves:YES];
}
RefPtr<nsCocoaWindow> widget(mWidget);
KeyEventState* currentKeyEvent = PushKeyEvent(aNativeEvent, aUniqueId);
AutoKeyEventStateCleaner remover(this);
RefPtr<TextInputHandler> kungFuDeathGrip(this);
// When we're already in a composition, we need always to mark the eKeyDown
// event as "processed by IME". So, let's dispatch eKeyDown event here in
// such case.
if (IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(true)) {
MOZ_LOG_KEY_OR_IME(LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, eKeyDown "
"caused focus move or "
"something and canceling the composition",
this));
return false;
}
// macOS supports shortcut keys using the `Fn` key. Check first if this key
// event is such a shortcut key.
if (nsCocoaUtils::ModifiersForEvent(aNativeEvent) & MODIFIER_FN) {
if (mWidget->SendEventToNativeMenuSystem(aNativeEvent)) {
return true;
}
}
// Let Cocoa interpret the key events, caching IsIMEComposing first.
bool wasComposing = IsIMEComposing();
bool interpretKeyEventsCalled = false;
// Don't call interpretKeyEvents when a plugin has focus. If we call it,
// for example, a character is inputted twice during a composition in e10s
// mode.
if (IsIMEEnabled() || IsASCIICapableOnly()) {
MOZ_LOG_KEY_OR_IME(LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, calling "
"interpretKeyEvents",
this));
[mView interpretKeyEvents:[NSArray arrayWithObject:aNativeEvent]];
interpretKeyEventsCalled = true;
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, called interpretKeyEvents",
this));
}
if (Destroyed()) {
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, widget was destroyed",
this));
return currentKeyEvent->IsDefaultPrevented();
}
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, wasComposing=%s, "
"IsIMEComposing()=%s",
this, TrueOrFalse(wasComposing), TrueOrFalse(IsIMEComposing())));
if (currentKeyEvent->CanDispatchKeyDownEvent()) {
// Dispatch eKeyDown event if nobody has dispatched it yet.
// NOTE: Although reaching here means that the native keydown event may
// not be handled by IME. However, we cannot know if it is.
// For example, Japanese IME of Apple shows candidate window for
// typing window. They, you can switch the sort order with Tab key.
// However, when you choose "Symbol" of the sort order, there may
// be no candiate words. In this case, IME handles the Tab key
// actually, but we cannot know it because composition string is
// not updated. So, let's mark eKeyDown event as "processed by IME"
// when there is composition string. This is same as Chrome.
MOZ_LOG_KEY_OR_IME(LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, trying to "
"dispatch eKeyDown "
"event since it's not yet dispatched",
this));
if (!MaybeDispatchCurrentKeydownEvent(IsIMEComposing())) {
return true; // treat the eKeydDown event as consumed.
}
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, eKeyDown event has been "
"dispatched",
this));
}
if (currentKeyEvent->CanDispatchKeyPressEvent() && !wasComposing &&
!IsIMEComposing()) {
nsresult rv = mDispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG_KEY_OR_IME(
LogLevel::Error,
("%p TextInputHandler::HandleKeyDownEvent, "
"FAILED, due to BeginNativeInputTransaction() failure "
"at dispatching keypress",
this));
return false;
}
WidgetKeyboardEvent keypressEvent(true, eKeyPress, widget);
currentKeyEvent->InitKeyEvent(this, keypressEvent, false);
// If we called interpretKeyEvents and this isn't normal character input
// then IME probably ate the event for some reason. We do not want to
// send a key press event in that case.
// TODO:
// There are some other cases which IME eats the current event.
// 1. If key events were nested during calling interpretKeyEvents, it means
// that IME did something. Then, we should do nothing.
// 2. If one or more commands are called like "deleteBackward", we should
// dispatch keypress event at that time. Note that the command may have
// been a converted or generated action by IME. Then, we shouldn't do
// our default action for this key.
if (!(interpretKeyEventsCalled &&
IsNormalCharInputtingEvent(aNativeEvent))) {
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, trying to dispatch "
"eKeyPress event since it's not yet dispatched",
this));
nsEventStatus status = nsEventStatus_eIgnore;
currentKeyEvent->mKeyPressDispatched =
mDispatcher->MaybeDispatchKeypressEvents(keypressEvent, status,
currentKeyEvent);
currentKeyEvent->mKeyPressHandled =
(status == nsEventStatus_eConsumeNoDefault);
currentKeyEvent->mKeyPressDispatched = true;
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, eKeyPress event has been "
"dispatched",
this));
}
}
// Note: mWidget might have become null here. Don't count on it from here on.
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleKeyDownEvent, "
"keydown handled=%s, keypress handled=%s, causedOtherKeyEvents=%s, "
"compositionDispatched=%s",
this, TrueOrFalse(currentKeyEvent->mKeyDownHandled),
TrueOrFalse(currentKeyEvent->mKeyPressHandled),
TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents),
TrueOrFalse(currentKeyEvent->mCompositionDispatched)));
// Insert empty line to the log for easier to read.
MOZ_LOG_KEY_OR_IME(LogLevel::Info, (""));
return currentKeyEvent->IsDefaultPrevented();
NS_OBJC_END_TRY_BLOCK_RETURN(false);
}
void TextInputHandler::HandleKeyUpEvent(NSEvent* aNativeEvent) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleKeyUpEvent, aNativeEvent=%p, "
"type=%s, keyCode=%u (0x%X), modifierFlags=0x%lX, characters=\"%s\", "
"charactersIgnoringModifiers=\"%s\", "
"IsIMEComposing()=%s",
this, aNativeEvent, GetNativeKeyEventType(aNativeEvent),
[aNativeEvent keyCode], [aNativeEvent keyCode],
static_cast<unsigned long>([aNativeEvent modifierFlags]),
GetCharacters([aNativeEvent characters]),
GetCharacters([aNativeEvent charactersIgnoringModifiers]),
TrueOrFalse(IsIMEComposing())));
if (Destroyed()) {
MOZ_LOG_KEY_OR_IME(LogLevel::Info,
("%p TextInputHandler::HandleKeyUpEvent, "
"widget has been already destroyed",
this));
return;
}
nsresult rv = mDispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG_KEY_OR_IME(LogLevel::Error,
("%p TextInputHandler::HandleKeyUpEvent, "
"FAILED, due to BeginNativeInputTransaction() failure",
this));
return;
}
// Neither Chrome for macOS nor Safari marks "keyup" event as "processed by
// IME" even during composition. So, let's follow this behavior.
WidgetKeyboardEvent keyupEvent(true, eKeyUp, mWidget);
InitKeyEvent(aNativeEvent, keyupEvent, false);
KeyEventState currentKeyEvent(aNativeEvent);
nsEventStatus status = nsEventStatus_eIgnore;
mDispatcher->DispatchKeyboardEvent(eKeyUp, keyupEvent, status,
¤tKeyEvent);
if (!mCurrentKeyEvents.Length()) {
// No pending key. Then show text substitution panel if necessary.
ShowTextSubstitutionPanel();
}
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (Destroyed()) {
MOZ_LOG_KEY_OR_IME(LogLevel::Info,
("%p TextInputHandler::HandleFlagsChanged, "
"widget has been already destroyed",
this));
return;
}
RefPtr<nsCocoaWindow> kungFuDeathGrip(mWidget);
(void)kungFuDeathGrip; // Not referenced within this function
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleFlagsChanged, aNativeEvent=%p, "
"type=%s, keyCode=%s (0x%X), modifierFlags=0x%08lX, "
"sLastModifierState=0x%08lX, IsIMEComposing()=%s",
this, aNativeEvent, GetNativeKeyEventType(aNativeEvent),
GetKeyNameForNativeKeyCode([aNativeEvent keyCode]),
[aNativeEvent keyCode],
static_cast<unsigned long>([aNativeEvent modifierFlags]),
static_cast<unsigned long>(sLastModifierState),
TrueOrFalse(IsIMEComposing())));
MOZ_ASSERT([aNativeEvent type] == NSEventTypeFlagsChanged);
NSUInteger diff = [aNativeEvent modifierFlags] ^ sLastModifierState;
// Device dependent flags for left-control key, both shift keys, both command
// keys and both option keys have been defined in Next's SDK. But we
// shouldn't use it directly as far as possible since Cocoa SDK doesn't
// define them. Fortunately, we need them only when we dispatch keyup
// events. So, we can usually know the actual relation between keyCode and
// device dependent flags. However, we need to remove following flags first
// since the differences don't indicate modifier key state.
// NX_STYLUSPROXIMITYMASK: Probably used for pen like device.
// kCGEventFlagMaskNonCoalesced (= NX_NONCOALSESCEDMASK): See the document for
// Quartz Event Services.
diff &= ~(NX_STYLUSPROXIMITYMASK | kCGEventFlagMaskNonCoalesced);
switch ([aNativeEvent keyCode]) {
// CapsLock state and other modifier states are different:
// CapsLock state does not revert when the CapsLock key goes up, as the
// modifier state does for other modifier keys on key up.
case kVK_CapsLock: {
// Fire key down event for caps lock.
DispatchKeyEventForFlagsChanged(aNativeEvent, true);
// XXX should we fire keyup event too? The keyup event for CapsLock key
// is never dispatched on Gecko.
// XXX WebKit dispatches keydown event when CapsLock is locked, otherwise,
// keyup event. If we do so, we cannot keep the consistency with other
// platform's behavior...
break;
}
// If the event is caused by pressing or releasing a modifier key, just
// dispatch the key's event.
case kVK_Shift:
case kVK_RightShift:
case kVK_Command:
case kVK_RightCommand:
case kVK_Control:
case kVK_RightControl:
case kVK_Option:
case kVK_RightOption:
case kVK_Help: {
// We assume that at most one modifier is changed per event if the event
// is caused by pressing or releasing a modifier key.
bool isKeyDown = ([aNativeEvent modifierFlags] & diff) != 0;
DispatchKeyEventForFlagsChanged(aNativeEvent, isKeyDown);
// XXX Some applications might send the event with incorrect device-
// dependent flags.
if (isKeyDown &&
((diff & ~NSEventModifierFlagDeviceIndependentFlagsMask) != 0)) {
unsigned short keyCode = [aNativeEvent keyCode];
const ModifierKey* modifierKey =
GetModifierKeyForDeviceDependentFlags(diff);
if (modifierKey && modifierKey->keyCode != keyCode) {
// Although, we're not sure the actual cause of this case, the stored
// modifier information and the latest key event information may be
// mismatched. Then, let's reset the stored information.
// NOTE: If this happens, it may fail to handle
// NSEventTypeFlagsChanged event in the default case (below). However,
// it's the rare case handler and this case occurs rarely. So, we can
// ignore the edge case bug.
NS_WARNING("Resetting stored modifier key information");
mModifierKeys.Clear();
modifierKey = nullptr;
}
if (!modifierKey) {
mModifierKeys.AppendElement(ModifierKey(diff, keyCode));
}
}
break;
}
// Currently we don't support Fn key since other browsers don't dispatch
// events for it and we don't have keyCode for this key.
// It should be supported when we implement .key and .char.
case kVK_Function:
break;
// If the event is caused by something else than pressing or releasing a
// single modifier key (for example by the app having been deactivated
// using command-tab), use the modifiers themselves to determine which
// key's event to dispatch, and whether it's a keyup or keydown event.
// In all cases we assume one or more modifiers are being deactivated
// (never activated) -- otherwise we'd have received one or more events
// corresponding to a single modifier key being pressed.
default: {
NSUInteger modifiers = sLastModifierState;
AutoTArray<unsigned short, 10> dispatchedKeyCodes;
for (int32_t bit = 0; bit < 32; ++bit) {
NSUInteger flag = 1 << bit;
if (!(diff & flag)) {
continue;
}
// Given correct information from the application, a flag change here
// will normally be a deactivation (except for some lockable modifiers
// such as CapsLock). But some applications (like VNC) can send an
// activating event with a zero keyCode. So we need to check for that
// here.
bool dispatchKeyDown = ((flag & [aNativeEvent modifierFlags]) != 0);
unsigned short keyCode = 0;
if (flag & NSEventModifierFlagDeviceIndependentFlagsMask) {
switch (flag) {
case NSEventModifierFlagCapsLock:
keyCode = kVK_CapsLock;
dispatchKeyDown = true;
break;
case NSEventModifierFlagNumericPad:
// NSEventModifierFlagNumericPad is fired by VNC a lot. But not
// all of these events can really be Clear key events, so we just
// ignore them.
continue;
case NSEventModifierFlagHelp:
keyCode = kVK_Help;
break;
case NSEventModifierFlagFunction:
// An NSEventModifierFlagFunction change here will normally be a
// deactivation. But sometimes it will be an activation send (by
// VNC for example) with a zero keyCode.
continue;
// These cases (NSEventModifierFlagShift,
// NSEventModifierFlagControl, NSEventModifierFlagOption and
// NSEventModifierFlagCommand) should be handled by the other branch
// of the if statement, below (which handles device dependent
// flags). However, some applications (like VNC) can send key events
// without any device dependent flags, so we handle them here
// instead.
case NSEventModifierFlagShift:
keyCode = (modifiers & 0x0004) ? kVK_RightShift : kVK_Shift;
break;
case NSEventModifierFlagControl:
keyCode = (modifiers & 0x2000) ? kVK_RightControl : kVK_Control;
break;
case NSEventModifierFlagOption:
keyCode = (modifiers & 0x0040) ? kVK_RightOption : kVK_Option;
break;
case NSEventModifierFlagCommand:
keyCode = (modifiers & 0x0010) ? kVK_RightCommand : kVK_Command;
break;
default:
continue;
}
} else {
const ModifierKey* modifierKey =
GetModifierKeyForDeviceDependentFlags(flag);
if (!modifierKey) {
// See the note above (in the other branch of the if statement)
// about the NSEventModifierFlagShift, NSEventModifierFlagControl,
// NSEventModifierFlagOption and NSEventModifierFlagCommand cases.
continue;
}
keyCode = modifierKey->keyCode;
}
// Remove flags
modifiers &= ~flag;
switch (keyCode) {
case kVK_Shift: {
const ModifierKey* modifierKey =
GetModifierKeyForNativeKeyCode(kVK_RightShift);
if (!modifierKey ||
!(modifiers & modifierKey->GetDeviceDependentFlags())) {
modifiers &= ~NSEventModifierFlagShift;
}
break;
}
case kVK_RightShift: {
const ModifierKey* modifierKey =
GetModifierKeyForNativeKeyCode(kVK_Shift);
if (!modifierKey ||
!(modifiers & modifierKey->GetDeviceDependentFlags())) {
modifiers &= ~NSEventModifierFlagShift;
}
break;
}
case kVK_Command: {
const ModifierKey* modifierKey =
GetModifierKeyForNativeKeyCode(kVK_RightCommand);
if (!modifierKey ||
!(modifiers & modifierKey->GetDeviceDependentFlags())) {
modifiers &= ~NSEventModifierFlagCommand;
}
break;
}
case kVK_RightCommand: {
const ModifierKey* modifierKey =
GetModifierKeyForNativeKeyCode(kVK_Command);
if (!modifierKey ||
!(modifiers & modifierKey->GetDeviceDependentFlags())) {
modifiers &= ~NSEventModifierFlagCommand;
}
break;
}
case kVK_Control: {
const ModifierKey* modifierKey =
GetModifierKeyForNativeKeyCode(kVK_RightControl);
if (!modifierKey ||
!(modifiers & modifierKey->GetDeviceDependentFlags())) {
modifiers &= ~NSEventModifierFlagControl;
}
break;
}
case kVK_RightControl: {
const ModifierKey* modifierKey =
GetModifierKeyForNativeKeyCode(kVK_Control);
if (!modifierKey ||
!(modifiers & modifierKey->GetDeviceDependentFlags())) {
modifiers &= ~NSEventModifierFlagControl;
}
break;
}
case kVK_Option: {
const ModifierKey* modifierKey =
GetModifierKeyForNativeKeyCode(kVK_RightOption);
if (!modifierKey ||
!(modifiers & modifierKey->GetDeviceDependentFlags())) {
modifiers &= ~NSEventModifierFlagOption;
}
break;
}
case kVK_RightOption: {
const ModifierKey* modifierKey =
GetModifierKeyForNativeKeyCode(kVK_Option);
if (!modifierKey ||
!(modifiers & modifierKey->GetDeviceDependentFlags())) {
modifiers &= ~NSEventModifierFlagOption;
}
break;
}
case kVK_Help:
modifiers &= ~NSEventModifierFlagHelp;
break;
default:
break;
}
// Avoid dispatching same keydown/keyup events twice or more.
// We must be able to assume that there is no case to dispatch
// both keydown and keyup events with same key code value here.
if (dispatchedKeyCodes.Contains(keyCode)) {
continue;
}
dispatchedKeyCodes.AppendElement(keyCode);
NSEvent* event =
[NSEvent keyEventWithType:NSEventTypeFlagsChanged
location:[aNativeEvent locationInWindow]
modifierFlags:modifiers
timestamp:[aNativeEvent timestamp]
windowNumber:[aNativeEvent windowNumber]
context:nil
characters:@""
charactersIgnoringModifiers:@""
isARepeat:NO
keyCode:keyCode];
DispatchKeyEventForFlagsChanged(event, dispatchKeyDown);
if (Destroyed()) {
break;
}
// Stop if focus has changed.
// Check to see if mView is still the first responder.
if (![mView isFirstResponder]) {
break;
}
}
break;
}
}
// Be aware, the widget may have been destroyed.
sLastModifierState = [aNativeEvent modifierFlags];
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
const TextInputHandler::ModifierKey*
TextInputHandler::GetModifierKeyForNativeKeyCode(
unsigned short aKeyCode) const {
for (ModifierKeyArray::index_type i = 0; i < mModifierKeys.Length(); ++i) {
if (mModifierKeys[i].keyCode == aKeyCode) {
return &((ModifierKey&)mModifierKeys[i]);
}
}
return nullptr;
}
const TextInputHandler::ModifierKey*
TextInputHandler::GetModifierKeyForDeviceDependentFlags(
NSUInteger aFlags) const {
for (ModifierKeyArray::index_type i = 0; i < mModifierKeys.Length(); ++i) {
if (mModifierKeys[i].GetDeviceDependentFlags() ==
(aFlags & ~NSEventModifierFlagDeviceIndependentFlagsMask)) {
return &((ModifierKey&)mModifierKeys[i]);
}
}
return nullptr;
}
void TextInputHandler::DispatchKeyEventForFlagsChanged(NSEvent* aNativeEvent,
bool aDispatchKeyDown) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (Destroyed()) {
return;
}
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::DispatchKeyEventForFlagsChanged, aNativeEvent=%p, "
"type=%s, keyCode=%s (0x%X), aDispatchKeyDown=%s, IsIMEComposing()=%s",
this, aNativeEvent, GetNativeKeyEventType(aNativeEvent),
GetKeyNameForNativeKeyCode([aNativeEvent keyCode]),
[aNativeEvent keyCode], TrueOrFalse(aDispatchKeyDown),
TrueOrFalse(IsIMEComposing())));
if ([aNativeEvent type] != NSEventTypeFlagsChanged) {
return;
}
nsresult rv = mDispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG_KEY_OR_IME(
LogLevel::Error,
("%p TextInputHandler::DispatchKeyEventForFlagsChanged, "
"FAILED, due to BeginNativeInputTransaction() failure",
this));
return;
}
EventMessage message = aDispatchKeyDown ? eKeyDown : eKeyUp;
// Fire a key event for the modifier key. Note that even if modifier key
// is pressed during composition, we shouldn't mark the keyboard event as
// "processed by IME" since neither Chrome for macOS nor Safari does it.
WidgetKeyboardEvent keyEvent(true, message, mWidget);
InitKeyEvent(aNativeEvent, keyEvent, false);
KeyEventState currentKeyEvent(aNativeEvent);
nsEventStatus status = nsEventStatus_eIgnore;
mDispatcher->DispatchKeyboardEvent(message, keyEvent, status,
¤tKeyEvent);
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void TextInputHandler::InsertText(NSString* aString,
NSRange* aReplacementRange) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (Destroyed()) {
return;
}
KeyEventState* currentKeyEvent = GetCurrentKeyEvent();
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::InsertText, aString=\"%s\", aReplacementRange=%s, "
"IsIMEComposing()=%s, keyevent=%p, keydownDispatched=%s, "
"keydownHandled=%s, keypressDispatched=%s, causedOtherKeyEvents=%s, "
"compositionDispatched=%s",
this, GetCharacters(aString),
aReplacementRange ? ToString(*aReplacementRange).c_str() : "nullptr",
TrueOrFalse(IsIMEComposing()),
currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr,
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownDispatched)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownHandled) : "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCompositionDispatched)
: "N/A"));
InputContext context = mWidget->GetInputContext();
bool isEditable = (context.mIMEState.mEnabled == IMEEnabled::Enabled ||
context.mIMEState.mEnabled == IMEEnabled::Password);
NSRange selectedRange = SelectedRange();
nsAutoString str;
CopyNSStringToXPCOMString(aString, str);
AutoInsertStringClearer clearer(currentKeyEvent);
if (currentKeyEvent) {
currentKeyEvent->mInsertString = &str;
}
if (!IsIMEComposing() && str.IsEmpty()) {
// nothing to do if there is no content which can be removed.
if (!isEditable) {
return;
}
// If replacement range is specified, we need to remove the range.
// Otherwise, we need to remove the selected range if it's not collapsed.
if (aReplacementRange && aReplacementRange->location != NSNotFound) {
// nothing to do since the range is collapsed.
if (aReplacementRange->length == 0) {
return;
}
// If the replacement range is different from current selected range,
// select the range.
if (!NSEqualRanges(selectedRange, *aReplacementRange)) {
NS_ENSURE_TRUE_VOID(SetSelection(*aReplacementRange));
}
selectedRange = SelectedRange();
}
NS_ENSURE_TRUE_VOID(selectedRange.location != NSNotFound);
if (selectedRange.length == 0) {
return; // nothing to do
}
// If this is caused by a key input, the keypress event which will be
// dispatched later should cause the delete. Therefore, nothing to do here.
// Although, we're not sure if such case is actually possible.
if (!currentKeyEvent) {
return;
}
// When current keydown event causes this empty text input, let's
// dispatch eKeyDown event before any other events. Note that if we're
// in a composition, we've already dispatched eKeyDown event from
// TextInputHandler::HandleKeyDownEvent().
// XXX Should we mark this eKeyDown event as "processed by IME"?
RefPtr<TextInputHandler> kungFuDeathGrip(this);
if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(false)) {
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::InsertText, eKeyDown caused focus move or "
"something and canceling the composition",
this));
return;
}
// Delete the selected range.
WidgetContentCommandEvent deleteCommandEvent(true, eContentCommandDelete,
mWidget);
DispatchEvent(deleteCommandEvent);
NS_ENSURE_TRUE_VOID(deleteCommandEvent.mSucceeded);
// Be aware! The widget might be destroyed here.
return;
}
bool isReplacingSpecifiedRange =
isEditable && aReplacementRange &&
aReplacementRange->location != NSNotFound &&
!NSEqualRanges(selectedRange, *aReplacementRange);
// If this is not caused by pressing a key, there is a composition or
// replacing a range which is different from current selection, let's
// insert the text as committing a composition.
// If InsertText() is called two or more times, we should insert all
// text with composition events.
// XXX When InsertText() is called multiple times, Chromium dispatches
// only one composition event. So, we need to store InsertText()
// calls and flush later.
if (!currentKeyEvent || currentKeyEvent->mCompositionDispatched ||
IsIMEComposing() || isReplacingSpecifiedRange) {
InsertTextAsCommittingComposition(aString, aReplacementRange);
if (currentKeyEvent) {
currentKeyEvent->mCompositionDispatched = true;
}
return;
}
// Don't let the same event be fired twice when hitting
// enter/return for Bug 420502. However, Korean IME (or some other
// simple IME) may work without marked text. For example, composing
// character may be inserted as committed text and it's modified with
// aReplacementRange. When a keydown starts new composition with
// committing previous character, InsertText() may be called twice,
// one is for committing previous character and then, inserting new
// composing character as committed character. In the latter case,
// |CanDispatchKeyPressEvent()| returns true but we need to dispatch
// keypress event for the new character. So, when IME tries to insert
// printable characters, we should ignore current key event state even
// after the keydown has already caused dispatching composition event.
// XXX Anyway, we should sort out around this at fixing bug 1338460.
if (currentKeyEvent && !currentKeyEvent->CanDispatchKeyPressEvent() &&
(str.IsEmpty() || (str.Length() == 1 && !IsPrintableChar(str[0])))) {
return;
}
// This is the normal path to input a character when you press a key.
// Let's dispatch eKeyDown event now.
RefPtr<TextInputHandler> kungFuDeathGrip(this);
if (!MaybeDispatchCurrentKeydownEvent(false)) {
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::InsertText, eKeyDown caused focus move or "
"something and canceling the composition",
this));
return;
}
// XXX Shouldn't we hold mDispatcher instead of mWidget?
RefPtr<nsCocoaWindow> widget(mWidget);
nsresult rv = mDispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG_KEY_OR_IME(LogLevel::Error,
("%p TextInputHandler::InsertText, "
"FAILED, due to BeginNativeInputTransaction() failure",
this));
return;
}
MOZ_LOG_KEY_OR_IME(LogLevel::Info, ("%p TextInputHandler::InsertText, "
"maybe dispatches eKeyPress event "
"without control, alt and meta modifiers",
this));
// Dispatch keypress event with char instead of compositionchange event
WidgetKeyboardEvent keypressEvent(true, eKeyPress, widget);
// XXX Why do we need to dispatch keypress event for not inputting any
// string? If it wants to delete the specified range, should we
// dispatch an eContentCommandDelete event instead? Because this
// must not be caused by a key operation, a part of IME's processing.
// Don't set other modifiers from the current event, because here in
// -insertText: they've already been taken into account in creating
// the input string.
if (currentKeyEvent) {
currentKeyEvent->InitKeyEvent(this, keypressEvent, false);
} else {
nsCocoaUtils::InitInputEvent(keypressEvent, static_cast<NSEvent*>(nullptr));
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_USE_STRING;
keypressEvent.mKeyValue = str;
// FYI: TextEventDispatcher will set mKeyCode to 0 for printable key's
// keypress events even if they don't cause inputting non-empty string.
}
// TODO:
// If mCurrentKeyEvent.mKeyEvent is null, the text should be inputted as
// composition events.
nsEventStatus status = nsEventStatus_eIgnore;
bool keyPressDispatched = [&]() {
// If text content is chrome process, OnTextChange etc will be dispatched
// synchronously. We don't want to dismiss text substitution panel at this
// point.
AutoRestore<bool> block(mBlockDismissTextSubstitutionPanel);
mBlockDismissTextSubstitutionPanel = true;
return mDispatcher->MaybeDispatchKeypressEvents(keypressEvent, status,
currentKeyEvent);
}();
bool keyPressHandled = (status == nsEventStatus_eConsumeNoDefault);
// WebKit and text editor dismisses autocorrect panel by space, then process
// autocorrect.
if (keypressEvent.mKeyCode == NS_VK_SPACE && keyPressDispatched) {
mProcessTextSubstitution = true;
DismissTextSubstitutionPanel();
}
// Note: mWidget might have become null here. Don't count on it from here on.
if (currentKeyEvent) {
currentKeyEvent->mKeyPressHandled = keyPressHandled;
currentKeyEvent->mKeyPressDispatched = keyPressDispatched;
}
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
bool TextInputHandler::HandleCommand(Command aCommand) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
if (Destroyed()) {
return false;
}
KeyEventState* currentKeyEvent = GetCurrentKeyEvent();
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::HandleCommand, "
"aCommand=%s, IsIMEComposing()=%s, "
"keyevent=%p, keydownHandled=%s, keypressDispatched=%s, "
"causedOtherKeyEvents=%s, compositionDispatched=%s",
this, ToChar(aCommand), TrueOrFalse(IsIMEComposing()),
currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr,
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownHandled) : "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCompositionDispatched)
: "N/A"));
// The command shouldn't be handled, let's ignore it.
if (currentKeyEvent && !currentKeyEvent->CanHandleCommand()) {
return false;
}
// When current keydown event causes this command, let's dispatch
// eKeyDown event before any other events. Note that if we're in a
// composition, we've already dispatched eKeyDown event from
// TextInputHandler::HandleKeyDownEvent().
RefPtr<TextInputHandler> kungFuDeathGrip(this);
if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(false)) {
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::SetMarkedText, eKeyDown caused focus move or "
"something and canceling the composition",
this));
return false;
}
// If it's in composition, we cannot dispatch keypress event.
// Therefore, we should use different approach or give up to handle
// the command.
if (IsIMEComposing()) {
switch (aCommand) {
case Command::InsertLineBreak:
case Command::InsertParagraph: {
// Insert '\n' as committing composition.
// Otherwise, we need to dispatch keypress event because HTMLEditor
// doesn't treat "\n" in composition string as a line break unless
// the whitespace is treated as pre (see bug 1350541). In strictly
// speaking, we should dispatch keypress event as-is if it's handling
// NSEventTypeKeyDown event or should insert it with committing
// composition.
InsertTextAsCommittingComposition(@"\n", nullptr);
if (currentKeyEvent) {
currentKeyEvent->mCompositionDispatched = true;
}
return true;
}
case Command::DeleteCharBackward:
case Command::DeleteCharForward:
case Command::DeleteToBeginningOfLine:
case Command::DeleteWordBackward:
case Command::DeleteWordForward:
// Don't remove any contents during composition.
return false;
case Command::InsertTab:
case Command::InsertBacktab:
// Don't move focus during composition.
return false;
case Command::CharNext:
case Command::SelectCharNext:
case Command::WordNext:
case Command::SelectWordNext:
case Command::EndLine:
case Command::SelectEndLine:
case Command::CharPrevious:
case Command::SelectCharPrevious:
case Command::WordPrevious:
case Command::SelectWordPrevious:
case Command::BeginLine:
case Command::SelectBeginLine:
case Command::LinePrevious:
case Command::SelectLinePrevious:
case Command::MoveTop:
case Command::LineNext:
case Command::SelectLineNext:
case Command::MoveBottom:
case Command::SelectBottom:
case Command::SelectPageUp:
case Command::SelectPageDown:
case Command::ScrollBottom:
case Command::ScrollTop:
// Don't move selection during composition.
return false;
case Command::CancelOperation:
case Command::Complete:
// Don't handle Escape key by ourselves during composition.
return false;
case Command::ScrollPageUp:
case Command::ScrollPageDown:
// Allow to scroll.
break;
default:
break;
}
}
RefPtr<nsCocoaWindow> widget(mWidget);
nsresult rv = mDispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG_KEY_OR_IME(LogLevel::Error,
("%p, TextInputHandler::HandleCommand, "
"FAILED, due to BeginNativeInputTransaction() failure",
this));
return false;
}
// TODO: If it's not appropriate keypress but user customized the OS
// settings to do the command with other key, we should just set
// command to the keypress event and it should be handled as
// the key press in editor.
// If it's handling actual key event and hasn't cause any composition
// events nor other key events, we should expose actual modifier state.
// Otherwise, we should adjust Control, Option and Command state since
// editor may behave differently if some of them are active.
bool dispatchFakeKeyPress =
!(currentKeyEvent && currentKeyEvent->IsProperKeyEvent(aCommand));
WidgetKeyboardEvent keydownEvent(true, eKeyDown, widget);
WidgetKeyboardEvent keypressEvent(true, eKeyPress, widget);
if (!dispatchFakeKeyPress) {
// If we're acutally handling a key press, we should dispatch
// the keypress event as-is.
currentKeyEvent->InitKeyEvent(this, keydownEvent, false);
currentKeyEvent->InitKeyEvent(this, keypressEvent, false);
} else {
// Otherwise, we should dispatch "fake" keypress event.
// However, for making it possible to compute edit commands, we need to
// set current native key event to the fake keyboard event even if it's
// not same as what we expect since the native keyboard event caused
// this command.
NSEvent* keyEvent = currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr;
keydownEvent.mNativeKeyEvent = keypressEvent.mNativeKeyEvent = keyEvent;
NS_WARNING_ASSERTION(
keypressEvent.mNativeKeyEvent,
"Without native key event, NativeKeyBindings cannot compute aCommand");
switch (aCommand) {
case Command::InsertLineBreak:
case Command::InsertParagraph: {
// Although, Shift+Enter and Enter are work differently in HTML
// editor, we should expose actual Shift state if it's caused by
// Enter key for compatibility with Chromium. Chromium breaks
// line in HTML editor with default pargraph separator when Enter
// is pressed, with <br> element when Shift+Enter. Safari breaks
// line in HTML editor with default paragraph separator when
// Enter, Shift+Enter or Option+Enter. So, we should not change
// Shift+Enter meaning when there was composition string or not.
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_RETURN;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Enter;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::InsertLineBreak) {
// In default settings, Ctrl + Enter causes insertLineBreak command.
// So, let's make Ctrl state active of the keypress event.
keypressEvent.mModifiers |= MODIFIER_CONTROL;
}
break;
}
case Command::InsertTab:
case Command::InsertBacktab:
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_TAB;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Tab;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::InsertBacktab) {
keypressEvent.mModifiers |= MODIFIER_SHIFT;
}
break;
case Command::DeleteCharBackward:
case Command::DeleteToBeginningOfLine:
case Command::DeleteWordBackward: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_BACK;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Backspace;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::DeleteToBeginningOfLine) {
keypressEvent.mModifiers |= MODIFIER_META;
} else if (aCommand == Command::DeleteWordBackward) {
keypressEvent.mModifiers |= MODIFIER_ALT;
}
break;
}
case Command::DeleteCharForward:
case Command::DeleteWordForward: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_DELETE;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Delete;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::DeleteWordForward) {
keypressEvent.mModifiers |= MODIFIER_ALT;
}
break;
}
case Command::CharNext:
case Command::SelectCharNext:
case Command::WordNext:
case Command::SelectWordNext:
case Command::EndLine:
case Command::SelectEndLine: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_RIGHT;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_ArrowRight;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::SelectCharNext ||
aCommand == Command::SelectWordNext ||
aCommand == Command::SelectEndLine) {
keypressEvent.mModifiers |= MODIFIER_SHIFT;
}
if (aCommand == Command::WordNext ||
aCommand == Command::SelectWordNext) {
keypressEvent.mModifiers |= MODIFIER_ALT;
}
if (aCommand == Command::EndLine ||
aCommand == Command::SelectEndLine) {
keypressEvent.mModifiers |= MODIFIER_META;
}
break;
}
case Command::CharPrevious:
case Command::SelectCharPrevious:
case Command::WordPrevious:
case Command::SelectWordPrevious:
case Command::BeginLine:
case Command::SelectBeginLine: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_LEFT;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_ArrowLeft;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::SelectCharPrevious ||
aCommand == Command::SelectWordPrevious ||
aCommand == Command::SelectBeginLine) {
keypressEvent.mModifiers |= MODIFIER_SHIFT;
}
if (aCommand == Command::WordPrevious ||
aCommand == Command::SelectWordPrevious) {
keypressEvent.mModifiers |= MODIFIER_ALT;
}
if (aCommand == Command::BeginLine ||
aCommand == Command::SelectBeginLine) {
keypressEvent.mModifiers |= MODIFIER_META;
}
break;
}
case Command::LinePrevious:
case Command::SelectLinePrevious:
case Command::MoveTop:
case Command::SelectTop: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_UP;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_ArrowUp;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::SelectLinePrevious ||
aCommand == Command::SelectTop) {
keypressEvent.mModifiers |= MODIFIER_SHIFT;
}
if (aCommand == Command::MoveTop || aCommand == Command::SelectTop) {
keypressEvent.mModifiers |= MODIFIER_META;
}
break;
}
case Command::LineNext:
case Command::SelectLineNext:
case Command::MoveBottom:
case Command::SelectBottom: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_DOWN;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_ArrowDown;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::SelectLineNext ||
aCommand == Command::SelectBottom) {
keypressEvent.mModifiers |= MODIFIER_SHIFT;
}
if (aCommand == Command::MoveBottom ||
aCommand == Command::SelectBottom) {
keypressEvent.mModifiers |= MODIFIER_META;
}
break;
}
case Command::ScrollPageUp:
case Command::SelectPageUp: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_PAGE_UP;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_PageUp;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::SelectPageUp) {
keypressEvent.mModifiers |= MODIFIER_SHIFT;
}
break;
}
case Command::ScrollPageDown:
case Command::SelectPageDown: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_PAGE_DOWN;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_PageDown;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::SelectPageDown) {
keypressEvent.mModifiers |= MODIFIER_SHIFT;
}
break;
}
case Command::ScrollBottom:
case Command::ScrollTop: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
if (aCommand == Command::ScrollBottom) {
keypressEvent.mKeyCode = NS_VK_END;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_End;
} else {
keypressEvent.mKeyCode = NS_VK_HOME;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Home;
}
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
break;
}
case Command::CancelOperation:
case Command::Complete: {
nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent);
keypressEvent.mKeyCode = NS_VK_ESCAPE;
keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Escape;
keypressEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
if (aCommand == Command::Complete) {
keypressEvent.mModifiers |= MODIFIER_ALT;
}
break;
}
default:
return false;
}
nsCocoaUtils::InitInputEvent(keydownEvent, keyEvent);
keydownEvent.mKeyCode = keypressEvent.mKeyCode;
keydownEvent.mKeyNameIndex = keypressEvent.mKeyNameIndex;
keydownEvent.mModifiers = keypressEvent.mModifiers;
}
// We've stopped dispatching "keypress" events of non-printable keys on
// the web. Therefore, we need to dispatch eKeyDown event here for web
// apps. This is non-standard behavior if we've already dispatched a
// "keydown" event. However, Chrome also dispatches such fake "keydown"
// (and "keypress") event for making same behavior as Safari.
nsEventStatus status = nsEventStatus_eIgnore;
if (mDispatcher->DispatchKeyboardEvent(eKeyDown, keydownEvent, status,
nullptr)) {
bool keydownHandled = status == nsEventStatus_eConsumeNoDefault;
if (currentKeyEvent) {
currentKeyEvent->mKeyDownDispatched = true;
currentKeyEvent->mKeyDownHandled |= keydownHandled;
}
if (keydownHandled) {
// Don't dispatch eKeyPress event if preceding eKeyDown event is
// consumed for conforming to UI Events.
// XXX Perhaps, we should ignore previous eKeyDown event result
// even if we've already dispatched because it may notify web apps
// of different key information, e.g., it's handled by IME, but
// web apps want to handle only this key.
return true;
}
}
bool keyPressDispatched = mDispatcher->MaybeDispatchKeypressEvents(
keypressEvent, status, currentKeyEvent);
bool keyPressHandled = (status == nsEventStatus_eConsumeNoDefault);
// NOTE: mWidget might have become null here.
if (keyPressDispatched) {
// Record the keypress event state only when it dispatched actual Enter
// keypress event because in other cases, the keypress event just a
// messenger. E.g., if it's caused by different key, keypress event for
// the actual key should be dispatched.
if (!dispatchFakeKeyPress && currentKeyEvent) {
currentKeyEvent->mKeyPressHandled = keyPressHandled;
currentKeyEvent->mKeyPressDispatched = keyPressDispatched;
}
return true;
}
// If keypress event isn't dispatched as expected, we should fallback to
// using composition events.
if (aCommand == Command::InsertLineBreak ||
aCommand == Command::InsertParagraph) {
InsertTextAsCommittingComposition(@"\n", nullptr);
if (currentKeyEvent) {
currentKeyEvent->mCompositionDispatched = true;
}
return true;
}
return false;
NS_OBJC_END_TRY_BLOCK_RETURN(false);
}
bool TextInputHandler::DoCommandBySelector(const char* aSelector) {
RefPtr<nsCocoaWindow> widget(mWidget);
KeyEventState* currentKeyEvent = GetCurrentKeyEvent();
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::DoCommandBySelector, aSelector=\"%s\", "
"Destroyed()=%s, keydownDispatched=%s, keydownHandled=%s, "
"keypressDispatched=%s, keypressHandled=%s, causedOtherKeyEvents=%s",
this, aSelector ? aSelector : "", TrueOrFalse(Destroyed()),
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownDispatched)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownHandled) : "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressHandled) : "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents)
: "N/A"));
// If the command isn't caused by key operation, the command should
// be handled in the super class of the caller.
if (!currentKeyEvent) {
return Destroyed();
}
// When current keydown event causes this command, let's dispatch
// eKeyDown event before any other events. Note that if we're in a
// composition, we've already dispatched eKeyDown event from
// TextInputHandler::HandleKeyDownEvent().
RefPtr<TextInputHandler> kungFuDeathGrip(this);
if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(false)) {
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::SetMarkedText, eKeyDown caused focus move or "
"something and canceling the composition",
this));
return true;
}
// If the key operation causes this command, should dispatch a keypress
// event.
// XXX This must be worng. Even if this command is caused by the key
// operation, its our default action can be different from the
// command. So, in this case, we should dispatch a keypress event
// which have the command and editor should handle it.
if (currentKeyEvent->CanDispatchKeyPressEvent()) {
nsresult rv = mDispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG_KEY_OR_IME(
LogLevel::Error,
("%p TextInputHandler::DoCommandBySelector, "
"FAILED, due to BeginNativeInputTransaction() failure "
"at dispatching keypress",
this));
return Destroyed();
}
WidgetKeyboardEvent keypressEvent(true, eKeyPress, widget);
currentKeyEvent->InitKeyEvent(this, keypressEvent, false);
nsEventStatus status = nsEventStatus_eIgnore;
// If text content is chrome process, OnTextChange etc will be dispatched
// synchronously. We don't want to dismiss text substitution panel at this
// point.
{
AutoRestore<bool> block(mBlockDismissTextSubstitutionPanel);
mBlockDismissTextSubstitutionPanel = true;
currentKeyEvent->mKeyPressDispatched =
mDispatcher->MaybeDispatchKeypressEvents(keypressEvent, status,
currentKeyEvent);
}
currentKeyEvent->mKeyPressHandled =
(status == nsEventStatus_eConsumeNoDefault);
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandler::DoCommandBySelector, keypress event "
"dispatched, Destroyed()=%s, keypressHandled=%s",
this, TrueOrFalse(Destroyed()),
TrueOrFalse(currentKeyEvent->mKeyPressHandled)));
// WebKit and text editor dismisses autocorrect panel by enter, then process
// autocorrect.
mProcessTextSubstitution = (keypressEvent.mKeyCode == NS_VK_RETURN);
DismissTextSubstitutionPanel();
// This command is now dispatched with keypress event.
// So, this shouldn't be handled by nobody anymore.
return true;
}
// If the key operation didn't cause keypress event or caused keypress event
// but not prevented its default, we need to honor the command. For example,
// Korean IME sends "insertNewline:" when committing existing composition
// with Enter key press. In such case, the key operation has been consumed
// by the committing composition but we still need to handle the command.
if (Destroyed() || !currentKeyEvent->CanHandleCommand()) {
return true;
}
// cancelOperation: command is fired after Escape or Command + Period.
// However, if ChildView implements cancelOperation:, calling
// [[ChildView super] doCommandBySelector:aSelector] when Command + Period
// causes only a call of [ChildView cancelOperation:sender]. I.e.,
// [ChildView keyDown:theEvent] becomes to be never called. For avoiding
// this odd behavior, we need to handle the command before super class of
// ChildView only when current key event is proper event to fire Escape
// keypress event.
if (!strcmp(aSelector, "cancelOperation:") && currentKeyEvent &&
currentKeyEvent->IsProperKeyEvent(Command::CancelOperation)) {
return HandleCommand(Command::CancelOperation);
}
// Otherwise, we've not handled the command yet. Propagate the command
// to the super class of ChildView.
return false;
}
#pragma mark -
/******************************************************************************
*
* IMEInputHandler implementation (static methods)
*
******************************************************************************/
bool IMEInputHandler::sStaticMembersInitialized = false;
bool IMEInputHandler::sCachedIsForRTLLangage = false;
CFStringRef IMEInputHandler::sLatestIMEOpenedModeInputSourceID = nullptr;
IMEInputHandler* IMEInputHandler::sFocusedIMEHandler = nullptr;
// static
void IMEInputHandler::InitStaticMembers() {
if (sStaticMembersInitialized) return;
sStaticMembersInitialized = true;
// We need to check the keyboard layout changes on all applications.
CFNotificationCenterRef center = ::CFNotificationCenterGetDistributedCenter();
// XXX Don't we need to remove the observer at shut down?
// Mac Dev Center's document doesn't say how to remove the observer if
// the second parameter is NULL.
::CFNotificationCenterAddObserver(
center, NULL, OnCurrentTextInputSourceChange,
kTISNotifySelectedKeyboardInputSourceChanged, NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
// Initiailize with the current keyboard layout
OnCurrentTextInputSourceChange(
NULL, NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL, NULL);
}
// static
void IMEInputHandler::OnCurrentTextInputSourceChange(
CFNotificationCenterRef aCenter, void* aObserver, CFStringRef aName,
const void* aObject, CFDictionaryRef aUserInfo) {
// Cache the latest IME opened mode to sLatestIMEOpenedModeInputSourceID.
TISInputSourceWrapper tis;
tis.InitByCurrentInputSource();
if (tis.IsOpenedIMEMode()) {
tis.GetInputSourceID(sLatestIMEOpenedModeInputSourceID);
// Collect Input Source ID which includes input mode in most cases.
// However, if it's Japanese IME, collecting input mode (e.g.,
// "HiraganaKotei") does not make sense because in most languages,
// input mode changes "how to input", but Japanese IME changes
// "which type of characters to input". I.e., only Japanese IME
// users may use multiple input modes. If we'd collect each type of
// input mode of Japanese IMEs, it'd be difficult to count actual
// users of each IME from the result. So, only when active IME is
// a Japanese IME, we should use Bundle ID which does not contain
// input mode instead.
nsAutoString key;
if (tis.IsForJapaneseLanguage()) {
tis.GetBundleID(key);
} else {
tis.GetInputSourceID(key);
}
// 72 is kMaximumKeyStringLength in TelemetryScalar.cpp
if (key.Length() > 72) {
if (NS_IS_SURROGATE_PAIR(key[72 - 2], key[72 - 1])) {
key.Truncate(72 - 2);
} else {
key.Truncate(72 - 1);
}
// U+2026 is "..."
key.Append(char16_t(0x2026));
}
glean::widget::ime_name_on_mac.Get(NS_ConvertUTF16toUTF8(key)).Set(true);
}
if (MOZ_LOG_TEST(gIMELog, LogLevel::Info)) {
static CFStringRef sLastTIS = nullptr;
CFStringRef newTIS;
tis.GetInputSourceID(newTIS);
if (!sLastTIS ||
::CFStringCompare(sLastTIS, newTIS, 0) != kCFCompareEqualTo) {
TISInputSourceWrapper tis1, tis2, tis3, tis4, tis5;
tis1.InitByCurrentKeyboardLayout();
tis2.InitByCurrentASCIICapableInputSource();
tis3.InitByCurrentASCIICapableKeyboardLayout();
tis4.InitByCurrentInputMethodKeyboardLayoutOverride();
tis5.InitByTISInputSourceRef(tis.GetKeyboardLayoutInputSource());
CFStringRef is0 = nullptr, is1 = nullptr, is2 = nullptr, is3 = nullptr,
is4 = nullptr, is5 = nullptr, type0 = nullptr,
lang0 = nullptr, bundleID0 = nullptr;
tis.GetInputSourceID(is0);
tis1.GetInputSourceID(is1);
tis2.GetInputSourceID(is2);
tis3.GetInputSourceID(is3);
tis4.GetInputSourceID(is4);
tis5.GetInputSourceID(is5);
tis.GetInputSourceType(type0);
tis.GetPrimaryLanguage(lang0);
tis.GetBundleID(bundleID0);
MOZ_LOG(
gIMELog, LogLevel::Info,
("IMEInputHandler::OnCurrentTextInputSourceChange,\n"
" Current Input Source is changed to:\n"
" currentInputContext=%p\n"
" %s\n"
" type=%s %s\n"
" overridden keyboard layout=%s\n"
" used keyboard layout for translation=%s\n"
" primary language=%s\n"
" bundle ID=%s\n"
" current ASCII capable Input Source=%s\n"
" current Keyboard Layout=%s\n"
" current ASCII capable Keyboard Layout=%s",
[NSTextInputContext currentInputContext], GetCharacters(is0),
GetCharacters(type0), tis.IsASCIICapable() ? "- ASCII capable " : "",
GetCharacters(is4), GetCharacters(is5), GetCharacters(lang0),
GetCharacters(bundleID0), GetCharacters(is2), GetCharacters(is1),
GetCharacters(is3)));
}
sLastTIS = newTIS;
}
/**
* When the direction is changed, all the children are notified.
* No need to treat the initial case separately because it is covered
* by the general case (sCachedIsForRTLLangage is initially false)
*/
if (sCachedIsForRTLLangage != tis.IsForRTLLanguage()) {
WidgetUtils::SendBidiKeyboardInfoToContent();
sCachedIsForRTLLangage = tis.IsForRTLLanguage();
}
}
// static
void IMEInputHandler::FlushPendingMethods(nsITimer* aTimer, void* aClosure) {
NS_ASSERTION(aClosure, "aClosure is null");
static_cast<IMEInputHandler*>(aClosure)->ExecutePendingMethods();
}
// static
CFArrayRef IMEInputHandler::CreateAllIMEModeList() {
const void* keys[] = {kTISPropertyInputSourceType};
const void* values[] = {kTISTypeKeyboardInputMode};
CFDictionaryRef filter =
::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL);
NS_ASSERTION(filter, "failed to create the filter");
CFArrayRef list = ::TISCreateInputSourceList(filter, true);
::CFRelease(filter);
return list;
}
// static
void IMEInputHandler::DebugPrintAllIMEModes() {
if (MOZ_LOG_TEST(gIMELog, LogLevel::Info)) {
CFArrayRef list = CreateAllIMEModeList();
MOZ_LOG(gIMELog, LogLevel::Info, ("IME mode configuration:"));
CFIndex idx = ::CFArrayGetCount(list);
TISInputSourceWrapper tis;
for (CFIndex i = 0; i < idx; ++i) {
TISInputSourceRef inputSource = static_cast<TISInputSourceRef>(
const_cast<void*>(::CFArrayGetValueAtIndex(list, i)));
tis.InitByTISInputSourceRef(inputSource);
nsAutoString name, isid, bundleID;
tis.GetLocalizedName(name);
tis.GetInputSourceID(isid);
tis.GetBundleID(bundleID);
MOZ_LOG(
gIMELog, LogLevel::Info,
(" %s\t<%s>%s%s\n"
" bundled in <%s>\n",
NS_ConvertUTF16toUTF8(name).get(), NS_ConvertUTF16toUTF8(isid).get(),
tis.IsASCIICapable() ? "" : "\t(Isn't ASCII capable)",
tis.IsEnabled() ? "" : "\t(Isn't Enabled)",
NS_ConvertUTF16toUTF8(bundleID).get()));
}
::CFRelease(list);
}
}
// static
TSMDocumentID IMEInputHandler::GetCurrentTSMDocumentID() {
// At least on Mac OS X 10.6.x and 10.7.x, ::TSMGetActiveDocument() has a bug.
// The result of ::TSMGetActiveDocument() isn't modified for new active text
// input context until [NSTextInputContext currentInputContext] is called.
// Therefore, we need to call it here.
[NSTextInputContext currentInputContext];
return ::TSMGetActiveDocument();
}
#pragma mark -
/******************************************************************************
*
* IMEInputHandler implementation #1
* The methods are releated to the pending methods. Some jobs should be
* run after the stack is finished, e.g, some methods cannot run the jobs
* during processing the focus event. And also some other jobs should be
* run at the next focus event is processed.
* The pending methods are recorded in mPendingMethods. They are executed
* by ExecutePendingMethods via FlushPendingMethods.
*
******************************************************************************/
nsresult IMEInputHandler::NotifyIME(TextEventDispatcher* aTextEventDispatcher,
const IMENotification& aNotification) {
switch (aNotification.mMessage) {
case REQUEST_TO_COMMIT_COMPOSITION:
CommitIMEComposition();
return NS_OK;
case REQUEST_TO_CANCEL_COMPOSITION:
CancelIMEComposition();
return NS_OK;
case NOTIFY_IME_OF_FOCUS:
if (IsFocused()) {
nsIWidget* widget = aTextEventDispatcher->GetWidget();
MOZ_LOG(gIMELog, LogLevel::Debug,
("%p IMEInputHandler::NotifyIME(), IsFocused()=true, "
"widget=%p, IsPasswordEditor()=%s",
this, widget,
TrueOrFalse(widget &&
widget->GetInputContext().IsPasswordEditor())));
if (widget && widget->GetInputContext().IsPasswordEditor()) {
EnableSecureEventInput();
} else {
EnsureSecureEventInputDisabled();
}
} else if (MOZ_LOG_TEST(gIMELog, LogLevel::Debug)) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN
NSWindow* window = mView ? [mView window] : nil;
MOZ_LOG(gIMELog, LogLevel::Debug,
("%p IMEInputHandler::NotifyIME(), IsFocused()=false, "
"Destroyed()=%s, mView=%p, "
"[mView window]=%p, firstResponder=%p, isKeyWindow=%s, "
"isActive=%s",
this, TrueOrFalse(Destroyed()), mView, window,
window ? [window firstResponder] : nil,
TrueOrFalse(window && [window isKeyWindow]),
TrueOrFalse([[NSApplication sharedApplication] isActive])));
NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE)
}
OnFocusChangeInGecko(true);
return NS_OK;
case NOTIFY_IME_OF_BLUR:
OnFocusChangeInGecko(false);
return NS_OK;
case NOTIFY_IME_OF_SELECTION_CHANGE:
OnSelectionChange(aNotification);
return NS_OK;
case NOTIFY_IME_OF_POSITION_CHANGE:
OnLayoutChange();
return NS_OK;
case NOTIFY_IME_OF_TEXT_CHANGE:
OnTextChange(aNotification);
return NS_OK;
default:
return NS_ERROR_NOT_IMPLEMENTED;
}
}
NS_IMETHODIMP_(IMENotificationRequests)
IMEInputHandler::GetIMENotificationRequests() {
// XXX Shouldn't we move floating window which shows composition string
// when plugin has focus and its parent is scrolled or the window is
// moved?
return IMENotificationRequests(IMENotificationRequests::NOTIFY_TEXT_CHANGE);
}
NS_IMETHODIMP_(void)
IMEInputHandler::OnRemovedFrom(TextEventDispatcher* aTextEventDispatcher) {
// XXX When input transaction is being stolen by add-on, what should we do?
}
NS_IMETHODIMP_(void)
IMEInputHandler::WillDispatchKeyboardEvent(
TextEventDispatcher* aTextEventDispatcher,
WidgetKeyboardEvent& aKeyboardEvent, uint32_t aIndexOfKeypress,
void* aData) {
// If the keyboard event is not caused by a native key event, we can do
// nothing here.
if (!aData) {
return;
}
KeyEventState* currentKeyEvent = static_cast<KeyEventState*>(aData);
NSEvent* nativeEvent = currentKeyEvent->mKeyEvent;
nsAString* insertString = currentKeyEvent->mInsertString;
if (aKeyboardEvent.mMessage == eKeyPress && aIndexOfKeypress == 0 &&
(!insertString || insertString->IsEmpty())) {
// Inform the child process that this is an event that we want a reply
// from.
// XXX This should be called only when the target is a remote process.
// However, it's difficult to check it under widget/.
// So, let's do this here for now, then,
// EventStateManager::PreHandleEvent() will reset the flags if
// the event target isn't in remote process.
aKeyboardEvent.MarkAsWaitingReplyFromRemoteProcess();
}
if (KeyboardLayoutOverrideRef().mOverrideEnabled) {
TISInputSourceWrapper tis;
tis.InitByLayoutID(KeyboardLayoutOverrideRef().mKeyboardLayout, true);
tis.WillDispatchKeyboardEvent(nativeEvent, insertString, aIndexOfKeypress,
aKeyboardEvent);
} else {
TISInputSourceWrapper::CurrentInputSource().WillDispatchKeyboardEvent(
nativeEvent, insertString, aIndexOfKeypress, aKeyboardEvent);
}
// Remove basic modifiers from keypress event because if they are included
// but this causes inputting text, since TextEditor won't handle eKeyPress
// events whose ctrlKey, altKey or metaKey is true as text input.
// Note that this hack should be used only when an editor has focus because
// this is a hack for TextEditor and modifier key information may be
// important for current web app.
if (IsEditableContent() && insertString &&
aKeyboardEvent.mMessage == eKeyPress && aKeyboardEvent.mCharCode) {
aKeyboardEvent.mModifiers &=
~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META);
}
}
void IMEInputHandler::NotifyIMEOfFocusChangeInGecko() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::NotifyIMEOfFocusChangeInGecko, "
"Destroyed()=%s, IsFocused()=%s, inputContext=%p",
this, TrueOrFalse(Destroyed()), TrueOrFalse(IsFocused()),
mView ? [mView inputContext] : nullptr));
if (Destroyed()) {
return;
}
if (!IsFocused()) {
// retry at next focus event
mPendingMethods |= kNotifyIMEOfFocusChangeInGecko;
return;
}
MOZ_ASSERT(mView);
NSTextInputContext* inputContext = [mView inputContext];
NS_ENSURE_TRUE_VOID(inputContext);
// When an <input> element on a XUL <panel> element gets focus from an <input>
// element on the opener window of the <panel> element, the owner window
// still has native focus. Therefore, IMEs may store the opener window's
// level at this time because they don't know the actual focus is moved to
// different window. If IMEs try to get the newest window level after the
// focus change, we return the window level of the XUL <panel>'s widget.
// Therefore, let's emulate the native focus change. Then, IMEs can refresh
// the stored window level.
[inputContext deactivate];
[inputContext activate];
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void IMEInputHandler::SyncASCIICapableOnly() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::SyncASCIICapableOnly, "
"Destroyed()=%s, IsFocused()=%s, mIsASCIICapableOnly=%s, "
"GetCurrentTSMDocumentID()=%p",
this, TrueOrFalse(Destroyed()), TrueOrFalse(IsFocused()),
TrueOrFalse(mIsASCIICapableOnly), GetCurrentTSMDocumentID()));
if (Destroyed()) {
return;
}
if (!IsFocused()) {
// retry at next focus event
mPendingMethods |= kSyncASCIICapableOnly;
return;
}
TSMDocumentID doc = GetCurrentTSMDocumentID();
if (!doc) {
// retry
mPendingMethods |= kSyncASCIICapableOnly;
NS_WARNING("Application is active but there is no active document");
ResetTimer();
return;
}
if (mIsASCIICapableOnly) {
CFArrayRef ASCIICapableTISList = ::TISCreateASCIICapableInputSourceList();
::TSMSetDocumentProperty(doc, kTSMDocumentEnabledInputSourcesPropertyTag,
sizeof(CFArrayRef), &ASCIICapableTISList);
::CFRelease(ASCIICapableTISList);
} else {
::TSMRemoveDocumentProperty(doc,
kTSMDocumentEnabledInputSourcesPropertyTag);
}
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void IMEInputHandler::ResetTimer() {
NS_ASSERTION(mPendingMethods != 0,
"There are not pending methods, why this is called?");
if (mTimer) {
mTimer->Cancel();
} else {
mTimer = NS_NewTimer();
NS_ENSURE_TRUE(mTimer, );
}
mTimer->InitWithNamedFuncCallback(FlushPendingMethods, this, 0,
nsITimer::TYPE_ONE_SHOT,
"IMEInputHandler::FlushPendingMethods"_ns);
}
void IMEInputHandler::ExecutePendingMethods() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (mTimer) {
mTimer->Cancel();
mTimer = nullptr;
}
if (![[NSApplication sharedApplication] isActive]) {
// If we're not active, we should retry at focus event
return;
}
uint32_t pendingMethods = mPendingMethods;
// First, reset the pending method flags because if each methods cannot
// run now, they can reentry to the pending flags by theirselves.
mPendingMethods = 0;
if (pendingMethods & kSyncASCIICapableOnly) SyncASCIICapableOnly();
if (pendingMethods & kNotifyIMEOfFocusChangeInGecko) {
NotifyIMEOfFocusChangeInGecko();
}
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
#pragma mark -
/******************************************************************************
*
* IMEInputHandler implementation (native event handlers)
*
******************************************************************************/
TextRangeType IMEInputHandler::ConvertToTextRangeType(uint32_t aUnderlineStyle,
NSRange& aSelectedRange) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::ConvertToTextRangeType, "
"aUnderlineStyle=%u, aSelectedRange.length=%lu,",
this, aUnderlineStyle,
static_cast<unsigned long>(aSelectedRange.length)));
// We assume that aUnderlineStyle is NSUnderlineStyleSingle or
// NSUnderlineStyleThick. NSUnderlineStyleThick should indicate a selected
// clause. Otherwise, should indicate non-selected clause.
if (aSelectedRange.length == 0) {
switch (aUnderlineStyle) {
case NSUnderlineStyleSingle:
return TextRangeType::eRawClause;
case NSUnderlineStyleThick:
return TextRangeType::eSelectedRawClause;
default:
NS_WARNING("Unexpected line style");
return TextRangeType::eSelectedRawClause;
}
}
switch (aUnderlineStyle) {
case NSUnderlineStyleSingle:
return TextRangeType::eConvertedClause;
case NSUnderlineStyleThick:
return TextRangeType::eSelectedClause;
default:
NS_WARNING("Unexpected line style");
return TextRangeType::eSelectedClause;
}
}
uint32_t IMEInputHandler::GetRangeCount(NSAttributedString* aAttrString) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
// Iterate through aAttrString for the NSUnderlineStyleAttributeName and
// count the different segments adjusting limitRange as we go.
uint32_t count = 0;
NSRange effectiveRange;
NSRange limitRange = NSMakeRange(0, [aAttrString length]);
while (limitRange.length > 0) {
[aAttrString attribute:NSUnderlineStyleAttributeName
atIndex:limitRange.location
longestEffectiveRange:&effectiveRange
inRange:limitRange];
limitRange =
NSMakeRange(NSMaxRange(effectiveRange),
NSMaxRange(limitRange) - NSMaxRange(effectiveRange));
count++;
}
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::GetRangeCount, aAttrString=\"%s\", count=%u",
this, GetCharacters([aAttrString string]), count));
return count;
NS_OBJC_END_TRY_BLOCK_RETURN(0);
}
already_AddRefed<mozilla::TextRangeArray> IMEInputHandler::CreateTextRangeArray(
NSAttributedString* aAttrString, NSRange& aSelectedRange) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
RefPtr<mozilla::TextRangeArray> textRangeArray =
new mozilla::TextRangeArray();
// Note that we shouldn't append ranges when composition string
// is empty because it may cause TextComposition confused.
if (![aAttrString length]) {
return textRangeArray.forget();
}
// Convert the Cocoa range into the TextRange Array used in Gecko.
// Iterate through the attributed string and map the underline attribute to
// Gecko IME textrange attributes. We may need to change the code here if
// we change the implementation of validAttributesForMarkedText.
NSRange limitRange = NSMakeRange(0, [aAttrString length]);
uint32_t rangeCount = GetRangeCount(aAttrString);
for (uint32_t i = 0; i < rangeCount && limitRange.length > 0; i++) {
NSRange effectiveRange;
id attributeValue = [aAttrString attribute:NSUnderlineStyleAttributeName
atIndex:limitRange.location
longestEffectiveRange:&effectiveRange
inRange:limitRange];
TextRange range;
range.mStartOffset = effectiveRange.location;
range.mEndOffset = NSMaxRange(effectiveRange);
range.mRangeType =
ConvertToTextRangeType([attributeValue intValue], aSelectedRange);
textRangeArray->AppendElement(range);
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::CreateTextRangeArray, "
"range={ mStartOffset=%u, mEndOffset=%u, mRangeType=%s }",
this, range.mStartOffset, range.mEndOffset, ToChar(range.mRangeType)));
limitRange =
NSMakeRange(NSMaxRange(effectiveRange),
NSMaxRange(limitRange) - NSMaxRange(effectiveRange));
}
// Get current caret position.
TextRange range;
range.mStartOffset = aSelectedRange.location + aSelectedRange.length;
range.mEndOffset = range.mStartOffset;
range.mRangeType = TextRangeType::eCaret;
textRangeArray->AppendElement(range);
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::CreateTextRangeArray, "
"range={ mStartOffset=%u, mEndOffset=%u, mRangeType=%s }",
this, range.mStartOffset, range.mEndOffset, ToChar(range.mRangeType)));
return textRangeArray.forget();
NS_OBJC_END_TRY_BLOCK_RETURN(nullptr);
}
bool IMEInputHandler::DispatchCompositionStartEvent() {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::DispatchCompositionStartEvent, "
"mSelectedRange=%s, Destroyed()=%s, mView=%p, mWidget=%p, "
"inputContext=%p, mIsIMEComposing=%s",
this, ToString(SelectedRange()).c_str(), TrueOrFalse(Destroyed()),
mView, mWidget, mView ? [mView inputContext] : nullptr,
TrueOrFalse(mIsIMEComposing)));
RefPtr<IMEInputHandler> kungFuDeathGrip(this);
nsresult rv = mDispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG(gIMELog, LogLevel::Error,
("%p IMEInputHandler::DispatchCompositionStartEvent, "
"FAILED, due to BeginNativeInputTransaction() failure",
this));
return false;
}
NS_ASSERTION(!mIsIMEComposing, "There is a composition already");
mIsIMEComposing = true;
KeyEventState* currentKeyEvent = GetCurrentKeyEvent();
mIsDeadKeyComposing = currentKeyEvent && currentKeyEvent->mKeyEvent &&
TISInputSourceWrapper::CurrentInputSource().IsDeadKey(
currentKeyEvent->mKeyEvent);
nsEventStatus status;
// IME may have already reterieved the selection and cache it. Therefore, we
// should retreive selection range before dispatching eCompositionStart.
mIMECompositionStartBeforeStart = mIMECompositionStartInContent =
Some(SelectedRange().location);
mSelectedRangeOverride = Some(SelectedRange());
rv = mDispatcher->StartComposition(status);
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG(gIMELog, LogLevel::Error,
("%p IMEInputHandler::DispatchCompositionStartEvent, "
"FAILED, due to StartComposition() failure",
this));
return false;
}
if (Destroyed()) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::DispatchCompositionStartEvent, "
"destroyed by compositionstart event",
this));
return false;
}
// FYI: Dispathcing eCompositionStart may cause committing the composition if
// the focused editor is in chrome UI.
return mIsIMEComposing;
}
bool IMEInputHandler::DispatchCompositionChangeEvent(
const nsString& aText, NSAttributedString* aAttrString,
NSRange& aSelectedRange) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::DispatchCompositionChangeEvent, aText=\"%s\", "
"aAttrString=\"%s\", aSelectedRange=%s, Destroyed()=%s, mView=%p, "
"mWidget=%p, inputContext=%p, mIsIMEComposing=%s",
this, NS_ConvertUTF16toUTF8(aText).get(),
GetCharacters([aAttrString string]), ToString(aSelectedRange).c_str(),
TrueOrFalse(Destroyed()), mView, mWidget,
mView ? [mView inputContext] : nullptr, TrueOrFalse(mIsIMEComposing)));
NS_ENSURE_TRUE(!Destroyed(), false);
NS_ASSERTION(mIsIMEComposing, "We're not in composition");
RefPtr<IMEInputHandler> kungFuDeathGrip(this);
nsresult rv = mDispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG(gIMELog, LogLevel::Error,
("%p IMEInputHandler::DispatchCompositionChangeEvent, "
"FAILED, due to BeginNativeInputTransaction() failure",
this));
return false;
}
RefPtr<TextRangeArray> rangeArray =
CreateTextRangeArray(aAttrString, aSelectedRange);
rv = mDispatcher->SetPendingComposition(aText, rangeArray);
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG(gIMELog, LogLevel::Error,
("%p IMEInputHandler::DispatchCompositionChangeEvent, "
"FAILED, due to SetPendingComposition() failure",
this));
return false;
}
// For avoiding IME to be confused at the preceding text changes during
// composition, we should not use the actual offset in content so that we
// should use the location at composition start.
mSelectedRangeOverride = Some(
NSMakeRange(*mIMECompositionStartBeforeStart + aSelectedRange.location,
aSelectedRange.length));
if (mIMECompositionString) {
[mIMECompositionString release];
}
mIMECompositionString = [[aAttrString string] retain];
nsEventStatus status;
rv = mDispatcher->FlushPendingComposition(status);
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG(gIMELog, LogLevel::Error,
("%p IMEInputHandler::DispatchCompositionChangeEvent, "
"FAILED, due to FlushPendingComposition() failure",
this));
return false;
}
if (Destroyed()) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::DispatchCompositionChangeEvent, "
"destroyed by compositionchange event",
this));
return false;
}
// FYI: compositionstart may cause committing composition by the webapp.
return mIsIMEComposing;
NS_OBJC_END_TRY_BLOCK_RETURN(false);
}
bool IMEInputHandler::DispatchCompositionCommitEvent(
const nsAString* aCommitString) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::DispatchCompositionCommitEvent, "
"aCommitString=0x%p (\"%s\"), Destroyed()=%s, mView=%p, mWidget=%p, "
"inputContext=%p, mIsIMEComposing=%s",
this, aCommitString,
aCommitString ? NS_ConvertUTF16toUTF8(*aCommitString).get() : "",
TrueOrFalse(Destroyed()), mView, mWidget,
mView ? [mView inputContext] : nullptr, TrueOrFalse(mIsIMEComposing)));
NS_ASSERTION(mIsIMEComposing, "We're not in composition");
RefPtr<IMEInputHandler> kungFuDeathGrip(this);
// Finish overriding Selection and mSelectedRange will be updated before
// dispatching the committing composition below and allow OnSelectionChange()
// changes the result of SelectedRange().
mSelectedRangeOverride.reset();
if (!Destroyed()) {
// mSelectedRange will be updated asynchronously if focused editor is in a
// remote process. However, IME may retrieve selected range immediately.
// Therefore, we should emulate the selection after committing composition
// right now.
mSelectedRange.location = *mIMECompositionStartInContent;
if (aCommitString) {
mSelectedRange.location += aCommitString->Length();
} else if (mIMECompositionString) {
nsAutoString commitString;
CopyNSStringToXPCOMString(mIMECompositionString, commitString);
mSelectedRange.location += commitString.Length();
}
mSelectedRange.length = 0;
nsresult rv = mDispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG(gIMELog, LogLevel::Error,
("%p IMEInputHandler::DispatchCompositionCommitEvent, "
"FAILED, due to BeginNativeInputTransaction() failure",
this));
} else {
nsEventStatus status;
rv = mDispatcher->CommitComposition(status, aCommitString);
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG(gIMELog, LogLevel::Error,
("%p IMEInputHandler::DispatchCompositionCommitEvent, "
"FAILED, due to BeginNativeInputTransaction() failure",
this));
}
}
}
mIsIMEComposing = mIsDeadKeyComposing = false;
mIMECompositionStartBeforeStart.reset();
mIMECompositionStartInContent.reset();
if (mIMECompositionString) {
[mIMECompositionString release];
mIMECompositionString = nullptr;
}
if (Destroyed()) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::DispatchCompositionCommitEvent, "
"destroyed by compositioncommit event",
this));
return false;
}
return true;
NS_OBJC_END_TRY_BLOCK_RETURN(false);
}
bool IMEInputHandler::MaybeDispatchCurrentKeydownEvent(bool aIsProcessedByIME) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (Destroyed()) {
return false;
}
MOZ_ASSERT(mWidget);
KeyEventState* currentKeyEvent = GetCurrentKeyEvent();
if (!currentKeyEvent || !currentKeyEvent->CanDispatchKeyDownEvent()) {
return true;
}
NSEvent* nativeEvent = currentKeyEvent->mKeyEvent;
if (NS_WARN_IF(!nativeEvent) || [nativeEvent type] != NSEventTypeKeyDown) {
return true;
}
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::MaybeDispatchKeydownEvent, aIsProcessedByIME=%s "
"currentKeyEvent={ mKeyEvent(%p)={ type=%s, keyCode=%s (0x%X) } }, "
"aIsProcessedBy=%s, IsDeadKeyComposing()=%s",
this, TrueOrFalse(aIsProcessedByIME), nativeEvent,
GetNativeKeyEventType(nativeEvent),
GetKeyNameForNativeKeyCode([nativeEvent keyCode]), [nativeEvent keyCode],
TrueOrFalse(IsIMEComposing()), TrueOrFalse(IsDeadKeyComposing())));
RefPtr<IMEInputHandler> kungFuDeathGrip(this);
RefPtr<TextEventDispatcher> dispatcher(mDispatcher);
nsresult rv = dispatcher->BeginNativeInputTransaction();
if (NS_WARN_IF(NS_FAILED(rv))) {
MOZ_LOG(gIMELog, LogLevel::Error,
("%p IMEInputHandler::DispatchKeyEventForFlagsChanged, "
"FAILED, due to BeginNativeInputTransaction() failure",
this));
return false;
}
NSResponder* firstResponder = [[mView window] firstResponder];
// Mark currentKeyEvent as "dispatched eKeyDown event" and actually do it.
currentKeyEvent->mKeyDownDispatched = true;
RefPtr<nsCocoaWindow> widget(mWidget);
WidgetKeyboardEvent keydownEvent(true, eKeyDown, widget);
// Don't mark the eKeyDown event as "processed by IME" if the composition
// is started with dead key.
currentKeyEvent->InitKeyEvent(this, keydownEvent,
aIsProcessedByIME && !IsDeadKeyComposing());
nsEventStatus status = nsEventStatus_eIgnore;
dispatcher->DispatchKeyboardEvent(eKeyDown, keydownEvent, status,
currentKeyEvent);
currentKeyEvent->mKeyDownHandled =
(status == nsEventStatus_eConsumeNoDefault);
if (Destroyed()) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::MaybeDispatchKeydownEvent, "
"widget was destroyed by keydown event",
this));
return false;
}
// The key down event may have shifted the focus, in which case, we should
// not continue to handle current key sequence and let's commit current
// composition.
if (firstResponder != [[mView window] firstResponder]) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::MaybeDispatchKeydownEvent, "
"view lost focus by keydown event",
this));
CommitIMEComposition();
return false;
}
return true;
NS_OBJC_END_TRY_BLOCK_RETURN(false);
}
void IMEInputHandler::InsertTextAsCommittingComposition(
NSString* aString, NSRange* aReplacementRange) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::InsertTextAsCommittingComposition, "
"aAttrString=\"%s\", aReplacementRange=%s, Destroyed()=%s, "
"IsIMEComposing()=%s, mMarkedRange=%s",
this, GetCharacters(aString),
aReplacementRange ? ToString(*aReplacementRange).c_str() : "nullptr",
TrueOrFalse(Destroyed()), TrueOrFalse(IsIMEComposing()),
ToString(mMarkedRange).c_str()));
if (IgnoreIMECommit()) {
MOZ_CRASH("IMEInputHandler::InsertTextAsCommittingComposition() must not"
"be called while canceling the composition");
}
if (Destroyed()) {
return;
}
// When current keydown event causes this text input, let's dispatch
// eKeyDown event before any other events. Note that if we're in a
// composition, we've already dispatched eKeyDown event from
// TextInputHandler::HandleKeyDownEvent().
// XXX Should we mark the eKeyDown event as "processed by IME"?
// However, if the key causes two or more Unicode characters as
// UTF-16 string, this is used. So, perhaps, we need to improve
// HandleKeyDownEvent() before do that.
RefPtr<IMEInputHandler> kungFuDeathGrip(this);
if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(false)) {
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::InsertTextAsCommittingComposition, eKeyDown "
"caused focus move or something and canceling the composition",
this));
return;
}
// First, commit current composition with the latest composition string if the
// replacement range is different from marked range.
if (IsIMEComposing() && aReplacementRange &&
aReplacementRange->location != NSNotFound &&
!NSEqualRanges(MarkedRange(), *aReplacementRange)) {
if (!DispatchCompositionCommitEvent()) {
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::InsertTextAsCommittingComposition, "
"destroyed by commiting composition for setting replacement range",
this));
return;
}
}
nsString str;
CopyNSStringToXPCOMString(aString, str);
if (!IsIMEComposing()) {
MOZ_DIAGNOSTIC_ASSERT(!str.IsEmpty());
// If there is no selection and replacement range is specified, set the
// range as selection.
if (aReplacementRange && aReplacementRange->location != NSNotFound &&
!NSEqualRanges(SelectedRange(), *aReplacementRange)) {
NS_ENSURE_TRUE_VOID(SetSelection(*aReplacementRange));
}
if (!StaticPrefs::intl_ime_use_composition_events_for_insert_text()) {
// In the default settings, we should not use composition events for
// inserting text without key press nor IME composition because the
// other browsers do so. This will cause only a cancelable `beforeinput`
// event whose `inputType` is `insertText`.
WidgetContentCommandEvent insertTextEvent(true, eContentCommandInsertText,
mWidget);
insertTextEvent.mString = Some(str);
DispatchEvent(insertTextEvent);
return;
}
// Otherise, emulate an IME composition. This is our traditional behavior,
// but `beforeinput` events are not cancelable since they should be so for
// native IME limitation. So, this is now seriously imcompatible with the
// other browsers.
if (!DispatchCompositionStartEvent()) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::InsertTextAsCommittingComposition, "
"cannot continue handling composition after compositionstart",
this));
return;
}
}
if (!DispatchCompositionCommitEvent(&str)) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::InsertTextAsCommittingComposition, "
"destroyed by compositioncommit event",
this));
return;
}
mMarkedRange = NSMakeRange(NSNotFound, 0);
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void IMEInputHandler::SetMarkedText(NSAttributedString* aAttrString,
NSRange& aSelectedRange,
NSRange* aReplacementRange) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
KeyEventState* currentKeyEvent = GetCurrentKeyEvent();
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::SetMarkedText, aAttrString=\"%s\", "
"aSelectedRange=%s, aReplacementRange=%s, Destroyed()=%s, "
"IsIMEComposing()=%s, mMarkedRange=%s, keyevent=%p, "
"keydownDispatched=%s, keydownHandled=%s, keypressDispatched=%s, "
"causedOtherKeyEvents=%s, compositionDispatched=%s",
this, GetCharacters([aAttrString string]),
ToString(aSelectedRange).c_str(),
aReplacementRange ? ToString(*aReplacementRange).c_str() : "nullptr",
TrueOrFalse(Destroyed()), TrueOrFalse(IsIMEComposing()),
ToString(mMarkedRange).c_str(),
currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr,
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownDispatched)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownHandled) : "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents)
: "N/A",
currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCompositionDispatched)
: "N/A"));
RefPtr<IMEInputHandler> kungFuDeathGrip(this);
// If SetMarkedText() is called during handling a key press, that means that
// the key event caused this composition. So, keypress event shouldn't
// be dispatched later, let's mark the key event causing composition event.
if (currentKeyEvent) {
currentKeyEvent->mCompositionDispatched = true;
// When current keydown event causes this text input, let's dispatch
// eKeyDown event before any other events. Note that if we're in a
// composition, we've already dispatched eKeyDown event from
// TextInputHandler::HandleKeyDownEvent(). On the other hand, if we're
// not in composition, the key event starts new composition. So, we
// need to mark the eKeyDown event as "processed by IME".
if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(true)) {
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::SetMarkedText, eKeyDown caused focus move or "
"something and canceling the composition",
this));
return;
}
}
if (Destroyed()) {
return;
}
// First, commit current composition with the latest composition string if the
// replacement range is different from marked range.
if (IsIMEComposing() && aReplacementRange &&
aReplacementRange->location != NSNotFound &&
!NSEqualRanges(MarkedRange(), *aReplacementRange)) {
AutoRestore<bool> ignoreIMECommit(mIgnoreIMECommit);
mIgnoreIMECommit = false;
if (!DispatchCompositionCommitEvent()) {
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::SetMarkedText, "
"destroyed by commiting composition for setting replacement range",
this));
return;
}
}
nsString str;
CopyNSStringToXPCOMString([aAttrString string], str);
mMarkedRange.length = str.Length();
if (!IsIMEComposing() && !str.IsEmpty()) {
// If there is no selection and replacement range is specified, set the
// range as selection.
if (aReplacementRange && aReplacementRange->location != NSNotFound &&
!NSEqualRanges(SelectedRange(), *aReplacementRange)) {
// Set temporary selection range since OnSelectionChange is async.
mSelectedRange = *aReplacementRange;
if (NS_WARN_IF(!SetSelection(*aReplacementRange))) {
mSelectedRange.location = NSNotFound; // Marking dirty
return;
}
}
mMarkedRange.location = SelectedRange().location;
if (!DispatchCompositionStartEvent()) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::SetMarkedText, cannot continue handling "
"composition after dispatching compositionstart",
this));
return;
}
}
if (!str.IsEmpty()) {
if (!DispatchCompositionChangeEvent(str, aAttrString, aSelectedRange)) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::SetMarkedText, cannot continue handling "
"composition after dispatching compositionchange",
this));
}
return;
}
// If the composition string becomes empty string, we should commit
// current composition.
if (!DispatchCompositionCommitEvent(&EmptyString())) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::SetMarkedText, "
"destroyed by compositioncommit event",
this));
}
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
NSAttributedString* IMEInputHandler::GetAttributedSubstringFromRange(
NSRange& aRange, NSRange* aActualRange) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::GetAttributedSubstringFromRange, aRange=%s, "
"aActualRange=%p, Destroyed()=%s",
this, ToString(aRange).c_str(), aActualRange, TrueOrFalse(Destroyed())));
if (aActualRange) {
*aActualRange = NSMakeRange(NSNotFound, 0);
}
if (Destroyed() || aRange.location == NSNotFound || aRange.length == 0) {
return nil;
}
RefPtr<IMEInputHandler> kungFuDeathGrip(this);
// If we're in composing, the queried range may be in the composition string.
// In such case, we should use mIMECompositionString since if the composition
// string is handled by a remote process, the content cache may be out of
// date.
// XXX Should we set composition string attributes? Although, Blink claims
// that some attributes of marked text are supported, but they return
// just marked string without any style. So, let's keep current behavior
// at least for now.
NSUInteger compositionLength =
mIMECompositionString ? [mIMECompositionString length] : 0;
if (mIMECompositionStartBeforeStart.isSome() &&
aRange.location >= *mIMECompositionStartBeforeStart &&
aRange.location + aRange.length <=
*mIMECompositionStartBeforeStart + compositionLength) {
NSRange range = NSMakeRange(
aRange.location - *mIMECompositionStartBeforeStart, aRange.length);
NSString* nsstr = [mIMECompositionString substringWithRange:range];
NSMutableAttributedString* result =
[[[NSMutableAttributedString alloc] initWithString:nsstr
attributes:nil] autorelease];
// XXX We cannot return font information in this case. However, this
// case must occur only when IME tries to confirm if composing string
// is handled as expected.
if (aActualRange) {
*aActualRange = aRange;
}
if (MOZ_LOG_TEST(gIMELog, LogLevel::Info)) {
nsAutoString str;
CopyNSStringToXPCOMString(nsstr, str);
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::GetAttributedSubstringFromRange, "
"computed with mIMECompositionString (result string=\"%s\")",
this, NS_ConvertUTF16toUTF8(str).get()));
}
return result;
}
nsAutoString str;
WidgetQueryContentEvent queryTextContentEvent(true, eQueryTextContent,
mWidget);
WidgetQueryContentEvent::Options options;
int64_t startOffset = aRange.location;
if (mIMECompositionStartBeforeStart.isSome()) {
// The composition may be at different offset from the selection start
// offset at dispatching compositionstart because start of composition
// is fixed when composition string becomes non-empty in the editor.
// Therefore, we need to use query event which is relative to insertion
// point.
options.mRelativeToInsertionPoint = true;
startOffset -= *mIMECompositionStartBeforeStart;
}
queryTextContentEvent.InitForQueryTextContent(startOffset, aRange.length,
options);
queryTextContentEvent.RequestFontRanges();
DispatchEvent(queryTextContentEvent);
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::GetAttributedSubstringFromRange, "
"queryTextContentEvent={ mReply=%s }",
this, ToString(queryTextContentEvent.mReply).c_str()));
if (queryTextContentEvent.Failed()) {
return nil;
}
// We don't set vertical information at this point. If required,
// OS will calls drawsVerticallyForCharacterAtIndex.
NSMutableAttributedString* result =
nsCocoaUtils::GetNSMutableAttributedString(
queryTextContentEvent.mReply->DataRef(),
queryTextContentEvent.mReply->mFontRanges, false,
mWidget->BackingScaleFactor());
if (aActualRange) {
*aActualRange =
MakeNSRangeFrom(queryTextContentEvent.mReply->mOffsetAndData);
}
return result;
NS_OBJC_END_TRY_BLOCK_RETURN(nil);
}
bool IMEInputHandler::HasMarkedText() {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::HasMarkedText, mMarkedRange=%s", this,
ToString(mMarkedRange).c_str()));
return (mMarkedRange.location != NSNotFound) && (mMarkedRange.length != 0);
}
NSRange IMEInputHandler::MarkedRange() {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::MarkedRange, mMarkedRange=%s", this,
ToString(mMarkedRange).c_str()));
if (!HasMarkedText()) {
return NSMakeRange(NSNotFound, 0);
}
// XXX If MarkedRange() is requred by IME, we could return actual range in
// content. If we do that, IME can interact with the latest content
// information. E.g., actual surrounding text which may have already been
// modified by the web apps during the composition. On the other hand,
// there is no way to notify IME of when it's updated. Therefore, if
// `SelectedRange()` is called before `MarkedRange()`, the ranges will
// mismatch in IME. Therefore, probably we should not do that.
return mMarkedRange;
}
NSRange IMEInputHandler::SelectedRange() {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::SelectedRange, Destroyed()=%s, "
"mSelectedRange=%s, mSelectedRangeOverride=%s",
this, TrueOrFalse(Destroyed()), ToString(mSelectedRange).c_str(),
ToString(mSelectedRangeOverride).c_str()));
// If selection range is overridden during a composition, we should return the
// override instead of selected range in the content. That makes IME work
// without confusion even if IME caches the compositing range at starting
// composition and the web app changes the preceding text of the composition.
if (mSelectedRangeOverride.isSome()) {
return *mSelectedRangeOverride;
}
if (Destroyed()) {
return mSelectedRange;
}
if (mSelectedRange.location != NSNotFound) {
MOZ_ASSERT(mIMEHasFocus);
return mSelectedRange;
}
RefPtr<IMEInputHandler> kungFuDeathGrip(this);
WidgetQueryContentEvent querySelectedTextEvent(true, eQuerySelectedText,
mWidget);
DispatchEvent(querySelectedTextEvent);
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::SelectedRange, querySelectedTextEvent={ "
"mReply=%s }",
this, ToString(querySelectedTextEvent.mReply).c_str()));
if (querySelectedTextEvent.Failed()) {
return mSelectedRange;
}
mWritingMode = querySelectedTextEvent.mReply->WritingModeRef();
mRangeForWritingMode =
MakeNSRangeFrom(querySelectedTextEvent.mReply->mOffsetAndData);
if (mIMEHasFocus) {
mSelectedRange = mRangeForWritingMode;
}
return mRangeForWritingMode;
NS_OBJC_END_TRY_BLOCK_RETURN(mSelectedRange);
}
bool IMEInputHandler::DrawsVerticallyForCharacterAtIndex(uint32_t aCharIndex) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
if (Destroyed()) {
return false;
}
if (mRangeForWritingMode.location == NSNotFound) {
// Update cached writing-mode value for the current selection.
SelectedRange();
}
if (aCharIndex < mRangeForWritingMode.location ||
aCharIndex >
mRangeForWritingMode.location + mRangeForWritingMode.length) {
// It's not clear to me whether this ever happens in practice, but if an
// IME ever wants to query writing mode at an offset outside the current
// selection, the writing-mode value may not be correct for the index.
// In that case, use FirstRectForCharacterRange to get a fresh value.
// This does more work than strictly necessary (we don't need the rect
// here), but should be a rare case.
NS_WARNING(
"DrawsVerticallyForCharacterAtIndex not using cached writing mode");
NSRange range = NSMakeRange(aCharIndex, 1);
NSRange actualRange;
FirstRectForCharacterRange(range, &actualRange);
}
return mWritingMode.IsVertical();
NS_OBJC_END_TRY_BLOCK_RETURN(false);
}
NSRect IMEInputHandler::FirstRectForCharacterRange(NSRange& aRange,
NSRange* aActualRange) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::FirstRectForCharacterRange, Destroyed()=%s, "
"aRange=%s, aActualRange=%p }",
this, TrueOrFalse(Destroyed()), ToString(aRange).c_str(), aActualRange));
// XXX this returns first character rect or caret rect, it is limitation of
// now. We need more work for returns first line rect. But current
// implementation is enough for IMEs.
NSRect rect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
NSRange actualRange = NSMakeRange(NSNotFound, 0);
if (aActualRange) {
*aActualRange = actualRange;
}
if (Destroyed() || aRange.location == NSNotFound) {
return rect;
}
RefPtr<IMEInputHandler> kungFuDeathGrip(this);
LayoutDeviceIntRect r;
bool useCaretRect = (aRange.length == 0);
if (!useCaretRect) {
WidgetQueryContentEvent queryTextRectEvent(true, eQueryTextRect, mWidget);
WidgetQueryContentEvent::Options options;
int64_t startOffset = aRange.location;
if (mIMECompositionStartBeforeStart.isSome()) {
// The composition may be at different offset from the selection start
// offset at dispatching compositionstart because start of composition
// is fixed when composition string becomes non-empty in the editor.
// Therefore, we need to use query event which is relative to insertion
// point.
options.mRelativeToInsertionPoint = true;
startOffset -= *mIMECompositionStartBeforeStart;
}
queryTextRectEvent.InitForQueryTextRect(startOffset, 1, options);
DispatchEvent(queryTextRectEvent);
if (queryTextRectEvent.Succeeded()) {
r = queryTextRectEvent.mReply->mRect;
actualRange = MakeNSRangeFrom(queryTextRectEvent.mReply->mOffsetAndData);
mWritingMode = queryTextRectEvent.mReply->WritingModeRef();
mRangeForWritingMode = actualRange;
} else {
useCaretRect = true;
}
}
if (useCaretRect) {
WidgetQueryContentEvent queryCaretRectEvent(true, eQueryCaretRect, mWidget);
WidgetQueryContentEvent::Options options;
int64_t startOffset = aRange.location;
if (mIMECompositionStartBeforeStart.isSome()) {
// The composition may be at different offset from the selection start
// offset at dispatching compositionstart because start of composition
// is fixed when composition string becomes non-empty in the editor.
// Therefore, we need to use query event which is relative to insertion
// point.
options.mRelativeToInsertionPoint = true;
startOffset -= *mIMECompositionStartBeforeStart;
}
queryCaretRectEvent.InitForQueryCaretRect(startOffset, options);
DispatchEvent(queryCaretRectEvent);
if (queryCaretRectEvent.Failed()) {
return rect;
}
r = queryCaretRectEvent.mReply->mRect;
r.width = 0;
actualRange.location = queryCaretRectEvent.mReply->StartOffset();
actualRange.length = 0;
}
// Widget relative -> Screen relative.
r += mWidget->WidgetToScreenOffset();
rect = nsCocoaUtils::GeckoRectToCocoaRectDevPix(
r, mWidget->BackingScaleFactor());
if (aActualRange) {
*aActualRange = actualRange;
}
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::FirstRectForCharacterRange, useCaretRect=%s "
"rect={ x=%f, y=%f, width=%f, height=%f }, actualRange=%s",
this, TrueOrFalse(useCaretRect), rect.origin.x, rect.origin.y,
rect.size.width, rect.size.height, ToString(actualRange).c_str()));
return rect;
NS_OBJC_END_TRY_BLOCK_RETURN(NSMakeRect(0.0, 0.0, 0.0, 0.0));
}
NSUInteger IMEInputHandler::CharacterIndexForPoint(NSPoint& aPoint) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::CharacterIndexForPoint, aPoint={ x=%f, y=%f }",
this, aPoint.x, aPoint.y));
NSWindow* mainWindow = [NSApp mainWindow];
if (!mWidget || !mainWindow) {
return NSNotFound;
}
WidgetQueryContentEvent queryCharAtPointEvent(true, eQueryCharacterAtPoint,
mWidget);
NSPoint ptInWindow = nsCocoaUtils::ConvertPointFromScreen(mainWindow, aPoint);
NSPoint ptInView = [mView convertPoint:ptInWindow fromView:nil];
queryCharAtPointEvent.mRefPoint.x =
static_cast<int32_t>(ptInView.x * mWidget->BackingScaleFactor());
queryCharAtPointEvent.mRefPoint.y =
static_cast<int32_t>(ptInView.y * mWidget->BackingScaleFactor());
mWidget->DispatchWindowEvent(queryCharAtPointEvent);
if (queryCharAtPointEvent.Failed() ||
queryCharAtPointEvent.DidNotFindChar() ||
queryCharAtPointEvent.mReply->StartOffset() >=
static_cast<uint32_t>(NSNotFound)) {
return NSNotFound;
}
return queryCharAtPointEvent.mReply->StartOffset();
NS_OBJC_END_TRY_BLOCK_RETURN(NSNotFound);
}
extern "C" {
extern NSString* NSTextInputReplacementRangeAttributeName;
}
NSArray* IMEInputHandler::GetValidAttributesForMarkedText() {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::GetValidAttributesForMarkedText", this));
// Return same attributes as Chromium (see render_widget_host_view_mac.mm)
// because most IMEs must be tested with Safari (OS default) and Chrome
// (having most market share). Therefore, we need to follow their behavior.
// XXX It might be better to reuse an array instance for this result because
// this may be called a lot. Note that Chromium does so.
return
[NSArray arrayWithObjects:NSUnderlineStyleAttributeName,
NSUnderlineColorAttributeName,
NSMarkedClauseSegmentAttributeName,
NSTextInputReplacementRangeAttributeName, nil];
NS_OBJC_END_TRY_BLOCK_RETURN(nil);
}
#pragma mark -
/******************************************************************************
*
* IMEInputHandler implementation #2
*
******************************************************************************/
IMEInputHandler::IMEInputHandler(nsCocoaWindow* aWidget,
NSView<mozView>* aNativeView)
: TextInputHandlerBase(aWidget, aNativeView),
mPendingMethods(0),
mCandidatedTextSubstitutionResult(nullptr),
mProcessTextSubstitution(false),
mRangeForWritingMode(),
mIsIMEComposing(false),
mIsDeadKeyComposing(false),
mIsIMEEnabled(true),
mIsASCIICapableOnly(false),
mIgnoreIMECommit(false),
mIMEHasFocus(false),
mEnableTextSubstitution(false) {
InitStaticMembers();
mMarkedRange.location = NSNotFound;
mMarkedRange.length = 0;
mSelectedRange.location = NSNotFound;
mSelectedRange.length = 0;
}
IMEInputHandler::~IMEInputHandler() {
if (mTimer) {
mTimer->Cancel();
mTimer = nullptr;
}
if (sFocusedIMEHandler == this) {
sFocusedIMEHandler = nullptr;
}
if (mIMECompositionString) {
[mIMECompositionString release];
mIMECompositionString = nullptr;
}
}
void IMEInputHandler::OnFocusChangeInGecko(bool aFocus) {
MOZ_LOG(
gIMELog, LogLevel::Info,
("%p IMEInputHandler::OnFocusChangeInGecko, aFocus=%s, Destroyed()=%s, "
"sFocusedIMEHandler=%p",
this, TrueOrFalse(aFocus), TrueOrFalse(Destroyed()),
sFocusedIMEHandler));
mSelectedRange.location = NSNotFound; // Marking dirty
mIMEHasFocus = aFocus;
DismissTextSubstitutionPanel();
// This is called when the native focus is changed and when the native focus
// isn't changed but the focus is changed in Gecko.
if (!aFocus) {
if (sFocusedIMEHandler == this) sFocusedIMEHandler = nullptr;
return;
}
sFocusedIMEHandler = this;
// We need to notify IME of focus change in Gecko as native focus change
// because the window level of the focused element in Gecko may be changed.
mPendingMethods |= kNotifyIMEOfFocusChangeInGecko;
ResetTimer();
}
bool IMEInputHandler::OnDestroyWidget(nsCocoaWindow* aDestroyingWidget) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::OnDestroyWidget, aDestroyingWidget=%p, "
"sFocusedIMEHandler=%p, IsIMEComposing()=%s",
this, aDestroyingWidget, sFocusedIMEHandler,
TrueOrFalse(IsIMEComposing())));
// If we're not focused, the focused IMEInputHandler may have been
// created by another widget/nsCocoaWindow.
if (sFocusedIMEHandler && sFocusedIMEHandler != this) {
sFocusedIMEHandler->OnDestroyWidget(aDestroyingWidget);
}
if (!TextInputHandlerBase::OnDestroyWidget(aDestroyingWidget)) {
return false;
}
if (IsIMEComposing()) {
// If our view is in the composition, we should clean up it.
CancelIMEComposition();
}
mSelectedRange.location = NSNotFound; // Marking dirty
mIMEHasFocus = false;
return true;
}
void IMEInputHandler::SendCommittedText(NSString* aString) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::SendCommittedText, mView=%p, mWidget=%p, "
"inputContext=%p, mIsIMEComposing=%s",
this, mView, mWidget, mView ? [mView inputContext] : nullptr,
TrueOrFalse(mIsIMEComposing)));
NS_ENSURE_TRUE(mWidget, );
// XXX We should send the string without mView.
if (!mView) {
return;
}
if ([mView conformsToProtocol:@protocol(NSTextInputClient)]) {
NSObject<NSTextInputClient>* textInputClient =
static_cast<NSObject<NSTextInputClient>*>(mView);
[textInputClient insertText:aString
replacementRange:NSMakeRange(NSNotFound, 0)];
}
// Last resort. If we cannot retrieve NSTextInputProtocol from mView
// or blocking to call our InsertText(), we should call InsertText()
// directly to commit composition forcibly.
if (mIsIMEComposing) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::SendCommittedText, trying to insert text "
"directly "
"due to IME not calling our InsertText()",
this));
static_cast<TextInputHandler*>(this)->InsertText(aString);
MOZ_ASSERT(!mIsIMEComposing);
}
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void IMEInputHandler::KillIMEComposition() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::KillIMEComposition, mView=%p, mWidget=%p, "
"inputContext=%p, mIsIMEComposing=%s, "
"Destroyed()=%s, IsFocused()=%s",
this, mView, mWidget, mView ? [mView inputContext] : nullptr,
TrueOrFalse(mIsIMEComposing), TrueOrFalse(Destroyed()),
TrueOrFalse(IsFocused())));
if (Destroyed() || NS_WARN_IF(!mView)) {
return;
}
NSTextInputContext* inputContext = [mView inputContext];
if (NS_WARN_IF(!inputContext)) {
return;
}
[inputContext discardMarkedText];
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void IMEInputHandler::CommitIMEComposition() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::CommitIMEComposition, mIMECompositionString=%s",
this, GetCharacters(mIMECompositionString)));
// If this is called before dispatching eCompositionStart, IsIMEComposing()
// returns false. Even in such case, we need to commit composition *in*
// IME if this is called by preceding eKeyDown event of eCompositionStart.
// So, we need to call KillIMEComposition() even when IsIMEComposing()
// returns false.
KillIMEComposition();
if (!IsIMEComposing()) return;
// If the composition is still there, KillIMEComposition only kills the
// composition in TSM. We also need to finish the our composition too.
SendCommittedText(mIMECompositionString);
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void IMEInputHandler::CancelIMEComposition() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (!IsIMEComposing()) return;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::CancelIMEComposition, mIMECompositionString=%s",
this, GetCharacters(mIMECompositionString)));
// For canceling the current composing, we need to ignore the param of
// insertText. But this code is ugly...
mIgnoreIMECommit = true;
KillIMEComposition();
mIgnoreIMECommit = false;
if (!IsIMEComposing()) return;
// If the composition is still there, KillIMEComposition only kills the
// composition in TSM. We also need to kill the our composition too.
SendCommittedText(@"");
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
bool IMEInputHandler::IsFocused() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
NS_ENSURE_TRUE(!Destroyed(), false);
NSWindow* window = [mView window];
NS_ENSURE_TRUE(window, false);
return [window firstResponder] == mView && [window isKeyWindow] &&
[[NSApplication sharedApplication] isActive];
NS_OBJC_END_TRY_BLOCK_RETURN(false);
}
bool IMEInputHandler::IsIMEOpened() {
TISInputSourceWrapper tis;
tis.InitByCurrentInputSource();
return tis.IsOpenedIMEMode();
}
void IMEInputHandler::SetASCIICapableOnly(bool aASCIICapableOnly) {
if (aASCIICapableOnly == mIsASCIICapableOnly) return;
CommitIMEComposition();
mIsASCIICapableOnly = aASCIICapableOnly;
SyncASCIICapableOnly();
}
void IMEInputHandler::EnableIME(bool aEnableIME) {
if (aEnableIME == mIsIMEEnabled) return;
CommitIMEComposition();
mIsIMEEnabled = aEnableIME;
}
void IMEInputHandler::SetIMEOpenState(bool aOpenIME) {
if (!IsFocused() || IsIMEOpened() == aOpenIME) return;
if (!aOpenIME) {
TISInputSourceWrapper tis;
tis.InitByCurrentASCIICapableInputSource();
tis.Select();
return;
}
// If we know the latest IME opened mode, we should select it.
if (sLatestIMEOpenedModeInputSourceID) {
TISInputSourceWrapper tis;
tis.InitByInputSourceID(sLatestIMEOpenedModeInputSourceID);
tis.Select();
return;
}
// XXX If the current input source is a mode of IME, we should turn on it,
// but we haven't found such way...
// Finally, we should refer the system locale but this is a little expensive,
// we shouldn't retry this (if it was succeeded, we already set
// sLatestIMEOpenedModeInputSourceID at that time).
static bool sIsPrefferredIMESearched = false;
if (sIsPrefferredIMESearched) return;
sIsPrefferredIMESearched = true;
OpenSystemPreferredLanguageIME();
}
void IMEInputHandler::OpenSystemPreferredLanguageIME() {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::OpenSystemPreferredLanguageIME", this));
CFArrayRef langList = ::CFLocaleCopyPreferredLanguages();
if (!langList) {
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::OpenSystemPreferredLanguageIME, langList "
"is NULL",
this));
return;
}
CFIndex count = ::CFArrayGetCount(langList);
for (CFIndex i = 0; i < count; i++) {
CFLocaleRef locale = ::CFLocaleCreate(
kCFAllocatorDefault,
static_cast<CFStringRef>(::CFArrayGetValueAtIndex(langList, i)));
if (!locale) {
continue;
}
bool changed = false;
CFStringRef lang = static_cast<CFStringRef>(
::CFLocaleGetValue(locale, kCFLocaleLanguageCode));
NS_ASSERTION(lang, "lang is null");
if (lang) {
TISInputSourceWrapper tis;
tis.InitByLanguage(lang);
if (tis.IsOpenedIMEMode()) {
if (MOZ_LOG_TEST(gIMELog, LogLevel::Info)) {
CFStringRef foundTIS;
tis.GetInputSourceID(foundTIS);
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::OpenSystemPreferredLanguageIME, "
"foundTIS=%s, lang=%s",
this, GetCharacters(foundTIS), GetCharacters(lang)));
}
tis.Select();
changed = true;
}
}
::CFRelease(locale);
if (changed) {
break;
}
}
::CFRelease(langList);
}
void IMEInputHandler::OnSelectionChange(
const IMENotification& aIMENotification) {
MOZ_ASSERT(aIMENotification.mSelectionChangeData.IsInitialized());
const IMENotification::SelectionChangeDataBase& selectionChangeData =
aIMENotification.mSelectionChangeData;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p "
"IMEInputHandler::OnSelectionChange(aIMENotification."
"mSelectionChangeData=%s)",
this, ToString(selectionChangeData).c_str()));
// mSelectedRange and mRangeForWritingMode should be the range in the actual
// content. Therefore, they should be maintained here. On the other hand,
// mSelectedRangeOverride needs to keep selection range which is probably
// expected by IME. Therefore, we shouldn't touch the override here.
if (!selectionChangeData.HasRange()) {
mSelectedRange.location = NSNotFound;
mSelectedRange.length = 0;
mRangeForWritingMode.location = NSNotFound;
mRangeForWritingMode.length = 0;
return;
}
mWritingMode = selectionChangeData.GetWritingMode();
mRangeForWritingMode =
NSMakeRange(selectionChangeData.mOffset, selectionChangeData.Length());
if (mIMEHasFocus) {
mSelectedRange = mRangeForWritingMode;
}
}
void IMEInputHandler::OnLayoutChange() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
if (!IsFocused()) {
return;
}
NSTextInputContext* inputContext = [mView inputContext];
[inputContext invalidateCharacterCoordinates];
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
static NSTextCheckingType GetTextCheckingTypes() {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
NSTextCheckingType types = 0;
if (StaticPrefs::widget_macos_automatic_text_replacement() &&
[NSSpellChecker isAutomaticTextReplacementEnabled]) {
types |= NSTextCheckingTypeReplacement;
}
if (StaticPrefs::widget_macos_automatic_quote_substitution() &&
[NSSpellChecker isAutomaticQuoteSubstitutionEnabled]) {
types |= NSTextCheckingTypeQuote;
}
if (StaticPrefs::widget_macos_automatic_dash_substitution() &&
[NSSpellChecker isAutomaticDashSubstitutionEnabled]) {
types |= NSTextCheckingTypeDash;
}
return types;
NS_OBJC_END_TRY_BLOCK_RETURN(0);
}
void IMEInputHandler::OnTextChange(const IMENotification& aIMENotification) {
if (mIMECompositionStartInContent.isSome()) {
mIMECompositionStartInContent =
Some(aIMENotification.mTextChangeData.ComputeNewOffset(
*mIMECompositionStartInContent));
}
HandleTextSubstitution(aIMENotification);
}
void IMEInputHandler::HandleTextSubstitution(
const IMENotification& aIMENotification) {
if (!StaticPrefs::widget_macos_automatic_text_replacement() &&
!StaticPrefs::widget_macos_automatic_quote_substitution() &&
!StaticPrefs::widget_macos_automatic_dash_substitution()) {
return;
}
// Dismiss text substitution panel since this text change might be script etc
if (!mBlockDismissTextSubstitutionPanel) {
mProcessTextSubstitution = false;
DismissTextSubstitutionPanel();
}
// Set new text substitution data to show its panel by current changed text.
//
// We don't handle text substitution when the following.
// - Current input type isn't allowed. Accepted by textarea or
// contenteditable.
// - This inputting is by IME
// - Current text transaction is replacement or deletion.
// - Selection isn't collapsed
if (!mEnableTextSubstitution) {
return;
}
MOZ_LOG(gIMELog, LogLevel::Verbose,
("%p IMEInputHandler::HandleTextSubstitution, "
"aIMENotification.mTextChangeData=%s",
this, ToString(aIMENotification.mTextChangeData).c_str()));
if (aIMENotification.mTextChangeData.mCausedOnlyByComposition) {
return;
}
if (aIMENotification.mTextChangeData.mStartOffset !=
aIMENotification.mTextChangeData.mRemovedEndOffset) {
// Text substitution runs on adding text only
return;
}
NS_DispatchToCurrentThreadQueue(
NewRunnableMethod<uint32_t>(
"IMEInputHandler::OnTextSubstitution", this,
&IMEInputHandler::OnTextSubstitution,
aIMENotification.mTextChangeData.mAddedEndOffset),
100, EventQueuePriority::Idle);
}
void IMEInputHandler::OnTextSubstitution(uint32_t aStartOffset) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::OnTextSubstitution, aStartOffset=%u", this,
aStartOffset));
if (Destroyed() || !IsFocused()) {
return;
}
NSTextCheckingType checkingTypes = GetTextCheckingTypes();
if (!checkingTypes) {
return;
}
// We fetch previous 10 characters to analyze text contextual for text
// replacement.
const uint32_t fetchLength =
StaticPrefs::widget_macos_automatic_text_substitution_fetch_length();
uint32_t startFetch =
std::max<uint32_t>(fetchLength, aStartOffset) - fetchLength;
WidgetQueryContentEvent queryTextContentEvent(true, eQueryTextContent,
mWidget);
WidgetQueryContentEvent::Options options;
queryTextContentEvent.InitForQueryTextContent(
startFetch, aStartOffset - startFetch, options);
DispatchEvent(queryTextContentEvent);
if (NS_WARN_IF(queryTextContentEvent.Failed())) {
return;
}
NSString* str;
if (!queryTextContentEvent.mReply->DataRef().IsEmpty() &&
NS_IS_LOW_SURROGATE(queryTextContentEvent.mReply->DataRef().CharAt(0))) {
str = nsCocoaUtils::ToNSString(
Substring(queryTextContentEvent.mReply->DataRef(), 1));
} else {
str = nsCocoaUtils::ToNSString(queryTextContentEvent.mReply->DataRef());
}
NSSpellChecker* spellchecker = [NSSpellChecker sharedSpellChecker];
if (!spellchecker) {
return;
}
NSArray* results = [spellchecker checkString:str
range:NSMakeRange(0, [str length])
types:checkingTypes
options:nil
inSpellDocumentWithTag:0
orthography:nil
wordCount:nil];
if (!results.count) {
return;
}
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::HandleTextSubstitution, found text "
"substitution for correction.",
this));
NSTextCheckingResult* candidate = nullptr;
for (NSTextCheckingResult* checkingResult in results) {
NSRange candidateRange = checkingResult.range;
if (!NSLocationInRange(
aStartOffset - startFetch,
NSMakeRange(candidateRange.location, candidateRange.length + 1))) {
continue;
}
if (checkingResult.resultType &
(NSTextCheckingTypeQuote | NSTextCheckingTypeDash)) {
// XXX We might have to adjust caret position on out of loop.
// But dash/quote replacement is on caret position now.
const nsDependentSubstring& originalStr =
Substring(queryTextContentEvent.mReply->DataRef(),
candidateRange.location, candidateRange.length);
candidateRange.location += startFetch;
ReplaceTextForTextSubstitution(originalStr,
checkingResult.replacementString,
candidateRange, PreventSetSelection::No);
continue;
}
// Found text replacement data.
candidate = checkingResult;
break;
}
if (!candidate) {
return;
}
// NSTextCheckingResult.range is read only, so re-create this result object.
NSRange candidatedRange = NSMakeRange(candidate.range.location + startFetch,
candidate.range.length);
mCandidatedTextSubstitutionResult = [[NSTextCheckingResult
correctionCheckingResultWithRange:candidatedRange
replacementString:candidate.replacementString
alternativeStrings:candidate.alternativeStrings] retain];
mOriginalTextForTextSubstitution =
Substring(queryTextContentEvent.mReply->DataRef(),
candidatedRange.location - startFetch, candidatedRange.length);
// Allow to work text substitution for mouse operation. If any key event is
// dispatched, mProcessTextSubstitution will be updated.
mProcessTextSubstitution = true;
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void IMEInputHandler::ShowTextSubstitutionPanel() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::ShowTextSubstitutionPanel", this));
if (!mCandidatedTextSubstitutionResult) {
return;
}
// We won't get text rect of non-composition string on e10s. So we get caret
// rect instead.
NSRect rect = [&]() {
WidgetQueryContentEvent queryCaretRectEvent(true, eQueryCaretRect, mWidget);
WidgetQueryContentEvent::Options options;
queryCaretRectEvent.InitForQueryCaretRect(
mCandidatedTextSubstitutionResult.range.location +
mCandidatedTextSubstitutionResult.range.length,
options);
DispatchEvent(queryCaretRectEvent);
if (queryCaretRectEvent.Succeeded()) {
LayoutDeviceIntRect r = queryCaretRectEvent.mReply->mRect;
return nsCocoaUtils::DevPixelsToCocoaPoints(
r, mWidget->BackingScaleFactor());
}
return NSMakeRect(0, 0, 0, 0);
}();
if (Destroyed()) {
return;
}
uint32_t replacementLocation =
mCandidatedTextSubstitutionResult.range.location;
NSSpellChecker* spellchecker = [NSSpellChecker sharedSpellChecker];
if (!spellchecker) {
return;
}
[spellchecker
showCorrectionIndicatorOfType:NSCorrectionIndicatorTypeDefault
primaryString:mCandidatedTextSubstitutionResult
.replacementString
alternativeStrings:mCandidatedTextSubstitutionResult
.alternativeStrings
forStringInRect:rect
view:mView
completionHandler:^(NSString* aAcceptedString) {
// This is always called when panel is closed.
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::ShowTextSubstitutionPanel, "
"dismissing correction panel",
this));
if (!mProcessTextSubstitution) {
return;
}
mProcessTextSubstitution = false;
// Replace text when this panel is closed by space or return
// key.
if (!aAcceptedString || Destroyed() || !IsFocused() ||
mOriginalTextForTextSubstitution.IsEmpty()) {
return;
}
NSRange replacementRange =
NSMakeRange(replacementLocation,
mOriginalTextForTextSubstitution.Length());
// Do replace text then set caret to new position
ReplaceTextForTextSubstitution(
mOriginalTextForTextSubstitution, aAcceptedString,
replacementRange, PreventSetSelection::Yes);
mOriginalTextForTextSubstitution.Truncate();
}];
[mCandidatedTextSubstitutionResult release];
mCandidatedTextSubstitutionResult = nullptr;
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void IMEInputHandler::DismissTextSubstitutionPanel() {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::DismissTextSubstitutionPanel, "
"mProcessTextSubstitution=%s",
this, mProcessTextSubstitution ? "true" : "false"));
NSSpellChecker* spellchecker = [NSSpellChecker sharedSpellChecker];
if (!spellchecker) {
return;
}
[spellchecker dismissCorrectionIndicatorForView:mView];
if (mCandidatedTextSubstitutionResult) {
[mCandidatedTextSubstitutionResult release];
mCandidatedTextSubstitutionResult = nullptr;
}
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void IMEInputHandler::ReplaceTextForTextSubstitution(
const nsAString& aOriginalString, NSString* aNewString,
const NSRange& aRange, PreventSetSelection aPreventSetSelection) {
nsAutoString insertStr;
nsCocoaUtils::GetStringForNSString(aNewString, insertStr);
MOZ_LOG(gIMELog, LogLevel::Info,
("%p IMEInputHandler::ReplaceTextForTextsubstitution, "
"aOriginalString=\"%s\", aNewString=\"%s\", aRange=%s",
this, NS_ConvertUTF16toUTF8(aOriginalString).get(),
NS_ConvertUTF16toUTF8(insertStr).get(), ToString(aRange).c_str()));
WidgetContentCommandEvent replaceTextEvent(true, eContentCommandReplaceText,
mWidget);
replaceTextEvent.mString = Some(insertStr);
replaceTextEvent.mSelection.mReplaceSrcString = aOriginalString;
replaceTextEvent.mSelection.mOffset = aRange.location;
replaceTextEvent.mSelection.mPreventSetSelection =
aPreventSetSelection == PreventSetSelection::Yes;
DispatchEvent(replaceTextEvent);
if (!replaceTextEvent.mSucceeded || Destroyed()) {
MOZ_LOG(
gIMELog, LogLevel::Error,
("%p IMEInputHandler::ReplaceTextForTextsubstitution, FAILED", this));
}
}
bool IMEInputHandler::OnHandleEvent(NSEvent* aEvent) {
if (!IsFocused()) {
return false;
}
bool allowConsumeEvent = true;
if (!IsIMEComposing()) {
// Hack for bug of Korean IMEs on Catalina (10.15).
// If we are inactivated during composition, active Korean IME keeps
// consuming all mousedown events of any mouse buttons. So, we should
// allow Korean IMEs to handle mousedown events only when there is
// composition string.
// List of ID of Korean IME:
// * com.apple.inputmethod.Korean.2SetKorean
// * com.apple.inputmethod.Korean.3SetKorean
// * com.apple.inputmethod.Korean.390Sebulshik
// * com.apple.inputmethod.Korean.GongjinCheongRomaja
// * com.apple.inputmethod.Korean.HNCRomaja
TISInputSourceWrapper tis;
tis.InitByCurrentInputSource();
nsAutoString inputSourceID;
tis.GetInputSourceID(inputSourceID);
allowConsumeEvent =
!StringBeginsWith(inputSourceID, u"com.apple.inputmethod.Korean."_ns);
}
NSTextInputContext* inputContext = [mView inputContext];
return [inputContext handleEvent:aEvent] && allowConsumeEvent;
}
#pragma mark -
/******************************************************************************
*
* TextInputHandlerBase implementation
*
******************************************************************************/
int32_t TextInputHandlerBase::sSecureEventInputCount = 0;
NS_IMPL_ISUPPORTS(TextInputHandlerBase, TextEventDispatcherListener,
nsISupportsWeakReference)
TextInputHandlerBase::TextInputHandlerBase(nsCocoaWindow* aWidget,
NSView<mozView>* aNativeView)
: mWidget(aWidget), mDispatcher(aWidget->GetTextEventDispatcher()) {
gHandlerInstanceCount++;
mView = [aNativeView retain];
}
TextInputHandlerBase::~TextInputHandlerBase() {
[mView release];
if (--gHandlerInstanceCount == 0) {
TISInputSourceWrapper::Shutdown();
}
}
bool TextInputHandlerBase::OnDestroyWidget(nsCocoaWindow* aDestroyingWidget) {
MOZ_LOG_KEY_OR_IME(LogLevel::Info,
("%p TextInputHandlerBase::OnDestroyWidget, "
"aDestroyingWidget=%p, mWidget=%p",
this, aDestroyingWidget, mWidget));
if (aDestroyingWidget != mWidget) {
return false;
}
mWidget = nullptr;
mDispatcher = nullptr;
return true;
}
bool TextInputHandlerBase::DispatchEvent(WidgetGUIEvent& aEvent) {
return mWidget->DispatchWindowEvent(aEvent);
}
void TextInputHandlerBase::InitKeyEvent(NSEvent* aNativeKeyEvent,
WidgetKeyboardEvent& aKeyEvent,
bool aIsProcessedByIME,
const nsAString* aInsertString) {
NS_ASSERTION(aNativeKeyEvent, "aNativeKeyEvent must not be NULL");
if (mKeyboardOverride.mOverrideEnabled) {
TISInputSourceWrapper tis;
tis.InitByLayoutID(mKeyboardOverride.mKeyboardLayout, true);
tis.InitKeyEvent(aNativeKeyEvent, aKeyEvent, aIsProcessedByIME,
aInsertString);
return;
}
TISInputSourceWrapper::CurrentInputSource().InitKeyEvent(
aNativeKeyEvent, aKeyEvent, aIsProcessedByIME, aInsertString);
}
nsresult TextInputHandlerBase::SynthesizeNativeKeyEvent(
int32_t aNativeKeyboardLayout, int32_t aNativeKeyCode,
uint32_t aModifierFlags, const nsAString& aCharacters,
const nsAString& aUnmodifiedCharacters) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
uint32_t modifierFlags =
nsCocoaUtils::ConvertWidgetModifiersToMacModifierFlags(
static_cast<nsIWidget::Modifiers>(aModifierFlags));
NSInteger windowNumber = [[mView window] windowNumber];
bool sendFlagsChangedEvent = IsModifierKey(aNativeKeyCode);
NSEventType eventType =
sendFlagsChangedEvent ? NSEventTypeFlagsChanged : NSEventTypeKeyDown;
NSEvent* downEvent = [NSEvent
keyEventWithType:eventType
location:NSMakePoint(0, 0)
modifierFlags:modifierFlags
timestamp:0
windowNumber:windowNumber
context:nil
characters:XPCOMStringToNSString(aCharacters)
charactersIgnoringModifiers:XPCOMStringToNSString(aUnmodifiedCharacters)
isARepeat:NO
keyCode:aNativeKeyCode];
NSEvent* upEvent = sendFlagsChangedEvent
? nil
: nsCocoaUtils::MakeNewCocoaEventWithType(
NSEventTypeKeyUp, downEvent);
if (downEvent && (sendFlagsChangedEvent || upEvent)) {
KeyboardLayoutOverride currentLayout = mKeyboardOverride;
mKeyboardOverride.mKeyboardLayout = aNativeKeyboardLayout;
mKeyboardOverride.mOverrideEnabled = true;
[NSApp sendEvent:downEvent];
if (upEvent) {
[NSApp sendEvent:upEvent];
}
// processKeyDownEvent and keyUp block exceptions so we're sure to
// reach here to restore mKeyboardOverride
mKeyboardOverride = currentLayout;
}
return NS_OK;
NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
}
NSInteger TextInputHandlerBase::GetWindowLevel() {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
MOZ_LOG_KEY_OR_IME(LogLevel::Info,
("%p TextInputHandlerBase::GetWindowLevel, Destryoed()=%s",
this, TrueOrFalse(Destroyed())));
if (Destroyed()) {
return NSNormalWindowLevel;
}
// When an <input> element on a XUL <panel> is focused, the actual focused
// view is the panel's parent view (mView). But the editor is displayed on the
// popped-up widget's view (editorView). We want the latter's window level.
NSView<mozView>* editorView = mWidget->GetEditorView();
NS_ENSURE_TRUE(editorView, NSNormalWindowLevel);
NSInteger windowLevel = [[editorView window] level];
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandlerBase::GetWindowLevel, windowLevel=%s (%lX)", this,
GetWindowLevelName(windowLevel),
static_cast<unsigned long>(windowLevel)));
return windowLevel;
NS_OBJC_END_TRY_BLOCK_RETURN(NSNormalWindowLevel);
}
NS_IMETHODIMP
TextInputHandlerBase::AttachNativeKeyEvent(WidgetKeyboardEvent& aKeyEvent) {
NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
// Don't try to replace a native event if one already exists.
// OS X doesn't have an OS modifier, can't make a native event.
if (aKeyEvent.mNativeKeyEvent) {
return NS_OK;
}
MOZ_LOG_KEY_OR_IME(
LogLevel::Info,
("%p TextInputHandlerBase::AttachNativeKeyEvent, key=0x%X, char=0x%X, "
"mod=0x%X",
this, aKeyEvent.mKeyCode, aKeyEvent.mCharCode, aKeyEvent.mModifiers));
NSInteger windowNumber = [[mView window] windowNumber];
NSGraphicsContext* context = [NSGraphicsContext currentContext];
aKeyEvent.mNativeKeyEvent = nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(
aKeyEvent, windowNumber, context);
return NS_OK;
NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
}
bool TextInputHandlerBase::SetSelection(NSRange& aRange) {
MOZ_ASSERT(!Destroyed());
RefPtr<TextInputHandlerBase> kungFuDeathGrip(this);
WidgetSelectionEvent selectionEvent(true, eSetSelection, mWidget);
selectionEvent.mOffset = aRange.location;
selectionEvent.mLength = aRange.length;
selectionEvent.mReversed = false;
selectionEvent.mExpandToClusterBoundary = false;
DispatchEvent(selectionEvent);
NS_ENSURE_TRUE(selectionEvent.mSucceeded, false);
return !Destroyed();
}
/* static */ bool TextInputHandlerBase::IsPrintableChar(char16_t aChar) {
return (aChar >= 0x20 && aChar <= 0x7E) || aChar >= 0xA0;
}
/* static */ bool TextInputHandlerBase::IsSpecialGeckoKey(
UInt32 aNativeKeyCode) {
// this table is used to determine which keys are special and should not
// generate a charCode
switch (aNativeKeyCode) {
// modifiers - we don't get separate events for these yet
case kVK_Escape:
case kVK_Shift:
case kVK_RightShift:
case kVK_Command:
case kVK_RightCommand:
case kVK_CapsLock:
case kVK_Control:
case kVK_RightControl:
case kVK_Option:
case kVK_RightOption:
case kVK_ANSI_KeypadClear:
case kVK_Function:
// function keys
case kVK_F1:
case kVK_F2:
case kVK_F3:
case kVK_F4:
case kVK_F5:
case kVK_F6:
case kVK_F7:
case kVK_F8:
case kVK_F9:
case kVK_F10:
case kVK_F11:
case kVK_F12:
case kVK_PC_Pause:
case kVK_PC_ScrollLock:
case kVK_PC_PrintScreen:
case kVK_F16:
case kVK_F17:
case kVK_F18:
case kVK_F19:
case kVK_PC_Insert:
case kVK_PC_Delete:
case kVK_Tab:
case kVK_PC_Backspace:
case kVK_PC_ContextMenu:
case kVK_JIS_Eisu:
case kVK_JIS_Kana:
case kVK_Home:
case kVK_End:
case kVK_PageUp:
case kVK_PageDown:
case kVK_LeftArrow:
case kVK_RightArrow:
case kVK_UpArrow:
case kVK_DownArrow:
case kVK_Return:
case kVK_ANSI_KeypadEnter:
case kVK_Powerbook_KeypadEnter:
return true;
}
return false;
}
/* static */ bool TextInputHandlerBase::IsNormalCharInputtingEvent(
NSEvent* aNativeEvent) {
if ([aNativeEvent type] != NSEventTypeKeyDown &&
[aNativeEvent type] != NSEventTypeKeyUp) {
return false;
}
nsAutoString nativeChars;
CopyNSStringToXPCOMString([aNativeEvent characters], nativeChars);
// this is not character inputting event, simply.
if (nativeChars.IsEmpty() ||
([aNativeEvent modifierFlags] & NSEventModifierFlagCommand)) {
return false;
}
return !IsControlChar(nativeChars[0]);
}
/* static */ bool TextInputHandlerBase::IsModifierKey(UInt32 aNativeKeyCode) {
switch (aNativeKeyCode) {
case kVK_CapsLock:
case kVK_RightCommand:
case kVK_Command:
case kVK_Shift:
case kVK_Option:
case kVK_Control:
case kVK_RightShift:
case kVK_RightOption:
case kVK_RightControl:
case kVK_Function:
return true;
}
return false;
}
/* static */ void TextInputHandlerBase::EnableSecureEventInput() {
sSecureEventInputCount++;
::EnableSecureEventInput();
MOZ_LOG(gIMELog, LogLevel::Debug,
("EnableSecureEventInput() called (%d)", sSecureEventInputCount));
}
/* static */ void TextInputHandlerBase::DisableSecureEventInput() {
if (!sSecureEventInputCount) {
return;
}
sSecureEventInputCount--;
::DisableSecureEventInput();
MOZ_LOG(gIMELog, LogLevel::Debug,
("DisableSecureEventInput() called (%d)", sSecureEventInputCount));
}
/* static */ bool TextInputHandlerBase::IsSecureEventInputEnabled() {
// sSecureEventInputCount is our mechanism to track when Secure Event Input
// is enabled. Non-zero indicates we have enabled Secure Input. But
// zero does not mean that Secure Input is _disabled_ because another
// application may have enabled it. If the OS reports Secure Event
// Input is disabled though, a non-zero sSecureEventInputCount is an error.
NS_ASSERTION(::IsSecureEventInputEnabled() || 0 == sSecureEventInputCount,
"sSecureEventInputCount is not zero when the OS thinks "
"SecureEventInput is disabled.");
return !!sSecureEventInputCount;
}
/* static */ void TextInputHandlerBase::EnsureSecureEventInputDisabled() {
while (sSecureEventInputCount) {
TextInputHandlerBase::DisableSecureEventInput();
}
}
#pragma mark -
/******************************************************************************
*
* TextInputHandlerBase::KeyEventState implementation
*
******************************************************************************/
void TextInputHandlerBase::KeyEventState::InitKeyEvent(
TextInputHandlerBase* aHandler, WidgetKeyboardEvent& aKeyEvent,
bool aIsProcessedByIME) {
NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
MOZ_ASSERT(aHandler);
MOZ_RELEASE_ASSERT(mKeyEvent);
NSEvent* nativeEvent = mKeyEvent;
if (!mInsertedString.IsEmpty()) {
nsAutoString unhandledString;
GetUnhandledString(unhandledString);
NSString* unhandledNSString = XPCOMStringToNSString(unhandledString);
// If the key event's some characters were already handled by
// InsertString() calls, we need to create a dummy event which doesn't
// include the handled characters.
nativeEvent =
[NSEvent keyEventWithType:[mKeyEvent type]
location:[mKeyEvent locationInWindow]
modifierFlags:[mKeyEvent modifierFlags]
timestamp:[mKeyEvent timestamp]
windowNumber:[mKeyEvent windowNumber]
context:nil
characters:unhandledNSString
charactersIgnoringModifiers:[mKeyEvent charactersIgnoringModifiers]
isARepeat:[mKeyEvent isARepeat]
keyCode:[mKeyEvent keyCode]];
}
aKeyEvent.mUniqueId = mUniqueId;
aHandler->InitKeyEvent(nativeEvent, aKeyEvent, aIsProcessedByIME,
mInsertString);
NS_OBJC_END_TRY_IGNORE_BLOCK;
}
void TextInputHandlerBase::KeyEventState::GetUnhandledString(
nsAString& aUnhandledString) const {
aUnhandledString.Truncate();
if (NS_WARN_IF(!mKeyEvent)) {
return;
}
nsAutoString characters;
CopyNSStringToXPCOMString([mKeyEvent characters], characters);
if (characters.IsEmpty()) {
return;
}
if (mInsertedString.IsEmpty()) {
aUnhandledString = characters;
return;
}
// The insertes string must match with the start of characters.
MOZ_ASSERT(StringBeginsWith(characters, mInsertedString));
aUnhandledString = nsDependentSubstring(characters, mInsertedString.Length());
}
#pragma mark -
/******************************************************************************
*
* TextInputHandlerBase::AutoInsertStringClearer implementation
*
******************************************************************************/
TextInputHandlerBase::AutoInsertStringClearer::~AutoInsertStringClearer() {
if (mState && mState->mInsertString) {
// If inserting string is a part of characters of the event,
// we should record it as inserted string.
nsAutoString characters;
CopyNSStringToXPCOMString([mState->mKeyEvent characters], characters);
nsAutoString insertedString(mState->mInsertedString);
insertedString += *mState->mInsertString;
if (StringBeginsWith(characters, insertedString)) {
mState->mInsertedString = insertedString;
}
}
if (mState) {
mState->mInsertString = nullptr;
}
}
#undef MOZ_LOG_KEY_OR_IME
|