DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (dcc6d7a0dc00)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sts=2 sw=2 et cin: */
/* 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 "mozilla/Logging.h"

#include "IMMHandler.h"
#include "nsWindow.h"
#include "nsWindowDefs.h"
#include "WinUtils.h"
#include "KeyboardLayout.h"
#include <algorithm>

#include "mozilla/CheckedInt.h"
#include "mozilla/MiscEvents.h"
#include "mozilla/TextEvents.h"

#ifndef IME_PROP_ACCEPT_WIDE_VKEY
#define IME_PROP_ACCEPT_WIDE_VKEY 0x20
#endif

//-------------------------------------------------------------------------
//
// from http://download.microsoft.com/download/6/0/9/60908e9e-d2c1-47db-98f6-216af76a235f/msime.h
// The document for this has been removed from MSDN...
//
//-------------------------------------------------------------------------

#define RWM_MOUSE           TEXT("MSIMEMouseOperation")

#define IMEMOUSE_NONE       0x00    // no mouse button was pushed
#define IMEMOUSE_LDOWN      0x01
#define IMEMOUSE_RDOWN      0x02
#define IMEMOUSE_MDOWN      0x04
#define IMEMOUSE_WUP        0x10    // wheel up
#define IMEMOUSE_WDOWN      0x20    // wheel down

static const char*
GetBoolName(bool aBool)
{
  return aBool ? "true" : "false";
}

static void
HandleSeparator(nsACString& aDesc)
{
  if (!aDesc.IsEmpty()) {
    aDesc.AppendLiteral(" | ");
  }
}

class GetIMEGeneralPropertyName : public nsAutoCString
{
public:
  GetIMEGeneralPropertyName(DWORD aFlags)
  {
    if (!aFlags) {
      AppendLiteral("no flags");
      return;
    }
    if (aFlags & IME_PROP_AT_CARET) {
      AppendLiteral("IME_PROP_AT_CARET");
    }
    if (aFlags & IME_PROP_SPECIAL_UI) {
      HandleSeparator(*this);
      AppendLiteral("IME_PROP_SPECIAL_UI");
    }
    if (aFlags & IME_PROP_CANDLIST_START_FROM_1) {
      HandleSeparator(*this);
      AppendLiteral("IME_PROP_CANDLIST_START_FROM_1");
    }
    if (aFlags & IME_PROP_UNICODE) {
      HandleSeparator(*this);
      AppendLiteral("IME_PROP_UNICODE");
    }
    if (aFlags & IME_PROP_COMPLETE_ON_UNSELECT) {
      HandleSeparator(*this);
      AppendLiteral("IME_PROP_COMPLETE_ON_UNSELECT");
    }
    if (aFlags & IME_PROP_ACCEPT_WIDE_VKEY) {
      HandleSeparator(*this);
      AppendLiteral("IME_PROP_ACCEPT_WIDE_VKEY");
    }
  }
  virtual ~GetIMEGeneralPropertyName() {}
};

class GetIMEUIPropertyName : public nsAutoCString
{
public:
  GetIMEUIPropertyName(DWORD aFlags)
  {
    if (!aFlags) {
      AppendLiteral("no flags");
      return;
    }
    if (aFlags & UI_CAP_2700) {
      AppendLiteral("UI_CAP_2700");
    }
    if (aFlags & UI_CAP_ROT90) {
      HandleSeparator(*this);
      AppendLiteral("UI_CAP_ROT90");
    }
    if (aFlags & UI_CAP_ROTANY) {
      HandleSeparator(*this);
      AppendLiteral("UI_CAP_ROTANY");
    }
  }
  virtual ~GetIMEUIPropertyName() {}
};

class GetWritingModeName : public nsAutoCString
{
public:
  GetWritingModeName(const WritingMode& aWritingMode)
  {
    if (!aWritingMode.IsVertical()) {
      Assign("Horizontal");
      return;
    }
    if (aWritingMode.IsVerticalLR()) {
      Assign("Vertical (LR)");
      return;
    }
    Assign("Vertical (RL)");
  }
  virtual ~GetWritingModeName() {}
};

class GetReconvertStringLog : public nsAutoCString
{
public:
  GetReconvertStringLog(RECONVERTSTRING* aReconv)
  {
    AssignLiteral("{ dwSize=");
    AppendInt(static_cast<uint32_t>(aReconv->dwSize));
    AppendLiteral(", dwVersion=");
    AppendInt(static_cast<uint32_t>(aReconv->dwVersion));
    AppendLiteral(", dwStrLen=");
    AppendInt(static_cast<uint32_t>(aReconv->dwStrLen));
    AppendLiteral(", dwStrOffset=");
    AppendInt(static_cast<uint32_t>(aReconv->dwStrOffset));
    AppendLiteral(", dwCompStrLen=");
    AppendInt(static_cast<uint32_t>(aReconv->dwCompStrLen));
    AppendLiteral(", dwCompStrOffset=");
    AppendInt(static_cast<uint32_t>(aReconv->dwCompStrOffset));
    AppendLiteral(", dwTargetStrLen=");
    AppendInt(static_cast<uint32_t>(aReconv->dwTargetStrLen));
    AppendLiteral(", dwTargetStrOffset=");
    AppendInt(static_cast<uint32_t>(aReconv->dwTargetStrOffset));
    AppendLiteral(", result str=\"");
    if (aReconv->dwStrLen) {
      char16_t* strStart =
        reinterpret_cast<char16_t*>(
          reinterpret_cast<char*>(aReconv) + aReconv->dwStrOffset);
      nsDependentString str(strStart, aReconv->dwStrLen);
      Append(NS_ConvertUTF16toUTF8(str));
    }
    AppendLiteral("\" }");
  }
  virtual ~GetReconvertStringLog() {}
};

namespace mozilla {
namespace widget {

static IMMHandler* gIMMHandler = nullptr;

PRLogModuleInfo* gIMMLog = nullptr;

/******************************************************************************
 * IMEContext
 ******************************************************************************/

IMEContext::IMEContext(HWND aWnd)
  : mWnd(aWnd)
  , mIMC(::ImmGetContext(aWnd))
{
}

IMEContext::IMEContext(nsWindow* aWindow)
  : mWnd(aWindow->GetWindowHandle())
  , mIMC(::ImmGetContext(aWindow->GetWindowHandle()))
{
}

void
IMEContext::Init(HWND aWnd)
{
  Clear();
  mWnd = aWnd;
  mIMC = ::ImmGetContext(mWnd);
}

void
IMEContext::Init(nsWindow* aWindow)
{
  Init(aWindow->GetWindowHandle());
}

void
IMEContext::Clear()
{
  if (mWnd && mIMC) {
    ::ImmReleaseContext(mWnd, mIMC);
  }
  mWnd = nullptr;
  mIMC = nullptr;
}

/******************************************************************************
 * IMMHandler
 ******************************************************************************/

static UINT sWM_MSIME_MOUSE = 0; // mouse message for MSIME 98/2000

WritingMode IMMHandler::sWritingModeOfCompositionFont;
nsString IMMHandler::sIMEName;
UINT IMMHandler::sCodePage = 0;
DWORD IMMHandler::sIMEProperty = 0;
DWORD IMMHandler::sIMEUIProperty = 0;
bool IMMHandler::sAssumeVerticalWritingModeNotSupported = false;
bool IMMHandler::sHasFocus = false;

// static
void
IMMHandler::EnsureHandlerInstance()
{
  if (!gIMMHandler) {
    gIMMHandler = new IMMHandler();
  }
}

// static
void
IMMHandler::Initialize()
{
  if (!gIMMLog) {
    gIMMLog = PR_NewLogModule("nsIMM32HandlerWidgets");
  }
  if (!sWM_MSIME_MOUSE) {
    sWM_MSIME_MOUSE = ::RegisterWindowMessage(RWM_MOUSE);
  }
  sAssumeVerticalWritingModeNotSupported =
    Preferences::GetBool(
      "intl.imm.vertical_writing.always_assume_not_supported", false);
  InitKeyboardLayout(nullptr, ::GetKeyboardLayout(0));
}

// static
void
IMMHandler::Terminate()
{
  if (!gIMMHandler)
    return;
  delete gIMMHandler;
  gIMMHandler = nullptr;
}

// static
bool
IMMHandler::IsComposingOnOurEditor()
{
  return gIMMHandler && gIMMHandler->mIsComposing;
}

// static
bool
IMMHandler::IsComposingOnPlugin()
{
  return gIMMHandler && gIMMHandler->mIsComposingOnPlugin;
}

// static
bool
IMMHandler::IsComposingWindow(nsWindow* aWindow)
{
  return gIMMHandler && gIMMHandler->mComposingWindow == aWindow;
}

// static
bool
IMMHandler::IsTopLevelWindowOfComposition(nsWindow* aWindow)
{
  if (!gIMMHandler || !gIMMHandler->mComposingWindow) {
    return false;
  }
  HWND wnd = gIMMHandler->mComposingWindow->GetWindowHandle();
  return WinUtils::GetTopLevelHWND(wnd, true) == aWindow->GetWindowHandle();
}

// static
bool
IMMHandler::IsJapanist2003Active()
{
  return sIMEName.EqualsLiteral("Japanist 2003");
}

// static
bool
IMMHandler::IsGoogleJapaneseInputActive()
{
  // NOTE: Even on Windows for en-US, the name of Google Japanese Input is
  //       written in Japanese.
  return sIMEName.Equals(L"Google \x65E5\x672C\x8A9E\x5165\x529B "
                         L"IMM32 \x30E2\x30B8\x30E5\x30FC\x30EB");
}

// static
bool
IMMHandler::ShouldDrawCompositionStringOurselves()
{
  // If current IME has special UI or its composition window should not
  // positioned to caret position, we should now draw composition string
  // ourselves.
  return !(sIMEProperty & IME_PROP_SPECIAL_UI) &&
          (sIMEProperty & IME_PROP_AT_CARET);
}

// static
bool
IMMHandler::IsVerticalWritingSupported()
{
  // Even if IME claims that they support vertical writing mode but it may not
  // support vertical writing mode for its candidate window.
  if (sAssumeVerticalWritingModeNotSupported) {
    return false;
  }
  // Google Japanese Input doesn't support vertical writing mode.  We should
  // return false if it's active IME.
  if (IsGoogleJapaneseInputActive()) {
    return false;
  }
  return !!(sIMEUIProperty & (UI_CAP_2700 | UI_CAP_ROT90 | UI_CAP_ROTANY));
}

// static
void
IMMHandler::InitKeyboardLayout(nsWindow* aWindow,
                               HKL aKeyboardLayout)
{
  UINT IMENameLength = ::ImmGetDescriptionW(aKeyboardLayout, nullptr, 0);
  if (IMENameLength) {
    // Add room for the terminating null character
    sIMEName.SetLength(++IMENameLength);
    IMENameLength =
      ::ImmGetDescriptionW(aKeyboardLayout, wwc(sIMEName.BeginWriting()),
                           IMENameLength);
    // Adjust the length to ignore the terminating null character
    sIMEName.SetLength(IMENameLength);
  } else {
    sIMEName.Truncate();
  }

  WORD langID = LOWORD(aKeyboardLayout);
  ::GetLocaleInfoW(MAKELCID(langID, SORT_DEFAULT),
                   LOCALE_IDEFAULTANSICODEPAGE | LOCALE_RETURN_NUMBER,
                   (PWSTR)&sCodePage, sizeof(sCodePage) / sizeof(WCHAR));
  sIMEProperty = ::ImmGetProperty(aKeyboardLayout, IGP_PROPERTY);
  sIMEUIProperty = ::ImmGetProperty(aKeyboardLayout, IGP_UI);

  // If active IME is a TIP of TSF, we cannot retrieve the name with IMM32 API.
  // For hacking some bugs of some TIP, we should set an IME name from the
  // pref.
  if (sCodePage == 932 && sIMEName.IsEmpty()) {
    sIMEName =
      Preferences::GetString("intl.imm.japanese.assume_active_tip_name_as");
  }

  // Whether the IME supports vertical writing mode might be changed or
  // some IMEs may need specific font for their UI.  Therefore, we should
  // update composition font forcibly here.
  if (aWindow) {
    MaybeAdjustCompositionFont(aWindow, sWritingModeOfCompositionFont, true);
  }

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: InitKeyboardLayout, aKeyboardLayout=%08x (\"%s\"), sCodePage=%lu, "
     "sIMEProperty=%s, sIMEUIProperty=%s",
     aKeyboardLayout, NS_ConvertUTF16toUTF8(sIMEName).get(),
     sCodePage, GetIMEGeneralPropertyName(sIMEProperty).get(),
     GetIMEUIPropertyName(sIMEUIProperty).get()));
}

// static
UINT
IMMHandler::GetKeyboardCodePage()
{
  return sCodePage;
}

// static
nsIMEUpdatePreference
IMMHandler::GetIMEUpdatePreference()
{
  return nsIMEUpdatePreference(
    nsIMEUpdatePreference::NOTIFY_POSITION_CHANGE |
    nsIMEUpdatePreference::NOTIFY_SELECTION_CHANGE |
    nsIMEUpdatePreference::NOTIFY_MOUSE_BUTTON_EVENT_ON_CHAR);
}

