1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508
|
# vim:et sts=4 sw=4
#
# ibus-table - The Tables engine for IBus
#
# Copyright (c) 2008-2009 Yu Yuwei <acevery@gmail.com>
# Copyright (c) 2009-2014 Caius "kaio" CHANCE <me@kaio.net>
# Copyright (c) 2012-2022 Mike FABIAN <mfabian@redhat.com>
# Copyright (c) 2019 Peng Wu <alexepico@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
'''
This file implements the ibus engine for ibus-table
'''
__all__ = (
"TabEngine",
)
from typing import Any
from typing import List
from typing import Tuple
from typing import Iterable
from typing import Dict
from typing import Union
from typing import Optional
from typing import Callable
import sys
import os
import re
import ast
import copy
import time
import logging
import subprocess
from gettext import dgettext
_: Callable[[str], str] = lambda a: dgettext('ibus-table', a)
N_: Callable[[str], str] = lambda a: a
# pylint: disable=wrong-import-position
from gi import require_version # type: ignore
require_version('IBus', '1.0')
from gi.repository import IBus # type: ignore
require_version('Gio', '2.0')
from gi.repository import Gio
require_version('GLib', '2.0')
from gi.repository import GLib
# pylint: enable=wrong-import-position
#import tabsqlitedb
from gi.repository import GObject
import it_util
import it_active_window
import it_sound
import ibus_table_location
LOGGER = logging.getLogger('ibus-table')
def ascii_ispunct(character: str) -> bool:
'''
Use our own function instead of ascii.ispunct()
from “from curses import ascii” because the behaviour
of the latter is kind of weird. In Python 3.3.2 it does
for example:
# >>> from curses import ascii
# >>> ascii.ispunct('.')
# True
# >>> ascii.ispunct(u'.')
# True
# >>> ascii.ispunct('a')
# False
# >>> ascii.ispunct(u'a')
# False
# >>>
# >>> ascii.ispunct(u'あ')
# True
# >>> ascii.ispunct('あ')
# True
# >>>
あ isn’t punctuation. ascii.ispunct() only really works
in the ascii range, it returns weird results when used
over the whole unicode range. Maybe we should better use
unicodedata.category(), which works fine to figure out
what is punctuation for all of unicode. But at the moment
I am only porting from Python2 to Python3 and just want to
preserve the original behaviour for the moment.
By the way, Python 3.6.6 does not seem the above bug
anymore, in Python 3.6.6 we get
# >>> from curses import ascii
# >>> ascii.ispunct('あ')
# False
# >>>
Examples:
>>> ascii_ispunct('.')
True
>>> ascii_ispunct('a')
False
>>> ascii_ispunct('あ')
False
'''
return bool(character in '''!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~''')
THEME: Dict[str, Union[bool, int]] = {
"dark": False,
"candidate_text": it_util.color_string_to_argb('#1973a2'),
"system_phrase": it_util.color_string_to_argb('#000000'),
"user_phrase": it_util.color_string_to_argb('#7700c3'),
"system_phrase_unused": it_util.color_string_to_argb('#000000'),
"debug_text": it_util.color_string_to_argb('#00ff00'),
"preedit_left": it_util.color_string_to_argb('#f90f0f'), # bright red
"preedit_right": it_util.color_string_to_argb('#1edc1a'), # light green
"preedit_invalid": it_util.color_string_to_argb('#ff00ff'), # magenta
"aux_text": it_util.color_string_to_argb('#9515b5'),
}
THEME_DARK: Dict[str, Union[bool, int]] = {
"dark": True,
"candidate_text": it_util.color_string_to_argb('#7bc8f0'),
"system_phrase": it_util.color_string_to_argb('#ffffff'),
"user_phrase": it_util.color_string_to_argb('#c078ee'),
"system_phrase_unused": it_util.color_string_to_argb('#f0f0f0'),
"debug_text": it_util.color_string_to_argb('#00ff00'),
"preedit_left": it_util.color_string_to_argb('#f9f90f'),
"preedit_right": it_util.color_string_to_argb('#1edc1a'),
"preedit_invalid": it_util.color_string_to_argb('#ff00ff'),
"aux_text": it_util.color_string_to_argb('#dd70f9'),
}
__HALF_FULL_TABLE: List[Tuple[int, int, int]] = [
(0x0020, 0x3000, 1),
(0x0021, 0xFF01, 0x5E),
(0x00A2, 0xFFE0, 2),
(0x00A5, 0xFFE5, 1),
(0x00A6, 0xFFE4, 1),
(0x00AC, 0xFFE2, 1),
(0x00AF, 0xFFE3, 1),
(0x20A9, 0xFFE6, 1),
(0xFF61, 0x3002, 1),
(0xFF62, 0x300C, 2),
(0xFF64, 0x3001, 1),
(0xFF65, 0x30FB, 1),
(0xFF66, 0x30F2, 1),
(0xFF67, 0x30A1, 1),
(0xFF68, 0x30A3, 1),
(0xFF69, 0x30A5, 1),
(0xFF6A, 0x30A7, 1),
(0xFF6B, 0x30A9, 1),
(0xFF6C, 0x30E3, 1),
(0xFF6D, 0x30E5, 1),
(0xFF6E, 0x30E7, 1),
(0xFF6F, 0x30C3, 1),
(0xFF70, 0x30FC, 1),
(0xFF71, 0x30A2, 1),
(0xFF72, 0x30A4, 1),
(0xFF73, 0x30A6, 1),
(0xFF74, 0x30A8, 1),
(0xFF75, 0x30AA, 2),
(0xFF77, 0x30AD, 1),
(0xFF78, 0x30AF, 1),
(0xFF79, 0x30B1, 1),
(0xFF7A, 0x30B3, 1),
(0xFF7B, 0x30B5, 1),
(0xFF7C, 0x30B7, 1),
(0xFF7D, 0x30B9, 1),
(0xFF7E, 0x30BB, 1),
(0xFF7F, 0x30BD, 1),
(0xFF80, 0x30BF, 1),
(0xFF81, 0x30C1, 1),
(0xFF82, 0x30C4, 1),
(0xFF83, 0x30C6, 1),
(0xFF84, 0x30C8, 1),
(0xFF85, 0x30CA, 6),
(0xFF8B, 0x30D2, 1),
(0xFF8C, 0x30D5, 1),
(0xFF8D, 0x30D8, 1),
(0xFF8E, 0x30DB, 1),
(0xFF8F, 0x30DE, 5),
(0xFF94, 0x30E4, 1),
(0xFF95, 0x30E6, 1),
(0xFF96, 0x30E8, 6),
(0xFF9C, 0x30EF, 1),
(0xFF9D, 0x30F3, 1),
(0xFFA0, 0x3164, 1),
(0xFFA1, 0x3131, 30),
(0xFFC2, 0x314F, 6),
(0xFFCA, 0x3155, 6),
(0xFFD2, 0x315B, 9),
(0xFFE9, 0x2190, 4),
(0xFFED, 0x25A0, 1),
(0xFFEE, 0x25CB, 1)]
def unichar_half_to_full(char: str) -> str:
'''
Convert a character to full width if possible.
:param char: A character to convert to full width
Examples:
>>> unichar_half_to_full('a')
'a'
>>> unichar_half_to_full('a')
'a'
>>> unichar_half_to_full('☺')
'☺'
'''
code = ord(char)
for half, full, size in __HALF_FULL_TABLE:
if half <= code < half + size:
return chr(full + code - half)
return char
def unichar_full_to_half(char: str) -> str:
'''
Convert a character to half width if possible.
:param char: A character to convert to half width
:type char: String
:rtype: String
Examples:
>>> unichar_full_to_half('a')
'a'
>>> unichar_full_to_half('a')
'a'
>>> unichar_full_to_half('☺')
'☺'
'''
code = ord(char)
for half, full, size in __HALF_FULL_TABLE:
if full <= code < full + size:
return chr(half + code - full)
return char
SAVE_USER_COUNT_MAX = 16
SAVE_USER_TIMEOUT = 30 # in seconds
IBUS_VERSION = (IBus.MAJOR_VERSION, IBus.MINOR_VERSION, IBus.MICRO_VERSION)
class TabEngine(IBus.EngineSimple): # type: ignore
'''The IM Engine for Tables'''
def __init__(
self,
bus: IBus.Bus,
obj_path: str,
database: Any, # tabsqlitedb.TabSqliteDb
unit_test: bool = False) -> None:
LOGGER.info(
'TabEngine.__init__(bus=%s, obj_path=%s, database=%s)',
bus, obj_path, database)
LOGGER.info('ibus version = %s', '.'.join(map(str, IBUS_VERSION)))
if hasattr(IBus.Engine.props, 'has_focus_id'):
super().__init__(
connection=bus.get_connection(),
object_path=obj_path,
has_focus_id=True)
LOGGER.info('This ibus version has focus id.')
else:
super().__init__(
connection=bus.get_connection(),
object_path=obj_path)
LOGGER.info('This ibus version does *not* have focus id.')
# Load $HOME/.XCompose file:
self.add_table_by_locale(None)
self._unit_test = unit_test
self._input_purpose: int = 0
self._input_hints: int = 0
self._bus = bus
# this is the backend sql db we need for our IME
# we receive this db from IMEngineFactory
#self.db = tabsqlitedb.TabSqliteDb( name = dbname )
self.database = database
self._setup_process: Optional[subprocess.Popen[Any]] = None
self._icon_dir = os.path.join(ibus_table_location.data(), 'icons')
self._engine_name = os.path.basename(
self.database.filename).replace('.db', '').replace(' ', '_')
LOGGER.info('self._engine_name = %s', self._engine_name)
self._gsettings: Gio.Settings = Gio.Settings(
schema='org.freedesktop.ibus.engine.table',
path=f'/org/freedesktop/ibus/engine/table/{self._engine_name}/')
self._gsettings.connect('changed', self.on_gsettings_value_changed)
self._prop_dict: Dict[str, IBus.Property] = {}
self._sub_props_dict: Dict[str, IBus.PropList] = {}
self.main_prop_list: List[IBus.Property] = []
self.chinese_mode_menu: Dict[str, Any] = {}
self.chinese_mode_properties: Dict[str, Any] = {}
self.input_mode_menu: Dict[str, Any] = {}
self.input_mode_properties: Dict[str, Any] = {}
self.letter_width_menu: Dict[str, Any] = {}
self.letter_width_properties: Dict[str, Any] = {}
self.punctuation_width_menu: Dict[str, Any] = {}
self.punctuation_width_properties: Dict[str, Any] = {}
self.pinyin_mode_menu: Dict[str, Any] = {}
self.pinyin_mode_properties: Dict[str, Any] = {}
self.suggestion_mode_menu: Dict[str, Any] = {}
self.suggestion_mode_properties: Dict[str, Any] = {}
self.onechar_mode_menu: Dict[str, Any] = {}
self.onechar_mode_properties: Dict[str, Any] = {}
self.autocommit_mode_menu: Dict[str, Any] = {}
self.autocommit_mode_properties: Dict[str, Any] = {}
self._setup_property: Optional[IBus.Property] = None
self._im_client: str = ''
self.theme = THEME
self._keybindings: Dict[str, List[str]] = {}
self._hotkeys: Optional[it_util.HotKeys] = None
# self._ime_py: Indicates whether this table supports pinyin mode
self._ime_py = self.database.ime_properties.get('pinyin_mode')
if self._ime_py:
self._ime_py = bool(self._ime_py.lower() == 'true')
else:
LOGGER.info('We could not find "pinyin_mode" entry in database, '
'is it an outdated database?')
self._ime_py = False
# self._ime_sg: Indicates whether this table supports suggestion mode
self._ime_sg = self.database.ime_properties.get('suggestion_mode')
if self._ime_sg:
self._ime_sg = bool(self._ime_sg.lower() == 'true')
else:
LOGGER.info(
'We could not find "suggestion_mode" entry in database, '
'is it an outdated database?')
self._ime_sg = False
self._symbol = self.database.ime_properties.get('symbol')
if self._symbol is None or self._symbol == '':
self._symbol = self.database.ime_properties.get('status_prompt')
if self._symbol is None:
self._symbol = ''
# some Chinese tables have “STATUS_PROMPT = CN” replace it
# with the shorter and nicer “中”:
if self._symbol == 'CN':
self._symbol = '中'
# workaround for the translit and translit-ua tables which
# have 2 character symbols. '☑' + self._symbol then is
# 3 characters and currently gnome-shell ignores symbols longer
# than 3 characters:
if self._symbol == 'Ya':
self._symbol = 'Я'
if self._symbol == 'Yi':
self._symbol = 'Ї'
# now we check and update the valid input characters
self._valid_input_chars = self.database.ime_properties.get(
'valid_input_chars')
self._pinyin_valid_input_chars = 'abcdefghijklmnopqrstuvwxyz!@#$%'
self._debug_level: int = it_util.variant_to_value(
self._gsettings.get_value('debuglevel'))
self._debug_level = max(self._debug_level, 0) # minimum
self._debug_level = min(self._debug_level, 255) # maximum
LOGGER.info('self._debug_level=%s', self._debug_level)
dynamic_adjust: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('dynamicadjust'))
if dynamic_adjust is None:
if self.database.ime_properties.get('dynamic_adjust'):
dynamic_adjust = self.database.ime_properties.get(
'dynamic_adjust').lower() == 'true'
LOGGER.info('Got "dynamic_adjust" entry from database.')
else:
LOGGER.info(
'Could not find "dynamic_adjust" entry from database, '
'is it an outdated database?')
if dynamic_adjust is None:
dynamic_adjust = it_util.variant_to_value(
self._gsettings.get_value('dynamicadjust'))
self._dynamic_adjust: bool = dynamic_adjust
single_wildcard_char: Optional[str] = it_util.variant_to_value(
self._gsettings.get_user_value('singlewildcardchar'))
if single_wildcard_char is None:
if self.database.ime_properties.get('single_wildcard_char'):
single_wildcard_char = self.database.ime_properties.get(
'single_wildcard_char')
else:
single_wildcard_char = it_util.variant_to_value(
self._gsettings.get_value('singlewildcardchar'))
self._single_wildcard_char: str = single_wildcard_char
if len(self._single_wildcard_char) > 1:
self._single_wildcard_char = self._single_wildcard_char[0]
multi_wildcard_char: Optional[str] = it_util.variant_to_value(
self._gsettings.get_user_value('multiwildcardchar'))
if multi_wildcard_char is None:
if self.database.ime_properties.get('multi_wildcard_char'):
multi_wildcard_char = self.database.ime_properties.get(
'multi_wildcard_char')
else:
multi_wildcard_char = it_util.variant_to_value(
self._gsettings.get_value('multiwildcardchar'))
self._multi_wildcard_char: str = multi_wildcard_char
if len(self._multi_wildcard_char) > 1:
self._multi_wildcard_char = self._multi_wildcard_char[0]
auto_wildcard: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('autowildcard'))
if auto_wildcard is None:
if self.database.ime_properties.get('auto_wildcard'):
auto_wildcard = self.database.ime_properties.get(
'auto_wildcard').lower() == 'true'
LOGGER.info('Got "auto_wildcard" entry from database.')
else:
auto_wildcard = it_util.variant_to_value(
self._gsettings.get_value('autowildcard'))
self._auto_wildcard: bool = auto_wildcard
self._max_key_length = int(
self.database.ime_properties.get('max_key_length'))
self._max_key_length_pinyin = 7
self._remember_input_mode: bool = it_util.variant_to_value(
self._gsettings.get_value('rememberinputmode'))
# 0 = Direct input, i.e. table input OFF (aka “English input mode”),
# most characters are just passed through to the application
# (but some fullwidth ↔ halfwidth conversion may be done even
# in this mode, depending on the settings)
# 1 = Table input ON (aka “Table input mode”, “Chinese mode”)
self._input_mode: int = 1
if self._remember_input_mode:
self._input_mode = it_util.variant_to_value(
self._gsettings.get_value('inputmode'))
self._sound_backend: str = it_util.variant_to_value(
self._gsettings.get_value('soundbackend'))
self._error_sound_object: Optional[it_sound.SoundObject] = None
self._error_sound_file: str = ''
self._error_sound: bool = it_util.variant_to_value(
self._gsettings.get_value('errorsound'))
self.set_error_sound_file(
it_util.variant_to_value(
self._gsettings.get_value('errorsoundfile')),
update_gsettings=False)
# self._prev_key: hold the key event last time.
self._prev_key: Optional[it_util.KeyEvent] = None
self._prev_char: Optional[str] = None
self._double_quotation_state = False
self._single_quotation_state = False
# self._prefix: the previous commit character or phrase
self._prefix = ''
self._py_mode = False
# suggestion mode
self._sg_mode = False
self._sg_mode_active = False
self._full_width_letter: List[Optional[bool]] = [None, None]
self._full_width_letter = [
it_util.variant_to_value(
self._gsettings.get_value('endeffullwidthletter')),
it_util.variant_to_value(
self._gsettings.get_user_value('tabdeffullwidthletter'))
]
if self._full_width_letter[1] is None:
if self.database.ime_properties.get('def_full_width_letter'):
self._full_width_letter[1] = self.database.ime_properties.get(
'def_full_width_letter').lower() == 'true'
if self._full_width_letter[1] is None:
self._full_width_letter[1] = it_util.variant_to_value(
self._gsettings.get_value('tabdeffullwidthletter'))
self._full_width_punct: List[Optional[bool]] = [None, None]
self._full_width_punct = [
it_util.variant_to_value(
self._gsettings.get_value('endeffullwidthpunct')),
it_util.variant_to_value(
self._gsettings.get_user_value('tabdeffullwidthpunct'))
]
if self._full_width_punct[1] is None:
if self.database.ime_properties.get('def_full_width_punct'):
self._full_width_punct[1] = self.database.ime_properties.get(
'def_full_width_punct').lower() == 'true'
if self._full_width_punct[1] is None:
self._full_width_punct[1] = it_util.variant_to_value(
self._gsettings.get_value('tabdeffullwidthpunct'))
auto_commit: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('autocommit'))
if auto_commit is None:
if self.database.ime_properties.get('auto_commit'):
auto_commit = self.database.ime_properties.get(
'auto_commit').lower() == 'true'
else:
auto_commit = it_util.variant_to_value(
self._gsettings.get_value('autocommit'))
self._auto_commit: bool = auto_commit
# self._commit_invalid_mode: This selects what is committed
# when a character which is not in the set of valid input
# characters for the current table is typed.
#
# 0 means to commit the current candidate
# 1 means to commit the raw characters typed so far
self._commit_invalid_mode: int = it_util.variant_to_value(
self._gsettings.get_value('commitinvalidmode'))
# If auto select is true, then the first candidate phrase will
# be selected automatically during typing. Auto select is true
# by default for the stroke5 table for example.
auto_select: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('autoselect'))
if auto_select is None:
if self.database.ime_properties.get('auto_select'):
auto_select = self.database.ime_properties.get(
'auto_select').lower() == 'true'
LOGGER.info('Got "auto_select" entry from database.')
else:
auto_select = it_util.variant_to_value(
self._gsettings.get_value('autoselect'))
self._auto_select: bool = auto_select
always_show_lookup: Optional[bool] = it_util.variant_to_value(
self._gsettings.get_user_value('alwaysshowlookup'))
if always_show_lookup is None:
if self.database.ime_properties.get('always_show_lookup'):
always_show_lookup = self.database.ime_properties.get(
'always_show_lookup').lower() == 'true'
LOGGER.info('Got "always_show_lookup" entry from database.')
else:
always_show_lookup = it_util.variant_to_value(
self._gsettings.get_value('alwaysshowlookup'))
self._always_show_lookup: bool = always_show_lookup
# The values below will be reset in
# self.clear_input_not_committed_to_preedit()
self._chars_valid = '' # valid user input in table mode
self._chars_invalid = '' # invalid user input in table mode
self._chars_valid_update_candidates_last = ''
self._chars_invalid_update_candidates_last = ''
# self._candidates holds the “best” candidates matching the user input
# [(tabkeys, phrase, freq, user_freq), ...]
self._candidates: List[Tuple[str, str, int, int]] = []
self._candidates_previous: List[Tuple[str, str, int, int]] = []
# self._u_chars: holds the user input of the phrases which
# have been automatically committed to preedit (but not yet
# “really” committed).
self._u_chars: List[str] = []
# self._strings: holds the phrases which have been
# automatically committed to preedit (but not yet “really”
# committed).
#
# self._u_chars and self._strings should always have the same
# length, if I understand it correctly.
#
# Example when using the wubi-jidian86 table:
#
# self._u_chars = ['gaaa', 'gggg', 'ihty']
# self._strings = ['形式', '王', '小']
#
# I.e. after typing 'gaaa', '形式' is in the preedit and
# both self._u_chars and self._strings are empty. When typing
# another 'g', the maximum key length of the wubi table (which is 4)
# is exceeded and '形式' is automatically committed to the preedit
# (but not yet “really” committed, i.e. not yet committed into
# the application). The key 'gaaa' and the matching phrase '形式'
# are stored in self._u_chars and self._strings respectively
# and 'gaaa' is removed from self._chars_valid. Now self._chars_valid
# contains only the 'g' which starts a new search for candidates ...
# When removing the 'g' with backspace, the 'gaaa' is moved
# back from self._u_chars into self._chars_valid again and
# the same candidate list is shown as before the last 'g' had
# been entered.
self._strings: List[str] = []
# self._cursor_precommit: The cursor
# position in the array of strings which have already been
# committed to preëdit but not yet “really” committed.
self._cursor_precommit = 0
self._prompt_characters = ast.literal_eval(
self.database.ime_properties.get('char_prompts'))
# self._onechar: whether we only select single character
self._onechar: bool = it_util.variant_to_value(
self._gsettings.get_value('onechar'))
# self._chinese_mode: the candidate filter mode,
# 0 means to show simplified Chinese only
# 1 means to show traditional Chinese only
# 2 means to show all characters but show simplified Chinese first
# 3 means to show all characters but show traditional Chinese first
# 4 means to show all characters
# we use LC_CTYPE or LANG to determine which one to use if
# no default comes from the user GSettings.
chinese_mode: Optional[int] = it_util.variant_to_value(
self._gsettings.get_user_value('chinesemode'))
if chinese_mode is None:
chinese_mode = it_util.get_default_chinese_mode(
self.database)
elif self._debug_level > 1:
LOGGER.debug(
'Chinese mode found in Gsettings, mode=%s', chinese_mode)
self._chinese_mode: int = chinese_mode
# If auto select is true, then the first candidate phrase will
# be selected automatically during typing. Auto select is true
# by default for the stroke5 table for example.
self._auto_select = it_util.variant_to_value(
self._gsettings.get_user_value('autoselect'))
if self._auto_select is None:
if self.database.ime_properties.get('auto_select') is not None:
self._auto_select = self.database.ime_properties.get(
'auto_select').lower() == 'true'
if self._auto_select is None:
self._auto_select = it_util.variant_to_value(
self._gsettings.get_value('autoselect'))
self._default_keybindings: Dict[str, List[str]] = {}
self._default_keybindings = it_util.get_default_keybindings(
self._gsettings, self.database)
self._input_method_menu: List[str] = []
self._input_method_menu = self._gsettings.get_strv('inputmethodmenu')
self._page_size: int = it_util.variant_to_value(
self._gsettings.get_default_value('lookuptablepagesize'))
for index in range(1, 10):
if not self._default_keybindings[f'commit_candidate_{index + 1}']:
self._page_size = min(index, self._page_size)
break
user_page_size: Optional[int] = it_util.variant_to_value(
self._gsettings.get_user_value('lookuptablepagesize'))
if user_page_size is not None:
self._page_size = user_page_size
orientation: Optional[int] = it_util.variant_to_value(
self._gsettings.get_user_value('lookuptableorientation'))
if orientation is None:
orientation = self.database.get_orientation()
self._orientation: int = orientation
user_keybindings = it_util.variant_to_value(
self._gsettings.get_user_value('keybindings'))
if not user_keybindings:
user_keybindings = {}
self.set_keybindings(user_keybindings, update_gsettings=False)
use_dark_theme = it_util.variant_to_value(
self._gsettings.get_user_value('darktheme'))
if use_dark_theme:
self.set_dark_theme(True, update_gsettings=False)
self._lookup_table = self.get_new_lookup_table()
self.chinese_mode_properties = {
'ChineseMode.Simplified': {
'number': 0,
'symbol': '簡',
'icon': 'sc-mode.svg',
# Translators: This is the menu entry to select
# when one wants to input only Simplified Chinese.
'label': _('Simplified Chinese'),
'tooltip':
_('Switch to “Simplified Chinese only”.')},
'ChineseMode.Traditional': {
'number': 1,
'symbol': '繁',
'icon': 'tc-mode.svg',
# Translators: This is the menu entry to select
# when one wants to input only Traditonal Chinese
'label': _('Traditional Chinese'),
'tooltip':
_('Switch to “Traditional Chinese only”.')},
'ChineseMode.SimplifiedFirst': {
'number': 2,
'symbol': '簡/大',
'icon': 'scb-mode.svg',
# Translators: This is the menu entry to select when
# one wants to input both Simplified and Traditional
# Chinese but wants the Simplified Chinese to be
# preferred, i.e. shown higher up in the candidate
# lists.
'label': _('Simplified Chinese first'),
'tooltip':
_('Switch to “Simplified Chinese before traditional”.')},
'ChineseMode.TraditionalFirst': {
'number': 3,
'symbol': '繁/大',
'icon': 'tcb-mode.svg',
# Translators: This is the menu entry to select when
# one wants to input both Simplified and Traditional
# Chinese but wants the Traditional Chinese to be
# preferred, i.e. shown higher up in the candidate
# lists.
'label': _('Traditional Chinese first'),
'tooltip':
_('Switch to “Traditional Chinese before simplified”.')},
'ChineseMode.All': {
'number': 4,
'symbol': '大',
'icon': 'cb-mode.svg',
# Translators: This is the menu entry to select when
# one wants to input both Simplified and Traditional
# Chinese and has no particular preference whether
# simplified or traditional characters should be higher
# up in the candidate lists.
'label': _('All Chinese characters'),
'tooltip': _('Switch to “All Chinese characters”.')}
}
self.chinese_mode_menu = {
'key': 'ChineseMode',
'label': _('Chinese mode'),
'tooltip': _('Switch Chinese mode'),
'shortcut_hint': repr(
self._keybindings['switch_to_next_chinese_mode']),
'sub_properties': self.chinese_mode_properties
}
if self.database.is_db_chinese:
self.input_mode_properties = {
'InputMode.Direct': {
'number': 0,
'symbol': '英',
'icon': 'english.svg',
'label': _('English'),
'tooltip': _('Switch to English input')},
'InputMode.Table': {
'number': 1,
'symbol': '中',
'symbol_table': '中',
'symbol_pinyin': '拼音',
'icon': 'chinese.svg',
'label': _('Chinese'),
'tooltip': _('Switch to Chinese input')}
}
else:
self.input_mode_properties = {
'InputMode.Direct': {
'number': 0,
'symbol': '☐' + self._symbol,
'icon': 'english.svg',
'label': _('Direct'),
'tooltip': _('Switch to direct input')},
'InputMode.Table': {
'number': 1,
'symbol': '☑' + self._symbol,
'icon': 'ibus-table.svg',
'label': _('Table'),
'tooltip': _('Switch to table input')}
}
# The symbol of the property “InputMode” is displayed
# in the input method indicator of the Gnome3 panel.
# This depends on the property name “InputMode” and
# is case sensitive!
self.input_mode_menu = {
'key': 'InputMode',
'label': _('Input mode'),
'tooltip': _('Switch Input mode'),
'shortcut_hint': repr(
self._keybindings['toggle_input_mode_on_off']),
'sub_properties': self.input_mode_properties
}
self.letter_width_properties = {
'LetterWidth.Half': {
'number': 0,
'symbol': '◑',
'icon': 'half-letter.svg',
'label': _('Half'),
'tooltip': _('Switch to halfwidth letters')},
'LetterWidth.Full': {
'number': 1,
'symbol': '●',
'icon': 'full-letter.svg',
'label': _('Full'),
'tooltip': _('Switch to fullwidth letters')}
}
self.letter_width_menu = {
'key': 'LetterWidth',
'label': _('Letter width'),
'tooltip': _('Switch letter width'),
'shortcut_hint': repr(
self._keybindings['toggle_letter_width']),
'sub_properties': self.letter_width_properties
}
self.punctuation_width_properties = {
'PunctuationWidth.Half': {
'number': 0,
'symbol': ',.',
'icon': 'half-punct.svg',
'label': _('Half'),
'tooltip': _('Switch to halfwidth punctuation')},
'PunctuationWidth.Full': {
'number': 1,
'symbol': '、。',
'icon': 'full-punct.svg',
'label': _('Full'),
'tooltip': _('Switch to fullwidth punctuation')}
}
self.punctuation_width_menu = {
'key': 'PunctuationWidth',
'label': _('Punctuation width'),
'tooltip': _('Switch punctuation width'),
'shortcut_hint': repr(
self._keybindings['toggle_punctuation_width']),
'sub_properties': self.punctuation_width_properties
}
self.pinyin_mode_properties = {
'PinyinMode.Table': {
'number': 0,
'symbol': '☐ 拼音',
'icon': 'tab-mode.svg',
'label': _('Table'),
'tooltip': _('Switch to table mode')},
'PinyinMode.Pinyin': {
'number': 1,
'symbol': '☑ 拼音',
'icon': 'py-mode.svg',
'label': _('Pinyin'),
'tooltip': _('Switch to pinyin mode')}
}
self.pinyin_mode_menu = {
'key': 'PinyinMode',
'label': _('Pinyin mode'),
'tooltip': _('Switch pinyin mode'),
'shortcut_hint': repr(
self._keybindings['toggle_pinyin_mode']),
'sub_properties': self.pinyin_mode_properties
}
self.suggestion_mode_properties = {
'SuggestionMode.Disabled': {
'number': 0,
'symbol': '☐ 联想',
'icon': 'tab-mode.svg',
'label': _('Suggestion disabled'),
'tooltip': _('Switch to suggestion mode')},
'SuggestionMode.Enabled': {
'number': 1,
'symbol': '☑ 联想',
'icon': 'tab-mode.svg',
'label': _('Suggestion enabled'),
'tooltip': _('Switch to suggestion mode')}
}
self.suggestion_mode_menu = {
'key': 'SuggestionMode',
'label': _('Suggestion mode'),
'tooltip': _('Switch suggestion mode'),
'shortcut_hint': repr(
self._keybindings['toggle_suggestion_mode']),
'sub_properties': self.suggestion_mode_properties
}
self.onechar_mode_properties = {
'OneCharMode.Phrase': {
'number': 0,
'symbol': '☐ 1',
'icon': 'phrase.svg',
'label': _('Multiple character match'),
'tooltip':
_('Switch to matching multiple characters at once')},
'OneCharMode.OneChar': {
'number': 1,
'symbol': '☑ 1',
'icon': 'onechar.svg',
'label': _('Single character match'),
'tooltip':
_('Switch to matching only single characters')}
}
self.onechar_mode_menu = {
'key': 'OneCharMode',
'label': _('Onechar mode'),
'tooltip': _('Switch onechar mode'),
'shortcut_hint': repr(
self._keybindings['toggle_onechar_mode']),
'sub_properties': self.onechar_mode_properties
}
self.autocommit_mode_properties = {
'AutoCommitMode.Direct': {
'number': 0,
'symbol': '☐ ↑',
'icon': 'ncommit.svg',
'label': _('Normal'),
'tooltip':
_('Switch to normal commit mode '
+ '(automatic commits go into the preedit '
+ 'instead of into the application. '
+ 'This enables automatic definitions of new shortcuts)')},
'AutoCommitMode.Normal': {
'number': 1,
'symbol': '☑ ↑',
'icon': 'acommit.svg',
'label': _('Direct'),
'tooltip':
_('Switch to direct commit mode '
+ '(automatic commits go directly into the application)')}
}
self.autocommit_mode_menu = {
'key': 'AutoCommitMode',
'label': _('Autocommit mode'),
'tooltip': _('Switch autocommit mode'),
'shortcut_hint': repr(
self._keybindings['toggle_autocommit_mode']),
'sub_properties': self.autocommit_mode_properties
}
self._init_properties()
self._save_user_count = 0
self._save_user_start = time.time()
self._save_user_count_max = SAVE_USER_COUNT_MAX
self._save_user_timeout = SAVE_USER_TIMEOUT
self.reset()
self.sync_timeout_id = GObject.timeout_add_seconds(
1, self._sync_user_db)
self.connect('process-key-event', self.__do_process_key_event)
LOGGER.info(
'********** Initialized and ready for input: **********')
def get_new_lookup_table(self) -> IBus.LookupTable:
'''
Get a new lookup table
'''
lookup_table = IBus.LookupTable()
lookup_table.clear()
lookup_table.set_page_size(self._page_size)
lookup_table.set_orientation(self._orientation)
lookup_table.set_cursor_visible(True)
lookup_table.set_round(True)
for index in range(0, 10):
label = ''
if self._keybindings[f'commit_candidate_{index + 1}']:
keybinding = self._keybindings[
f'commit_candidate_{index + 1}'][0]
key = it_util.keybinding_to_keyevent(keybinding)
label = keybinding
if key.unicode and not key.name.startswith('KP_'):
label = key.unicode
lookup_table.append_label(IBus.Text.new_from_string(label))
return lookup_table
def clear_all_input_and_preedit(self) -> None:
'''
Clear all input, whether committed to preëdit or not.
'''
if self._debug_level > 1:
LOGGER.debug('clear_all_input_and_preedit()')
self.clear_input_not_committed_to_preedit()
self._u_chars = []
self._strings = []
self._cursor_precommit = 0
self._prefix = ''
self._sg_mode_active = False
self.update_candidates()
def is_empty(self) -> bool:
'''Checks whether the preëdit is empty
Returns True if the preëdit is empty, False if not.
'''
return self._chars_valid + self._chars_invalid == ''
def clear_input_not_committed_to_preedit(self) -> None:
'''
Clear the input which has not yet been committed to preëdit.
'''
if self._debug_level > 1:
LOGGER.debug('clear_input_not_committed_to_preedit()')
self._chars_valid = ''
self._chars_invalid = ''
self._chars_valid_update_candidates_last = ''
self._chars_invalid_update_candidates_last = ''
self._lookup_table.clear()
self._lookup_table.set_cursor_visible(True)
self._candidates = []
self._candidates_previous = []
def add_input(self, char: str) -> bool:
'''
Add input character and update candidates.
Returns “True” if candidates were found, “False” if not.
'''
if (self._chars_invalid
or (not self._py_mode
and (char not in
self._valid_input_chars
+ self._single_wildcard_char
+ self._multi_wildcard_char))
or (self._py_mode
and (char not in
self._pinyin_valid_input_chars
+ self._single_wildcard_char
+ self._multi_wildcard_char))):
self._chars_invalid += char
else:
self._chars_valid += char
res = self.update_candidates()
return res
def pop_input(self) -> str:
'''remove and display last input char held'''
last_input_char = ''
if self._chars_invalid:
last_input_char = self._chars_invalid[-1]
self._chars_invalid = self._chars_invalid[:-1]
elif self._chars_valid:
last_input_char = self._chars_valid[-1]
self._chars_valid = self._chars_valid[:-1]
if (not self._chars_valid) and self._u_chars:
self._chars_valid = self._u_chars.pop(
self._cursor_precommit - 1)
self._strings.pop(self._cursor_precommit - 1)
self._cursor_precommit -= 1
self.update_candidates()
return last_input_char
def get_input_chars(self) -> str:
'''get characters held, valid and invalid'''
return self._chars_valid + self._chars_invalid
def split_strings_committed_to_preedit(
self, index: int, index_in_phrase: int) -> None:
'''Splits strings committed to preedit'''
head = self._strings[index][:index_in_phrase]
tail = self._strings[index][index_in_phrase:]
self._u_chars.pop(index)
self._strings.pop(index)
self._u_chars.insert(index, self.database.parse_phrase(head))
self._strings.insert(index, head)
self._u_chars.insert(index+1, self.database.parse_phrase(tail))
self._strings.insert(index+1, tail)
def remove_preedit_before_cursor(self) -> None:
'''Remove preëdit left of cursor'''
if self._chars_invalid:
return
if self.get_input_chars():
self.commit_to_preedit()
if not self._strings:
return
if self._cursor_precommit <= 0:
return
self._u_chars = self._u_chars[self._cursor_precommit:]
self._strings = self._strings[self._cursor_precommit:]
self._cursor_precommit = 0
def remove_preedit_after_cursor(self) -> None:
'''Remove preëdit right of cursor'''
if self._chars_invalid:
return
if self.get_input_chars():
self.commit_to_preedit()
if not self._strings:
return
if self._cursor_precommit >= len(self._strings):
return
self._u_chars = self._u_chars[:self._cursor_precommit]
self._strings = self._strings[:self._cursor_precommit]
self._cursor_precommit = len(self._strings)
def remove_preedit_character_before_cursor(self) -> None:
'''Remove character before cursor in strings comitted to preëdit'''
if self._chars_invalid:
return
if self.get_input_chars():
self.commit_to_preedit()
if not self._strings:
return
if self._cursor_precommit < 1:
return
self._cursor_precommit -= 1
self._chars_valid = self._u_chars.pop(self._cursor_precommit)
self._strings.pop(self._cursor_precommit)
self.update_candidates()
def remove_preedit_character_after_cursor(self) -> None:
'''Remove character after cursor in strings committed to preëdit'''
if self._chars_invalid:
return
if self.get_input_chars():
self.commit_to_preedit()
if not self._strings:
return
if self._cursor_precommit > len(self._strings) - 1:
return
self._u_chars.pop(self._cursor_precommit)
self._strings.pop(self._cursor_precommit)
def get_preedit_tabkeys_parts(
self) -> Tuple[Tuple[str, ...], str, Tuple[str, ...]]:
'''Returns the tabkeys which were used to type the parts
of the preëdit string.
Such as “(left_of_current_edit, current_edit, right_of_current_edit)”
“left_of_current_edit” and “right_of_current_edit” are
strings of tabkeys which have been typed to get the phrases
which have already been committed to preëdit, but not
“really” committed yet. “current_edit” is the string of
tabkeys of the part of the preëdit string which is not
committed at all.
For example, the return value could look like:
(('gggg', 'aahw'), 'adwu', ('ijgl', 'jbus'))
See also get_preedit_string_parts() which might return something
like
(('王', '工具'), '其', ('漫画', '最新'))
when the wubi-jidian86 table is used.
'''
left_of_current_edit: Tuple[str, ...] = ()
current_edit = ''
right_of_current_edit: Tuple[str, ...] = ()
if self.get_input_chars():
current_edit = self.get_input_chars()
if self._u_chars:
left_of_current_edit = tuple(
self._u_chars[:self._cursor_precommit])
right_of_current_edit = tuple(
self._u_chars[self._cursor_precommit:])
return (left_of_current_edit, current_edit, right_of_current_edit)
def get_preedit_tabkeys_complete(self) -> str:
'''Returns the tabkeys which belong to the parts of the preëdit
string as a single string
'''
(left_tabkeys,
current_tabkeys,
right_tabkeys) = self.get_preedit_tabkeys_parts()
return (''.join(left_tabkeys)
+ current_tabkeys
+ ''.join(right_tabkeys))
def get_preedit_string_parts(
self) -> Tuple[Tuple[str, ...], str, Tuple[str, ...]]:
'''Returns the phrases which are parts of the preëdit string.
Such as “(left_of_current_edit, current_edit, right_of_current_edit)”
“left_of_current_edit” and “right_of_current_edit” are
tuples of strings which have already been committed to preëdit, but not
“really” committed yet. “current_edit” is the phrase in the part of the
preëdit string which is not yet committed at all.
For example, the return value could look like:
(('王', '工具'), '其', ('漫画', '最新'))
See also get_preedit_tabkeys_parts() which might return something
like
(('gggg', 'aahw'), 'adwu', ('ijgl', 'jbus'))
when the wubi-jidian86 table is used.
'''
left_of_current_edit: Tuple[str, ...] = ()
current_edit = ''
right_of_current_edit: Tuple[str, ...] = ()
if self._candidates:
current_edit = self._candidates[
int(self._lookup_table.get_cursor_pos())][1]
elif self.get_input_chars():
current_edit = self.get_input_chars()
if self._strings:
left_of_current_edit = tuple(
self._strings[:self._cursor_precommit])
right_of_current_edit = tuple(
self._strings[self._cursor_precommit:])
return (left_of_current_edit, current_edit, right_of_current_edit)
def get_preedit_string_complete(self) -> str:
'''Returns the phrases which are parts of the preëdit string as a
single string
'''
if self._sg_mode_active:
if self._candidates:
return self._candidates[
int(self._lookup_table.get_cursor_pos())][0]
return ''
(left_strings,
current_string,
right_strings) = self.get_preedit_string_parts()
return (''.join(left_strings)
+ current_string
+ ''.join(right_strings))
def get_caret(self) -> int:
'''Get caret position in preëdit string'''
caret = 0
if self._cursor_precommit and self._strings:
for part in self._strings[:self._cursor_precommit]:
caret += len(part)
if self._candidates:
caret += len(
self._candidates[int(self._lookup_table.get_cursor_pos())][1])
else:
caret += len(self.get_input_chars())
return caret
def arrow_left(self) -> None:
'''Move cursor left in the preëdit string.'''
if self._chars_invalid:
return
if self.get_input_chars():
self.commit_to_preedit()
if not self._strings:
return
if self._cursor_precommit <= 0:
return
if len(self._strings[self._cursor_precommit-1]) <= 1:
self._cursor_precommit -= 1
else:
self.split_strings_committed_to_preedit(
self._cursor_precommit-1, -1)
self.update_candidates()
def arrow_right(self) -> None:
'''Move cursor right in the preëdit string.'''
if self._chars_invalid:
return
if self.get_input_chars():
self.commit_to_preedit()
if not self._strings:
return
if self._cursor_precommit >= len(self._strings):
return
self._cursor_precommit += 1
if len(self._strings[self._cursor_precommit-1]) > 1:
self.split_strings_committed_to_preedit(
self._cursor_precommit-1, 1)
self.update_candidates()
def control_arrow_left(self) -> None:
'''Move cursor to the beginning of the preëdit string.'''
if self._chars_invalid:
return
if self.get_input_chars():
self.commit_to_preedit()
if not self._strings:
return
self._cursor_precommit = 0
self.update_candidates()
def control_arrow_right(self) -> None:
'''Move cursor to the end of the preëdit string'''
if self._chars_invalid:
return
if self.get_input_chars():
self.commit_to_preedit()
if not self._strings:
return
self._cursor_precommit = len(self._strings)
self.update_candidates()
def append_table_candidate(
self,
tabkeys: str = '',
phrase: str = '',
freq: int = 0,
user_freq: int = 0) -> None:
'''append table candidate to lookup table'''
assert self._input_mode == 1
if self._debug_level > 1:
LOGGER.debug(
'tabkeys=%s phrase=%s freq=%s user_freq=%s',
tabkeys, phrase, freq, user_freq)
if not tabkeys or not phrase:
return
mwild = self._multi_wildcard_char
swild = self._single_wildcard_char
if ((mwild and mwild in self._chars_valid)
or (swild and swild in self._chars_valid)):
# show all tabkeys if wildcard in tabkeys
remaining_tabkeys = tabkeys
else:
regexp = self._chars_valid
regexp = re.escape(regexp)
match = re.match(r'^' + regexp, tabkeys)
if match:
remaining_tabkeys = tabkeys[match.end():]
else:
# This should never happen! For the candidates
# added to the lookup table here, a match has
# been found for self._chars_valid in the database.
# In that case, the above regular expression should
# match as well.
remaining_tabkeys = tabkeys
if self._debug_level > 1:
LOGGER.debug(
'remaining_tabkeys=%s '
'self._chars_valid=%s phrase=%s',
remaining_tabkeys, self._chars_valid, phrase)
table_code = ''
if not self._py_mode:
remaining_tabkeys_new = ''
for char in remaining_tabkeys:
if char in self._prompt_characters:
remaining_tabkeys_new += self._prompt_characters[char]
else:
remaining_tabkeys_new += char
remaining_tabkeys = remaining_tabkeys_new
candidate_text = phrase + ' ' + remaining_tabkeys
if table_code:
candidate_text = candidate_text + ' ' + table_code
attrs = IBus.AttrList()
attrs.append(IBus.attr_foreground_new(
self.theme["candidate_text"], 0, len(candidate_text)))
if freq < 0:
# this is a user defined phrase:
attrs.append(
IBus.attr_foreground_new(
self.theme["user_phrase"], 0, len(phrase)))
elif user_freq > 0:
# this is a system phrase which has already been used by the user:
attrs.append(IBus.attr_foreground_new(
self.theme["system_phrase"], 0, len(phrase)))
else:
# this is a system phrase that has not been used yet:
attrs.append(IBus.attr_foreground_new(
self.theme["system_phrase_unused"], 0, len(phrase)))
if self._debug_level > 0:
debug_text = ' ' + str(freq) + ' ' + str(user_freq)
candidate_text += debug_text
attrs.append(IBus.attr_foreground_new(
self.theme["debug_text"],
len(candidate_text) - len(debug_text),
len(candidate_text)))
text = IBus.Text.new_from_string(candidate_text)
text.set_attributes(attrs)
self._lookup_table.append_candidate(text)
self._lookup_table.set_cursor_visible(True)
@staticmethod
def get_common_prefix_sorted_list(asc_table_codes: List[str]) -> List[int]:
# pylint: disable=line-too-long
'''
(branch from, node index of branch from), (code, asc table codes index, same prefix count), ...
for input
["w","wx","wxa","wxb","wxbc","wccd", "wxbd", "ilonga"]
build a tree like this
(-1, 0),('w', 0, 1),('wx', 1, 2),('wxa', 2, 3),
(0, 2),('wxb', 3, 3),('wxbc', 4, 4),
(0, 1),('wccd', 5, 2),
(1, 1),('wxbd', 6, 4),
(-1, 0),('ilonga', 7, 1),
'''
# pylint: enable=line-too-long
prefix_tree: List[List[Tuple[Any, ...]]] = []
for code_idx, code in enumerate(asc_table_codes):
branch_count = len(prefix_tree)
branch_idx = branch_count - 1
node_idx = 0
# traverse branches
while branch_idx >= 0:
prefix_branch = prefix_tree[branch_idx]
branch_count = len(prefix_branch)
node_idx = branch_count - 1
# traverse nodes
while node_idx > 0:
node = prefix_branch[node_idx]
if code.startswith(node[0]):
# make a leaf
if node_idx == branch_count - 1:
# extends branch
prefix_branch.append((code, code_idx, node[2] + 1))
else:
# in a new branch
new_branch = [(branch_idx, node_idx), (code, code_idx, node[2] + 1)]
prefix_tree.append(new_branch)
break
# next node
node_idx -= 1
if node_idx > 0:
break
# next branch
branch_idx -= 1
if node_idx == 0:
# new root branch
new_branch = [(branch_idx, node_idx), (code, code_idx, 1)]
prefix_tree.append(new_branch)
# tree leaf holds the max same-prefix count code
nodes = [branch[-1] for branch in prefix_tree]
# sort by max same-prefix count then idx
nodes = sorted(nodes,
key=lambda n: int(n[2]) * 16 + int(n[1]),
reverse=True)
idx_array = [node[1] for node in nodes]
return idx_array
def select_best_idx_from_prefix_list(
self,
asc_table_codes: List[str],
sorted_idx_list: List[int]) -> int:
'''Select the best index from a prefix list'''
if self._engine_name == 'erbi-qs':
# for erbi-qs, code start with i/u/v is auxiliary
for i in sorted_idx_list:
first_char = asc_table_codes[i][0]
if first_char in ('i', 'u', 'v'):
continue
return i
return sorted_idx_list[0]
def append_pinyin_candidate(
self,
tabkeys: str = '',
phrase:str = '',
freq: int =0,
user_freq: int = 0) -> None:
'''append pinyin candidate to lookup table'''
assert self._input_mode == 1
assert self._py_mode
if self._debug_level > 1:
LOGGER.debug(
'tabkeys=%s phrase=%s freq=%s user_freq=%s',
tabkeys, phrase, freq, user_freq)
if not tabkeys or not phrase:
return
regexp = self._chars_valid
regexp = re.escape(regexp)
match = re.match(r'^'+regexp, tabkeys)
if match:
remaining_tabkeys = tabkeys[match.end():]
else:
# This should never happen! For the candidates
# added to the lookup table here, a match has
# been found for self._chars_valid in the database.
# In that case, the above regular expression should
# match as well.
remaining_tabkeys = tabkeys
if self._debug_level > 1:
LOGGER.debug(
'remaining_tabkeys=%s '
'self._chars_valid=%s phrase=%s',
remaining_tabkeys, self._chars_valid, phrase)
table_code = ''
if self.database.is_db_chinese and self._py_mode:
# restore tune symbol
remaining_tabkeys = remaining_tabkeys.replace(
'!', '↑1').replace(
'@', '↑2').replace(
'#', '↑3').replace(
'$', '↑4').replace(
'%', '↑5')
# If in pinyin mode, phrase can only be one character.
# When using pinyin mode for a table like Wubi or Cangjie,
# the reason is probably because one does not know the
# Wubi or Cangjie code. So get that code from the table
# and display it as well to help the user learn that code.
# The Wubi tables contain several codes for the same
# character, therefore self.database.find_zi_code(phrase) may
# return a list. The last code in that list is the full
# table code for that characters, other entries in that
# list are shorter substrings of the full table code which
# are not interesting to display. Therefore, we use only
# the last element of the list of table codes.
possible_table_codes = self.database.find_zi_code(phrase)
if possible_table_codes:
idx_array = self.get_common_prefix_sorted_list(possible_table_codes)
idx = self.select_best_idx_from_prefix_list(possible_table_codes, idx_array)
table_code = possible_table_codes[idx]
table_code_new = ''
for char in table_code:
if char in self._prompt_characters:
table_code_new += self._prompt_characters[char]
else:
table_code_new += char
table_code = table_code_new
candidate_text = phrase + ' ' + remaining_tabkeys
if table_code:
candidate_text = candidate_text + ' ' + table_code
attrs = IBus.AttrList()
attrs.append(IBus.attr_foreground_new(
self.theme["candidate_text"], 0, len(candidate_text)))
# this is a pinyin character:
attrs.append(IBus.attr_foreground_new(
self.theme["system_phrase"], 0, len(phrase)))
if self._debug_level > 0:
debug_text = ' ' + str(freq) + ' ' + str(user_freq)
candidate_text += debug_text
attrs.append(IBus.attr_foreground_new(
self.theme["debug_text"],
len(candidate_text) - len(debug_text),
len(candidate_text)))
text = IBus.Text.new_from_string(candidate_text)
text.set_attributes(attrs)
self._lookup_table.append_candidate(text)
self._lookup_table.set_cursor_visible(True)
def append_suggestion_candidate(
self,
prefix: str = '',
phrase: str = '',
freq: int = 0,
user_freq: int = 0) -> None:
'''append suggestion candidate to lookup table'''
assert self._input_mode == 1
assert self._sg_mode
if self._debug_level > 1:
LOGGER.debug(
'tabkeys=%s phrase=%s freq=%s user_freq=%s',
prefix, phrase, freq, user_freq)
if not prefix or not phrase:
return
if not phrase.startswith(prefix):
return
candidate_text = phrase
attrs = IBus.AttrList()
attrs.append(IBus.attr_foreground_new(
self.theme["candidate_text"], 0, len(candidate_text)))
# this is a suggestion candidate:
attrs.append(IBus.attr_foreground_new(
self.theme["system_phrase"], 0, len(phrase)))
if self._debug_level > 0:
debug_text = ' ' + str(freq) + ' ' + str(user_freq)
candidate_text += debug_text
attrs.append(IBus.attr_foreground_new(
self.theme["debug_text"],
len(candidate_text) - len(debug_text),
len(candidate_text)))
text = IBus.Text.new_from_string(candidate_text)
text.set_attributes(attrs)
self._lookup_table.append_candidate(text)
self._lookup_table.set_cursor_visible(True)
def update_candidates(self, force: bool = False) -> bool:
'''
Searches for candidates and updates the lookuptable.
:param force: Force update candidates even if no change to input
Returns “True” if candidates were found and “False” if not.
'''
if self._debug_level > 1:
LOGGER.debug(
'self._chars_valid=%s '
'self._chars_invalid=%s '
'self._chars_valid_update_candidates_last=%s '
'self._chars_invalid_update_candidates_last=%s '
'self._candidates=%s '
'self.database.startchars=%s '
'self._strings=%s',
self._chars_valid,
self._chars_invalid,
self._chars_valid_update_candidates_last,
self._chars_invalid_update_candidates_last,
self._candidates,
self.database.startchars,
self._strings)
if (not force and not self._sg_mode_active
and
self._chars_valid == self._chars_valid_update_candidates_last
and
self._chars_invalid == self._chars_invalid_update_candidates_last):
# The input did not change since we came here last, do
# nothing and leave candidates and lookup table unchanged:
return bool(self._candidates)
self._chars_valid_update_candidates_last = self._chars_valid
self._chars_invalid_update_candidates_last = self._chars_invalid
self._lookup_table.clear()
self._lookup_table.set_cursor_visible(True)
if not self._sg_mode_active:
if self._chars_invalid or not self._chars_valid:
self._candidates = []
self._candidates_previous = self._candidates
return False
if (not self._sg_mode_active
and self._py_mode
and self.database.is_db_chinese):
self._candidates = (
self.database.select_chinese_characters_by_pinyin(
tabkeys=self._chars_valid,
chinese_mode=self._chinese_mode,
single_wildcard_char=self._single_wildcard_char,
multi_wildcard_char=self._multi_wildcard_char))
elif not self._sg_mode_active:
self._candidates = self.database.select_words(
tabkeys=self._chars_valid,
onechar=self._onechar,
chinese_mode=self._chinese_mode,
single_wildcard_char=self._single_wildcard_char,
multi_wildcard_char=self._multi_wildcard_char,
auto_wildcard=self._auto_wildcard,
dynamic_adjust=self._dynamic_adjust)
elif self._sg_mode_active and self._sg_mode:
self._candidates = self.database.select_suggestion_candidate(
self._prefix)
else:
assert False
# If only a wildcard character has been typed, insert a
# special candidate at the first position for the wildcard
# character itself. For example, if “?” is used as a
# wildcard character and this is the only character typed, add
# a candidate ('?', '?', 0, 1000000000) in halfwidth mode or a
# candidate ('?', '?', 0, 1000000000) in fullwidth mode.
# This is needed to make it possible to input the wildcard
# characters themselves, if “?” acted only as a wildcard
# it would be impossible to input a fullwidth question mark.
if not self._sg_mode_active:
if (self._chars_valid
in [self._single_wildcard_char, self._multi_wildcard_char]):
wildcard_key = self._chars_valid
wildcard_phrase = self._chars_valid
if ascii_ispunct(wildcard_key):
if self._full_width_punct[1]:
wildcard_phrase = unichar_half_to_full(wildcard_phrase)
else:
wildcard_phrase = unichar_full_to_half(wildcard_phrase)
else:
if self._full_width_letter[1]:
wildcard_phrase = unichar_half_to_full(wildcard_phrase)
else:
wildcard_phrase = unichar_full_to_half(wildcard_phrase)
self._candidates.insert(
0, (wildcard_key, wildcard_phrase, 0, 1000000000))
if self._candidates:
self.fill_lookup_table()
self._candidates_previous = self._candidates
return True
# There are only valid and no invalid input characters but no
# matching candidates could be found from the databases. The
# last of self._chars_valid must have caused this. That
# character is valid in the sense that it is listed in
# self._valid_input_chars, it is only invalid in the sense
# that after adding this character, no candidates could be
# found anymore. Add this character to self._chars_invalid
# and remove it from self._chars_valid.
if self._chars_valid:
self._chars_invalid += self._chars_valid[-1]
self._chars_valid = self._chars_valid[:-1]
self._chars_valid_update_candidates_last = self._chars_valid
self._chars_invalid_update_candidates_last = self._chars_invalid
return False
def commit_to_preedit(self) -> bool:
'''Add selected phrase in lookup table to preëdit string'''
if not self._sg_mode_active:
if not self._chars_valid:
return False
if self._candidates:
if not self._sg_mode_active:
phrase = self._candidates[self.get_cursor_pos()][1]
self._u_chars.insert(
self._cursor_precommit,
self._candidates[self.get_cursor_pos()][0])
self._strings.insert(
self._cursor_precommit, phrase)
self._prefix = phrase
elif self._sg_mode_active:
phrase = self._candidates[self.get_cursor_pos()][0]
phrase = phrase[len(self._prefix):]
self._u_chars.insert(self._cursor_precommit,
'')
self._strings.insert(self._cursor_precommit,
phrase)
self._prefix = ''
self._sg_mode_active = False
else:
assert False
self._cursor_precommit += 1
self.clear_input_not_committed_to_preedit()
self.update_candidates()
return True
def commit_to_preedit_current_page(self, index: int) -> bool:
'''
Commits the candidate at position “index” in the current
page of the lookup table to the preëdit. Does not yet “really”
commit the candidate, only to the preëdit.
'''
cursor_pos = self._lookup_table.get_cursor_pos()
cursor_in_page = self._lookup_table.get_cursor_in_page()
current_page_start = cursor_pos - cursor_in_page
real_index = current_page_start + index
if real_index >= len(self._candidates):
# the index given is out of range we do not commit anything
return False
self._lookup_table.set_cursor_pos(real_index)
return self.commit_to_preedit()
def get_aux_strings(self) -> str:
'''Get aux strings'''
input_chars = self.get_input_chars()
if input_chars:
aux_string = input_chars
if self._debug_level > 0 and self._u_chars:
(tabkeys_left,
dummy_tabkeys_current,
tabkeys_right) = self.get_preedit_tabkeys_parts()
(strings_left,
dummy_string_current,
strings_right) = self.get_preedit_string_parts()
aux_string = ''
for i, string in enumerate(strings_left):
aux_string += f'({tabkeys_left[i]} {string}) '
aux_string += input_chars
for i, string in enumerate(strings_right):
aux_string += f' ({tabkeys_right[i]} {string})'
if self._py_mode:
aux_string = aux_string.replace(
'!', '1').replace(
'@', '2').replace(
'#', '3').replace(
'$', '4').replace(
'%', '5')
else:
aux_string_new = ''
for char in aux_string:
if char in self._prompt_characters:
aux_string_new += self._prompt_characters[char]
else:
aux_string_new += char
aux_string = aux_string_new
return aux_string
# There are no input strings at the moment. But there could
# be stuff committed to the preëdit. If there is something
# committed to the preëdit, show some information in the
# auxiliary text.
#
# For the character at the position of the cursor in the
# preëdit, show a list of possible input key sequences which
# could be used to type that character at the left side of the
# auxiliary text.
#
# If the preëdit is longer than one character, show the input
# key sequence which will be defined for the complete current
# contents of the preëdit, if the preëdit is committed.
aux_string = ''
if self._strings:
if self._cursor_precommit >= len(self._strings):
char = self._strings[-1][0]
else:
char = self._strings[self._cursor_precommit][0]
aux_string = ' '.join(self.database.find_zi_code(char))
cstr = ''.join(self._strings)
if self.database.user_can_define_phrase:
if len(cstr) > 1:
aux_string += ('\t#: ' + self.database.parse_phrase(cstr))
aux_string_new = ''
for char in aux_string:
if char in self._prompt_characters:
aux_string_new += self._prompt_characters[char]
else:
aux_string_new += char
return aux_string_new
def fill_lookup_table(self) -> None:
'''Fill more entries to self._lookup_table if needed.
If the cursor in _lookup_table moved beyond current length,
add more entries from _candidiate[0] to _lookup_table.'''
looklen = self._lookup_table.get_number_of_candidates()
psize = self._lookup_table.get_page_size()
if (self._lookup_table.get_cursor_pos() + psize >= looklen and
looklen < len(self._candidates)):
endpos = looklen + psize
batch = self._candidates[looklen:endpos]
for candidate in batch:
if (self._input_mode
and not self._py_mode and not self._sg_mode_active):
self.append_table_candidate(
tabkeys=candidate[0],
phrase=candidate[1],
freq=candidate[2],
user_freq=candidate[3])
elif (self._input_mode
and self._py_mode and not self._sg_mode_active):
self.append_pinyin_candidate(
tabkeys=candidate[0],
phrase=candidate[1],
freq=candidate[2],
user_freq=candidate[3])
elif self._input_mode and self._sg_mode_active:
self.append_suggestion_candidate(
prefix=self._prefix,
phrase=candidate[0],
freq=int(candidate[1]))
else:
assert False
def cursor_down(self) -> bool:
'''Process Arrow Down Key Event
Move Lookup Table cursor down'''
self.fill_lookup_table()
res = bool(self._lookup_table.cursor_down())
if not res and self._candidates:
return True
return res
def cursor_up(self) -> bool:
'''Process Arrow Up Key Event
Move Lookup Table cursor up'''
res = bool(self._lookup_table.cursor_up())
if not res and self._candidates:
return True
return res
def page_down(self) -> bool:
'''Process Page Down Key Event
Move Lookup Table page down'''
self.fill_lookup_table()
res = bool(self._lookup_table.page_down())
if not res and self._candidates:
return True
return res
def page_up(self) -> bool:
'''Process Page Up Key Event
move Lookup Table page up'''
res = bool(self._lookup_table.page_up())
if not res and self._candidates:
return True
return res
def remove_candidate_from_user_database(self, index: int) -> bool:
'''Remove the candidate shown at index in the lookup table
from the user database.
If that candidate is not in the user database at all, nothing
happens.
If this is a candidate which is also in the system database,
removing it from the user database only means that its user
frequency data is reset. It might still appear in subsequent
matches but with much lower priority.
If this is a candidate which is user defined and not in the system
database, it will not match at all anymore after removing it.
:param index: The index in the current page of the lookup table.
The topmost candidate has the index 0 (and usually the
label “1”)
:return: True if successful, False if not
'''
if self._debug_level > 1:
LOGGER.debug('index=%s', index)
cursor_pos = self._lookup_table.get_cursor_pos()
cursor_in_page = self._lookup_table.get_cursor_in_page()
current_page_start = cursor_pos - cursor_in_page
real_index = current_page_start + index
if len(self._candidates) > real_index: # this index is valid
candidate = self._candidates[real_index]
self.database.remove_phrase(
tabkeys=candidate[0], phrase=candidate[1], commit=True)
# call update_candidates() to get a new SQL query. The
# input has not really changed, therefore we must clear
# the remembered list of characters to
# force update_candidates() to really do something and not
# return immediately:
self._chars_valid_update_candidates_last = ''
self._chars_invalid_update_candidates_last = ''
self.update_candidates()
return True
return False
def get_cursor_pos(self) -> int:
'''get lookup table cursor position'''
return int(self._lookup_table.get_cursor_pos())
def get_lookup_table(self) -> IBus.LookupTable:
'''Get lookup table'''
return self._lookup_table
def remove_char(self) -> None:
'''Process remove_char Key Event'''
if self._debug_level > 1:
LOGGER.debug('remove_char()')
if self.get_input_chars():
self.pop_input()
return
self.remove_preedit_character_before_cursor()
def delete(self) -> None:
'''Process delete Key Event'''
if self.get_input_chars():
return
self.remove_preedit_character_after_cursor()
def select_next_candidate_in_current_page(self) -> bool:
'''Cycle cursor to next candidate in the page.'''
total = len(self._candidates)
if total > 0:
page_size = self._lookup_table.get_page_size()
pos = self._lookup_table.get_cursor_pos()
page = int(pos/page_size)
pos += 1
if pos >= (page+1)*page_size or pos >= total:
pos = page*page_size
self._lookup_table.set_cursor_pos(pos)
return True
return False
def select_previous_candidate_in_current_page(self) -> bool:
'''Cycle cursor to previous candidate in the page.'''
total = len(self._candidates)
if total > 0:
page_size = self._lookup_table.get_page_size()
pos = self._lookup_table.get_cursor_pos()
page = int(pos/page_size)
pos -= 1
if pos < page*page_size or pos < 0:
pos = min(((page + 1) * page_size) - 1, total)
self._lookup_table.set_cursor_pos(pos)
return True
return False
def one_candidate(self) -> bool:
'''Return true if there is only one candidate'''
return len(self._candidates) == 1
def reset(self) -> None:
'''Clear the preëdit and close the lookup table
'''
self.clear_all_input_and_preedit()
self._double_quotation_state = False
self._single_quotation_state = False
self._prev_key = None
self._update_ui()
def do_destroy(self) -> None: # pylint: disable=arguments-differ
'''Called when this input engine is destroyed
'''
if self.sync_timeout_id > 0:
GObject.source_remove(self.sync_timeout_id)
self.sync_timeout_id = 0
self.reset()
self.do_focus_out()
if self._save_user_count > 0:
self.database.sync_usrdb()
self._save_user_count = 0
super().destroy()
def set_debug_level(
self, debug_level: int, update_gsettings: bool = True) -> None:
'''Sets the debug level
:param debug_level: The debug level (>= 0 and <= 255)
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the Gsettings key changed
to avoid endless loops when the Gsettings
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug(
'(%s, update_gsettings = %s)', debug_level, update_gsettings)
if debug_level == self._debug_level:
return
if 0 <= debug_level <= 255:
self._debug_level = debug_level
self.reset()
if update_gsettings:
self._gsettings.set_value(
'debuglevel',
GLib.Variant.new_int32(debug_level))
def get_debug_level(self) -> int:
'''Returns the current debug level'''
return self._debug_level
def set_dynamic_adjust(
self, dynamic_adjust: bool, update_gsettings: bool = True) -> None:
'''Sets whether dynamic adjustment of the candidates is used.
:param dynamic_adjust: True if dynamic adjustment is used, False if not
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the Gsettings key changed
to avoid endless loops when the Gsettings
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug(
'(%s, update_gsettings = %s)',
dynamic_adjust, update_gsettings)
if dynamic_adjust == self._dynamic_adjust:
return
self._dynamic_adjust = dynamic_adjust
self.database.reset_phrases_cache()
if update_gsettings:
self._gsettings.set_value(
'dynamicadjust',
GLib.Variant.new_boolean(dynamic_adjust))
def get_dynamic_adjust(self) -> bool:
'''Returns whether dynamic adjustment of the candidates is used.'''
return self._dynamic_adjust
def set_error_sound(
self, error_sound: bool, update_gsettings: bool = True) -> None:
'''Sets whether a sound is played on error or not
:param error_sound: True if a sound is played on error, False if not
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the Gsettings key changed
to avoid endless loops when the Gsettings
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug(
'(%s, update_gsettings = %s)', error_sound, update_gsettings)
if error_sound == self._error_sound:
return
self._error_sound = error_sound
if update_gsettings:
self._gsettings.set_value(
'errorsound',
GLib.Variant.new_boolean(error_sound))
def get_error_sound(self) -> bool:
'''Returns whether a sound is played on error or not'''
return self._error_sound
def set_error_sound_file(
self, path: str = '', update_gsettings: bool = True) -> None:
'''Sets the path of the .wav file containing the sound
to play on error.
:param path: The path of the .wav file containing the error sound
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug(
'(%s, update_gsettings = %s)', path, update_gsettings)
if path == self._error_sound_file:
return
self._error_sound_file = path
if update_gsettings:
self._gsettings.set_value(
'errorsoundfile',
GLib.Variant.new_string(path))
self._error_sound_object = it_sound.SoundObject(
os.path.expanduser(path),
audio_backend=self._sound_backend)
def get_error_sound_file(self) -> str:
'''
Return the path of the .wav file containing the error sound.
'''
return self._error_sound_file
def set_sound_backend(
self,
sound_backend: Union[str, Any],
update_gsettings: bool = True) -> None:
'''Sets the sound backend to use
:param sound_backend: The name of sound backend to use
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug(
'(%s, update_gsettings = %s)', sound_backend, update_gsettings)
if not isinstance(sound_backend, str):
return
if sound_backend == self._sound_backend:
return
self._sound_backend = sound_backend
if update_gsettings:
self._gsettings.set_value(
'soundbackend',
GLib.Variant.new_string(sound_backend))
self._error_sound_object = it_sound.SoundObject(
os.path.expanduser(self._error_sound_file),
audio_backend=self._sound_backend)
def get_sound_backend(self) -> str:
'''
Return the name of the currently used sound backend
'''
return self._sound_backend
def set_keybindings(self,
keybindings: Union[Dict[str, List[str]], Any],
update_gsettings: bool = True) -> None:
'''Set current key bindings
:param keybindings: The key bindings to use
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the Gsettings key changed
to avoid endless loops when the Gsettings
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug(
'(%s, update_gsettings = %s)', keybindings, update_gsettings)
if not isinstance(keybindings, dict):
return
keybindings = copy.deepcopy(keybindings)
self._keybindings = copy.deepcopy(self._default_keybindings)
# Update the default settings with the possibly changed settings:
it_util.dict_update_existing_keys(self._keybindings, keybindings)
# Update hotkeys:
self._hotkeys = it_util.HotKeys(self._keybindings)
# New keybindings might have changed the keys to commit candidates
# from the lookup table and then the labels of the lookup table
# might need to be updated:
self._lookup_table = self.get_new_lookup_table()
# Some property menus have tooltips which show hints for the
# key bindings. These may need to be updated if the key
# bindings have changed.
#
# I don’t check whether the key bindings really have changed,
# just update all the properties anyway.
#
# But update them only if the properties have already been
# initialized. At program start they might still be empty at
# the time when self.set_keybindings() is called.
if self._prop_dict:
if self.chinese_mode_menu:
self.chinese_mode_menu['shortcut_hint'] = (
repr(self._keybindings['switch_to_next_chinese_mode']))
if self.input_mode_menu:
self.input_mode_menu['shortcut_hint'] = (
repr(self._keybindings['toggle_input_mode_on_off']))
if self.letter_width_menu:
self.letter_width_menu['shortcut_hint'] = (
repr(self._keybindings['toggle_letter_width']))
if self.punctuation_width_menu:
self.punctuation_width_menu['shortcut_hint'] = (
repr(self._keybindings['toggle_punctuation_width']))
if self.pinyin_mode_menu:
self.pinyin_mode_menu['shortcut_hint'] = (
repr(self._keybindings['toggle_pinyin_mode']))
if self.suggestion_mode_menu:
self.suggestion_mode_menu['shortcut_hint'] = (
repr(self._keybindings['toggle_suggestion_mode']))
if self.onechar_mode_menu:
self.onechar_mode_menu['shortcut_hint'] = (
repr(self._keybindings['toggle_onechar_mode']))
if self.autocommit_mode_menu:
self.autocommit_mode_menu['shortcut_hint'] = (
repr(self._keybindings['toggle_autocommit_mode']))
self._init_properties()
if update_gsettings:
variant_dict = GLib.VariantDict(GLib.Variant('a{sv}', {}))
for command in sorted(self._keybindings):
variant_array = GLib.Variant.new_array(
GLib.VariantType('s'),
[GLib.Variant.new_string(x)
for x in self._keybindings[command]])
variant_dict.insert_value(command, variant_array)
self._gsettings.set_value(
'keybindings',
variant_dict.end())
def get_keybindings(self) -> Dict[str, List[str]]:
'''Get current key bindings'''
# It is important to return a copy, we do not want to change
# the private member variable directly.
return self._keybindings.copy()
def set_input_mode(self,
input_mode: int = 1,
update_gsettings: bool = True) -> None:
'''Sets whether direct input or the current table is used.
:param input_mode: Whether to use direct input.
0: Use direct input.
1: Use the current table.
'''
if input_mode == self._input_mode:
return
self._input_mode = input_mode
if update_gsettings:
self._gsettings.set_value(
"inputmode",
GLib.Variant.new_int32(self._input_mode))
self._init_or_update_property_menu(
self.input_mode_menu,
self._input_mode)
# Letter width and punctuation width depend on the input mode.
# Therefore, the properties for letter width and punctuation
# width need to be updated here:
self._init_or_update_property_menu(
self.letter_width_menu,
self._full_width_letter[self._input_mode])
self._init_or_update_property_menu(
self.punctuation_width_menu,
self._full_width_punct[self._input_mode])
self.reset()
def set_remember_input_mode(self,
remember_input_mode: bool = True,
update_gsettings: bool = True) -> None:
'''Sets whether the input mode (direct or table) is remembered
:param remember_input_mode: Whether to remember the input mode.
False: Do not remember
True: Remember.
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the Gsettings key changed
to avoid endless loops when the Gsettings
key is changed twice in a short time.
'''
LOGGER.info(
'(%s, update_gsettings = %s)', remember_input_mode, update_gsettings)
remember_input_mode = bool(remember_input_mode)
if remember_input_mode == self._remember_input_mode:
return
self._remember_input_mode = remember_input_mode
if update_gsettings:
self._gsettings.set_value(
'rememberinputmode',
GLib.Variant.new_boolean(remember_input_mode))
def get_remember_input_mode(self) -> bool:
'''
Return whether the input mode is remembered.
'''
return self._remember_input_mode
def set_dark_theme(
self,
use_dark_theme: bool = False,
update_gsettings: bool = True) -> None:
'''Set theme to dark theme on request'''
if use_dark_theme:
theme = THEME_DARK
else:
theme = THEME
if theme is not self.theme:
self.theme = theme
self._update_ui()
if update_gsettings:
self._gsettings.set_value(
"darktheme",
GLib.Variant.new_boolean(use_dark_theme))
def get_input_mode(self) -> int:
'''
Return the current input mode, direct input: 0, table input: 1.
'''
return self._input_mode
def set_pinyin_mode(self, mode: bool = False) -> None:
'''Sets whether Pinyin is used.
:param mode: Whether to use Pinyin.
True: Use Pinyin.
False: Use the current table.
:type mode: Boolean
'''
if not self._ime_py:
return
if mode == self._py_mode:
return
# The pinyin mode is never saved to GSettings on purpose
self._py_mode = mode
self._init_or_update_property_menu(
self.pinyin_mode_menu, mode)
if mode:
self.input_mode_properties['InputMode.Table']['symbol'] = (
self.input_mode_properties['InputMode.Table']['symbol_pinyin'])
else:
self.input_mode_properties['InputMode.Table']['symbol'] = (
self.input_mode_properties['InputMode.Table']['symbol_table'])
self._init_or_update_property_menu(
self.input_mode_menu,
self._input_mode)
self._update_ui()
def get_pinyin_mode(self) -> bool:
'''Return the current pinyin mode'''
return self._py_mode
def set_suggestion_mode(self, mode: bool = False) -> None:
'''Sets whether Suggestion is used.
:param mode: Whether to use Suggestion.
True: Use Suggestion.
False: Not use Suggestion.
'''
if not self._ime_sg:
return
if mode == self._sg_mode:
return
self.commit_to_preedit()
self._sg_mode = mode
self._init_or_update_property_menu(
self.suggestion_mode_menu, mode)
self._update_ui()
def get_suggestion_mode(self) -> bool:
'''Return the current suggestion mode'''
return self._sg_mode
def set_onechar_mode(
self, mode: bool = False, update_gsettings: bool = True) -> None:
'''Sets whether only single characters should be matched in
the database.
:param mode: Whether only single characters should be matched.
True: Match only single characters.
False: Possibly match multiple characters at once.
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if mode == self._onechar:
return
self._onechar = mode
self._init_or_update_property_menu(
self.onechar_mode_menu, mode)
self.database.reset_phrases_cache()
if update_gsettings:
self._gsettings.set_value(
"onechar",
GLib.Variant.new_boolean(mode))
def get_onechar_mode(self) -> bool:
'''
Returns whether only single characters are matched in the database.
'''
return self._onechar
def set_autocommit_mode(
self, mode: bool = False, update_gsettings: bool = True) -> None:
'''Sets whether automatic commits go into the preëdit or into the
application.
:param mode: Whether automatic commits go into the preëdit
or into the application.
True: Into the application.
False: Into the preëdit.
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if mode == self._auto_commit:
return
self._auto_commit = mode
self._init_or_update_property_menu(
self.autocommit_mode_menu, mode)
if update_gsettings:
self._gsettings.set_value(
"autocommit",
GLib.Variant.new_boolean(mode))
def get_autocommit_mode(self) -> bool:
'''Returns the current auto-commit mode'''
return self._auto_commit
def set_commit_invalid_mode(
self, mode: int = 0, update_gsettings: bool = True) -> None:
'''Sets the commit invalid mode
This selects what is committed when a character which is not
in the set of valid input characters for the current table is
typed.
0 means to commit the current candidate
1 means to commit the raw characters typed so far
:param mode: The mode (0 <= mode <= 1)
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug('mode=%s', mode)
if mode == self._commit_invalid_mode:
return
self._commit_invalid_mode = mode
if update_gsettings:
self._gsettings.set_value(
"commitinvalidmode",
GLib.Variant.new_int32(mode))
def get_commit_invalid_mode(self) -> int:
'''Return the current comimt invalid mode'''
return self._commit_invalid_mode
def set_autoselect_mode(
self, mode: bool = False, update_gsettings: bool = True) -> None:
'''Sets whether the first candidate will be selected
automatically during typing.
:param mode: Whether to select the first candidate automatically.
:type mode: Boolean
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
:type update_gsettings: Boolean
'''
if mode == self._auto_select:
return
self._auto_select = mode
if update_gsettings:
self._gsettings.set_value(
"autoselect",
GLib.Variant.new_boolean(mode))
def get_autoselect_mode(self) -> bool:
'''Returns the current auto-select mode'''
return self._auto_select
def set_autowildcard_mode(
self, mode: bool = False, update_gsettings: bool = True) -> None:
'''Sets whether a wildcard should be automatically appended
to the input.
:param mode: Whether to append a wildcard automatically.
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if mode == self._auto_wildcard:
return
self._auto_wildcard = mode
self.database.reset_phrases_cache()
if update_gsettings:
self._gsettings.set_value(
"autowildcard",
GLib.Variant.new_boolean(mode))
def get_autowildcard_mode(self) -> bool:
'''Returns the current automatic wildcard mode'''
return self._auto_wildcard
def set_single_wildcard_char(
self, char: str = '', update_gsettings: bool = True) -> None:
'''Sets the single wildchard character.
:param char: The character to use as a single wildcard
(String of length 1).
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if char == self._single_wildcard_char:
return
self._single_wildcard_char = char
self.database.reset_phrases_cache()
if update_gsettings:
self._gsettings.set_value(
"singlewildcardchar",
GLib.Variant.new_string(char))
def get_single_wildcard_char(self) -> str:
'''
Return the character currently used as a single wildcard.
(String of length 1.)
'''
return self._single_wildcard_char
def set_multi_wildcard_char(
self, char: str = '', update_gsettings: bool = True) -> None:
'''Sets the multi wildchard character.
:param char: The character to use as a multi wildcard.
(String of length 1.)
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if len(char) > 1:
char = char[0]
if char == self._multi_wildcard_char:
return
self._multi_wildcard_char = char
self.database.reset_phrases_cache()
if update_gsettings:
self._gsettings.set_value(
"multiwildcardchar",
GLib.Variant.new_string(char))
def get_multi_wildcard_char(self) -> str:
'''
Return the character currently used as a multi wildcard.
(String of length 1.)
'''
return self._multi_wildcard_char
def set_always_show_lookup(
self, mode: bool = False, update_gsettings: bool = True) -> None:
'''Sets the whether the lookup table is shown.
:param mode: Whether to show the lookup table.
True: Lookup table is shown
False: Lookup table is hidden
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if mode == self._always_show_lookup:
return
self._always_show_lookup = mode
if update_gsettings:
self._gsettings.set_value(
"alwaysshowlookup",
GLib.Variant.new_boolean(mode))
def get_always_show_lookup(self) -> bool:
'''Returns whether the lookup table is shown or hidden'''
return self._always_show_lookup
def set_lookup_table_orientation(
self, orientation: int, update_gsettings: bool = True) -> None:
'''Sets the orientation of the lookup table
:param orientation: The orientation of the lookup table
0 <= orientation <= 2
IBUS_ORIENTATION_HORIZONTAL = 0,
IBUS_ORIENTATION_VERTICAL = 1,
IBUS_ORIENTATION_SYSTEM = 2.
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug('orientation(%s)', orientation)
if orientation == self._orientation:
return
if 0 <= orientation <= 2:
self._orientation = orientation
self._lookup_table.set_orientation(orientation)
if update_gsettings:
self._gsettings.set_value(
'lookuptableorientation',
GLib.Variant.new_int32(orientation))
def get_lookup_table_orientation(self) -> int:
'''Returns the current orientation of the lookup table'''
return self._orientation
def set_page_size(
self, page_size: int, update_gsettings: bool = True) -> None:
'''Sets the page size of the lookup table
:param page_size: The page size of the lookup table
1 <= page size <= number of select keys
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug('page_size=%s', page_size)
if page_size == self._page_size:
return
for index in range(1, 10):
if not self._default_keybindings[f'commit_candidate_{index + 1}']:
page_size = min(index, page_size)
break
page_size = max(page_size, 1)
self._page_size = page_size
# get a new lookup table to adapt to the new page size:
self._lookup_table = self.get_new_lookup_table()
self.reset()
if update_gsettings:
self._gsettings.set_value(
'lookuptablepagesize',
GLib.Variant.new_int32(page_size))
def get_page_size(self) -> int:
'''Returns the current page size of the lookup table'''
return self._page_size
def set_letter_width(
self,
mode: bool = False,
input_mode: int = 0,
update_gsettings: bool = True) -> None:
'''
Sets whether full width letters should be used.
:param mode: Whether to use full width letters
:param input_mode: The input mode (direct input: 0, table: 1)
for which to set the full width letter mode.
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the Gsettings key changed
to avoid endless loops when the Gsettings
key is changed twice in a short time.
'''
if mode == self._full_width_letter[input_mode]:
return
self._full_width_letter[input_mode] = mode
if input_mode == self._input_mode:
self._init_or_update_property_menu(
self.letter_width_menu, mode)
if update_gsettings:
if input_mode:
self._gsettings.set_value(
"tabdeffullwidthletter",
GLib.Variant.new_boolean(mode))
else:
self._gsettings.set_value(
"endeffullwidthletter",
GLib.Variant.new_boolean(mode))
def get_letter_width(self) -> List[Optional[bool]]:
'''Return the current full width letter modes: [Boolean, Boolean]'''
return self._full_width_letter
def set_punctuation_width(
self,
mode: bool = False,
input_mode: int = 0,
update_gsettings: bool = True) -> None:
'''
Sets whether full width punctuation should be used.
:param mode: Whether to use full width punctuation
:param input_mode: The input mode (direct input: 0, table: 1)
for which to set the full width punctuation mode.
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the Gsettings key changed
to avoid endless loops when the Gsettings
key is changed twice in a short time.
'''
if mode == self._full_width_punct[input_mode]:
return
self._full_width_punct[input_mode] = mode
if input_mode == self._input_mode:
self._init_or_update_property_menu(
self.punctuation_width_menu, mode)
if update_gsettings:
if input_mode:
self._gsettings.set_value(
"tabdeffullwidthpunct",
GLib.Variant.new_boolean(mode))
else:
self._gsettings.set_value(
"endeffullwidthpunct",
GLib.Variant.new_boolean(mode))
def get_punctuation_width(self) -> List[Optional[bool]]:
'''Return the current full width punctuation modes: [Boolean, Boolean]
'''
return self._full_width_punct
def set_chinese_mode(
self, mode: int = 0, update_gsettings: bool = True) -> None:
'''Sets the candidate filter mode used for Chinese
0 means to show simplified Chinese only
1 means to show traditional Chinese only
2 means to show all characters but show simplified Chinese first
3 means to show all characters but show traditional Chinese first
4 means to show all characters
:param mode: The Chinese filter mode, 0 <= mode <= 4
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if self._debug_level > 1:
LOGGER.debug('mode=%s', mode)
if mode == self._chinese_mode:
return
self._chinese_mode = mode
self.database.reset_phrases_cache()
self._init_or_update_property_menu(
self.chinese_mode_menu, mode)
if update_gsettings:
self._gsettings.set_value(
"chinesemode",
GLib.Variant.new_int32(mode))
def get_chinese_mode(self) -> int:
'''
Return the current Chinese mode.
0 means to show simplified Chinese only
1 means to show traditional Chinese only
2 means to show all characters but show simplified Chinese first
3 means to show all characters but show traditional Chinese first
4 means to show all characters
'''
return self._chinese_mode
def set_input_method_menu(
self,
input_method_menu: Optional[List[str]] = None,
update_gsettings: bool = True) -> None:
'''Sets the visible input method menu items.
:param input_method_menu: The visible input method menu items
:param update_gsettings: Whether to write the change to Gsettings.
Set this to False if this method is
called because the dconf key changed
to avoid endless loops when the dconf
key is changed twice in a short time.
'''
if input_method_menu is None:
input_method_menu = []
if self._debug_level > 1:
LOGGER.debug('input_method_menu=%s', input_method_menu)
if input_method_menu == self._input_method_menu:
return
self._input_method_menu = input_method_menu
self._init_properties()
if update_gsettings:
self._gsettings.set_value(
"inputmethodmenu",
GLib.Variant.new_strv(input_method_menu))
def get_input_method_menu(self) -> List[str]:
'''
Return the visible input method menu items.
'''
return self._input_method_menu
def _init_or_update_property_menu(
self,
menu: Dict[str, Any],
current_mode: Union[int, bool, None] = 0) -> None:
'''
Initialize or update a ibus property menu
'''
if self._debug_level > 1:
LOGGER.debug(
'menu=%s current_mode=%s', repr(menu), current_mode)
if not current_mode:
current_mode = 0
menu_key = menu['key']
sub_properties_dict = menu['sub_properties']
symbol = ''
icon = ''
label = ''
tooltip = ''
for prop in sub_properties_dict:
if sub_properties_dict[prop]['number'] == int(current_mode):
symbol = sub_properties_dict[prop]['symbol']
icon = sub_properties_dict[prop]['icon']
label = f'{menu["label"]} ({symbol}) {menu["shortcut_hint"]}'
tooltip = f'{menu["tooltip"]}\n{menu["shortcut_hint"]}'
visible = True
self._init_or_update_sub_properties(
menu_key, sub_properties_dict, current_mode=current_mode)
if menu_key not in self._prop_dict: # initialize property
self._prop_dict[menu_key] = IBus.Property(
key=menu_key,
prop_type=IBus.PropType.MENU,
label=IBus.Text.new_from_string(label),
symbol=IBus.Text.new_from_string(symbol),
icon=os.path.join(self._icon_dir, icon),
tooltip=IBus.Text.new_from_string(tooltip),
sensitive=visible,
visible=visible,
state=IBus.PropState.UNCHECKED,
sub_props=self._sub_props_dict[menu_key])
self.main_prop_list.append(self._prop_dict[menu_key])
else: # update the property
self._prop_dict[menu_key].set_label(
IBus.Text.new_from_string(label))
self._prop_dict[menu_key].set_symbol(
IBus.Text.new_from_string(symbol))
self._prop_dict[menu_key].set_icon(
os.path.join(self._icon_dir, icon))
self._prop_dict[menu_key].set_tooltip(
IBus.Text.new_from_string(tooltip))
self._prop_dict[menu_key].set_sensitive(visible)
self._prop_dict[menu_key].set_visible(visible)
self.update_property(self._prop_dict[menu_key]) # important!
def _init_or_update_sub_properties(
self,
menu_key: str,
modes: Dict[str, Any],
current_mode: int = 0) -> None:
'''
Initialize or update the sub-properties of a property menu entry.
'''
if menu_key not in self._sub_props_dict:
update = False
self._sub_props_dict[menu_key] = IBus.PropList()
else:
update = True
visible = True
for mode in sorted(modes, key=lambda x: (int(modes[x]['number']))):
if modes[mode]['number'] == int(current_mode):
state = IBus.PropState.CHECKED
else:
state = IBus.PropState.UNCHECKED
label = modes[mode]['label']
if 'tooltip' in modes[mode]:
tooltip = modes[mode]['tooltip']
else:
tooltip = ''
if not update: # initialize property
self._prop_dict[mode] = IBus.Property(
key=mode,
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(label),
icon=os.path.join(modes[mode]['icon']),
tooltip=IBus.Text.new_from_string(tooltip),
sensitive=visible,
visible=visible,
state=state,
sub_props=None)
self._sub_props_dict[menu_key].append(
self._prop_dict[mode])
else: # update property
self._prop_dict[mode].set_label(
IBus.Text.new_from_string(label))
self._prop_dict[mode].set_tooltip(
IBus.Text.new_from_string(tooltip))
self._prop_dict[mode].set_sensitive(visible)
self._prop_dict[mode].set_visible(visible)
self._prop_dict[mode].set_state(state)
self.update_property(self._prop_dict[mode]) # important!
def _init_properties(self) -> None:
'''
Initialize the ibus property menus
'''
self._prop_dict = {}
self._sub_props_dict = {}
self.main_prop_list = IBus.PropList()
_input_method_menu = self.get_input_method_menu()
self._init_or_update_property_menu(
self.input_mode_menu,
self._input_mode)
if "chinese_mode" in _input_method_menu and \
self.database.is_db_chinese and self._chinese_mode != -1:
self._init_or_update_property_menu(
self.chinese_mode_menu,
self._chinese_mode)
if self.database.is_db_cjk:
if "letter_width" in _input_method_menu:
self._init_or_update_property_menu(
self.letter_width_menu,
self._full_width_letter[self._input_mode])
if "punctuation_width" in _input_method_menu:
self._init_or_update_property_menu(
self.punctuation_width_menu,
self._full_width_punct[self._input_mode])
if "pinyin_mode" in _input_method_menu and self._ime_py:
self._init_or_update_property_menu(
self.pinyin_mode_menu,
self._py_mode)
if "suggestion_mode" in _input_method_menu and self._ime_sg:
self._init_or_update_property_menu(
self.suggestion_mode_menu,
self._sg_mode)
if "onechar_mode" in _input_method_menu and self.database.is_db_cjk:
self._init_or_update_property_menu(
self.onechar_mode_menu,
self._onechar)
if "autocommit_mode" in _input_method_menu and \
self.database.user_can_define_phrase and self.database.rules:
self._init_or_update_property_menu(
self.autocommit_mode_menu,
self._auto_commit)
self._setup_property = IBus.Property(
key='setup',
label=IBus.Text.new_from_string(_('Setup')),
icon='gtk-preferences',
tooltip=IBus.Text.new_from_string(
_('Configure ibus-table “%(engine-name)s”')
% {'engine-name': self._engine_name}),
sensitive=True,
visible=True)
self.main_prop_list.append(self._setup_property)
self.register_properties(self.main_prop_list)
def do_property_activate( # pylint: disable=arguments-differ
self,
ibus_property: str,
prop_state: IBus.PropState = IBus.PropState.UNCHECKED) -> None:
'''
Handle clicks on properties
'''
if self._debug_level > 1:
LOGGER.debug(
'ibus_property=%s prop_state=%s', ibus_property, prop_state)
if ibus_property == "setup":
self._start_setup()
return
if prop_state != IBus.PropState.CHECKED:
# If the mouse just hovered over a menu button and
# no sub-menu entry was clicked, there is nothing to do:
return
if ibus_property.startswith(self.input_mode_menu['key']+'.'):
self.set_input_mode(
self.input_mode_properties[ibus_property]['number'])
return
if (ibus_property.startswith(self.pinyin_mode_menu['key']+'.')
and self._ime_py):
self.set_pinyin_mode(
bool(self.pinyin_mode_properties[ibus_property]['number']))
return
if (ibus_property.startswith(self.suggestion_mode_menu['key']+'.')
and self._ime_sg):
self.set_suggestion_mode(
bool(self.suggestion_mode_properties[ibus_property]['number']))
return
if (ibus_property.startswith(self.onechar_mode_menu['key']+'.')
and self.database.is_db_cjk):
self.set_onechar_mode(
bool(self.onechar_mode_properties[ibus_property]['number']))
return
if (ibus_property.startswith(self.autocommit_mode_menu['key']+'.')
and self.database.user_can_define_phrase
and self.database.rules):
self.set_autocommit_mode(
bool(self.autocommit_mode_properties[ibus_property]['number']))
return
if (ibus_property.startswith(self.letter_width_menu['key']+'.')
and self.database.is_db_cjk):
self.set_letter_width(
bool(self.letter_width_properties[ibus_property]['number']),
input_mode=self._input_mode)
return
if (ibus_property.startswith(self.punctuation_width_menu['key']+'.')
and self.database.is_db_cjk):
self.set_punctuation_width(
bool(self.punctuation_width_properties[
ibus_property]['number']),
input_mode=self._input_mode)
return
if (ibus_property.startswith(self.chinese_mode_menu['key']+'.')
and self.database.is_db_chinese
and self._chinese_mode != -1):
self.set_chinese_mode(
self.chinese_mode_properties[ibus_property]['number'])
return
def _start_setup(self) -> None:
'''Start the setup tool if it is not running yet'''
if self._is_setup_running():
LOGGER.info('Another setup tool is still running, terminating it ...')
self._stop_setup()
if os.getenv('IBUS_TABLE_LIB_LOCATION'):
setup_cmd = os.path.join(
os.getenv('IBUS_TABLE_LIB_LOCATION', ''),
'ibus-setup-table')
cmd = [setup_cmd, '--engine-name', f'table:{self._engine_name}']
else:
setup_python_script = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'../setup/main.py')
cmd = [sys.executable, setup_python_script,
'--engine-name', f'table:{self._engine_name}']
LOGGER.info('Starting setup tool: "%s"', ' '.join(cmd))
try:
self._setup_process = subprocess.Popen( # pylint: disable=consider-using-with
cmd)
except Exception as error: # pylint: disable=broad-except
LOGGER.exception(
'Exception when starting setup tools: %s: %s',
error.__class__.__name__, error)
self._setup_process = None
def _is_setup_running(self) -> bool:
'''Check if the setup process is still running.'''
if self._setup_process is None:
return False
return self._setup_process.poll() is None # None means still running
def _stop_setup(self) -> None:
'''Terminate the setup process if running.'''
if self._is_setup_running() and self._setup_process:
self._setup_process.terminate()
# self._setup_process.kill()
LOGGER.info('Stopped setup tool.')
def _play_error_sound(self) -> None:
'''Play an error sound if enabled and possible'''
if self._error_sound and self._error_sound_object:
try:
self._error_sound_object.play()
except Exception as error: # pylint: disable=broad-except
LOGGER.exception('Playing error sound failed: %s: %s',
error.__class__.__name__, error)
def _update_preedit(self) -> None:
'''Update Preedit String in UI'''
if self._sg_mode_active:
self.hide_preedit_text()
return
preedit_string_parts = self.get_preedit_string_parts()
left_of_current_edit = ''.join(preedit_string_parts[0])
current_edit = preedit_string_parts[1]
right_of_current_edit = ''.join(preedit_string_parts[2])
if self._input_mode and not self._sg_mode_active:
current_edit_new = ''
for char in current_edit:
if char in self._prompt_characters:
current_edit_new += self._prompt_characters[char]
else:
current_edit_new += char
current_edit = current_edit_new
preedit_string_complete = (
left_of_current_edit + current_edit + right_of_current_edit)
if not preedit_string_complete:
# Not using super().update_preedit_text_with_mode() because
# IBus.EngineSimple does not have that method.
IBus.Engine.update_preedit_text_with_mode(
self,
IBus.Text.new_from_string(''), 0, False,
IBus.PreeditFocusMode.COMMIT)
return
color_left = self.theme["preedit_left"] # bright red
color_right = self.theme["preedit_right"] # light green
color_invalid = self.theme["preedit_invalid"] # magenta
attrs = IBus.AttrList()
attrs.append(
IBus.attr_foreground_new(
color_left,
0,
len(left_of_current_edit)))
attrs.append(
IBus.attr_foreground_new(
color_right,
len(left_of_current_edit) + len(current_edit),
len(preedit_string_complete)))
if self._chars_invalid:
self._play_error_sound()
attrs.append(
IBus.attr_foreground_new(
color_invalid,
len(left_of_current_edit) + len(current_edit)
- len(self._chars_invalid),
len(left_of_current_edit) + len(current_edit)
))
attrs.append(
IBus.attr_underline_new(
IBus.AttrUnderline.SINGLE,
0,
len(preedit_string_complete)))
text = IBus.Text.new_from_string(preedit_string_complete)
text.set_attributes(attrs)
# Not using super().update_preedit_text_with_mode() because
# IBus.EngineSimple does not have that method.
IBus.Engine.update_preedit_text_with_mode(
self,
text, self.get_caret(), True, IBus.PreeditFocusMode.COMMIT)
def _update_aux(self) -> None:
'''Update Aux String in UI'''
if self._sg_mode_active:
return
aux_string = self.get_aux_strings()
if self._candidates:
aux_string += (
f' ({self._lookup_table.get_cursor_pos() +1} / '
f'{self._lookup_table.get_number_of_candidates()})')
if aux_string:
if self._debug_level > 0 and not self._unit_test:
client = f'🪟{self._im_client}'
aux_string += client
attrs = IBus.AttrList()
attrs.append(IBus.attr_foreground_new(
self.theme["aux_text"], 0, len(aux_string)))
text = IBus.Text.new_from_string(aux_string)
text.set_attributes(attrs)
visible = True
if not aux_string or not self._always_show_lookup:
visible = False
super().update_auxiliary_text(text, visible)
else:
self.hide_auxiliary_text()
def _update_lookup_table(self) -> None:
'''Update Lookup Table in UI'''
if not self._candidates:
# Also make sure to hide lookup table if there are
# no candidates to display. On f17, this makes no
# difference but gnome-shell in f18 will display
# an empty suggestion popup if the number of candidates
# is zero!
self.hide_lookup_table()
return
if self._input_mode and not self._sg_mode_active:
if self.is_empty():
self.hide_lookup_table()
return
if not self._always_show_lookup:
self.hide_lookup_table()
return
self.update_lookup_table(self.get_lookup_table(), True)
def _update_ui(self) -> None:
'''Update User Interface'''
self._update_lookup_table()
self._update_preedit()
self._update_aux()
def _check_phrase(self, tabkeys: str = '', phrase: str = '') -> None:
"""Check the given phrase and update save user db info"""
if not tabkeys or not phrase:
return
self.database.check_phrase(
tabkeys=tabkeys,
phrase=phrase,
dynamic_adjust=self._dynamic_adjust)
if self._save_user_count <= 0:
self._save_user_start = time.time()
self._save_user_count += 1
def _sync_user_db(self) -> bool:
"""Save user db to disk"""
if self._save_user_count >= 0:
now = time.time()
time_delta = now - self._save_user_start
if (self._save_user_count > self._save_user_count_max or
time_delta >= self._save_user_timeout):
self.database.sync_usrdb()
self._save_user_count = 0
self._save_user_start = now
return True
def commit_string(self, phrase: str, tabkeys: str = '') -> None:
'''
Commit the string “phrase”, update the user database,
and clear the preëdit.
:param phrase: The text to commit
:param tabkeys: The keys typed to produce this text
'''
if self._debug_level > 1:
LOGGER.debug('phrase=%s', phrase)
self.clear_all_input_and_preedit()
self._update_ui()
self._prefix = phrase
super().commit_text(IBus.Text.new_from_string(phrase))
if phrase:
self._prev_char = phrase[-1]
else:
self._prev_char = None
self._check_phrase(tabkeys=tabkeys, phrase=phrase)
def commit_everything_unless_invalid(self) -> bool:
'''
Commits the current input to the preëdit and then
commits the preëdit to the application unless there are
invalid input characters.
Returns “True” if something was committed, “False” if not.
'''
if self._debug_level > 1:
LOGGER.debug('self._chars_invalid=%s',
self._chars_invalid)
if self._chars_invalid:
return False
if self._input_mode and self._sg_mode_active:
self.commit_to_preedit()
if not self.is_empty():
self.commit_to_preedit()
self.commit_string(self.get_preedit_string_complete(),
tabkeys=self.get_preedit_tabkeys_complete())
return True
def _convert_to_full_width(self, char: str) -> str:
'''Convert half width character to full width'''
# This function handles punctuation that does not comply to the
# Unicode conversion formula in unichar_half_to_full(char).
# For ".", "\"", "'"; there are even variations under specific
# cases. This function should be more abstracted by extracting
# that to another handling function later on.
special_punct_dict = {"<": "《", # 《 U+300A LEFT DOUBLE ANGLE BRACKET
">": "》", # 》 U+300B RIGHT DOUBLE ANGLE BRACKET
"[": "「", # 「 U+300C LEFT CORNER BRACKET
"]": "」", # 」U+300D RIGHT CORNER BRACKET
"{": "『", # 『 U+300E LEFT WHITE CORNER BRACKET
"}": "』", # 』U+300F RIGHT WHITE CORNER BRACKET
"\\": "、", # 、 U+3001 IDEOGRAPHIC COMMA
"^": "……", # … U+2026 HORIZONTAL ELLIPSIS
"_": "——", # — U+2014 EM DASH
"$": "¥" # ¥ U+FFE5 FULLWIDTH YEN SIGN
}
# special puncts w/o further conditions
if char in special_punct_dict:
if char in ["\\", "^", "_", "$"]:
return special_punct_dict[char]
if self._input_mode:
return special_punct_dict[char]
# special puncts w/ further conditions
if char == ".":
if (self._prev_char
and self._prev_char.isdigit()
and self._prev_key
and chr(self._prev_key.val) == self._prev_char):
return "."
return "。" # 。U+3002 IDEOGRAPHIC FULL STOP
if char == "\"":
self._double_quotation_state = not self._double_quotation_state
if self._double_quotation_state:
return "“" # “ U+201C LEFT DOUBLE QUOTATION MARK
return "”" # ” U+201D RIGHT DOUBLE QUOTATION MARK
if char == "'":
self._single_quotation_state = not self._single_quotation_state
if self._single_quotation_state:
return "‘" # ‘ U+2018 LEFT SINGLE QUOTATION MARK
return "’" # ’ U+2019 RIGHT SINGLE QUOTATION MARK
return unichar_half_to_full(char)
def do_candidate_clicked( # pylint: disable=arguments-differ
self, index: int, _button: int, _state: int) -> bool:
if self._debug_level > 1:
LOGGER.debug('index=%s _button=%s state=%s', index, _button, _state)
if self.commit_to_preedit_current_page(index):
# commits to preëdit
self.commit_string(
self.get_preedit_string_complete(),
tabkeys=self.get_preedit_tabkeys_complete())
return True
return False
def _command_setup(self) -> bool:
'''Handle hotkey for the command “setup”
:return: True if the key was completely handled, False if not.
'''
self._start_setup()
return True
def _command_toggle_input_mode_on_off(self) -> bool:
'''Handle hotkey for the command “toggle_input_mode_on_off”
:return: True if the key was completely handled, False if not.
'''
if not self.is_empty():
commit_string = self.get_preedit_tabkeys_complete()
self.commit_string(commit_string)
self.set_input_mode(int(not self._input_mode))
return True
def _command_toggle_letter_width(self) -> bool:
'''Handle hotkey for the command “toggle_letter_width”
:return: True if the key was completely handled, False if not.
'''
if not self.database.is_db_cjk:
return False
self.set_letter_width(
not self._full_width_letter[self._input_mode],
input_mode=self._input_mode)
return True
def _command_toggle_punctuation_width(self) -> bool:
'''Handle hotkey for the command “toggle_punctuation_width”
:return: True if the key was completely handled, False if not.
'''
if not self.database.is_db_cjk:
return False
self.set_punctuation_width(
not self._full_width_punct[self._input_mode],
input_mode=self._input_mode)
return True
def _command_cancel(self) -> bool:
'''Handle hotkey for the command “cancel”
:return: True if the key was completely handled, False if not.
'''
if self.is_empty():
return False
self.reset()
self._update_ui()
return True
def _command_toggle_suggestion_mode(self) -> bool:
'''Handle hotkey for the command “toggle_suggestion_mode”
:return: True if the key was completely handled, False if not.
'''
if not self._ime_sg:
return False
self.set_suggestion_mode(not self._sg_mode)
return True
def _command_commit_to_preedit(self) -> bool:
'''Handle hotkey for the command “commit_to_preedit”
:return: True if the key was completely handled, False if not.
'''
if self.is_empty():
return False
res = self.commit_to_preedit()
self._update_ui()
return res
def _command_toggle_pinyin_mode(self) -> bool:
'''Handle hotkey for the command “toggle_pinyin_mode”
:return: True if the key was completely handled, False if not.
'''
if not self._ime_py:
return False
self.set_pinyin_mode(not self._py_mode)
if not self.is_empty():
# Feed the current input in once again to get
# the candidates and preedit to update correctly
# for the new mode:
chars = self._chars_valid + self._chars_invalid
self._chars_valid = ''
self._chars_invalid = ''
for char in chars:
self.add_input(char)
self.update_candidates(force=True)
self._update_ui()
return True
def _command_select_next_candidate_in_current_page(self) -> bool:
'''Handle hotkey for the command
“select_next_candidate_in_current_page”
:return: True if the key was completely handled, False if not.
'''
res = self.select_next_candidate_in_current_page()
self._update_ui()
return res
def _command_select_previous_candidate_in_current_page(self) -> bool:
'''Handle hotkey for the command
“select_previous_candidate_in_current_page”
:return: True if the key was completely handled, False if not.
'''
res = self.select_previous_candidate_in_current_page()
self._update_ui()
return res
def _command_toggle_onechar_mode(self) -> bool:
'''Handle hotkey for the command “toggle_onechar_mode”
:return: True if the key was completely handled, False if not.
'''
if not self.database.is_db_cjk:
return False
self.set_onechar_mode(not self._onechar)
if not self.is_empty():
self.update_candidates(True)
self._update_ui()
return True
def _command_toggle_autocommit_mode(self) -> bool:
'''Handle hotkey for the command “toggle_autocommit_mode”
:return: True if the key was completely handled, False if not.
'''
if self.database.user_can_define_phrase and self.database.rules:
self.set_autocommit_mode(not self._auto_commit)
return True
return False
def _command_switch_to_next_chinese_mode(self) -> bool:
'''Handle hotkey for the command “switch_to_next_chinese_mode”
:return: True if the key was completely handled, False if not.
'''
if not self.database.is_db_chinese:
return False
self.set_chinese_mode((self._chinese_mode+1) % 5)
if not self.is_empty():
self.update_candidates(True)
self._update_ui()
return True
def _command_commit(self) -> bool:
'''Handle hotkey for the command “commit”
:return: True if the key was completely handled, False if not.
'''
if (self._u_chars
or not self.is_empty()
or self._sg_mode_active):
if self.commit_everything_unless_invalid():
if self._auto_select:
self.commit_string(' ')
if (self._sg_mode
and self._input_mode
and not self._sg_mode_active):
self._sg_mode_active = True
self.update_candidates()
self._update_ui()
return True
return False
def _command_lookup_table_page_down(self) -> bool:
'''Handle hotkey for the command “lookup_table_page_down”
:return: True if the key was completely handled, False if not.
'''
if not self._candidates:
return False
res = self.page_down()
self._update_ui()
return res
def _command_lookup_table_page_up(self) -> bool:
'''Handle hotkey for the command “lookup_table_page_up”
:return: True if the key was completely handled, False if not.
'''
if not self._candidates:
return False
res = self.page_up()
self._update_ui()
return res
def _execute_commit_candidate_to_preedit_number(self, number: int) -> bool:
'''Execute the hotkey command “commit_candidate_to_preedit_<number>”
:return: True if the key was completely handled, False if not.
:param number: The number of the candidate
'''
if self.client_capabilities & it_util.Capabilite.OSK:
LOGGER.info(
'OSK is visible: '
'do not commit candidate to preedit by number %s', number)
return False
if not self._candidates:
return False
index = number - 1
res = self.commit_to_preedit_current_page(index)
self._update_ui()
return res
def _command_commit_candidate_to_preedit_1(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_1”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(1)
def _command_commit_candidate_to_preedit_2(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_2”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(2)
def _command_commit_candidate_to_preedit_3(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_3”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(3)
def _command_commit_candidate_to_preedit_4(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_4”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(4)
def _command_commit_candidate_to_preedit_5(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_5”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(5)
def _command_commit_candidate_to_preedit_6(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_6”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(6)
def _command_commit_candidate_to_preedit_7(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_7”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(7)
def _command_commit_candidate_to_preedit_8(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_8”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(8)
def _command_commit_candidate_to_preedit_9(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_9”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(9)
def _command_commit_candidate_to_preedit_10(self) -> bool:
'''Handle hotkey for the command “commit_candidate_to_preedit_10”
:return: True if the key was completely handled, False if not.
'''
return self._execute_commit_candidate_to_preedit_number(10)
def _execute_remove_candidate_number(self, number: int) -> bool:
'''Execute the hotkey command “remove_candidate_<number>”
:return: True if the key was completely handled, False if not.
:param number: The number of the candidate
'''
if self.client_capabilities & it_util.Capabilite.OSK:
LOGGER.info(
'OSK is visible: do not remove candidate by number %s', number)
return False
if not self._candidates:
return False
index = number - 1
res = self.remove_candidate_from_user_database(index)
self._update_ui()
return res
def _command_remove_candidate_1(self) -> bool:
'''Handle hotkey for the command “remove_candidate_1”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(1)
def _command_remove_candidate_2(self) -> bool:
'''Handle hotkey for the command “remove_candidate_2”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(2)
def _command_remove_candidate_3(self) -> bool:
'''Handle hotkey for the command “remove_candidate_3”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(3)
def _command_remove_candidate_4(self) -> bool:
'''Handle hotkey for the command “remove_candidate_4”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(4)
def _command_remove_candidate_5(self) -> bool:
'''Handle hotkey for the command “remove_candidate_5”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(5)
def _command_remove_candidate_6(self) -> bool:
'''Handle hotkey for the command “remove_candidate_6”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(6)
def _command_remove_candidate_7(self) -> bool:
'''Handle hotkey for the command “remove_candidate_7”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(7)
def _command_remove_candidate_8(self) -> bool:
'''Handle hotkey for the command “remove_candidate_8”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(8)
def _command_remove_candidate_9(self) -> bool:
'''Handle hotkey for the command “remove_candidate_9”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(9)
def _command_remove_candidate_10(self) -> bool:
'''Handle hotkey for the command “remove_candidate_10”
:return: True if the key was completely handled, False if not.
'''
return self._execute_remove_candidate_number(10)
def _execute_command_commit_candidate_number(self, number: int) -> bool:
'''Execute the hotkey command “commit_candidate_<number>”
:return: True if the key was completely handled, False if not.
:param number: The number of the candidate
'''
if self.client_capabilities & it_util.Capabilite.OSK:
LOGGER.info(
'OSK is visible: do not commit candidate by number %s', number)
return False
if not self._candidates or number > len(self._candidates):
return False
index = number - 1
if not 0 <= index < self._page_size:
return False
if self.commit_to_preedit_current_page(index):
self.commit_string(
self.get_preedit_string_complete(),
tabkeys=self.get_preedit_tabkeys_complete())
if (self._sg_mode
and self._input_mode
and not self._sg_mode_active):
self._sg_mode_active = True
self.update_candidates()
self._update_ui()
return True
return False
def _command_commit_candidate_1(self) -> bool:
'''Handle hotkey for the command “commit_candidate_1”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(1)
def _command_commit_candidate_2(self) -> bool:
'''Handle hotkey for the command “commit_candidate_2”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(2)
def _command_commit_candidate_3(self) -> bool:
'''Handle hotkey for the command “commit_candidate_3”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(3)
def _command_commit_candidate_4(self) -> bool:
'''Handle hotkey for the command “commit_candidate_4”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(4)
def _command_commit_candidate_5(self) -> bool:
'''Handle hotkey for the command “commit_candidate_5”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(5)
def _command_commit_candidate_6(self) -> bool:
'''Handle hotkey for the command “commit_candidate_6”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(6)
def _command_commit_candidate_7(self) -> bool:
'''Handle hotkey for the command “commit_candidate_7”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(7)
def _command_commit_candidate_8(self) -> bool:
'''Handle hotkey for the command “commit_candidate_8”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(8)
def _command_commit_candidate_9(self) -> bool:
'''Handle hotkey for the command “commit_candidate_9”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(9)
def _command_commit_candidate_10(self) -> bool:
'''Handle hotkey for the command “commit_candidate_10”
:return: True if the key was completely handled, False if not.
'''
return self._execute_command_commit_candidate_number(10)
def _handle_hotkeys(
self,
key: it_util.KeyEvent,
commands: Iterable[str] = ()) -> Tuple[bool, bool]:
'''Handle hotkey commands
:return: True if the key was completely handled, False if not.
:param key: The typed key. If this is a hotkey,
execute the command for this hotkey.
:param commands: A list of commands to check whether
the key matches the keybinding for one of
these commands.
If the list of commands is empty, check
*all* commands in the self._keybindings
dictionary.
'''
if self._debug_level > 1:
LOGGER.debug('KeyEvent object: %s\n', key)
if self._debug_level > 5:
LOGGER.debug('self._hotkeys=%s\n', str(self._hotkeys))
if not commands:
# If no specific command list to match is given, try to
# match against all commands. Sorting shouldn’t really
# matter, but maybe better do it sorted, then it is done
# in the same order as the commands are displayed by
# default in the setup tool.
commands = sorted(self._keybindings.keys())
for command in commands:
if (self._prev_key, key, command) in self._hotkeys: # type: ignore
if self._debug_level > 1:
LOGGER.debug('matched command=%s', command)
command_function_name = f'_command_{command}'
try:
command_function = getattr(self, command_function_name)
except (AttributeError,):
LOGGER.exception('There is no function %s',
command_function_name)
return (False, False)
if command_function():
if key.name in ('Shift_L', 'Shift_R',
'Control_L', 'Control_R',
'Alt_L', 'Alt_R',
'Meta_L', 'Meta_R',
'Super_L', 'Super_R',
'ISO_Level3_Shift'):
return(True, False)
return (True, True)
return (False, False)
def _return_false(self, keyval: int, keycode: int, state: int) -> bool:
'''A replacement for “return False” in do_process_key_event()
do_process_key_event should return “True” if a key event has
been handled completely. It should return “False” if the key
event should be passed to the application.
But just doing “return False” doesn’t work well when trying to
do the unit tests. The MockEngine class in the unit tests
cannot get that return value. Therefore, it cannot do the
necessary updates to the self._mock_committed_text etc. which
prevents proper testing of the effects of such keys passed to
the application. Instead of “return False”, one can also use
self.forward_key_event(keyval, keycode, keystate) to pass the
key to the application. And this works fine with the unit
tests because a forward_key_event function is implemented in
MockEngine as well which then gets the key and can test its
effects.
Unfortunately, “forward_key_event()” does not work in Qt5
applications because the ibus module in Qt5 does not implement
“forward_key_event()”. Therefore, always using
“forward_key_event()” instead of “return False” in
“do_process_key_event()” would break ibus-typing-table
completely for all Qt5 applictions.
To work around this problem and make unit testing possible
without breaking Qt5 applications, we use this helper function
which uses “forward_key_event()” when unit testing and “return
False” during normal usage.
'''
if self._unit_test:
self.forward_key_event(keyval, keycode, state)
return True
return False
def __do_process_key_event(
self,
_obj: IBus.EngineSimple,
keyval: int, keycode: int, state: int) -> bool:
'''This function is connected to the 'process-key-event' signal.'''
return self._do_process_key_event(keyval, keycode, state)
def _do_process_key_event(
self, keyval: int, keycode: int, state: int) -> bool:
'''Process Key Events
Key Events include Key Press and Key Release,
modifier means Key Pressed
'''
key = it_util.KeyEvent(keyval, keycode, state)
if self._debug_level > 1:
LOGGER.debug('KeyEvent object: %s', key)
if (self._input_purpose
in [it_util.InputPurpose.PASSWORD.value,
it_util.InputPurpose.PIN.value]):
if self._debug_level > 0:
LOGGER.debug(
'Disable because of input purpose PASSWORD or PIN')
return self._return_false(keyval, keycode, state)
result = self._process_key_event(key)
self._prev_key = key
return result
def _process_key_event(self, key: it_util.KeyEvent) -> bool:
'''
Internal method to process key event
Returns True if the key event has been completely handled by
ibus-table and should not be passed through anymore.
Returns False if the key event has not been handled completely
and is passed through.
'''
(match, return_value) = self._handle_hotkeys(
key, commands=['toggle_input_mode_on_off',
'toggle_letter_width',
'toggle_punctuation_width',
'setup'])
if match:
return return_value
if self._input_mode:
(match, return_value) = self._handle_hotkeys(key)
if match:
return return_value
return self._table_mode_process_key_event(key)
return self._english_mode_process_key_event(key)
def cond_letter_translate(self, char: str) -> str:
'''Converts “char” to full width *if* full width letter mode is on for
the current input mode (direct input or table mode) *and* if
the current table is for CJK.
:param char: The character to maybe convert to full width
'''
if self._full_width_letter[self._input_mode] and self.database.is_db_cjk:
return self._convert_to_full_width(char)
return char
def cond_punct_translate(self, char: str) -> str:
'''Converts “char” to full width *if* full width punctuation mode is
on for the current input mode (direct input or table mode)
*and* if the current table is for CJK.
:param char: The character to maybe convert to full width
'''
if self._full_width_punct[self._input_mode] and self.database.is_db_cjk:
return self._convert_to_full_width(char)
return char
def _english_mode_process_key_event(self, key: it_util.KeyEvent) -> bool:
'''
Process a key event in “English” (“Direct input”) mode.
'''
# Ignore key release events
if key.state & IBus.ModifierType.RELEASE_MASK:
return self._return_false(key.val, key.code, key.state)
if key.val >= 128:
return self._return_false(key.val, key.code, key.state)
# we ignore all hotkeys here
if (key.state
& (IBus.ModifierType.CONTROL_MASK
|IBus.ModifierType.MOD1_MASK)):
return self._return_false(key.val, key.code, key.state)
keychar = IBus.keyval_to_unicode(key.val)
if ascii_ispunct(keychar):
trans_char = self.cond_punct_translate(keychar)
else:
trans_char = self.cond_letter_translate(keychar)
if trans_char == keychar:
return self._return_false(key.val, key.code, key.state)
self.commit_string(trans_char)
return True
def _table_mode_process_key_event(self, key: it_util.KeyEvent) -> bool:
'''
Process a key event in “Table” mode, i.e. when the
table is actually used and not switched off by using
direct input.
'''
if self._debug_level > 0:
LOGGER.debug('KeyEvent object: %s', key)
# Ignore key release events (Should be below all hotkey matches
# because some of them might match on a release event)
if key.state & IBus.ModifierType.RELEASE_MASK:
return self._return_false(key.val, key.code, key.state)
keychar = IBus.keyval_to_unicode(key.val)
# Section to handle leading invalid input:
#
# This is the first character typed, if it is invalid
# input, handle it immediately here, if it is valid, continue.
if (self.is_empty()
and not self.get_preedit_string_complete()):
if ((keychar not in (
self._valid_input_chars
+ self._single_wildcard_char
+ self._multi_wildcard_char)
or (self.database.startchars
and keychar not in self.database.startchars))
and (not key.state &
(IBus.ModifierType.MOD1_MASK |
IBus.ModifierType.CONTROL_MASK))):
if self._debug_level > 0:
LOGGER.debug(
'leading invalid input: '
'keychar=%s',
keychar)
if ascii_ispunct(keychar):
trans_char = self.cond_punct_translate(keychar)
else:
trans_char = self.cond_letter_translate(keychar)
if trans_char == keychar:
self._prev_char = trans_char
return self._return_false(key.val, key.code, key.state)
self.commit_string(trans_char)
return True
if key.val in (IBus.KEY_Return, IBus.KEY_KP_Enter):
if (self.is_empty()
and not self.get_preedit_string_complete()):
# When IBus.KEY_Return is typed,
# IBus.keyval_to_unicode(key.val) returns a non-empty
# string. But when IBus.KEY_KP_Enter is typed it
# returns an empty string. Therefore, when typing
# IBus.KEY_KP_Enter as leading input, the key is not
# handled by the section to handle leading invalid
# input but it ends up here. If it is leading input
# (i.e. the preëdit is empty) we should always pass
# IBus.KEY_KP_Enter to the application:
return self._return_false(key.val, key.code, key.state)
if self._auto_select:
self.commit_to_preedit()
commit_string = self.get_preedit_string_complete()
self.commit_string(commit_string)
return self._return_false(key.val, key.code, key.state)
commit_string = self.get_preedit_tabkeys_complete()
self.commit_string(commit_string)
return True
if key.val in (IBus.KEY_Tab, IBus.KEY_KP_Tab) and self._auto_select:
# Used for example for the Russian transliteration method
# “translit”, which uses “auto select”. If for example
# a file with the name “шшш” exists and one types in
# a bash shell:
#
# “ls sh”
#
# the “sh” is converted to “ш” and one sees
#
# “ls ш”
#
# in the shell where the “ш” is still in preëdit
# because “shh” would be converted to “щ”, i.e. there
# is more than one candidate and the input method is still
# waiting whether one more “h” will be typed or not. But
# if the next character typed is a Tab, the preëdit is
# committed here and “False” is returned to pass the Tab
# character through to the bash to complete the file name
# to “шшш”.
self.commit_to_preedit()
self.commit_string(self.get_preedit_string_complete())
return self._return_false(key.val, key.code, key.state)
if key.val in (IBus.KEY_Down, IBus.KEY_KP_Down):
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
res = self.cursor_down()
self._update_ui()
return res
if key.val in (IBus.KEY_Up, IBus.KEY_KP_Up):
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
res = self.cursor_up()
self._update_ui()
return res
if (key.val in (IBus.KEY_Left, IBus.KEY_KP_Left)
and key.state & IBus.ModifierType.CONTROL_MASK):
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
self.control_arrow_left()
self._update_ui()
return True
if (key.val in (IBus.KEY_Right, IBus.KEY_KP_Right)
and key.state & IBus.ModifierType.CONTROL_MASK):
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
self.control_arrow_right()
self._update_ui()
return True
if key.val in (IBus.KEY_Left, IBus.KEY_KP_Left):
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
self.arrow_left()
self._update_ui()
return True
if key.val in (IBus.KEY_Right, IBus.KEY_KP_Right):
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
self.arrow_right()
self._update_ui()
return True
if (key.val == IBus.KEY_BackSpace
and key.state & IBus.ModifierType.CONTROL_MASK):
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
self.remove_preedit_before_cursor()
self._update_ui()
return True
if key.val == IBus.KEY_BackSpace:
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
self.remove_char()
self._update_ui()
return True
if (key.val == IBus.KEY_Delete
and key.state & IBus.ModifierType.CONTROL_MASK):
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
self.remove_preedit_after_cursor()
self._update_ui()
return True
if key.val == IBus.KEY_Delete:
if not self.get_preedit_string_complete():
return self._return_false(key.val, key.code, key.state)
self.delete()
self._update_ui()
return True
# now we ignore all other hotkeys
if (key.state
& (IBus.ModifierType.CONTROL_MASK
|IBus.ModifierType.MOD1_MASK)):
return self._return_false(key.val, key.code, key.state)
if key.state & IBus.ModifierType.MOD1_MASK:
return self._return_false(key.val, key.code, key.state)
# Section to handle valid input characters:
if (keychar
and (keychar in (self._valid_input_chars
+ self._single_wildcard_char
+ self._multi_wildcard_char)
or (self._input_mode and self._py_mode
and keychar in self._pinyin_valid_input_chars))):
if self._debug_level > 0:
LOGGER.debug(
'valid input: keychar=%s', keychar)
# Deactivate suggestion mode:
if self._input_mode and self._sg_mode_active:
self.clear_all_input_and_preedit()
self._sg_mode_active = False
if self._input_mode and self._py_mode:
if ((len(self._chars_valid)
== self._max_key_length_pinyin)
or (len(self._chars_valid) > 1
and self._chars_valid[-1] in '!@#$%')):
if self._auto_commit:
self.commit_everything_unless_invalid()
else:
self.commit_to_preedit()
elif self._input_mode and not self._py_mode:
if ((len(self._chars_valid)
== self._max_key_length)
or (len(self._chars_valid)
in self.database.possible_tabkeys_lengths)):
if self._auto_commit:
self.commit_everything_unless_invalid()
else:
self.commit_to_preedit()
else:
assert False
res = self.add_input(keychar)
if not res:
if self._auto_select and self._candidates_previous:
# Used for example for the Russian transliteration method
# “translit”, which uses “auto select”.
# The “translit” table contains:
#
# sh ш
# shh щ
#
# so typing “sh” matches “ш” and “щ”. The
# candidate with the shortest key sequence comes
# first in the lookup table, therefore “sh ш”
# is shown in the preëdit (The other candidate,
# “shh щ” comes second in the lookup table and
# could be selected using arrow-down. But
# “translit” hides the lookup table by default).
#
# Now, when after typing “sh” one types “s”,
# the key “shs” has no match, so add_input('s')
# returns “False” and we end up here. We pop the
# last character “s” which caused the match to
# fail, commit first of the previous candidates,
# i.e. “sh ш” and feed the “s” into the
# key event handler again.
self.pop_input()
self.commit_everything_unless_invalid()
return self._table_mode_process_key_event(key)
self.commit_everything_unless_invalid()
self._update_ui()
return True
if (self._auto_commit and self.one_candidate()
and
(self._chars_valid
== self._candidates[0][0])):
self.commit_everything_unless_invalid()
self._update_ui()
return True
# Section to handle trailing invalid input:
#
# If the key has still not been handled when this point is
# reached, it cannot be a valid input character. Neither can
# it be a select key nor a page-up/page-down key. Adding this
# key to the tabkeys and search for matching candidates in the
# table would thus be pointless.
#
# So we commit all pending input immediately and then commit
# this invalid input character as well, possibly converted to
# fullwidth or halfwidth.
if keychar:
if self._debug_level > 0:
LOGGER.debug(
'trailing invalid input: keychar=%s', keychar)
if not self._candidates or self._commit_invalid_mode == 1:
self.commit_string(self.get_preedit_tabkeys_complete())
else:
self.commit_to_preedit()
self.commit_string(self.get_preedit_string_complete())
if ascii_ispunct(keychar):
self.commit_string(self.cond_punct_translate(keychar))
else:
self.commit_string(self.cond_letter_translate(keychar))
return True
# What kind of key was this??
#
# keychar = IBus.keyval_to_unicode(key.val)
#
# returned no result. So whatever this was, we cannot handle it,
# just pass it through to the application by returning “False”.
return self._return_false(key.val, key.code, key.state)
def do_focus_in(self) -> None: # pylint: disable=arguments-differ
'''
Called for ibus < 1.5.27 when a window gets focus while
this input engine is enabled
'''
if self._debug_level > 1:
LOGGER.debug('entering do_focus_in()\n')
self.do_focus_in_id('', '')
def do_focus_in_id( # pylint: disable=arguments-differ
self, object_path: str, client: str) -> None:
'''Called for ibus >= 1.5.27 when a window gets focus while
this input engine is enabled
:param object_path: Example:
'/org/freedesktop/IBus/InputContext_23'
:param client: Possible values and examples where these values occur:
'': unknown
'fake': focus where input is impossible
(e.g. desktop background)
'xim': XIM
(Gtk3 programs in a Gnome Xorg session
when GTK_IM_MODULE is unset also use xim)
'gtk-im:<program-name>': Gtk2 input module
'gtk3-im:<program-name>': Gtk3 input module
'gtk4-im:<program-name>': Gtk4 input module
'gnome-shell': Entries handled by gnome-shell
(like the command line dialog
opened with Alt+F2 or the search
field when pressing the Super
key.) When GTK_IM_MODULE is
unset in a Gnome Wayland session
all programs which would show
'gtk3-im' or 'gtk4-im' with
GTK_IM_MODULE=ibus then show
'gnome-shell' instead.
'Qt': Qt4 input module
'QIBusInputContext': Qt5 input module
In case of the Gtk input modules, the name of the
client is also shown after the “:”, for example
like 'gtk3-im:firefox', 'gtk4-im:gnome-text-editor', …
'''
if self._debug_level > 1:
LOGGER.debug('object_path=%s client=%s\n', object_path, client)
self._im_client = client
if ':' not in self._im_client:
(program_name,
_window_title) = it_active_window.get_active_window()
if program_name:
self._im_client += ':' + program_name
if self._debug_level > 1:
LOGGER.debug('self._im_client=%s\n', self._im_client)
self.register_properties(self.main_prop_list)
self._update_ui()
def do_focus_out(self) -> None: # pylint: disable=arguments-differ
'''
Called for ibus < 1.5.27 when a window loses focus while
this input engine is enabled
'''
if self._debug_level > 1:
LOGGER.debug('entering do_focus_out()\n')
self.do_focus_out_id('')
def do_focus_out_id( # pylint: disable=arguments-differ
self, object_path: str) -> None:
'''
Called for ibus >= 1.5.27 when a window loses focus while
this input engine is enabled
'''
if self._debug_level > 1:
LOGGER.debug('object_path=%s\n', object_path)
self._im_client = ''
# Do not do self._input_purpose = 0 here, see
# https://gitlab.gnome.org/GNOME/gnome-shell/-/issues/5966#note_1576732
# if the input purpose is set correctly on focus in, then it
# should not be necessary to reset it here.
self.clear_all_input_and_preedit()
self._update_ui()
def do_reset(self, *_args: Any, **_kwargs: Any) -> None:
'''Called when the mouse pointer is used to move to cursor to a
different position in the current window.
Also called when certain keys are pressed:
Return, KP_Enter, ISO_Enter, Up, Down, (and others?)
Even some key sequences like space + Left and space + Right
seem to call this.
'''
if self._debug_level > 1:
LOGGER.debug('do_reset()\n')
self.reset()
def do_set_content_type( # pylint: disable=arguments-differ
self, purpose: int, hints: int) -> None:
'''Called when the input purpose or hints change'''
LOGGER.debug('purpose=%s hints=%s\n', purpose, format(hints, '016b'))
self._input_purpose = purpose
self._input_hints = hints
if self._debug_level > 1:
if (self._input_purpose
in [int(x) for x in list(it_util.InputPurpose)]):
for input_purpose in list(it_util.InputPurpose):
if self._input_purpose == input_purpose:
LOGGER.debug(
'self._input_purpose = %s (%s)',
self._input_purpose, str(input_purpose))
else:
LOGGER.debug(
'self._input_purpose = %s (Unknown)',
self._input_purpose)
for hint in it_util.InputHints:
if self._input_hints & hint:
LOGGER.debug(
'hint: %s %s',
str(hint), format(int(hint), '016b'))
def do_enable(self, *_args: Any, **_kwargs: Any) -> None:
'''Called when this input engine is enabled'''
if self._debug_level > 1:
LOGGER.debug('do_enable()\n')
# Tell the input-context that the engine will utilize
# surrounding-text:
self.get_surrounding_text()
self.do_focus_in()
def do_disable(self, *_args: Any, **_kwargs: Any) -> None:
'''Called when this input engine is disabled'''
if self._debug_level > 1:
LOGGER.debug('do_disable()\n')
self.clear_all_input_and_preedit()
self._update_ui()
def do_page_up(self, *_args: Any, **_kwargs: Any) -> bool:
'''Called when the page up button in the lookup table is clicked with
the mouse
'''
if self.page_up():
self._update_ui()
return True
return False
def do_page_down(self, *_args: Any, **_kwargs: Any) -> bool:
'''Called when the page down button in the lookup table is clicked with
the mouse
'''
if self.page_down():
self._update_ui()
return True
return False
def do_cursor_up(self, *_args: Any, **_kwargs: Any) -> bool:
'''Called when the mouse wheel is rolled up in the candidate area of
the lookup table
'''
res = self.cursor_up()
self._update_ui()
return res
def do_cursor_down(self, *_args: Any, **_kwargs: Any) -> bool:
'''Called when the mouse wheel is rolled down in the candidate area of
the lookup table
'''
res = self.cursor_down()
self._update_ui()
return res
def on_gsettings_value_changed(
self, _settings: Gio.Settings, key: str) -> None:
'''
Called when a value in the settings has been changed.
'''
value = it_util.variant_to_value(self._gsettings.get_value(key))
LOGGER.debug('Settings changed for engine “%s”: key=%s value=%s',
self._engine_name, key, value)
set_functions = {
'debuglevel':
{'set_function': self.set_debug_level, 'kwargs': {}},
'dynamicadjust':
{'set_function': self.set_dynamic_adjust, 'kwargs': {}},
'errorsound':
{'set_function': self.set_error_sound, 'kwargs': {}},
'errorsoundfile':
{'set_function': self.set_error_sound_file, 'kwargs': {}},
'soundbackend':
{'set_function': self.set_sound_backend, 'kwargs': {}},
'keybindings':
{'set_function': self.set_keybindings, 'kwargs': {}},
'autoselect':
{'set_function': self.set_autoselect_mode, 'kwargs': {}},
'autocommit':
{'set_function': self.set_autocommit_mode, 'kwargs': {}},
'commitinvalidmode':
{'set_function': self.set_commit_invalid_mode, 'kwargs': {}},
'chinesemode':
{'set_function': self.set_chinese_mode, 'kwargs': {}},
'lookuptableorientation':
{'set_function': self.set_lookup_table_orientation, 'kwargs': {}},
'lookuptablepagesize':
{'set_function': self.set_page_size, 'kwargs': {}},
'onechar':
{'set_function': self.set_onechar_mode, 'kwargs': {}},
'alwaysshowlookup':
{'set_function': self.set_always_show_lookup, 'kwargs': {}},
'singlewildcardchar':
{'set_function': self.set_single_wildcard_char, 'kwargs': {}},
'multiwildcardchar':
{'set_function': self.set_multi_wildcard_char, 'kwargs': {}},
'autowildcard':
{'set_function': self.set_autowildcard_mode, 'kwargs': {}},
'endeffullwidthletter':
{'set_function': self.set_letter_width,
'kwargs': {'input_mode': 0}},
'endeffullwidthpunct':
{'set_function': self.set_punctuation_width,
'kwargs': {'input_mode': 0}},
'tabdeffullwidthletter':
{'set_function': self.set_letter_width,
'kwargs': {'input_mode': 1}},
'tabdeffullwidthpunct':
{'set_function': self.set_punctuation_width,
'kwargs': {'input_mode': 1}},
'inputmode':
{'set_function': self.set_input_mode, 'kwargs': {}},
'rememberinputmode':
{'set_function': self.set_remember_input_mode, 'kwargs': {}},
'darktheme':
{'set_function': self.set_dark_theme, 'kwargs': {}},
'inputmethodmenu':
{'set_function': self.set_input_method_menu, 'kwargs': {}}
}
if key in set_functions:
set_function = set_functions[key]['set_function']
kwargs = set_functions[key]['kwargs']
if key != 'inputmode':
kwargs.update({'update_gsettings': False}) # type: ignore
set_function(value, **kwargs) # type: ignore
return
LOGGER.debug('Unknown key')
return
if __name__ == "__main__":
LOG_HANDLER = logging.StreamHandler(stream=sys.stderr)
LOGGER.setLevel(logging.DEBUG)
LOGGER.addHandler(LOG_HANDLER)
import doctest
(FAILED, ATTEMPTED) = doctest.testmod()
sys.exit(FAILED)
|