// used for checking the lParam of WM_IME_COMPOSITION
#define IS_COMPOSING_LPARAM(lParam) \
  ((lParam) & (GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS))
#define IS_COMMITTING_LPARAM(lParam) ((lParam) & GCS_RESULTSTR)
// Some IMEs (e.g., the standard IME for Korean) don't have caret position,
// then, we should not set caret position to compositionchange event.
#define NO_IME_CARET -1

IMMHandler::IMMHandler()
  : mComposingWindow(nullptr)
  , mCursorPosition(NO_IME_CARET)
  , mCompositionStart(0)
  , mIsComposing(false)
  , mIsComposingOnPlugin(false)
  , mNativeCaretIsCreated(false)
{
  MOZ_LOG(gIMMLog, LogLevel::Debug, ("IMM: IMMHandler is created"));
}

IMMHandler::~IMMHandler()
{
  if (mIsComposing) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: ~IMMHandler, ERROR, the instance is still composing"));
  }
  MOZ_LOG(gIMMLog, LogLevel::Debug, ("IMM: IMMHandler is destroyed"));
}

nsresult
IMMHandler::EnsureClauseArray(int32_t aCount)
{
  NS_ENSURE_ARG_MIN(aCount, 0);
  mClauseArray.SetCapacity(aCount + 32);
  return NS_OK;
}

nsresult
IMMHandler::EnsureAttributeArray(int32_t aCount)
{
  NS_ENSURE_ARG_MIN(aCount, 0);
  mAttributeArray.SetCapacity(aCount + 64);
  return NS_OK;
}

// static
void
IMMHandler::CommitComposition(nsWindow* aWindow, bool aForce)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: CommitComposition, aForce=%s, aWindow=%p, hWnd=%08x, "
     "mComposingWindow=%p%s",
     GetBoolName(aForce), aWindow, aWindow->GetWindowHandle(),
     gIMMHandler ? gIMMHandler->mComposingWindow : nullptr,
     gIMMHandler && gIMMHandler->mComposingWindow ?
       IsComposingOnOurEditor() ? " (composing on editor)" :
                                  " (composing on plug-in)" : ""));
  if (!aForce && !IsComposingWindow(aWindow)) {
    return;
  }

  IMEContext context(aWindow);
  bool associated = context.AssociateDefaultContext();
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: CommitComposition, associated=%s",
     GetBoolName(associated)));

  if (context.IsValid()) {
    ::ImmNotifyIME(context.get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
    ::ImmNotifyIME(context.get(), NI_COMPOSITIONSTR, CPS_CANCEL, 0);
  }

  if (associated) {
    context.Disassociate();
  }
}

// static
void
IMMHandler::CancelComposition(nsWindow* aWindow, bool aForce)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: CancelComposition, aForce=%s, aWindow=%p, hWnd=%08x, "
     "mComposingWindow=%p%s",
     GetBoolName(aForce), aWindow, aWindow->GetWindowHandle(),
     gIMMHandler ? gIMMHandler->mComposingWindow : nullptr,
     gIMMHandler && gIMMHandler->mComposingWindow ?
       IsComposingOnOurEditor() ? " (composing on editor)" :
                                  " (composing on plug-in)" : ""));
  if (!aForce && !IsComposingWindow(aWindow)) {
    return;
  }

  IMEContext context(aWindow);
  bool associated = context.AssociateDefaultContext();
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: CancelComposition, associated=%s",
     GetBoolName(associated)));

  if (context.IsValid()) {
    ::ImmNotifyIME(context.get(), NI_COMPOSITIONSTR, CPS_CANCEL, 0);
  }

  if (associated) {
    context.Disassociate();
  }
}

// static
void
IMMHandler::OnFocusChange(bool aFocus, nsWindow* aWindow)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnFocusChange(aFocus=%s, aWindow=%p), sHasFocus=%s, "
     "IsComposingWindow(aWindow)=%s, aWindow->Destroyed()=%s",
     GetBoolName(aFocus), aWindow, GetBoolName(sHasFocus),
     GetBoolName(IsComposingWindow(aWindow)),
     GetBoolName(aWindow->Destroyed())));

  if (!aFocus && IsComposingWindow(aWindow) && aWindow->Destroyed()) {
    CancelComposition(aWindow);
  }
  if (gIMMHandler) {
    gIMMHandler->mSelection.Clear();
  }
  sHasFocus = aFocus;
}

// static
void
IMMHandler::OnUpdateComposition(nsWindow* aWindow)
{
  if (!gIMMHandler) {
    return;
  }
 
  if (aWindow->PluginHasFocus()) {
    return;
  }

  IMEContext context(aWindow);
  gIMMHandler->SetIMERelatedWindowsPos(aWindow, context);
}

// static
void
IMMHandler::OnSelectionChange(nsWindow* aWindow,
                              const IMENotification& aIMENotification,
                              bool aIsIMMActive)
{
  if (!aIMENotification.mSelectionChangeData.mCausedByComposition &&
      aIsIMMActive) {
    MaybeAdjustCompositionFont(aWindow,
      aIMENotification.mSelectionChangeData.GetWritingMode());
  }
  // MaybeAdjustCompositionFont() may create gIMMHandler.  So, check it
  // after a call of MaybeAdjustCompositionFont().
  if (gIMMHandler) {
    gIMMHandler->mSelection.Update(aIMENotification);
  }
}

// static
void
IMMHandler::MaybeAdjustCompositionFont(nsWindow* aWindow,
                                       const WritingMode& aWritingMode,
                                       bool aForceUpdate)
{
  switch (sCodePage) {
    case 932: // Japanese Shift-JIS
    case 936: // Simlified Chinese GBK
    case 949: // Korean
    case 950: // Traditional Chinese Big5
      EnsureHandlerInstance();
      break;
    default:
      // If there is no instance of nsIMM32Hander, we shouldn't waste footprint.
      if (!gIMMHandler) {
        return;
      }
  }

  // Like Navi-Bar of ATOK, some IMEs may require proper composition font even
  // before sending WM_IME_STARTCOMPOSITION.
  IMEContext context(aWindow);
  gIMMHandler->AdjustCompositionFont(context, aWritingMode, aForceUpdate);
}

// static
bool
IMMHandler::ProcessInputLangChangeMessage(nsWindow* aWindow,
                                          WPARAM wParam,
                                          LPARAM lParam,
                                          MSGResult& aResult)
{
  aResult.mResult = 0;
  aResult.mConsumed = false;
  // We don't need to create the instance of the handler here.
  if (gIMMHandler) {
    gIMMHandler->OnInputLangChange(aWindow, wParam, lParam, aResult);
  }
  InitKeyboardLayout(aWindow, reinterpret_cast<HKL>(lParam));
  // We can release the instance here, because the instance may be never
  // used. E.g., the new keyboard layout may not use IME, or it may use TSF.
  Terminate();
  // Don't return as "processed", the messages should be processed on nsWindow
  // too.
  return false;
}

// static
bool
IMMHandler::ProcessMessage(nsWindow* aWindow,
                           UINT msg,
                           WPARAM& wParam,
                           LPARAM& lParam,
                           MSGResult& aResult)
{
  // XXX We store the composing window in mComposingWindow.  If IME messages are
  // sent to different window, we should commit the old transaction.  And also
  // if the new window handle is not focused, probably, we should not start
  // the composition, however, such case should not be, it's just bad scenario.

  // When a plug-in has focus or compsition, we should dispatch the IME events
  // to the plug-in.
  if (aWindow->PluginHasFocus() || IsComposingOnPlugin()) {
      return ProcessMessageForPlugin(aWindow, msg, wParam, lParam, aResult);
  }

  aResult.mResult = 0;
  switch (msg) {
    case WM_INPUTLANGCHANGE:
      return ProcessInputLangChangeMessage(aWindow, wParam, lParam, aResult);
    case WM_IME_STARTCOMPOSITION:
      EnsureHandlerInstance();
      return gIMMHandler->OnIMEStartComposition(aWindow, aResult);
    case WM_IME_COMPOSITION:
      EnsureHandlerInstance();
      return gIMMHandler->OnIMEComposition(aWindow, wParam, lParam, aResult);
    case WM_IME_ENDCOMPOSITION:
      EnsureHandlerInstance();
      return gIMMHandler->OnIMEEndComposition(aWindow, aResult);
    case WM_IME_CHAR:
      return OnIMEChar(aWindow, wParam, lParam, aResult);
    case WM_IME_NOTIFY:
      return OnIMENotify(aWindow, wParam, lParam, aResult);
    case WM_IME_REQUEST:
      EnsureHandlerInstance();
      return gIMMHandler->OnIMERequest(aWindow, wParam, lParam, aResult);
    case WM_IME_SELECT:
      return OnIMESelect(aWindow, wParam, lParam, aResult);
    case WM_IME_SETCONTEXT:
      return OnIMESetContext(aWindow, wParam, lParam, aResult);
    case WM_KEYDOWN:
      return OnKeyDownEvent(aWindow, wParam, lParam, aResult);
    case WM_CHAR:
      if (!gIMMHandler) {
        return false;
      }
      return gIMMHandler->OnChar(aWindow, wParam, lParam, aResult);
    default:
      return false;
  };
}

// static
bool
IMMHandler::ProcessMessageForPlugin(nsWindow* aWindow,
                                    UINT msg,
                                    WPARAM& wParam,
                                    LPARAM& lParam,
                                    MSGResult& aResult)
{
  aResult.mResult = 0;
  aResult.mConsumed = false;
  switch (msg) {
    case WM_INPUTLANGCHANGEREQUEST:
    case WM_INPUTLANGCHANGE:
      aWindow->DispatchPluginEvent(msg, wParam, lParam, false);
      return ProcessInputLangChangeMessage(aWindow, wParam, lParam, aResult);
    case WM_IME_COMPOSITION:
      EnsureHandlerInstance();
      return gIMMHandler->OnIMECompositionOnPlugin(aWindow, wParam, lParam,
                                                   aResult);
    case WM_IME_STARTCOMPOSITION:
      EnsureHandlerInstance();
      return gIMMHandler->OnIMEStartCompositionOnPlugin(aWindow, wParam,
                                                        lParam, aResult);
    case WM_IME_ENDCOMPOSITION:
      EnsureHandlerInstance();
      return gIMMHandler->OnIMEEndCompositionOnPlugin(aWindow, wParam, lParam,
                                                      aResult);
    case WM_IME_CHAR:
      EnsureHandlerInstance();
      return gIMMHandler->OnIMECharOnPlugin(aWindow, wParam, lParam, aResult);
    case WM_IME_SETCONTEXT:
      return OnIMESetContextOnPlugin(aWindow, wParam, lParam, aResult);
    case WM_CHAR:
      if (!gIMMHandler) {
        return false;
      }
      return gIMMHandler->OnCharOnPlugin(aWindow, wParam, lParam, aResult);
    case WM_IME_COMPOSITIONFULL:
    case WM_IME_CONTROL:
    case WM_IME_KEYDOWN:
    case WM_IME_KEYUP:
    case WM_IME_REQUEST:
    case WM_IME_SELECT:
      aResult.mConsumed =
        aWindow->DispatchPluginEvent(msg, wParam, lParam, false);
      return true;
  }
  return false;
}

/****************************************************************************
 * message handlers
 ****************************************************************************/

void
IMMHandler::OnInputLangChange(nsWindow* aWindow,
                              WPARAM wParam,
                              LPARAM lParam,
                              MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnInputLangChange, hWnd=%08x, wParam=%08x, lParam=%08x",
     aWindow->GetWindowHandle(), wParam, lParam));

  aWindow->NotifyIME(REQUEST_TO_COMMIT_COMPOSITION);
  NS_ASSERTION(!mIsComposing, "ResetInputState failed");

  if (mIsComposing) {
    HandleEndComposition(aWindow);
  }

  aResult.mConsumed = false;
}

bool
IMMHandler::OnIMEStartComposition(nsWindow* aWindow,
                                  MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMEStartComposition, hWnd=%08x, mIsComposing=%s",
     aWindow->GetWindowHandle(), GetBoolName(mIsComposing)));
  aResult.mConsumed = ShouldDrawCompositionStringOurselves();
  if (mIsComposing) {
    NS_WARNING("Composition has been already started");
    return true;
  }

  IMEContext context(aWindow);
  HandleStartComposition(aWindow, context);
  return true;
}

bool
IMMHandler::OnIMEComposition(nsWindow* aWindow,
                             WPARAM wParam,
                             LPARAM lParam,
                             MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMEComposition, hWnd=%08x, lParam=%08x, mIsComposing=%s, "
     "GCS_RESULTSTR=%s, GCS_COMPSTR=%s, GCS_COMPATTR=%s, GCS_COMPCLAUSE=%s, "
     "GCS_CURSORPOS=%s,",
     aWindow->GetWindowHandle(), lParam, GetBoolName(mIsComposing),
     GetBoolName(lParam & GCS_RESULTSTR), GetBoolName(lParam & GCS_COMPSTR),
     GetBoolName(lParam & GCS_COMPATTR), GetBoolName(lParam & GCS_COMPCLAUSE),
     GetBoolName(lParam & GCS_CURSORPOS)));

  MOZ_ASSERT(!aWindow->PluginHasFocus(),
    "OnIMEComposition should not be called when a plug-in has focus");

  IMEContext context(aWindow);
  aResult.mConsumed = HandleComposition(aWindow, context, lParam);
  return true;
}

bool
IMMHandler::OnIMEEndComposition(nsWindow* aWindow,
                                MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMEEndComposition, hWnd=%08x, mIsComposing=%s",
     aWindow->GetWindowHandle(), GetBoolName(mIsComposing)));

  aResult.mConsumed = ShouldDrawCompositionStringOurselves();
  if (!mIsComposing) {
    return true;
  }

  // Korean IME posts WM_IME_ENDCOMPOSITION first when we hit space during
  // composition. Then, we should ignore the message and commit the composition
  // string at following WM_IME_COMPOSITION.
  MSG compositionMsg;
  if (WinUtils::PeekMessage(&compositionMsg, aWindow->GetWindowHandle(),
                            WM_IME_STARTCOMPOSITION, WM_IME_COMPOSITION,
                            PM_NOREMOVE) &&
      compositionMsg.message == WM_IME_COMPOSITION &&
      IS_COMMITTING_LPARAM(compositionMsg.lParam)) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: OnIMEEndComposition, WM_IME_ENDCOMPOSITION is followed by "
       "WM_IME_COMPOSITION, ignoring the message..."));
    return true;
  }

  // Otherwise, e.g., ChangJie doesn't post WM_IME_COMPOSITION before
  // WM_IME_ENDCOMPOSITION when composition string becomes empty.
  // Then, we should dispatch a compositionupdate event, a compositionchange
  // event and a compositionend event.
  // XXX Shouldn't we dispatch the compositionchange event with actual or
  //     latest composition string?
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMEEndComposition, mCompositionString=\"%s\"%s",
     NS_ConvertUTF16toUTF8(mCompositionString).get(),
     mCompositionString.IsEmpty() ? "" : ", but canceling it..."));

  HandleEndComposition(aWindow, &EmptyString());

  return true;
}

// static
bool
IMMHandler::OnIMEChar(nsWindow* aWindow,
                      WPARAM wParam,
                      LPARAM lParam,
                      MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMEChar, hWnd=%08x, char=%08x",
     aWindow->GetWindowHandle(), wParam));

  // We don't need to fire any compositionchange events from here. This method
  // will be called when the composition string of the current IME is not drawn
  // by us and some characters are committed. In that case, the committed
  // string was processed in nsWindow::OnIMEComposition already.

  // We need to consume the message so that Windows don't send two WM_CHAR msgs
  aResult.mConsumed = true;
  return true;
}

// static
bool
IMMHandler::OnIMECompositionFull(nsWindow* aWindow,
                                 MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMECompositionFull, hWnd=%08x",
     aWindow->GetWindowHandle()));

  // not implement yet
  aResult.mConsumed = false;
  return true;
}

// static
bool
IMMHandler::OnIMENotify(nsWindow* aWindow,
                        WPARAM wParam,
                        LPARAM lParam,
                        MSGResult& aResult)
{
  switch (wParam) {
    case IMN_CHANGECANDIDATE:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_CHANGECANDIDATE, lParam=%08x",
         aWindow->GetWindowHandle(), lParam));
      break;
    case IMN_CLOSECANDIDATE:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_CLOSECANDIDATE, lParam=%08x",
         aWindow->GetWindowHandle(), lParam));
      break;
    case IMN_CLOSESTATUSWINDOW:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_CLOSESTATUSWINDOW",
         aWindow->GetWindowHandle()));
      break;
    case IMN_GUIDELINE:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_GUIDELINE",
         aWindow->GetWindowHandle()));
      break;
    case IMN_OPENCANDIDATE:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_OPENCANDIDATE, lParam=%08x",
         aWindow->GetWindowHandle(), lParam));
      break;
    case IMN_OPENSTATUSWINDOW:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_OPENSTATUSWINDOW",
         aWindow->GetWindowHandle()));
      break;
    case IMN_SETCANDIDATEPOS:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_SETCANDIDATEPOS, lParam=%08x",
         aWindow->GetWindowHandle(), lParam));
      break;
    case IMN_SETCOMPOSITIONFONT:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_SETCOMPOSITIONFONT",
         aWindow->GetWindowHandle()));
      break;
    case IMN_SETCOMPOSITIONWINDOW:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_SETCOMPOSITIONWINDOW",
         aWindow->GetWindowHandle()));
      break;
    case IMN_SETCONVERSIONMODE:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_SETCONVERSIONMODE",
         aWindow->GetWindowHandle()));
      break;
    case IMN_SETOPENSTATUS:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_SETOPENSTATUS",
         aWindow->GetWindowHandle()));
      break;
    case IMN_SETSENTENCEMODE:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_SETSENTENCEMODE",
         aWindow->GetWindowHandle()));
      break;
    case IMN_SETSTATUSWINDOWPOS:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_SETSTATUSWINDOWPOS",
         aWindow->GetWindowHandle()));
      break;
    case IMN_PRIVATE:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMENotify, hWnd=%08x, IMN_PRIVATE",
         aWindow->GetWindowHandle()));
      break;
  }

  // not implement yet
  aResult.mConsumed = false;
  return true;
}

bool
IMMHandler::OnIMERequest(nsWindow* aWindow,
                         WPARAM wParam,
                         LPARAM lParam,
                         MSGResult& aResult)
{
  switch (wParam) {
    case IMR_RECONVERTSTRING:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMERequest, hWnd=%08x, IMR_RECONVERTSTRING",
         aWindow->GetWindowHandle()));
      aResult.mConsumed = HandleReconvert(aWindow, lParam, &aResult.mResult);
      return true;
    case IMR_QUERYCHARPOSITION:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMERequest, hWnd=%08x, IMR_QUERYCHARPOSITION",
         aWindow->GetWindowHandle()));
      aResult.mConsumed =
        HandleQueryCharPosition(aWindow, lParam, &aResult.mResult);
      return true;
    case IMR_DOCUMENTFEED:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMERequest, hWnd=%08x, IMR_DOCUMENTFEED",
         aWindow->GetWindowHandle()));
      aResult.mConsumed = HandleDocumentFeed(aWindow, lParam, &aResult.mResult);
      return true;
    default:
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: OnIMERequest, hWnd=%08x, wParam=%08x",
         aWindow->GetWindowHandle(), wParam));
      aResult.mConsumed = false;
      return true;
  }
}

// static
bool
IMMHandler::OnIMESelect(nsWindow* aWindow,
                        WPARAM wParam,
                        LPARAM lParam,
                        MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMESelect, hWnd=%08x, wParam=%08x, lParam=%08x",
     aWindow->GetWindowHandle(), wParam, lParam));

  // not implement yet
  aResult.mConsumed = false;
  return true;
}

// static
bool
IMMHandler::OnIMESetContext(nsWindow* aWindow,
                            WPARAM wParam,
                            LPARAM lParam,
                            MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMESetContext, hWnd=%08x, %s, lParam=%08x",
     aWindow->GetWindowHandle(), wParam ? "Active" : "Deactive", lParam));

  aResult.mConsumed = false;

  // NOTE: If the aWindow is top level window of the composing window because
  // when a window on deactive window gets focus, WM_IME_SETCONTEXT (wParam is
  // TRUE) is sent to the top level window first.  After that,
  // WM_IME_SETCONTEXT (wParam is FALSE) is sent to the top level window.
  // Finally, WM_IME_SETCONTEXT (wParam is TRUE) is sent to the focused window.
  // The top level window never becomes composing window, so, we can ignore
  // the WM_IME_SETCONTEXT on the top level window.
  if (IsTopLevelWindowOfComposition(aWindow)) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: OnIMESetContext, hWnd=%08x is top level window"));
    return true;
  }

  // When IME context is activating on another window,
  // we should commit the old composition on the old window.
  bool cancelComposition = false;
  if (wParam && gIMMHandler) {
    cancelComposition =
      gIMMHandler->CommitCompositionOnPreviousWindow(aWindow);
  }

  if (wParam && (lParam & ISC_SHOWUICOMPOSITIONWINDOW) &&
      ShouldDrawCompositionStringOurselves()) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: OnIMESetContext, ISC_SHOWUICOMPOSITIONWINDOW is removed"));
    lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
  }

  // We should sent WM_IME_SETCONTEXT to the DefWndProc here because the
  // ancestor windows shouldn't receive this message.  If they receive the
  // message, we cannot know whether which window is the target of the message.
  aResult.mResult = ::DefWindowProc(aWindow->GetWindowHandle(),
                                    WM_IME_SETCONTEXT, wParam, lParam);

  // Cancel composition on the new window if we committed our composition on
  // another window.
  if (cancelComposition) {
    CancelComposition(aWindow, true);
  }

  aResult.mConsumed = true;
  return true;
}

bool
IMMHandler::OnChar(nsWindow* aWindow,
                   WPARAM wParam,
                   LPARAM lParam,
                   MSGResult& aResult)
{
  // The return value must be same as aResult.mConsumed because only when we
  // consume the message, the caller shouldn't do anything anymore but
  // otherwise, the caller should handle the message.
  aResult.mConsumed = false;
  if (IsIMECharRecordsEmpty()) {
    return aResult.mConsumed;
  }
  WPARAM recWParam;
  LPARAM recLParam;
  DequeueIMECharRecords(recWParam, recLParam);
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnChar, aWindow=%p, wParam=%08x, lParam=%08x, "
     "recorded: wParam=%08x, lParam=%08x",
     aWindow->GetWindowHandle(), wParam, lParam, recWParam, recLParam));
  // If an unexpected char message comes, we should reset the records,
  // of course, this shouldn't happen.
  if (recWParam != wParam || recLParam != lParam) {
    ResetIMECharRecords();
    return aResult.mConsumed;
  }
  // Eat the char message which is caused by WM_IME_CHAR because we should
  // have processed the IME messages, so, this message could be come from
  // a windowless plug-in.
  aResult.mConsumed = true;
  return aResult.mConsumed;
}

/****************************************************************************
 * message handlers for plug-in
 ****************************************************************************/

bool
IMMHandler::OnIMEStartCompositionOnPlugin(nsWindow* aWindow,
                                          WPARAM wParam,
                                          LPARAM lParam,
                                          MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMEStartCompositionOnPlugin, hWnd=%08x, mIsComposingOnPlugin=%s",
     aWindow->GetWindowHandle(), GetBoolName(mIsComposingOnPlugin)));
  mIsComposingOnPlugin = true;
  mComposingWindow = aWindow;
  IMEContext context(aWindow);
  SetIMERelatedWindowsPosOnPlugin(aWindow, context);
  // On widnowless plugin, we should assume that the focused editor is always
  // in horizontal writing mode.
  AdjustCompositionFont(context, WritingMode());
  aResult.mConsumed =
    aWindow->DispatchPluginEvent(WM_IME_STARTCOMPOSITION, wParam, lParam,
                                 false);
  return true;
}

bool
IMMHandler::OnIMECompositionOnPlugin(nsWindow* aWindow,
                                     WPARAM wParam,
                                     LPARAM lParam,
                                     MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMECompositionOnPlugin, hWnd=%08x, lParam=%08x, "
     "mIsComposingOnPlugin=%s, GCS_RESULTSTR=%s, GCS_COMPSTR=%s, "
     "GCS_COMPATTR=%s, GCS_COMPCLAUSE=%s, GCS_CURSORPOS=%s",
     aWindow->GetWindowHandle(), lParam, GetBoolName(mIsComposingOnPlugin),
     GetBoolName(lParam & GCS_RESULTSTR), GetBoolName(lParam & GCS_COMPSTR),
     GetBoolName(lParam & GCS_COMPATTR), GetBoolName(lParam & GCS_COMPCLAUSE),
     GetBoolName(lParam & GCS_CURSORPOS)));
  // We should end composition if there is a committed string.
  if (IS_COMMITTING_LPARAM(lParam)) {
    mIsComposingOnPlugin = false;
    mComposingWindow = nullptr;
  }
  // Continue composition if there is still a string being composed.
  if (IS_COMPOSING_LPARAM(lParam)) {
    mIsComposingOnPlugin = true;
    mComposingWindow = aWindow;
    IMEContext context(aWindow);
    SetIMERelatedWindowsPosOnPlugin(aWindow, context);
  }
  aResult.mConsumed =
    aWindow->DispatchPluginEvent(WM_IME_COMPOSITION, wParam, lParam, true);
  return true;
}

bool
IMMHandler::OnIMEEndCompositionOnPlugin(nsWindow* aWindow,
                                        WPARAM wParam,
                                        LPARAM lParam,
                                        MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMEEndCompositionOnPlugin, hWnd=%08x, mIsComposingOnPlugin=%s",
     aWindow->GetWindowHandle(), GetBoolName(mIsComposingOnPlugin)));

  mIsComposingOnPlugin = false;
  mComposingWindow = nullptr;

  if (mNativeCaretIsCreated) {
    ::DestroyCaret();
    mNativeCaretIsCreated = false;
  }

  aResult.mConsumed =
    aWindow->DispatchPluginEvent(WM_IME_ENDCOMPOSITION, wParam, lParam,
                                 false);
  return true;
}

bool
IMMHandler::OnIMECharOnPlugin(nsWindow* aWindow,
                              WPARAM wParam,
                              LPARAM lParam,
                              MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMECharOnPlugin, hWnd=%08x, char=%08x, scancode=%08x",
     aWindow->GetWindowHandle(), wParam, lParam));

  aResult.mConsumed =
    aWindow->DispatchPluginEvent(WM_IME_CHAR, wParam, lParam, true);

  if (!aResult.mConsumed) {
    // Record the WM_CHAR messages which are going to be coming.
    EnsureHandlerInstance();
    EnqueueIMECharRecords(wParam, lParam);
  }
  return true;
}

// static
bool
IMMHandler::OnIMESetContextOnPlugin(nsWindow* aWindow,
                                    WPARAM wParam,
                                    LPARAM lParam,
                                    MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnIMESetContextOnPlugin, hWnd=%08x, %s, lParam=%08x",
     aWindow->GetWindowHandle(), wParam ? "Active" : "Deactive", lParam));

  // If the IME context becomes active on a plug-in, we should commit
  // our composition.  And also we should cancel the composition on new
  // window.  Note that if IsTopLevelWindowOfComposition(aWindow) returns
  // true, we should ignore the message here, see the comment in
  // OnIMESetContext() for the detail.
  if (wParam && gIMMHandler && !IsTopLevelWindowOfComposition(aWindow)) {
    if (gIMMHandler->CommitCompositionOnPreviousWindow(aWindow)) {
      CancelComposition(aWindow);
    }
  }

  // Dispatch message to the plug-in.
  // XXX When a windowless plug-in gets focus, we should send
  //     WM_IME_SETCONTEXT
  aWindow->DispatchPluginEvent(WM_IME_SETCONTEXT, wParam, lParam, false);

  // We should send WM_IME_SETCONTEXT to the DefWndProc here.  It shouldn't
  // be received on ancestor windows, see OnIMESetContext() for the detail.
  aResult.mResult = ::DefWindowProc(aWindow->GetWindowHandle(),
                                    WM_IME_SETCONTEXT, wParam, lParam);

  // Don't synchronously dispatch the pending events when we receive
  // WM_IME_SETCONTEXT because we get it during plugin destruction.
  // (bug 491848)
  aResult.mConsumed = true;
  return true;
}

bool
IMMHandler::OnCharOnPlugin(nsWindow* aWindow,
                           WPARAM wParam,
                           LPARAM lParam,
                           MSGResult& aResult)
{
  // We should never consume char message on windowless plugin.
  aResult.mConsumed = false;
  if (IsIMECharRecordsEmpty()) {
    return false;
  }

  WPARAM recWParam;
  LPARAM recLParam;
  DequeueIMECharRecords(recWParam, recLParam);
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnCharOnPlugin, aWindow=%p, wParam=%08x, lParam=%08x, "
     "recorded: wParam=%08x, lParam=%08x",
     aWindow->GetWindowHandle(), wParam, lParam, recWParam, recLParam));
  // If an unexpected char message comes, we should reset the records,
  // of course, this shouldn't happen.
  if (recWParam != wParam || recLParam != lParam) {
    ResetIMECharRecords();
  }
  // WM_CHAR on plug-in is always handled by nsWindow.
  return false;
}

/****************************************************************************
 * others
 ****************************************************************************/

void
IMMHandler::HandleStartComposition(nsWindow* aWindow,
                                   const IMEContext& aContext)
{
  NS_PRECONDITION(!mIsComposing,
    "HandleStartComposition is called but mIsComposing is TRUE");
  NS_PRECONDITION(!aWindow->PluginHasFocus(),
    "HandleStartComposition should not be called when a plug-in has focus");

  Selection& selection = GetSelection();
  if (!selection.EnsureValidSelection(aWindow)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleStartComposition, FAILED, due to "
       "Selection::EnsureValidSelection() failure"));
    return;
  }

  AdjustCompositionFont(aContext, selection.mWritingMode);

  mCompositionStart = selection.mOffset;
  mCursorPosition = NO_IME_CARET;

  WidgetCompositionEvent event(true, eCompositionStart, aWindow);
  LayoutDeviceIntPoint point(0, 0);
  aWindow->InitEvent(event, &point);
  DispatchEvent(aWindow, event);

  mIsComposing = true;
  mComposingWindow = aWindow;

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: HandleStartComposition, START composition, mCompositionStart=%ld",
     mCompositionStart));
}

bool
IMMHandler::HandleComposition(nsWindow* aWindow,
                              const IMEContext& aContext,
                              LPARAM lParam)
{
  NS_PRECONDITION(!aWindow->PluginHasFocus(),
    "HandleComposition should not be called when a plug-in has focus");

  // for bug #60050
  // MS-IME 95/97/98/2000 may send WM_IME_COMPOSITION with non-conversion
  // mode before it send WM_IME_STARTCOMPOSITION.
  // However, ATOK sends a WM_IME_COMPOSITION before WM_IME_STARTCOMPOSITION,
  // and if we access ATOK via some APIs, ATOK will sometimes fail to
  // initialize its state.  If WM_IME_STARTCOMPOSITION is already in the
  // message queue, we should ignore the strange WM_IME_COMPOSITION message and
  // skip to the next.  So, we should look for next composition message
  // (WM_IME_STARTCOMPOSITION or WM_IME_ENDCOMPOSITION or WM_IME_COMPOSITION),
  // and if it's WM_IME_STARTCOMPOSITION, and one more next composition message
  // is WM_IME_COMPOSITION, current IME is ATOK, probably.  Otherwise, we
  // should start composition forcibly.
  if (!mIsComposing) {
    MSG msg1, msg2;
    HWND wnd = aWindow->GetWindowHandle();
    if (WinUtils::PeekMessage(&msg1, wnd, WM_IME_STARTCOMPOSITION,
                              WM_IME_COMPOSITION, PM_NOREMOVE) &&
        msg1.message == WM_IME_STARTCOMPOSITION &&
        WinUtils::PeekMessage(&msg2, wnd, WM_IME_ENDCOMPOSITION,
                              WM_IME_COMPOSITION, PM_NOREMOVE) &&
        msg2.message == WM_IME_COMPOSITION) {
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: HandleComposition, Ignores due to find a "
         "WM_IME_STARTCOMPOSITION"));
      return ShouldDrawCompositionStringOurselves();
    }
  }

  bool startCompositionMessageHasBeenSent = mIsComposing;

  //
  // This catches a fixed result
  //
  if (IS_COMMITTING_LPARAM(lParam)) {
    if (!mIsComposing) {
      HandleStartComposition(aWindow, aContext);
    }

    GetCompositionString(aContext, GCS_RESULTSTR, mCompositionString);

    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: HandleComposition, GCS_RESULTSTR"));

    HandleEndComposition(aWindow, &mCompositionString);

    if (!IS_COMPOSING_LPARAM(lParam)) {
      return ShouldDrawCompositionStringOurselves();
    }
  }


  //
  // This provides us with a composition string
  //
  if (!mIsComposing) {
    HandleStartComposition(aWindow, aContext);
  }

  //--------------------------------------------------------
  // 1. Get GCS_COMPSTR
  //--------------------------------------------------------
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: HandleComposition, GCS_COMPSTR"));

  nsAutoString previousCompositionString(mCompositionString);
  GetCompositionString(aContext, GCS_COMPSTR, mCompositionString);

  if (!IS_COMPOSING_LPARAM(lParam)) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: HandleComposition, lParam doesn't indicate composing, "
       "mCompositionString=\"%s\", previousCompositionString=\"%s\"",
       NS_ConvertUTF16toUTF8(mCompositionString).get(),
       NS_ConvertUTF16toUTF8(previousCompositionString).get()));

    // If composition string isn't changed, we can trust the lParam.
    // So, we need to do nothing.
    if (previousCompositionString == mCompositionString) {
      return ShouldDrawCompositionStringOurselves();
    }

    // IME may send WM_IME_COMPOSITION without composing lParam values
    // when composition string becomes empty (e.g., using Backspace key).
    // If composition string is empty, we should dispatch a compositionchange
    // event with empty string and clear the clause information.
    if (mCompositionString.IsEmpty()) {
      mClauseArray.Clear();
      mAttributeArray.Clear();
      mCursorPosition = 0;
      DispatchCompositionChangeEvent(aWindow, aContext);
      return ShouldDrawCompositionStringOurselves();
    }

    // Otherwise, we cannot trust the lParam value.  We might need to
    // dispatch compositionchange event with the latest composition string
    // information.
  }

  // See https://bugzilla.mozilla.org/show_bug.cgi?id=296339
  if (mCompositionString.IsEmpty() && !startCompositionMessageHasBeenSent) {
    // In this case, maybe, the sender is MSPinYin. That sends *only*
    // WM_IME_COMPOSITION with GCS_COMP* and GCS_RESULT* when
    // user inputted the Chinese full stop. So, that doesn't send
    // WM_IME_STARTCOMPOSITION and WM_IME_ENDCOMPOSITION.
    // If WM_IME_STARTCOMPOSITION was not sent and the composition
    // string is null (it indicates the composition transaction ended),
    // WM_IME_ENDCOMPOSITION may not be sent. If so, we cannot run
    // HandleEndComposition() in other place.
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: HandleComposition, Aborting GCS_COMPSTR"));
    HandleEndComposition(aWindow);
    return IS_COMMITTING_LPARAM(lParam);
  }

  //--------------------------------------------------------
  // 2. Get GCS_COMPCLAUSE
  //--------------------------------------------------------
  long clauseArrayLength =
    ::ImmGetCompositionStringW(aContext.get(), GCS_COMPCLAUSE, nullptr, 0);
  clauseArrayLength /= sizeof(uint32_t);

  if (clauseArrayLength > 0) {
    nsresult rv = EnsureClauseArray(clauseArrayLength);
    NS_ENSURE_SUCCESS(rv, false);

    // Intelligent ABC IME (Simplified Chinese IME, the code page is 936)
    // will crash in ImmGetCompositionStringW for GCS_COMPCLAUSE (bug 424663).
    // See comment 35 of the bug for the detail. Therefore, we should use A
    // API for it, however, we should not kill Unicode support on all IMEs.
    bool useA_API = !(sIMEProperty & IME_PROP_UNICODE);

    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: HandleComposition, GCS_COMPCLAUSE, useA_API=%s",
       useA_API ? "TRUE" : "FALSE"));

    long clauseArrayLength2 = 
      useA_API ?
        ::ImmGetCompositionStringA(aContext.get(), GCS_COMPCLAUSE,
                                   mClauseArray.Elements(),
                                   mClauseArray.Capacity() * sizeof(uint32_t)) :
        ::ImmGetCompositionStringW(aContext.get(), GCS_COMPCLAUSE,
                                   mClauseArray.Elements(),
                                   mClauseArray.Capacity() * sizeof(uint32_t));
    clauseArrayLength2 /= sizeof(uint32_t);

    if (clauseArrayLength != clauseArrayLength2) {
      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: HandleComposition, GCS_COMPCLAUSE, clauseArrayLength=%ld but "
         "clauseArrayLength2=%ld",
         clauseArrayLength, clauseArrayLength2));
      if (clauseArrayLength > clauseArrayLength2)
        clauseArrayLength = clauseArrayLength2;
    }

    if (useA_API) {
      // Convert each values of sIMECompClauseArray. The values mean offset of
      // the clauses in ANSI string. But we need the values in Unicode string.
      nsAutoCString compANSIStr;
      if (ConvertToANSIString(mCompositionString, GetKeyboardCodePage(),
                              compANSIStr)) {
        uint32_t maxlen = compANSIStr.Length();
        mClauseArray[0] = 0; // first value must be 0
        for (int32_t i = 1; i < clauseArrayLength; i++) {
          uint32_t len = std::min(mClauseArray[i], maxlen);
          mClauseArray[i] = ::MultiByteToWideChar(GetKeyboardCodePage(), 
                                                  MB_PRECOMPOSED,
                                                  (LPCSTR)compANSIStr.get(),
                                                  len, nullptr, 0);
        }
      }
    }
  }
  // compClauseArrayLength may be negative. I.e., ImmGetCompositionStringW
  // may return an error code.
  mClauseArray.SetLength(std::max<long>(0, clauseArrayLength));

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: HandleComposition, GCS_COMPCLAUSE, mClauseLength=%ld",
     mClauseArray.Length()));

  //--------------------------------------------------------
  // 3. Get GCS_COMPATTR
  //--------------------------------------------------------
  // This provides us with the attribute string necessary 
  // for doing hiliting
  long attrArrayLength =
    ::ImmGetCompositionStringW(aContext.get(), GCS_COMPATTR, nullptr, 0);
  attrArrayLength /= sizeof(uint8_t);

  if (attrArrayLength > 0) {
    nsresult rv = EnsureAttributeArray(attrArrayLength);
    NS_ENSURE_SUCCESS(rv, false);
    attrArrayLength =
      ::ImmGetCompositionStringW(aContext.get(), GCS_COMPATTR,
                                 mAttributeArray.Elements(),
                                 mAttributeArray.Capacity() * sizeof(uint8_t));
  }

  // attrStrLen may be negative. I.e., ImmGetCompositionStringW may return an
  // error code.
  mAttributeArray.SetLength(std::max<long>(0, attrArrayLength));

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: HandleComposition, GCS_COMPATTR, mAttributeLength=%ld",
     mAttributeArray.Length()));

  //--------------------------------------------------------
  // 4. Get GCS_CURSOPOS
  //--------------------------------------------------------
  // Some IMEs (e.g., the standard IME for Korean) don't have caret position.
  if (lParam & GCS_CURSORPOS) {
    mCursorPosition =
      ::ImmGetCompositionStringW(aContext.get(), GCS_CURSORPOS, nullptr, 0);
    if (mCursorPosition < 0) {
      mCursorPosition = NO_IME_CARET; // The result is error
    }
  } else {
    mCursorPosition = NO_IME_CARET;
  }

  NS_ASSERTION(mCursorPosition <= (long)mCompositionString.Length(),
               "illegal pos");

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: HandleComposition, GCS_CURSORPOS, mCursorPosition=%d",
     mCursorPosition));

  //--------------------------------------------------------
  // 5. Send the compositionchange event
  //--------------------------------------------------------
  DispatchCompositionChangeEvent(aWindow, aContext);

  return ShouldDrawCompositionStringOurselves();
}

void
IMMHandler::HandleEndComposition(nsWindow* aWindow,
                                 const nsAString* aCommitString)
{
  MOZ_ASSERT(mIsComposing,
    "HandleEndComposition is called but mIsComposing is FALSE");
  MOZ_ASSERT(!aWindow->PluginHasFocus(),
    "HandleComposition should not be called when a plug-in has focus");

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: HandleEndComposition(aWindow=0x%p, aCommitString=0x%p (\"%s\"))",
     aWindow, aCommitString,
     aCommitString ? NS_ConvertUTF16toUTF8(*aCommitString).get() : ""));

  if (mNativeCaretIsCreated) {
    ::DestroyCaret();
    mNativeCaretIsCreated = false;
  }

  EventMessage message =
    aCommitString ? eCompositionCommit : eCompositionCommitAsIs;
  WidgetCompositionEvent compositionCommitEvent(true, message, aWindow);
  LayoutDeviceIntPoint point(0, 0);
  aWindow->InitEvent(compositionCommitEvent, &point);
  if (aCommitString) {
    compositionCommitEvent.mData = *aCommitString;
  }
  DispatchEvent(aWindow, compositionCommitEvent);
  mIsComposing = false;
  mComposingWindow = nullptr;
}

bool
IMMHandler::HandleReconvert(nsWindow* aWindow,
                            LPARAM lParam,
                            LRESULT* oResult)
{
  *oResult = 0;
  RECONVERTSTRING* pReconv = reinterpret_cast<RECONVERTSTRING*>(lParam);

  Selection& selection = GetSelection();
  if (!selection.EnsureValidSelection(aWindow)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleReconvert, FAILED, due to "
       "Selection::EnsureValidSelection() failure"));
    return false;
  }

  uint32_t len = selection.Length();
  uint32_t needSize = sizeof(RECONVERTSTRING) + len * sizeof(WCHAR);

  if (!pReconv) {
    // Return need size to reconvert.
    if (len == 0) {
      MOZ_LOG(gIMMLog, LogLevel::Error,
        ("IMM: HandleReconvert, There are not selected text"));
      return false;
    }
    *oResult = needSize;
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: HandleReconvert, succeeded, result=%ld",
       *oResult));
    return true;
  }

  if (pReconv->dwSize < needSize) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: HandleReconvert, FAILED, pReconv->dwSize=%ld, needSize=%ld",
       pReconv->dwSize, needSize));
    return false;
  }

  *oResult = needSize;

  // Fill reconvert struct
  pReconv->dwVersion         = 0;
  pReconv->dwStrLen          = len;
  pReconv->dwStrOffset       = sizeof(RECONVERTSTRING);
  pReconv->dwCompStrLen      = len;
  pReconv->dwCompStrOffset   = 0;
  pReconv->dwTargetStrLen    = len;
  pReconv->dwTargetStrOffset = 0;

  ::CopyMemory(reinterpret_cast<LPVOID>(lParam + sizeof(RECONVERTSTRING)),
               selection.mString.get(), len * sizeof(WCHAR));

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: HandleReconvert, SUCCEEDED, pReconv=%s, result=%ld",
     GetReconvertStringLog(pReconv).get(), *oResult));

  return true;
}

bool
IMMHandler::HandleQueryCharPosition(nsWindow* aWindow,
                                    LPARAM lParam,
                                    LRESULT* oResult)
{
  uint32_t len = mIsComposing ? mCompositionString.Length() : 0;
  *oResult = false;
  IMECHARPOSITION* pCharPosition = reinterpret_cast<IMECHARPOSITION*>(lParam);
  if (!pCharPosition) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleQueryCharPosition, FAILED, due to pCharPosition is null"));
    return false;
  }
  if (pCharPosition->dwSize < sizeof(IMECHARPOSITION)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleReconvert, FAILED, pCharPosition->dwSize=%ld, "
       "sizeof(IMECHARPOSITION)=%ld",
       pCharPosition->dwSize, sizeof(IMECHARPOSITION)));
    return false;
  }
  if (::GetFocus() != aWindow->GetWindowHandle()) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleReconvert, FAILED, ::GetFocus()=%08x, OurWindowHandle=%08x",
       ::GetFocus(), aWindow->GetWindowHandle()));
    return false;
  }
  if (pCharPosition->dwCharPos > len) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleQueryCharPosition, FAILED, pCharPosition->dwCharPos=%ld, "
       "len=%ld",
       pCharPosition->dwCharPos, len));
    return false;
  }

  LayoutDeviceIntRect r;
  bool ret =
    GetCharacterRectOfSelectedTextAt(aWindow, pCharPosition->dwCharPos, r);
  NS_ENSURE_TRUE(ret, false);

  LayoutDeviceIntRect screenRect;
  // We always need top level window that is owner window of the popup window
  // even if the content of the popup window has focus.
  ResolveIMECaretPos(aWindow->GetTopLevelWindow(false),
                     r, nullptr, screenRect);

  // XXX This might need to check writing mode.  However, MSDN doesn't explain
  //     how to set the values in vertical writing mode. Additionally, IME
  //     doesn't work well with top-left of the character (this is explicitly
  //     documented) and its horizontal width.  So, it might be better to set
  //     top-right corner of the character and horizontal width, but we're not
  //     sure if it doesn't cause any problems with a lot of IMEs...
  pCharPosition->pt.x = screenRect.x;
  pCharPosition->pt.y = screenRect.y;

  pCharPosition->cLineHeight = r.height;

  WidgetQueryContentEvent editorRect(true, eQueryEditorRect, aWindow);
  aWindow->InitEvent(editorRect);
  DispatchEvent(aWindow, editorRect);
  if (NS_WARN_IF(!editorRect.mSucceeded)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleQueryCharPosition, eQueryEditorRect failed"));
    ::GetWindowRect(aWindow->GetWindowHandle(), &pCharPosition->rcDocument);
  } else {
    LayoutDeviceIntRect editorRectInWindow = editorRect.mReply.mRect;
    nsWindow* window = editorRect.mReply.mFocusedWidget ?
      static_cast<nsWindow*>(editorRect.mReply.mFocusedWidget) : aWindow;
    LayoutDeviceIntRect editorRectInScreen;
    ResolveIMECaretPos(window, editorRectInWindow, nullptr, editorRectInScreen);
    ::SetRect(&pCharPosition->rcDocument,
              editorRectInScreen.x, editorRectInScreen.y,
              editorRectInScreen.XMost(), editorRectInScreen.YMost());
  }

  *oResult = TRUE;

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: HandleQueryCharPosition, SUCCEEDED, pCharPosition={ pt={ x=%d, "
     "y=%d }, cLineHeight=%d, rcDocument={ left=%d, top=%d, right=%d, "
     "bottom=%d } }",
     pCharPosition->pt.x, pCharPosition->pt.y, pCharPosition->cLineHeight,
     pCharPosition->rcDocument.left, pCharPosition->rcDocument.top,
     pCharPosition->rcDocument.right, pCharPosition->rcDocument.bottom));
  return true;
}

bool
IMMHandler::HandleDocumentFeed(nsWindow* aWindow,
                               LPARAM lParam,
                               LRESULT* oResult)
{
  *oResult = 0;
  RECONVERTSTRING* pReconv = reinterpret_cast<RECONVERTSTRING*>(lParam);

  LayoutDeviceIntPoint point(0, 0);

  bool hasCompositionString =
    mIsComposing && ShouldDrawCompositionStringOurselves();

  int32_t targetOffset, targetLength;
  if (!hasCompositionString) {
    Selection& selection = GetSelection();
    if (!selection.EnsureValidSelection(aWindow)) {
      MOZ_LOG(gIMMLog, LogLevel::Error,
        ("IMM: HandleDocumentFeed, FAILED, due to "
         "Selection::EnsureValidSelection() failure"));
      return false;
    }
    targetOffset = int32_t(selection.mOffset);
    targetLength = int32_t(selection.Length());
  } else {
    targetOffset = int32_t(mCompositionStart);
    targetLength = int32_t(mCompositionString.Length());
  }

  // XXX nsString::Find and nsString::RFind take int32_t for offset, so,
  //     we cannot support this message when the current offset is larger than
  //     INT32_MAX.
  if (targetOffset < 0 || targetLength < 0 ||
      targetOffset + targetLength < 0) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleDocumentFeed, FAILED, due to the selection is out of "
       "range"));
    return false;
  }

  // Get all contents of the focused editor.
  WidgetQueryContentEvent textContent(true, eQueryTextContent, aWindow);
  textContent.InitForQueryTextContent(0, UINT32_MAX);
  aWindow->InitEvent(textContent, &point);
  DispatchEvent(aWindow, textContent);
  if (!textContent.mSucceeded) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleDocumentFeed, FAILED, due to eQueryTextContent failure"));
    return false;
  }

  nsAutoString str(textContent.mReply.mString);
  if (targetOffset > int32_t(str.Length())) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleDocumentFeed, FAILED, due to the caret offset is invalid"));
    return false;
  }

  // Get the focused paragraph, we decide that it starts from the previous CRLF
  // (or start of the editor) to the next one (or the end of the editor).
  int32_t paragraphStart = str.RFind("\n", false, targetOffset, -1) + 1;
  int32_t paragraphEnd =
    str.Find("\r", false, targetOffset + targetLength, -1);
  if (paragraphEnd < 0) {
    paragraphEnd = str.Length();
  }
  nsDependentSubstring paragraph(str, paragraphStart,
                                 paragraphEnd - paragraphStart);

  uint32_t len = paragraph.Length();
  uint32_t needSize = sizeof(RECONVERTSTRING) + len * sizeof(WCHAR);

  if (!pReconv) {
    *oResult = needSize;
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: HandleDocumentFeed, succeeded, result=%ld",
       *oResult));
    return true;
  }

  if (pReconv->dwSize < needSize) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: HandleDocumentFeed, FAILED, pReconv->dwSize=%ld, needSize=%ld",
       pReconv->dwSize, needSize));
    return false;
  }

  // Fill reconvert struct
  pReconv->dwVersion         = 0;
  pReconv->dwStrLen          = len;
  pReconv->dwStrOffset       = sizeof(RECONVERTSTRING);
  if (hasCompositionString) {
    pReconv->dwCompStrLen      = targetLength;
    pReconv->dwCompStrOffset   =
      (targetOffset - paragraphStart) * sizeof(WCHAR);
    // Set composition target clause information
    uint32_t offset, length;
    if (!GetTargetClauseRange(&offset, &length)) {
      MOZ_LOG(gIMMLog, LogLevel::Error,
        ("IMM: HandleDocumentFeed, FAILED, due to GetTargetClauseRange() "
         "failure"));
      return false;
    }
    pReconv->dwTargetStrLen    = length;
    pReconv->dwTargetStrOffset = (offset - paragraphStart) * sizeof(WCHAR);
  } else {
    pReconv->dwTargetStrLen    = targetLength;
    pReconv->dwTargetStrOffset =
      (targetOffset - paragraphStart) * sizeof(WCHAR);
    // There is no composition string, so, the length is zero but we should
    // set the cursor offset to the composition str offset.
    pReconv->dwCompStrLen      = 0;
    pReconv->dwCompStrOffset   = pReconv->dwTargetStrOffset;
  }

  *oResult = needSize;
  ::CopyMemory(reinterpret_cast<LPVOID>(lParam + sizeof(RECONVERTSTRING)),
               paragraph.BeginReading(), len * sizeof(WCHAR));

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: HandleDocumentFeed, SUCCEEDED, pReconv=%s, result=%ld",
     GetReconvertStringLog(pReconv).get(), *oResult));

  return true;
}

bool
IMMHandler::CommitCompositionOnPreviousWindow(nsWindow* aWindow)
{
  if (!mComposingWindow || mComposingWindow == aWindow) {
    return false;
  }

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: CommitCompositionOnPreviousWindow, mIsComposing=%s, "
     "mIsComposingOnPlugin=%s",
     GetBoolName(mIsComposing), GetBoolName(mIsComposingOnPlugin)));

  // If we have composition, we should dispatch composition events internally.
  if (mIsComposing) {
    IMEContext context(mComposingWindow);
    NS_ASSERTION(context.IsValid(), "IME context must be valid");

    HandleEndComposition(mComposingWindow);
    return true;
  }

  // XXX When plug-in has composition, we should commit composition on the
  // plug-in.  However, we need some more work for that.
  return mIsComposingOnPlugin;
}

static uint32_t
PlatformToNSAttr(uint8_t aAttr)
{
  switch (aAttr)
  {
    case ATTR_INPUT_ERROR:
    // case ATTR_FIXEDCONVERTED:
    case ATTR_INPUT:
      return NS_TEXTRANGE_RAWINPUT;
    case ATTR_CONVERTED:
      return NS_TEXTRANGE_CONVERTEDTEXT;
    case ATTR_TARGET_NOTCONVERTED:
      return NS_TEXTRANGE_SELECTEDRAWTEXT;
    case ATTR_TARGET_CONVERTED:
      return NS_TEXTRANGE_SELECTEDCONVERTEDTEXT;
    default:
      NS_ASSERTION(false, "unknown attribute");
      return NS_TEXTRANGE_CARETPOSITION;
  }
}

static const char*
GetRangeTypeName(uint32_t aRangeType)
{
  switch (aRangeType) {
    case NS_TEXTRANGE_RAWINPUT:
      return "NS_TEXTRANGE_RAWINPUT";
    case NS_TEXTRANGE_CONVERTEDTEXT:
      return "NS_TEXTRANGE_CONVERTEDTEXT";
    case NS_TEXTRANGE_SELECTEDRAWTEXT:
      return "NS_TEXTRANGE_SELECTEDRAWTEXT";
    case NS_TEXTRANGE_SELECTEDCONVERTEDTEXT:
      return "NS_TEXTRANGE_SELECTEDCONVERTEDTEXT";
    case NS_TEXTRANGE_CARETPOSITION:
      return "NS_TEXTRANGE_CARETPOSITION";
    default:
      return "UNKNOWN SELECTION TYPE!!";
  }
}

// static
void
IMMHandler::DispatchEvent(nsWindow* aWindow, WidgetGUIEvent& aEvent)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: DispatchEvent(aWindow=0x%p, aEvent={ mMessage=%s }, "
     "aWindow->Destroyed()=%s",
     aWindow, ToChar(aEvent.mMessage), GetBoolName(aWindow->Destroyed())));

  if (aWindow->Destroyed()) {
    return;
  }

  aWindow->DispatchWindowEvent(&aEvent);
}

void
IMMHandler::DispatchCompositionChangeEvent(nsWindow* aWindow,
                                           const IMEContext& aContext)
{
  NS_ASSERTION(mIsComposing, "conflict state");
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: DispatchCompositionChangeEvent"));

  // If we don't need to draw composition string ourselves, we don't need to
  // fire compositionchange event during composing.
  if (!ShouldDrawCompositionStringOurselves()) {
    // But we need to adjust composition window pos and native caret pos, here.
    SetIMERelatedWindowsPos(aWindow, aContext);
    return;
  }

  RefPtr<nsWindow> kungFuDeathGrip(aWindow);

  LayoutDeviceIntPoint point(0, 0);

  WidgetCompositionEvent event(true, eCompositionChange, aWindow);

  aWindow->InitEvent(event, &point);

  event.mRanges = CreateTextRangeArray();
  event.mData = mCompositionString;

  DispatchEvent(aWindow, event);

  // Calling SetIMERelatedWindowsPos will be failure on e10s at this point.
  // compositionchange event will notify NOTIFY_IME_OF_COMPOSITION_UPDATE, then
  // it will call SetIMERelatedWindowsPos.
}

already_AddRefed<TextRangeArray>
IMMHandler::CreateTextRangeArray()
{
  // Sogou (Simplified Chinese IME) returns contradictory values: The cursor
  // position is actual cursor position. However, other values (composition
  // string and attributes) are empty. So, if you want to remove following
  // assertion, be careful.
  NS_ASSERTION(ShouldDrawCompositionStringOurselves(),
    "CreateTextRangeArray is called when we don't need to fire "
    "compositionchange event");

  RefPtr<TextRangeArray> textRangeArray = new TextRangeArray();

  TextRange range;
  if (mCompositionString.IsEmpty()) {
    // Don't append clause information if composition string is empty.
  } else if (mClauseArray.Length() == 0) {
    // Some IMEs don't return clause array information, then, we assume that
    // all characters in the composition string are in one clause.
    range.mStartOffset = 0;
    range.mEndOffset = mCompositionString.Length();
    range.mRangeType = NS_TEXTRANGE_RAWINPUT;
    textRangeArray->AppendElement(range);

    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: CreateTextRangeArray, mClauseLength=0"));
  } else {
    // iterate over the attributes
    uint32_t lastOffset = 0;
    for (uint32_t i = 0; i < mClauseArray.Length() - 1; i++) {
      uint32_t current = mClauseArray[i + 1];
      if (current > mCompositionString.Length()) {
        MOZ_LOG(gIMMLog, LogLevel::Info,
          ("IMM: CreateTextRangeArray, mClauseArray[%ld]=%lu. "
           "This is larger than mCompositionString.Length()=%lu",
           i + 1, current, mCompositionString.Length()));
        current = int32_t(mCompositionString.Length());
      }

      range.mRangeType = PlatformToNSAttr(mAttributeArray[lastOffset]);
      range.mStartOffset = lastOffset;
      range.mEndOffset = current;
      textRangeArray->AppendElement(range);

      lastOffset = current;

      MOZ_LOG(gIMMLog, LogLevel::Info,
        ("IMM: CreateTextRangeArray, index=%ld, rangeType=%s, range=[%lu-%lu]",
         i, GetRangeTypeName(range.mRangeType), range.mStartOffset,
         range.mEndOffset));
    }
  }

  if (mCursorPosition == NO_IME_CARET) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: CreateTextRangeArray, no caret"));
    return textRangeArray.forget();
  }

  uint32_t cursor = static_cast<uint32_t>(mCursorPosition);
  if (cursor > mCompositionString.Length()) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: CreateTextRangeArray, mCursorPosition=%ld. "
       "This is larger than mCompositionString.Length()=%lu",
       mCursorPosition, mCompositionString.Length()));
    cursor = mCompositionString.Length();
  }

  // If caret is in the target clause, the target clause will be painted as
  // normal selection range.  Since caret shouldn't be in selection range on
  // Windows, we shouldn't append caret range in such case.
  const TextRange* targetClause = textRangeArray->GetTargetClause();
  if (targetClause &&
      cursor >= targetClause->mStartOffset &&
      cursor <= targetClause->mEndOffset) {
    // Forget the caret position specified by IME since Gecko's caret position
    // will be at the end of composition string.
    mCursorPosition = NO_IME_CARET;
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: CreateTextRangeArray, no caret due to it's in the target clause, "
       "now, mCursorPosition is NO_IME_CARET"));
    return textRangeArray.forget();
  }

  range.mStartOffset = range.mEndOffset = cursor;
  range.mRangeType = NS_TEXTRANGE_CARETPOSITION;
  textRangeArray->AppendElement(range);

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: CreateTextRangeArray, caret position=%ld",
     range.mStartOffset));

  return textRangeArray.forget();
}

void
IMMHandler::GetCompositionString(const IMEContext& aContext,
                                 DWORD aIndex,
                                 nsAString& aCompositionString) const
{
  aCompositionString.Truncate();

  // Retrieve the size of the required output buffer.
  long lRtn = ::ImmGetCompositionStringW(aContext.get(), aIndex, nullptr, 0);
  if (lRtn < 0 ||
      !aCompositionString.SetLength((lRtn / sizeof(WCHAR)) + 1,
                                    mozilla::fallible)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: GetCompositionString, FAILED, due to OOM"));
    return; // Error or out of memory.
  }

  // Actually retrieve the composition string information.
  lRtn = ::ImmGetCompositionStringW(aContext.get(), aIndex,
                                    (LPVOID)aCompositionString.BeginWriting(),
                                    lRtn + sizeof(WCHAR));
  aCompositionString.SetLength(lRtn / sizeof(WCHAR));

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: GetCompositionString, succeeded, aCompositionString=\"%s\"",
     NS_ConvertUTF16toUTF8(aCompositionString).get()));
}

bool
IMMHandler::GetTargetClauseRange(uint32_t* aOffset,
                                 uint32_t* aLength)
{
  NS_ENSURE_TRUE(aOffset, false);
  NS_ENSURE_TRUE(mIsComposing, false);
  NS_ENSURE_TRUE(ShouldDrawCompositionStringOurselves(), false);

  bool found = false;
  *aOffset = mCompositionStart;
  for (uint32_t i = 0; i < mAttributeArray.Length(); i++) {
    if (mAttributeArray[i] == ATTR_TARGET_NOTCONVERTED ||
        mAttributeArray[i] == ATTR_TARGET_CONVERTED) {
      *aOffset = mCompositionStart + i;
      found = true;
      break;
    }
  }

  if (!aLength) {
    return true;
  }

  if (!found) {
    // The all composition string is targetted when there is no ATTR_TARGET_*
    // clause. E.g., there is only ATTR_INPUT
    *aLength = mCompositionString.Length();
    return true;
  }

  uint32_t offsetInComposition = *aOffset - mCompositionStart;
  *aLength = mCompositionString.Length() - offsetInComposition;
  for (uint32_t i = offsetInComposition; i < mAttributeArray.Length(); i++) {
    if (mAttributeArray[i] != ATTR_TARGET_NOTCONVERTED &&
        mAttributeArray[i] != ATTR_TARGET_CONVERTED) {
      *aLength = i - offsetInComposition;
      break;
    }
  }
  return true;
}

bool
IMMHandler::ConvertToANSIString(const nsAFlatString& aStr,
                                UINT aCodePage,
                                nsACString& aANSIStr)
{
  int len = ::WideCharToMultiByte(aCodePage, 0,
                                  (LPCWSTR)aStr.get(), aStr.Length(),
                                  nullptr, 0, nullptr, nullptr);
  NS_ENSURE_TRUE(len >= 0, false);

  if (!aANSIStr.SetLength(len, mozilla::fallible)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: ConvertToANSIString, FAILED, due to OOM"));
    return false;
  }
  ::WideCharToMultiByte(aCodePage, 0, (LPCWSTR)aStr.get(), aStr.Length(),
                        (LPSTR)aANSIStr.BeginWriting(), len, nullptr, nullptr);
  return true;
}

bool
IMMHandler::GetCharacterRectOfSelectedTextAt(nsWindow* aWindow,
                                             uint32_t aOffset,
                                             LayoutDeviceIntRect& aCharRect,
                                             WritingMode* aWritingMode)
{
  LayoutDeviceIntPoint point(0, 0);

  Selection& selection = GetSelection();
  if (!selection.EnsureValidSelection(aWindow)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: GetCharacterRectOfSelectedTextAt, FAILED, due to "
       "Selection::EnsureValidSelection() failure"));
    return false;
  }

  // The base offset of aOffset is the start of composition string during
  // composing or the start of selected string not during composing.
  uint32_t baseOffset =
    mIsComposing ? mCompositionStart : selection.mOffset;

  CheckedInt<uint32_t> checkingOffset =
    CheckedInt<uint32_t>(baseOffset) + aOffset;
  if (NS_WARN_IF(!checkingOffset.isValid()) ||
      checkingOffset.value() == UINT32_MAX) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: GetCharacterRectOfSelectedTextAt, FAILED, due to "
       "aOffset is too large (aOffset=%u, baseOffset=%u, mIsComposing=%s)",
       aOffset, baseOffset, GetBoolName(mIsComposing)));
    return false;
  }

  // If the offset is larger than the end of composition string or selected
  // string, we should return false since such case must be a bug of the caller
  // or the active IME.  If it's an IME's bug, we need to set targetLength to
  // aOffset.
  uint32_t targetLength =
    mIsComposing ? mCompositionString.Length() : selection.Length();
  if (NS_WARN_IF(aOffset > targetLength)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: GetCharacterRectOfSelectedTextAt, FAILED, due to "
       "aOffset is too large (aOffset=%u, targetLength=%u, mIsComposing=%s)",
       aOffset, targetLength, GetBoolName(mIsComposing)));
    return false;
  }

  uint32_t offset = checkingOffset.value();

  // If there is caret, we might be able to use caret rect.
  uint32_t caretOffset = UINT32_MAX;
  // There is a caret only when the normal selection is collapsed.
  if (selection.Collapsed()) {
    if (mIsComposing) {
      // If it's composing, mCursorPosition is the offset to caret in
      // the composition string.
      if (mCursorPosition != NO_IME_CARET) {
        MOZ_ASSERT(mCursorPosition >= 0);
        caretOffset = mCompositionStart + mCursorPosition;
      } else if (!ShouldDrawCompositionStringOurselves() ||
                 mCompositionString.IsEmpty()) {
        // Otherwise, if there is no composition string, we should assume that
        // there is a caret at the start of composition string.
        caretOffset = mCompositionStart;
      }
    } else {
      // If there is no composition, the selection offset is the caret offset.
      caretOffset = selection.mOffset;
    }
  }

  // If there is a caret and retrieving offset is same as the caret offset,
  // we should use the caret rect.
  if (offset != caretOffset) {
    WidgetQueryContentEvent charRect(true, eQueryTextRect, aWindow);
    charRect.InitForQueryTextRect(offset, 1);
    aWindow->InitEvent(charRect, &point);
    DispatchEvent(aWindow, charRect);
    if (charRect.mSucceeded) {
      aCharRect = charRect.mReply.mRect;
      if (aWritingMode) {
        *aWritingMode = charRect.GetWritingMode();
      }
      MOZ_LOG(gIMMLog, LogLevel::Debug,
        ("IMM: GetCharacterRectOfSelectedTextAt, Succeeded, aOffset=%u, "
         "aCharRect={ x: %ld, y: %ld, width: %ld, height: %ld }, "
         "charRect.GetWritingMode()=%s",
         aOffset, aCharRect.x, aCharRect.y, aCharRect.width, aCharRect.height,
         GetWritingModeName(charRect.GetWritingMode()).get()));
      return true;
    }
  }

  return GetCaretRect(aWindow, aCharRect, aWritingMode);
}

bool
IMMHandler::GetCaretRect(nsWindow* aWindow,
                         LayoutDeviceIntRect& aCaretRect,
                         WritingMode* aWritingMode)
{
  LayoutDeviceIntPoint point(0, 0);

  Selection& selection = GetSelection();
  if (!selection.EnsureValidSelection(aWindow)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: GetCaretRect, FAILED, due to "
       "Selection::EnsureValidSelection() failure"));
    return false;
  }

  WidgetQueryContentEvent caretRect(true, eQueryCaretRect, aWindow);
  caretRect.InitForQueryCaretRect(selection.mOffset);
  aWindow->InitEvent(caretRect, &point);
  DispatchEvent(aWindow, caretRect);
  if (!caretRect.mSucceeded) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: GetCaretRect, FAILED, due to eQueryCaretRect failure"));
    return false;
  }
  aCaretRect = caretRect.mReply.mRect;
  if (aWritingMode) {
    *aWritingMode = caretRect.GetWritingMode();
  }
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: GetCaretRect, SUCCEEDED, "
     "aCaretRect={ x: %ld, y: %ld, width: %ld, height: %ld }, "
     "caretRect.GetWritingMode()=%s",
     aCaretRect.x, aCaretRect.y, aCaretRect.width, aCaretRect.height,
     GetWritingModeName(caretRect.GetWritingMode()).get()));
  return true;
}

bool
IMMHandler::SetIMERelatedWindowsPos(nsWindow* aWindow,
                                    const IMEContext& aContext)
{
  LayoutDeviceIntRect r;
  // Get first character rect of current a normal selected text or a composing
  // string.
  WritingMode writingMode;
  bool ret = GetCharacterRectOfSelectedTextAt(aWindow, 0, r, &writingMode);
  NS_ENSURE_TRUE(ret, false);
  nsWindow* toplevelWindow = aWindow->GetTopLevelWindow(false);
  LayoutDeviceIntRect firstSelectedCharRect;
  ResolveIMECaretPos(toplevelWindow, r, aWindow, firstSelectedCharRect);

  // Set native caret size/position to our caret. Some IMEs honor it. E.g.,
  // "Intelligent ABC" (Simplified Chinese) and "MS PinYin 3.0" (Simplified
  // Chinese) on XP.
  LayoutDeviceIntRect caretRect(firstSelectedCharRect);
  if (GetCaretRect(aWindow, r)) {
    ResolveIMECaretPos(toplevelWindow, r, aWindow, caretRect);
  } else {
    NS_WARNING("failed to get caret rect");
    caretRect.width = 1;
  }
  if (!mNativeCaretIsCreated) {
    mNativeCaretIsCreated = ::CreateCaret(aWindow->GetWindowHandle(), nullptr,
                                          caretRect.width, caretRect.height);
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: SetIMERelatedWindowsPos, mNativeCaretIsCreated=%s, "
       "width=%ld, height=%ld",
       GetBoolName(mNativeCaretIsCreated), caretRect.width, caretRect.height));
  }
  ::SetCaretPos(caretRect.x, caretRect.y);

  if (ShouldDrawCompositionStringOurselves()) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: SetIMERelatedWindowsPos, Set candidate window"));

    // Get a rect of first character in current target in composition string.
    LayoutDeviceIntRect firstTargetCharRect, lastTargetCharRect;
    if (mIsComposing && !mCompositionString.IsEmpty()) {
      // If there are no targetted selection, we should use it's first character
      // rect instead.
      uint32_t offset, length;
      if (!GetTargetClauseRange(&offset, &length)) {
        MOZ_LOG(gIMMLog, LogLevel::Error,
          ("IMM: SetIMERelatedWindowsPos, FAILED, due to "
           "GetTargetClauseRange() failure"));
        return false;
      }
      ret = GetCharacterRectOfSelectedTextAt(aWindow,
                                             offset - mCompositionStart,
                                             firstTargetCharRect, &writingMode);
      NS_ENSURE_TRUE(ret, false);
      if (length) {
        ret = GetCharacterRectOfSelectedTextAt(aWindow,
                offset + length - 1 - mCompositionStart, lastTargetCharRect);
        NS_ENSURE_TRUE(ret, false);
      } else {
        lastTargetCharRect = firstTargetCharRect;
      }
    } else {
      // If there are no composition string, we should use a first character
      // rect.
      ret = GetCharacterRectOfSelectedTextAt(aWindow, 0,
                                             firstTargetCharRect, &writingMode);
      NS_ENSURE_TRUE(ret, false);
      lastTargetCharRect = firstTargetCharRect;
    }
    ResolveIMECaretPos(toplevelWindow, firstTargetCharRect,
                       aWindow, firstTargetCharRect);
    ResolveIMECaretPos(toplevelWindow, lastTargetCharRect,
                       aWindow, lastTargetCharRect);
    LayoutDeviceIntRect targetClauseRect;
    targetClauseRect.UnionRect(firstTargetCharRect, lastTargetCharRect);

    // Move the candidate window to proper position from the target clause as
    // far as possible.
    CANDIDATEFORM candForm;
    candForm.dwIndex = 0;
    if (!writingMode.IsVertical() || IsVerticalWritingSupported()) {
      candForm.dwStyle = CFS_EXCLUDE;
      // Candidate window shouldn't overlap the target clause in any writing
      // mode.
      candForm.rcArea.left = targetClauseRect.x;
      candForm.rcArea.right = targetClauseRect.XMost();
      candForm.rcArea.top = targetClauseRect.y;
      candForm.rcArea.bottom = targetClauseRect.YMost();
      if (!writingMode.IsVertical()) {
        // In horizontal layout, current point of interest should be top-left
        // of the first character.
        candForm.ptCurrentPos.x = firstTargetCharRect.x;
        candForm.ptCurrentPos.y = firstTargetCharRect.y;
      } else if (writingMode.IsVerticalRL()) {
        // In vertical layout (RL), candidate window should be positioned right
        // side of target clause.  However, we don't set vertical writing font
        // to the IME.  Therefore, the candidate window may be positioned
        // bottom-left of target clause rect with these information.
        candForm.ptCurrentPos.x = targetClauseRect.x;
        candForm.ptCurrentPos.y = targetClauseRect.y;
      } else {
        MOZ_ASSERT(writingMode.IsVerticalLR(), "Did we miss some causes?");
        // In vertical layout (LR), candidate window should be poisitioned left
        // side of target clause.  Although, we don't set vertical writing font
        // to the IME, the candidate window may be positioned bottom-right of
        // the target clause rect with these information.
        candForm.ptCurrentPos.x = targetClauseRect.XMost();
        candForm.ptCurrentPos.y = targetClauseRect.y;
      }
    } else {
      // If vertical writing is not supported by IME, let's set candidate
      // window position to the bottom-left of the target clause because
      // the position must be the safest position to prevent the candidate
      // window to overlap with the target clause.
      candForm.dwStyle = CFS_CANDIDATEPOS;
      candForm.ptCurrentPos.x = targetClauseRect.x;
      candForm.ptCurrentPos.y = targetClauseRect.YMost();
    }
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: SetIMERelatedWindowsPos, Calling ImmSetCandidateWindow()... "
       "ptCurrentPos={ x=%d, y=%d }, "
       "rcArea={ left=%d, top=%d, right=%d, bottom=%d }, "
       "writingMode=%s",
       candForm.ptCurrentPos.x, candForm.ptCurrentPos.y,
       candForm.rcArea.left, candForm.rcArea.top,
       candForm.rcArea.right, candForm.rcArea.bottom,
       GetWritingModeName(writingMode).get()));
    ::ImmSetCandidateWindow(aContext.get(), &candForm);
  } else {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: SetIMERelatedWindowsPos, Set composition window"));

    // Move the composition window to caret position (if selected some
    // characters, we should use first character rect of them).
    // And in this mode, IME adjusts the candidate window position
    // automatically. So, we don't need to set it.
    COMPOSITIONFORM compForm;
    compForm.dwStyle = CFS_POINT;
    compForm.ptCurrentPos.x =
      !writingMode.IsVerticalLR() ? firstSelectedCharRect.x :
                                    firstSelectedCharRect.XMost();
    compForm.ptCurrentPos.y = firstSelectedCharRect.y;
    ::ImmSetCompositionWindow(aContext.get(), &compForm);
  }

  return true;
}

void
IMMHandler::SetIMERelatedWindowsPosOnPlugin(nsWindow* aWindow,
                                            const IMEContext& aContext)
{
  WidgetQueryContentEvent editorRectEvent(true, eQueryEditorRect, aWindow);
  aWindow->InitEvent(editorRectEvent);
  DispatchEvent(aWindow, editorRectEvent);
  if (!editorRectEvent.mSucceeded) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: SetIMERelatedWindowsPosOnPlugin, "
       "FAILED, due to eQueryEditorRect failure"));
    return;
  }

  // Clip the plugin rect by the client rect of the window because composition
  // window needs to be specified the position in the client area.
  nsWindow* toplevelWindow = aWindow->GetTopLevelWindow(false);
  LayoutDeviceIntRect pluginRectInScreen =
    editorRectEvent.mReply.mRect + toplevelWindow->WidgetToScreenOffset();
  LayoutDeviceIntRect winRectInScreen;
  aWindow->GetClientBounds(winRectInScreen);
  // composition window cannot be positioned on the edge of client area.
  winRectInScreen.width--;
  winRectInScreen.height--;
  LayoutDeviceIntRect clippedPluginRect;
  clippedPluginRect.x =
    std::min(std::max(pluginRectInScreen.x, winRectInScreen.x),
             winRectInScreen.XMost());
  clippedPluginRect.y =
    std::min(std::max(pluginRectInScreen.y, winRectInScreen.y),
             winRectInScreen.YMost());
  int32_t xMost = std::min(pluginRectInScreen.XMost(), winRectInScreen.XMost());
  int32_t yMost = std::min(pluginRectInScreen.YMost(), winRectInScreen.YMost());
  clippedPluginRect.width = std::max(0, xMost - clippedPluginRect.x);
  clippedPluginRect.height = std::max(0, yMost - clippedPluginRect.y);
  clippedPluginRect -= aWindow->WidgetToScreenOffset();

  // Cover the plugin with native caret.  This prevents IME's window and plugin
  // overlap.
  if (mNativeCaretIsCreated) {
    ::DestroyCaret();
  }
  mNativeCaretIsCreated =
    ::CreateCaret(aWindow->GetWindowHandle(), nullptr,
                  clippedPluginRect.width, clippedPluginRect.height);
  ::SetCaretPos(clippedPluginRect.x, clippedPluginRect.y);

  // Set the composition window to bottom-left of the clipped plugin.
  // As far as we know, there is no IME for RTL language.  Therefore, this code
  // must not need to take care of RTL environment.
  COMPOSITIONFORM compForm;
  compForm.dwStyle = CFS_POINT;
  compForm.ptCurrentPos.x = clippedPluginRect.BottomLeft().x;
  compForm.ptCurrentPos.y = clippedPluginRect.BottomLeft().y;
  if (!::ImmSetCompositionWindow(aContext.get(), &compForm)) {
    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: SetIMERelatedWindowsPosOnPlugin, "
       "FAILED, due to ::ImmSetCompositionWindow() failure"));
    return;
  }
}

void
IMMHandler::ResolveIMECaretPos(nsIWidget* aReferenceWidget,
                               LayoutDeviceIntRect& aCursorRect,
                               nsIWidget* aNewOriginWidget,
                               LayoutDeviceIntRect& aOutRect)
{
  aOutRect = aCursorRect;

  if (aReferenceWidget == aNewOriginWidget)
    return;

  if (aReferenceWidget)
    aOutRect.MoveBy(aReferenceWidget->WidgetToScreenOffset());

  if (aNewOriginWidget)
    aOutRect.MoveBy(-aNewOriginWidget->WidgetToScreenOffset());
}

static void
SetHorizontalFontToLogFont(const nsAString& aFontFace,
                           LOGFONTW& aLogFont)
{
  aLogFont.lfEscapement = aLogFont.lfOrientation = 0;
  if (NS_WARN_IF(aFontFace.Length() > LF_FACESIZE - 1)) {
    memcpy(aLogFont.lfFaceName, L"System", sizeof(L"System"));
    return;
  }
  memcpy(aLogFont.lfFaceName, aFontFace.BeginReading(),
         aFontFace.Length() * sizeof(wchar_t));
  aLogFont.lfFaceName[aFontFace.Length()] = 0;
}

static void
SetVerticalFontToLogFont(const nsAString& aFontFace,
                         LOGFONTW& aLogFont)
{
  aLogFont.lfEscapement = aLogFont.lfOrientation = 2700;
  if (NS_WARN_IF(aFontFace.Length() > LF_FACESIZE - 2)) {
    memcpy(aLogFont.lfFaceName, L"@System", sizeof(L"@System"));
    return;
  }
  aLogFont.lfFaceName[0] = '@';
  memcpy(&aLogFont.lfFaceName[1], aFontFace.BeginReading(),
         aFontFace.Length() * sizeof(wchar_t));
  aLogFont.lfFaceName[aFontFace.Length() + 1] = 0;
}

void
IMMHandler::AdjustCompositionFont(const IMEContext& aContext,
                                  const WritingMode& aWritingMode,
                                  bool aForceUpdate)
{
  // An instance of IMMHandler is destroyed when active IME is changed.
  // Therefore, we need to store the information which are set to the IM
  // context to static variables since IM context is never recreated.
  static bool sCompositionFontsInitialized = false;
  static nsString sCompositionFont =
    Preferences::GetString("intl.imm.composition_font");

  // If composition font is customized by pref, we need to modify the
  // composition font of the IME context at first time even if the writing mode
  // is horizontal.
  bool setCompositionFontForcibly = aForceUpdate ||
    (!sCompositionFontsInitialized && !sCompositionFont.IsEmpty());

  static WritingMode sCurrentWritingMode;
  static nsString sCurrentIMEName;
  if (!setCompositionFontForcibly &&
      sWritingModeOfCompositionFont == aWritingMode &&
      sCurrentIMEName == sIMEName) {
    // Nothing to do if writing mode isn't being changed.
    return;
  }

  // Decide composition fonts for both horizontal writing mode and vertical
  // writing mode.  If the font isn't specified by the pref, use default
  // font which is already set to the IM context.  And also in vertical writing
  // mode, insert '@' to the start of the font.
  if (!sCompositionFontsInitialized) {
    sCompositionFontsInitialized = true;
    // sCompositionFontH must not start with '@' and its length is less than
    // LF_FACESIZE since it needs to end with null terminating character.
    if (sCompositionFont.IsEmpty() ||
        sCompositionFont.Length() > LF_FACESIZE - 1 ||
        sCompositionFont[0] == '@') {
      LOGFONTW defaultLogFont;
      if (NS_WARN_IF(!::ImmGetCompositionFont(aContext.get(),
                                              &defaultLogFont))) {
        MOZ_LOG(gIMMLog, LogLevel::Error,
          ("IMM: AdjustCompositionFont, ::ImmGetCompositionFont() failed"));
        sCompositionFont.AssignLiteral("System");
      } else {
        // The font face is typically, "System".
        sCompositionFont.Assign(defaultLogFont.lfFaceName);
      }
    }

    MOZ_LOG(gIMMLog, LogLevel::Info,
      ("IMM: AdjustCompositionFont, sCompositionFont=\"%s\" is initialized",
       NS_ConvertUTF16toUTF8(sCompositionFont).get()));
  }

  static nsString sCompositionFontForJapanist2003;
  if (IsJapanist2003Active() && sCompositionFontForJapanist2003.IsEmpty()) {
    const char* kCompositionFontForJapanist2003 =
      "intl.imm.composition_font.japanist_2003";
    sCompositionFontForJapanist2003 =
      Preferences::GetString(kCompositionFontForJapanist2003);
    // If the font name is not specified properly, let's use
    // "MS PGothic" instead.
    if (sCompositionFontForJapanist2003.IsEmpty() ||
        sCompositionFontForJapanist2003.Length() > LF_FACESIZE - 2 ||
        sCompositionFontForJapanist2003[0] == '@') {
      sCompositionFontForJapanist2003.AssignLiteral("MS PGothic");
    }
  }

  sWritingModeOfCompositionFont = aWritingMode;
  sCurrentIMEName = sIMEName;

  LOGFONTW logFont;
  memset(&logFont, 0, sizeof(logFont));
  if (!::ImmGetCompositionFont(aContext.get(), &logFont)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: AdjustCompositionFont, ::ImmGetCompositionFont() failed"));
    logFont.lfFaceName[0] = 0;
  }
  // Need to reset some information which should be recomputed with new font.
  logFont.lfWidth = 0;
  logFont.lfWeight = FW_DONTCARE;
  logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
  logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  logFont.lfPitchAndFamily = DEFAULT_PITCH;

  if (!mIsComposingOnPlugin &&
      aWritingMode.IsVertical() && IsVerticalWritingSupported()) {
    SetVerticalFontToLogFont(
      IsJapanist2003Active() ? sCompositionFontForJapanist2003 :
                               sCompositionFont, logFont);
  } else {
    SetHorizontalFontToLogFont(
      IsJapanist2003Active() ? sCompositionFontForJapanist2003 :
                               sCompositionFont, logFont);
  }
  MOZ_LOG(gIMMLog, LogLevel::Warning,
    ("IMM: AdjustCompositionFont, calling ::ImmSetCompositionFont(\"%s\")",
     NS_ConvertUTF16toUTF8(nsDependentString(logFont.lfFaceName)).get()));
  ::ImmSetCompositionFontW(aContext.get(), &logFont);
}

// static
nsresult
IMMHandler::OnMouseButtonEvent(nsWindow* aWindow,
                               const IMENotification& aIMENotification)
{
  // We don't need to create the instance of the handler here.
  if (!gIMMHandler) {
    return NS_OK;
  }

  if (!sWM_MSIME_MOUSE || !IsComposingOnOurEditor() ||
      !ShouldDrawCompositionStringOurselves()) {
    return NS_OK;
  }

  // We need to handle only mousedown event.
  if (aIMENotification.mMouseButtonEventData.mEventMessage != eMouseDown) {
    return NS_OK;
  }

  // If the character under the cursor is not in the composition string,
  // we don't need to notify IME of it.
  uint32_t compositionStart = gIMMHandler->mCompositionStart;
  uint32_t compositionEnd =
    compositionStart + gIMMHandler->mCompositionString.Length();
  if (aIMENotification.mMouseButtonEventData.mOffset < compositionStart ||
      aIMENotification.mMouseButtonEventData.mOffset >= compositionEnd) {
    return NS_OK;
  }

  BYTE button;
  switch (aIMENotification.mMouseButtonEventData.mButton) {
    case WidgetMouseEventBase::eLeftButton:
      button = IMEMOUSE_LDOWN;
      break;
    case WidgetMouseEventBase::eMiddleButton:
      button = IMEMOUSE_MDOWN;
      break;
    case WidgetMouseEventBase::eRightButton:
      button = IMEMOUSE_RDOWN;
      break;
    default:
      return NS_OK;
  }

  // calcurate positioning and offset
  // char :            JCH1|JCH2|JCH3
  // offset:           0011 1122 2233
  // positioning:      2301 2301 2301
  nsIntPoint cursorPos =
    aIMENotification.mMouseButtonEventData.mCursorPos.AsIntPoint();
  nsIntRect charRect =
    aIMENotification.mMouseButtonEventData.mCharRect.AsIntRect();
  int32_t cursorXInChar = cursorPos.x - charRect.x;
  // The event might hit to zero-width character, see bug 694913.
  // The reason might be:
  // * There are some zero-width characters are actually.
  // * font-size is specified zero.
  // But nobody reproduced this bug actually...
  // We should assume that user clicked on right most of the zero-width
  // character in such case.
  int positioning = 1;
  if (charRect.width > 0) {
    positioning = cursorXInChar * 4 / charRect.width;
    positioning = (positioning + 2) % 4;
  }

  int offset =
    aIMENotification.mMouseButtonEventData.mOffset - compositionStart;
  if (positioning < 2) {
    offset++;
  }

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnMouseButtonEvent, x,y=%ld,%ld, offset=%ld, positioning=%ld",
     cursorPos.x, cursorPos.y, offset, positioning));

  // send MS_MSIME_MOUSE message to default IME window.
  HWND imeWnd = ::ImmGetDefaultIMEWnd(aWindow->GetWindowHandle());
  IMEContext context(aWindow);
  if (::SendMessageW(imeWnd, sWM_MSIME_MOUSE,
                     MAKELONG(MAKEWORD(button, positioning), offset),
                     (LPARAM) context.get()) == 1) {
    return NS_SUCCESS_EVENT_CONSUMED;
  }
  return NS_OK;
}

// static
bool
IMMHandler::OnKeyDownEvent(nsWindow* aWindow,
                           WPARAM wParam,
                           LPARAM lParam,
                           MSGResult& aResult)
{
  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: OnKeyDownEvent, hWnd=%08x, wParam=%08x, lParam=%08x",
     aWindow->GetWindowHandle(), wParam, lParam));
  aResult.mConsumed = false;
  switch (wParam) {
    case VK_TAB:
    case VK_PRIOR:
    case VK_NEXT:
    case VK_END:
    case VK_HOME:
    case VK_LEFT:
    case VK_UP:
    case VK_RIGHT:
    case VK_DOWN:
    case VK_RETURN:
      // If IME didn't process the key message (the virtual key code wasn't
      // converted to VK_PROCESSKEY), and the virtual key code event causes
      // moving caret or editing text with keeping composing state, we should
      // cancel the composition here because we cannot support moving
      // composition string with DOM events (IE also cancels the composition
      // in same cases).  Then, this event will be dispatched.
      if (IsComposingOnOurEditor()) {
        // NOTE: We don't need to cancel the composition on another window.
        CancelComposition(aWindow, false);
      }
      return false;
    default:
      return false;
  }
}

/******************************************************************************
 * IMMHandler::Selection
 ******************************************************************************/

bool
IMMHandler::Selection::IsValid() const
{
  if (!mIsValid || NS_WARN_IF(mOffset == UINT32_MAX)) {
    return false;
  }
  CheckedInt<uint32_t> endOffset =
    CheckedInt<uint32_t>(mOffset) + Length();
  return endOffset.isValid();
}

bool
IMMHandler::Selection::Update(const IMENotification& aIMENotification)
{
  mOffset = aIMENotification.mSelectionChangeData.mOffset;
  mString = aIMENotification.mSelectionChangeData.String();
  mWritingMode = aIMENotification.mSelectionChangeData.GetWritingMode();
  mIsValid = true;

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: Selection::Update, aIMENotification={ mSelectionChangeData={ "
     "mOffset=%u, mLength=%u, GetWritingMode()=%s } }",
     mOffset, mString.Length(), GetWritingModeName(mWritingMode).get()));

  if (!IsValid()) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: Selection::Update, FAILED, due to invalid range"));
    Clear();
    return false;
  }
  return true;
}

bool
IMMHandler::Selection::Init(nsWindow* aWindow)
{
  Clear();

  WidgetQueryContentEvent selection(true, eQuerySelectedText, aWindow);
  LayoutDeviceIntPoint point(0, 0);
  aWindow->InitEvent(selection, &point);
  DispatchEvent(aWindow, selection);
  if (NS_WARN_IF(!selection.mSucceeded)) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: Selection::Init, FAILED, due to eQuerySelectedText failure"));
    return false;
  }
  // If the window is destroyed during querying selected text, we shouldn't
  // do anymore.
  if (aWindow->Destroyed()) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: Selection::Init, FAILED, due to the widget destroyed"));
    return false;
  }

  mOffset = selection.mReply.mOffset;
  mString = selection.mReply.mString;
  mWritingMode = selection.GetWritingMode();
  mIsValid = true;

  MOZ_LOG(gIMMLog, LogLevel::Info,
    ("IMM: Selection::Init, selection={ mReply={ mOffset=%u, "
     "mString.Length()=%u, mWritingMode=%s } }",
     mOffset, mString.Length(), GetWritingModeName(mWritingMode).get()));

  if (!IsValid()) {
    MOZ_LOG(gIMMLog, LogLevel::Error,
      ("IMM: Selection::Init, FAILED, due to invalid range"));
    Clear();
    return false;
  }
  return true;
}

bool
IMMHandler::Selection::EnsureValidSelection(nsWindow* aWindow)
{
  if (IsValid()) {
    return true;
  }
  return Init(aWindow);
}

} // namespace widget
} // namespace mozilla