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
|
unit gnugettext;
(**************************************************************)
(* *)
(* (C) Copyright by Lars B. Dybdahl and others *)
(* E-mail: Lars@dybdahl.dk, phone +45 70201241 *)
(* *)
(* Contributors: Peter Thornqvist, Troy Wolbrink, *)
(* Frank Andreas de Groot, Igor Siticov, *)
(* Jacques Garcia Vazquez *)
(* *)
(* See http://dybdahl.dk/dxgettext/ for more information *)
(* *)
(**************************************************************)
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// The names of any contributor may not be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
interface
// If the conditional define DXGETTEXTDEBUG is defined, debugging log is activated.
// Use DefaultInstance.DebugLogToFile() to write the log to a file.
{ $define DXGETTEXTDEBUG}
{$ifdef VER100}
// Delphi 3
{$DEFINE DELPHI5OROLDER}
{$DEFINE DELPHI6OROLDER}
{$DEFINE DELPHI7OROLDER}
{$endif}
{$ifdef VER110}
// C++ Builder 3
{$DEFINE DELPHI5OROLDER}
{$DEFINE DELPHI6OROLDER}
{$DEFINE DELPHI7OROLDER}
{$endif}
{$ifdef VER120}
// Delphi 4
{$DEFINE DELPHI5OROLDER}
{$DEFINE DELPHI6OROLDER}
{$DEFINE DELPHI7OROLDER}
{$endif}
{$ifdef VER125}
// C++ Builder 4
{$DEFINE DELPHI5OROLDER}
{$DEFINE DELPHI6OROLDER}
{$DEFINE DELPHI7OROLDER}
{$endif}
{$ifdef VER130}
// Delphi 5
{$DEFINE DELPHI5OROLDER}
{$DEFINE DELPHI6OROLDER}
{$DEFINE DELPHI7OROLDER}
{$ifdef WIN32}
{$DEFINE MSWINDOWS}
{$endif}
{$endif}
{$ifdef VER135}
// C++ Builder 5
{$DEFINE DELPHI5OROLDER}
{$DEFINE DELPHI6OROLDER}
{$DEFINE DELPHI7OROLDER}
{$ifdef WIN32}
{$DEFINE MSWINDOWS}
{$endif}
{$endif}
{$ifdef VER140}
// Delphi 6
{$DEFINE DELPHI6OROLDER}
{$DEFINE DELPHI7OROLDER}
{$endif}
{$ifdef VER150}
{$DEFINE DELPHI7OROLDER}
// Delphi 7
{$endif}
{$ifdef VER160}
// Delphi 8
{$endif}
uses
{$ifdef DELPHI5OROLDER}
gnugettextD5,
{$endif}
{$ifdef MSWINDOWS}
Windows,
{$endif}
{$ifdef LINUX}
Libc,
{$endif}
Classes, SysUtils, TypInfo;
(*****************************************************************************)
(* *)
(* MAIN API *)
(* *)
(*****************************************************************************)
// Main GNU gettext functions. See documentation for instructions on how to use them.
{$ifdef DELPHI5OROLDER}
function _(const szMsgId: widestring): widestring;
function gettext(const szMsgId: widestring): widestring;
function dgettext(const szDomain: ansistring; const szMsgId: widestring): widestring;
function dngettext(const szDomain: ansistring; const singular,plural: widestring; Number:longint): widestring;
function ngettext(const singular,plural: widestring; Number:longint): widestring;
{$endif}
{$ifndef DELPHI5OROLDER}
function _(const szMsgId: ansistring): widestring; overload;
function _(const szMsgId: widestring): widestring; overload;
function gettext(const szMsgId: ansistring): widestring; overload;
function gettext(const szMsgId: widestring): widestring; overload;
function dgettext(const szDomain: ansistring; const szMsgId: ansistring): widestring; overload;
function dgettext(const szDomain: ansistring; const szMsgId: widestring): widestring; overload;
function dngettext(const szDomain: ansistring; const singular,plural: ansistring; Number:longint): widestring; overload;
function dngettext(const szDomain: ansistring; const singular,plural: widestring; Number:longint): widestring; overload;
function ngettext(const singular,plural: ansistring; Number:longint): widestring; overload;
function ngettext(const singular,plural: widestring; Number:longint): widestring; overload;
{$endif}
procedure textdomain(const szDomain: ansistring);
function getcurrenttextdomain: ansistring;
procedure bindtextdomain(const szDomain: ansistring; const szDirectory: ansistring);
// Set language to use
procedure UseLanguage(LanguageCode: ansistring);
function GetCurrentLanguage:ansistring;
// Translates a component (form, frame etc.) to the currently selected language.
// Put TranslateComponent(self) in the OnCreate event of all your forms.
// See the manual for documentation on these functions
type
TTranslator=procedure (obj:TObject) of object;
procedure TP_Ignore(AnObject:TObject; const name:ansistring);
procedure TP_IgnoreClass (IgnClass:TClass);
procedure TP_IgnoreClassProperty (IgnClass:TClass;propertyname:ansistring);
procedure TP_GlobalIgnoreClass (IgnClass:TClass);
procedure TP_GlobalIgnoreClassProperty (IgnClass:TClass;propertyname:ansistring);
procedure TP_GlobalHandleClass (HClass:TClass;Handler:TTranslator);
procedure TranslateComponent(AnObject: TComponent; TextDomain:ansistring='');
procedure RetranslateComponent(AnObject: TComponent; TextDomain:ansistring='');
// Add more domains that resourcestrings can be extracted from. If a translation
// is not found in the default domain, this domain will be searched, too.
// This is useful for adding mo files for certain runtime libraries and 3rd
// party component libraries
procedure AddDomainForResourceString (domain:ansistring);
procedure RemoveDomainForResourceString (domain:ansistring);
{$ifndef CLR}
// Unicode-enabled way to get resourcestrings, automatically translated
// Use like this: ws:=LoadResStringW(@NameOfResourceString);
function LoadResString(ResStringRec: PResStringRec): widestring;
function LoadResStringA(ResStringRec: PResStringRec): ansistring;
function LoadResStringW(ResStringRec: PResStringRec): widestring;
{$endif}
// This returns an empty string if not translated or translator name is not specified.
function GetTranslatorNameAndEmail:widestring;
(*****************************************************************************)
(* *)
(* ADVANCED FUNCTIONALITY *)
(* *)
(*****************************************************************************)
const
DefaultTextDomain = 'default';
var
ExecutableFilename:ansistring; // This is set to paramstr(0) or the name of the DLL you are creating.
type
EGnuGettext=class(Exception);
EGGProgrammingError=class(EGnuGettext);
EGGComponentError=class(EGnuGettext);
EGGIOError=class(EGnuGettext);
EGGAnsi2WideConvError=class(EGnuGettext);
// This function will turn resourcestring hooks on or off, eventually with BPL file support.
// Please do not activate BPL file support when the package is in design mode.
const AutoCreateHooks=true;
procedure HookIntoResourceStrings (enabled:boolean=true; SupportPackages:boolean=false);
(*****************************************************************************)
(* *)
(* CLASS based implementation. *)
(* Use TGnuGettextInstance to have more than one language *)
(* in your application at the same time *)
(* *)
(*****************************************************************************)
{$ifdef MSWINDOWS}
{$ifndef DELPHI6OROLDER}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_CAST OFF}
{$endif}
{$endif}
{$ifndef DELPHI7OROLDER}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$endif}
type
TOnDebugLine = Procedure (Sender: TObject; const Line: ansistring; var Discard: Boolean) of Object; // Set Discard to false if output should still go to ordinary debug log
TGetPluralForm=function (Number:Longint):Integer;
TDebugLogger=procedure (line: ansistring) of object;
TMoFile= // Don't use this class. It's for internal use.
class // Threadsafe. Only constructor and destructor are writing to memory
private
doswap: boolean;
public
Users:Integer; // Reference count. If it reaches zero, this object should be destroyed.
constructor Create (filename:ansistring;Offset,Size:int64);
function gettext(msgid: ansistring;var found:boolean): ansistring; // uses mo file
property isSwappedArchitecture:boolean read doswap;
private
N, O, T: Cardinal; // Values defined at http://www.linuxselfhelp.com/gnu/gettext/html_chapter/gettext_6.html
startindex,startstep:integer;
momemory:array of byte;
function CardinalInMem(Offset: Cardinal): Cardinal;
end;
TDomain= // Don't use this class. It's for internal use.
class
private
Enabled:boolean;
vDirectory: string;
procedure setDirectory(dir: string);
public
DebugLogger:TDebugLogger;
Domain: ansistring;
property Directory: string read vDirectory write setDirectory;
constructor Create;
destructor Destroy; override;
// Set parameters
procedure SetLanguageCode (langcode:ansistring);
procedure SetFilename (filename:ansistring); // Bind this domain to a specific file
// Get information
procedure GetListOfLanguages(list:TStrings);
function GetTranslationProperty(Propertyname: string): WideString;
function gettext(msgid: ansistring): ansistring; // uses mo file
private
mofile:TMoFile;
SpecificFilename:ansistring;
curlang: ansistring;
OpenHasFailedBefore: boolean;
procedure OpenMoFile;
procedure CloseMoFile;
end;
TExecutable=
class
procedure Execute; virtual; abstract;
end;
TGnuGettextInstance=
class
private
fOnDebugLine:TOnDebugLine;
{$ifndef CLR}
CreatorThread:Cardinal; // Only this thread can use LoadResString
{$endif}
public
Enabled:Boolean; // Set this to false to disable translations
DesignTimeCodePage:Integer; // See MultiByteToWideChar() in Win32 API for documentation
constructor Create;
destructor Destroy; override;
procedure UseLanguage(LanguageCode: ansistring);
procedure GetListOfLanguages (domain:ansistring; list:TStrings); // Puts list of language codes, for which there are translations in the specified domain, into list
{$ifdef DELPHI5OROLDER}
function gettext(const szMsgId: widestring): widestring;
function ngettext(const singular,plural:widestring;Number:longint):widestring;
{$endif}
{$ifndef DELPHI5OROLDER}
function gettext(const szMsgId: ansistring): widestring; overload;
function gettext(const szMsgId: widestring): widestring; overload;
function ngettext(const singular,plural:ansistring;Number:longint):widestring; overload;
function ngettext(const singular,plural:widestring;Number:longint):widestring; overload;
{$endif}
function GetCurrentLanguage:ansistring;
function GetTranslationProperty (Propertyname:ansistring):WideString;
function GetTranslatorNameAndEmail:widestring;
// Form translation tools, these are not threadsafe. All TP_ procs must be called just before TranslateProperites()
procedure TP_Ignore(AnObject:TObject; const name:ansistring);
procedure TP_IgnoreClass (IgnClass:TClass);
procedure TP_IgnoreClassProperty (IgnClass:TClass;propertyname:ansistring);
procedure TP_GlobalIgnoreClass (IgnClass:TClass);
procedure TP_GlobalIgnoreClassProperty (IgnClass:TClass;propertyname:ansistring);
procedure TP_GlobalHandleClass (HClass:TClass;Handler:TTranslator);
procedure TranslateProperties(AnObject: TObject; textdomain:ansistring='');
procedure TranslateComponent(AnObject: TComponent; TextDomain:ansistring='');
procedure RetranslateComponent(AnObject: TComponent; TextDomain:ansistring='');
// Multi-domain functions
{$ifdef DELPHI5OROLDER}
function dgettext(const szDomain: ansistring; const szMsgId: widestring): widestring;
function dngettext(const szDomain: ansistring; singular,plural:widestring;Number:longint):widestring;
{$endif}
{$ifndef DELPHI5OROLDER}
function dgettext(const szDomain: ansistring; const szMsgId: ansistring): widestring; overload;
function dgettext(const szDomain: ansistring; const szMsgId: widestring): widestring; overload;
function dngettext(const szDomain: ansistring; singular,plural:ansistring;Number:longint):widestring; overload;
function dngettext(const szDomain: ansistring; singular,plural:widestring;Number:longint):widestring; overload;
{$endif}
procedure textdomain(const szDomain: ansistring);
function getcurrenttextdomain: ansistring;
procedure bindtextdomain(const szDomain: ansistring; const szDirectory: ansistring);
procedure bindtextdomainToFile (const szDomain: ansistring; const filename: ansistring); // Also works with files embedded in exe file
{$ifndef CLR}
// Windows API functions
function LoadResString(ResStringRec: PResStringRec): widestring;
{$endif}
// Output all log info to this file. This may only be called once.
procedure DebugLogToFile (filename:ansistring; append:boolean=false);
procedure DebugLogPause (PauseEnabled:boolean);
property OnDebugLine: TOnDebugLine read fOnDebugLine write fOnDebugLine; // If set, all debug output goes here
// Conversion according to design-time character set
function ansi2wide (s:ansistring):widestring;
protected
procedure TranslateStrings (sl:TStrings;TextDomain:ansistring);
// Override these three, if you want to inherited from this class
// to create a new class that handles other domain and language dependent
// issues
procedure WhenNewLanguage (LanguageID:ansistring); virtual; // Override to know when language changes
procedure WhenNewDomain (TextDomain:ansistring); virtual; // Override to know when text domain changes. Directory is purely informational
procedure WhenNewDomainDirectory (TextDomain:ansistring;Directory:string); virtual; // Override to know when any text domain's directory changes. It won't be called if a domain is fixed to a specific file.
private
curlang: ansistring;
curGetPluralForm:TGetPluralForm;
curmsgdomain: ansistring;
savefileCS: TMultiReadExclusiveWriteSynchronizer;
savefile: TextFile;
savememory: TStringList;
DefaultDomainDirectory:ansistring;
domainlist: TStringList; // List of domain names. Objects are TDomain.
TP_IgnoreList:TStringList; // Temporary list, reset each time TranslateProperties is called
TP_ClassHandling:TList; // Items are TClassMode. If a is derived from b, a comes first
TP_GlobalClassHandling:TList; // Items are TClassMode. If a is derived from b, a comes first
TP_Retranslator:TExecutable; // Cast this to TTP_Retranslator
DebugLogCS:TMultiReadExclusiveWriteSynchronizer;
DebugLog:TStream;
DebugLogOutputPaused:Boolean;
function TP_CreateRetranslator:TExecutable; // Must be freed by caller!
procedure FreeTP_ClassHandlingItems;
procedure DebugWriteln(line: ansistring);
function Getdomain(domain, DefaultDomainDirectory, CurLang: ansistring): TDomain; // Translates a single property of an object
{$ifndef CLR}
procedure TranslateProperty(AnObject: TObject; PropInfo: PPropInfo;
TodoList: TStrings; TextDomain:ansistring);
{$endif}
end;
var
DefaultInstance:TGnuGettextInstance;
implementation
(**************************************************************************)
// Some comments on the implementation:
// This unit should be independent of other units where possible.
// It should have a small footprint in any way.
(**************************************************************************)
// TMultiReadExclusiveWriteSynchronizer is used instead of TCriticalSection
// because it makes this unit independent of the SyncObjs unit
(**************************************************************************)
{$ifdef DELPHI5OROLDER}
uses
FileCtrl, System.Globalization;
{$endif}
{$ifdef CLR}
uses
System.Globalization;
{$endif}
type
TTP_RetranslatorItem=
class
obj:TObject;
Propname:ansistring;
OldValue:WideString;
end;
TTP_Retranslator=
class (TExecutable)
TextDomain:ansistring;
Instance:TGnuGettextInstance;
constructor Create;
destructor Destroy; override;
procedure Remember (obj:TObject; PropName:ansistring; OldValue:WideString);
procedure Execute; override;
private
list:TList;
end;
TEmbeddedFileInfo=
class
offset,size:int64;
end;
TFileLocator=
class // This class finds files even when embedded inside executable
constructor Create;
destructor Destroy; override;
procedure Analyze; // List files embedded inside executable
function FileExists (filename:string):boolean;
function GetMoFile (filename:string;DebugLogger:TDebugLogger):TMoFile;
procedure ReleaseMoFile (mofile:TMoFile);
private
basedirectory:ansistring;
filelist:TStringList; //Objects are TEmbeddedFileInfo. Filenames are relative to .exe file
MoFilesCS:TMultiReadExclusiveWriteSynchronizer;
MoFiles:TStringList; // Objects are filenames+offset, objects are TMoFile
function ReadInt64 (str:TStream):int64;
end;
TGnuGettextComponentMarker=
class (TComponent)
public
LastLanguage:ansistring;
Retranslator:TExecutable;
destructor Destroy; override;
end;
TClassMode=
class
HClass:TClass;
SpecialHandler:TTranslator;
PropertiesToIgnore:TStringList; // This is ignored if Handler is set
constructor Create;
destructor Destroy; override;
end;
TRStrinfo = record
strlength, stroffset: cardinal;
end;
TStrInfoArr = array[0..10000000] of TRStrinfo;
PStrInfoArr = ^TStrInfoArr;
TCharArray5=array[0..4] of ansichar;
{$ifndef CLR}
THook= // Replaces a runtime library procedure with a custom procedure
class
public
constructor Create (OldProcedure, NewProcedure: pointer; FollowJump:boolean=false);
destructor Destroy; override; // Restores unhooked state
procedure Reset (FollowJump:boolean=false); // Disables and picks up patch points again
procedure Disable;
procedure Enable;
private
oldproc,newproc:Pointer;
Patch:TCharArray5;
Original:TCharArray5;
PatchPosition:PChar;
procedure Shutdown; // Same as destroy, except that object is not destroyed
end;
{$endif}
var
// System information
Win32PlatformIsUnicode:boolean=False;
// Information about files embedded inside .exe file
FileLocator:TFileLocator;
// Hooks into runtime library functions
ResourceStringDomainListCS:TMultiReadExclusiveWriteSynchronizer;
ResourceStringDomainList:TStringList;
{$ifndef CLR}
HookLoadResString:THook;
HookLoadStr:THook;
HookFmtLoadStr:THook;
{$endif}
function utf8encodechar (wc:widechar):ansistring;
var
w:word;
begin
w:=ord(wc);
case w of
0..$7F:
Result:=ansichar(w);
$80..$3FF:
Result:=ansichar($C0+(w shr 6))+
ansichar($80+(w and $3F));
$400..$FFFF:
Result:=ansichar($E0+(w shr 12))+
ansichar($80+((w shr 6) and $3F))+
ansichar($80+(w and $3F));
else
raise Exception.Create ('Huh, what happened here?');
end;
end;
function utf8encode (ws:widestring):ansistring;
var
i:integer;
begin
Result:='';
for i:=1 to length(ws) do
Result:=Result+utf8encodechar(ws[i]);
end;
// If dummychar is #0, it will raise Exception when an error occurs
function utf8decode (s:ansistring;dummychar:widechar=#0):widestring;
var
i:integer;
b:byte;
c:cardinal;
mode:0..5;
begin
Result:='';
mode:=0;
c:=0;
for i:=1 to length(s) do begin
b:=ord(s[i]);
if mode=0 then begin
case b of
0..$7F:
Result:=Result+widechar(b);
$80..$BF,$FF:
begin
if dummychar=#0 then
raise Exception.Create ('Invalid byte sequence encountered in utf-8 string')
else
Result:=Result+dummychar;
mode:=0;
end;
$C0..$DF:
begin
c:=(b and $1F);
mode:=1;
end;
$E0..$EF:
begin
c:=(b and $F);
mode:=2;
end;
$F0..$F7:
begin
c:=(b and $7);
mode:=3;
end;
$F8..$FB:
begin
c:=(b and $3);
mode:=4;
end;
$FC..$FE:
begin
c:=(b and $1);
mode:=5;
end;
else
raise Exception.Create ('Huh? More than 256 different values in a byte?');
end;
end else begin
case b of
$00..$7F,$C0..$FF:
if dummychar=#0 then
raise Exception.Create ('Invalid byte sequence encountered in utf-8 string')
else
Result:=Result+dummychar;
$80..$BF:
begin
c:=c*$40+(b and $3F);
dec (mode);
if mode=0 then begin
if c<=$FFFF then
Result:=Result+chr(c)
else begin
if dummychar=#0 then
raise Exception.Create ('Utf-8 string contained unicode character larger than $FFFF. This is not supported.')
else
Result:=Result+dummychar;
end;
end;
end;
else
raise Exception.Create ('Huh? More than 256 different values in a byte?');
end;
end;
end;
if mode<>0 then begin
if dummychar=#0 then
raise Exception.Create ('Utf-8 string terminated unexpectedly in the middle of a multibyte sequence')
else
Result:=Result+dummychar;
end;
end;
function StripCR (s:ansistring):ansistring;
var
i:integer;
begin
i:=1;
while i<=length(s) do begin
if s[i]=#13 then delete (s,i,1) else inc (i);
end;
Result:=s;
end;
function GGGetEnvironmentVariable (name:ansistring):ansistring;
{$ifdef DELPHI5OROLDER}
var
len:DWORD;
{$endif}
begin
{$ifdef DELPHI5OROLDER}
SetLength (Result, 1000);
len:=Windows.GetEnvironmentVariable (PChar(name),PChar(Result),900);
SetLength (Result,len);
if len>900 then
if Windows.GetEnvironmentVariable (PChar(name),PChar(Result),len)<>len then
Result:='ERROR: Windows environment changes concurrently with this application';
{$endif}
{$ifndef DELPHI5OROLDER}
Result:=SysUtils.GetEnvironmentVariable(name);
{$endif}
end;
function LF2LineBreakA (s:ansistring):ansistring;
{$ifdef MSWINDOWS}
var
i:integer;
{$endif}
begin
{$ifdef MSWINDOWS}
Assert (sLinebreak=#13#10);
i:=1;
while i<=length(s) do begin
if (s[i]=#10) and (copy(s,i-1,1)<>#13) then begin
insert (#13,s,i);
inc (i,2);
end else
inc (i);
end;
{$endif}
Result:=s;
end;
function IsWriteProp(Info: PPropInfo): Boolean;
begin
{$ifndef CLR}
Result := Assigned(Info) and (Info^.SetProc <> nil);
{$else}
Result:=false;
{$endif}
end;
function string2csyntax(s: ansistring): ansistring;
// Converts a ansistring to the syntax that is used in .po files
var
i: integer;
c: ansichar;
begin
Result := '';
for i := 1 to length(s) do begin
c := s[i];
case c of
#32..#33, #35..#255: Result := Result + c;
#13: Result := Result + '\r';
#10: Result := Result + '\n"'#13#10'"';
#34: Result := Result + '\"';
else
Result := Result + '\0x' + IntToHex(ord(c), 2);
end;
end;
Result := '"' + Result + '"';
end;
function ResourceStringGettext(MsgId: widestring): widestring;
var
i:integer;
begin
if (msgid='') or (ResourceStringDomainListCS=nil) then begin
// This only happens during very complicated program startups that fail
// or when msgid=''
Result:=MsgId;
exit;
end;
ResourceStringDomainListCS.BeginRead;
try
for i:=0 to ResourceStringDomainList.Count-1 do begin
Result:=dgettext(ResourceStringDomainList.Strings[i], MsgId);
if Result<>MsgId then
break;
end;
finally
ResourceStringDomainListCS.EndRead;
end;
end;
{$ifndef DELPHI5OROLDER}
function gettext(const szMsgId: ansistring): widestring;
begin
Result:=DefaultInstance.gettext(szMsgId);
end;
{$endif}
function gettext(const szMsgId: widestring): widestring;
begin
Result:=DefaultInstance.gettext(szMsgId);
end;
{$ifndef DELPHI5OROLDER}
function _(const szMsgId: ansistring): widestring;
begin
Result:=DefaultInstance.gettext(szMsgId);
end;
{$endif}
function _(const szMsgId: widestring): widestring;
begin
Result:=DefaultInstance.gettext(szMsgId);
end;
{$ifndef DELPHI5OROLDER}
function dgettext(const szDomain: ansistring; const szMsgId: ansistring): widestring;
begin
Result:=DefaultInstance.dgettext(szDomain, szMsgId);
end;
{$endif}
function dgettext(const szDomain: ansistring; const szMsgId: widestring): widestring;
begin
Result:=DefaultInstance.dgettext(szDomain, szMsgId);
end;
{$ifndef DELPHI5OROLDER}
function dngettext(const szDomain: ansistring; const singular,plural: ansistring; Number:longint): widestring;
begin
Result:=DefaultInstance.dngettext(szDomain,singular,plural,Number);
end;
{$endif}
function dngettext(const szDomain: ansistring; const singular,plural: widestring; Number:longint): widestring;
begin
Result:=DefaultInstance.dngettext(szDomain,singular,plural,Number);
end;
{$ifndef DELPHI5OROLDER}
function ngettext(const singular,plural: ansistring; Number:longint): widestring;
begin
Result:=DefaultInstance.ngettext(singular,plural,Number);
end;
{$endif}
function ngettext(const singular,plural: widestring; Number:longint): widestring;
begin
Result:=DefaultInstance.ngettext(singular,plural,Number);
end;
procedure textdomain(const szDomain: ansistring);
begin
DefaultInstance.textdomain(szDomain);
end;
procedure SetGettextEnabled (enabled:boolean);
begin
DefaultInstance.Enabled:=enabled;
end;
function getcurrenttextdomain: ansistring;
begin
Result:=DefaultInstance.getcurrenttextdomain;
end;
procedure bindtextdomain(const szDomain: ansistring; const szDirectory: ansistring);
begin
DefaultInstance.bindtextdomain(szDomain, szDirectory);
end;
procedure TP_Ignore(AnObject:TObject; const name:ansistring);
begin
DefaultInstance.TP_Ignore(AnObject, name);
end;
procedure TP_GlobalIgnoreClass (IgnClass:TClass);
begin
DefaultInstance.TP_GlobalIgnoreClass(IgnClass);
end;
procedure TP_IgnoreClass (IgnClass:TClass);
begin
DefaultInstance.TP_IgnoreClass(IgnClass);
end;
procedure TP_IgnoreClassProperty (IgnClass:TClass;propertyname:ansistring);
begin
DefaultInstance.TP_IgnoreClassProperty(IgnClass,propertyname);
end;
procedure TP_GlobalIgnoreClassProperty (IgnClass:TClass;propertyname:ansistring);
begin
DefaultInstance.TP_GlobalIgnoreClassProperty(IgnClass,propertyname);
end;
procedure TP_GlobalHandleClass (HClass:TClass;Handler:TTranslator);
begin
DefaultInstance.TP_GlobalHandleClass (HClass, Handler);
end;
procedure TranslateProperties(AnObject: TObject; TextDomain:ansistring='');
begin
DefaultInstance.TranslateProperties(AnObject, TextDomain);
end;
procedure TranslateComponent(AnObject: TComponent; TextDomain:ansistring='');
begin
DefaultInstance.TranslateComponent(AnObject, TextDomain);
end;
procedure RetranslateComponent(AnObject: TComponent; TextDomain:ansistring='');
begin
DefaultInstance.RetranslateComponent(AnObject, TextDomain);
end;
{$ifdef MSWINDOWS}
// These constants are only used in Windows 95
// Thanks to Frank Andreas de Groot for this table
const
IDAfrikaans = $0436; IDAlbanian = $041C;
IDArabicAlgeria = $1401; IDArabicBahrain = $3C01;
IDArabicEgypt = $0C01; IDArabicIraq = $0801;
IDArabicJordan = $2C01; IDArabicKuwait = $3401;
IDArabicLebanon = $3001; IDArabicLibya = $1001;
IDArabicMorocco = $1801; IDArabicOman = $2001;
IDArabicQatar = $4001; IDArabic = $0401;
IDArabicSyria = $2801; IDArabicTunisia = $1C01;
IDArabicUAE = $3801; IDArabicYemen = $2401;
IDArmenian = $042B; IDAssamese = $044D;
IDAzeriCyrillic = $082C; IDAzeriLatin = $042C;
IDBasque = $042D; IDByelorussian = $0423;
IDBengali = $0445; IDBulgarian = $0402;
IDBurmese = $0455; IDCatalan = $0403;
IDChineseHongKong = $0C04; IDChineseMacao = $1404;
IDSimplifiedChinese = $0804; IDChineseSingapore = $1004;
IDTraditionalChinese = $0404; IDCroatian = $041A;
IDCzech = $0405; IDDanish = $0406;
IDBelgianDutch = $0813; IDDutch = $0413;
IDEnglishAUS = $0C09; IDEnglishBelize = $2809;
IDEnglishCanadian = $1009; IDEnglishCaribbean = $2409;
IDEnglishIreland = $1809; IDEnglishJamaica = $2009;
IDEnglishNewZealand = $1409; IDEnglishPhilippines = $3409;
IDEnglishSouthAfrica = $1C09; IDEnglishTrinidad = $2C09;
IDEnglishUK = $0809; IDEnglishUS = $0409;
IDEnglishZimbabwe = $3009; IDEstonian = $0425;
IDFaeroese = $0438; IDFarsi = $0429;
IDFinnish = $040B; IDBelgianFrench = $080C;
IDFrenchCameroon = $2C0C; IDFrenchCanadian = $0C0C;
IDFrenchCotedIvoire = $300C; IDFrench = $040C;
IDFrenchLuxembourg = $140C; IDFrenchMali = $340C;
IDFrenchMonaco = $180C; IDFrenchReunion = $200C;
IDFrenchSenegal = $280C; IDSwissFrench = $100C;
IDFrenchWestIndies = $1C0C; IDFrenchZaire = $240C;
IDFrisianNetherlands = $0462; IDGaelicIreland = $083C;
IDGaelicScotland = $043C; IDGalician = $0456;
IDGeorgian = $0437; IDGermanAustria = $0C07;
IDGerman = $0407; IDGermanLiechtenstein = $1407;
IDGermanLuxembourg = $1007; IDSwissGerman = $0807;
IDGreek = $0408; IDGujarati = $0447;
IDHebrew = $040D; IDHindi = $0439;
IDHungarian = $040E; IDIcelandic = $040F;
IDIndonesian = $0421; IDItalian = $0410;
IDSwissItalian = $0810; IDJapanese = $0411;
IDKannada = $044B; IDKashmiri = $0460;
IDKazakh = $043F; IDKhmer = $0453;
IDKirghiz = $0440; IDKonkani = $0457;
IDKorean = $0412; IDLao = $0454;
IDLatvian = $0426; IDLithuanian = $0427;
IDMacedonian = $042F; IDMalaysian = $043E;
IDMalayBruneiDarussalam = $083E; IDMalayalam = $044C;
IDMaltese = $043A; IDManipuri = $0458;
IDMarathi = $044E; IDMongolian = $0450;
IDNepali = $0461; IDNorwegianBokmol = $0414;
IDNorwegianNynorsk = $0814; IDOriya = $0448;
IDPolish = $0415; IDBrazilianPortuguese = $0416;
IDPortuguese = $0816; IDPunjabi = $0446;
IDRhaetoRomanic = $0417; IDRomanianMoldova = $0818;
IDRomanian = $0418; IDRussianMoldova = $0819;
IDRussian = $0419; IDSamiLappish = $043B;
IDSanskrit = $044F; IDSerbianCyrillic = $0C1A;
IDSerbianLatin = $081A; IDSesotho = $0430;
IDSindhi = $0459; IDSlovak = $041B;
IDSlovenian = $0424; IDSorbian = $042E;
IDSpanishArgentina = $2C0A; IDSpanishBolivia = $400A;
IDSpanishChile = $340A; IDSpanishColombia = $240A;
IDSpanishCostaRica = $140A; IDSpanishDominicanRepublic = $1C0A;
IDSpanishEcuador = $300A; IDSpanishElSalvador = $440A;
IDSpanishGuatemala = $100A; IDSpanishHonduras = $480A;
IDMexicanSpanish = $080A; IDSpanishNicaragua = $4C0A;
IDSpanishPanama = $180A; IDSpanishParaguay = $3C0A;
IDSpanishPeru = $280A; IDSpanishPuertoRico = $500A;
IDSpanishModernSort = $0C0A; IDSpanish = $040A;
IDSpanishUruguay = $380A; IDSpanishVenezuela = $200A;
IDSutu = $0430; IDSwahili = $0441;
IDSwedishFinland = $081D; IDSwedish = $041D;
IDTajik = $0428; IDTamil = $0449;
IDTatar = $0444; IDTelugu = $044A;
IDThai = $041E; IDTibetan = $0451;
IDTsonga = $0431; IDTswana = $0432;
IDTurkish = $041F; IDTurkmen = $0442;
IDUkrainian = $0422; IDUrdu = $0420;
IDUzbekCyrillic = $0843; IDUzbekLatin = $0443;
IDVenda = $0433; IDVietnamese = $042A;
IDWelsh = $0452; IDXhosa = $0434;
IDZulu = $0435;
function GetOSLanguage: ansistring;
var
langid: Cardinal;
langcode: ansistring;
CountryName: array[0..4] of ansichar;
LanguageName: array[0..4] of ansichar;
works: boolean;
begin
// The return value of GetLocaleInfo is compared with 3 = 2 characters and a zero
works := 3 = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, LanguageName, SizeOf(LanguageName));
works := works and (3 = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, CountryName,
SizeOf(CountryName)));
if works then begin
// Windows 98, Me, NT4, 2000, XP and newer
LangCode := PChar(@LanguageName[0]) + '_' + PChar(@CountryName[0]);
end else begin
// This part should only happen on Windows 95.
langid := GetThreadLocale;
case langid of
IDBelgianDutch: langcode := 'nl_BE';
IDBelgianFrench: langcode := 'fr_BE';
IDBrazilianPortuguese: langcode := 'pt_BR';
IDDanish: langcode := 'da_DK';
IDDutch: langcode := 'nl_NL';
IDEnglishUK: langcode := 'en_GB';
IDEnglishUS: langcode := 'en_US';
IDFinnish: langcode := 'fi_FI';
IDFrench: langcode := 'fr_FR';
IDFrenchCanadian: langcode := 'fr_CA';
IDGerman: langcode := 'de_DE';
IDGermanLuxembourg: langcode := 'de_LU';
IDGreek: langcode := 'gr_GR';
IDIcelandic: langcode := 'is_IS';
IDItalian: langcode := 'it_IT';
IDKorean: langcode := 'ko_KO';
IDNorwegianBokmol: langcode := 'nb_NO';
IDNorwegianNynorsk: langcode := 'nn_NO';
IDPolish: langcode := 'pl_PL';
IDPortuguese: langcode := 'pt_PT';
IDRussian: langcode := 'ru_RU';
IDSpanish, IDSpanishModernSort: langcode := 'es_ES';
IDSwedish: langcode := 'sv_SE';
IDSwedishFinland: langcode := 'sv_FI';
else
langcode := 'C';
end;
end;
Result := langcode;
end;
{$endif}
{$ifdef CLR}
function GetOSLanguage: string;
var
p:integer;
begin
Result:=CultureInfo.get_CurrentCulture.ToString;
p:=pos('-',Result);
if p<>0 then
Result[p]:='_';
end;
{$endif}
{$ifdef LINUX}
function GetOSLanguage: ansistring;
begin
Result:='';
end;
{$endif}
{$ifndef CLR}
function LoadResStringA(ResStringRec: PResStringRec): ansistring;
begin
if DefaultInstance<>nil then
Result:=DefaultInstance.LoadResString(ResStringRec)
else
Result:=PChar(ResStringRec.Identifier);
end;
{$endif}
function GetTranslatorNameAndEmail:widestring;
begin
Result:=DefaultInstance.GetTranslatorNameAndEmail;
end;
procedure UseLanguage(LanguageCode: ansistring);
begin
DefaultInstance.UseLanguage(LanguageCode);
end;
{$ifndef CLR}
type
PStrData = ^TStrData;
TStrData = record
Ident: Integer;
Str: ansistring;
end;
function SysUtilsEnumStringModules(Instance: Longint; Data: Pointer): Boolean;
{$IFDEF MSWINDOWS}
var
Buffer: array [0..1023] of ansichar;
begin
with PStrData(Data)^ do begin
SetString(Str, Buffer,
LoadString(Instance, Ident, Buffer, sizeof(Buffer)));
Result := Str = '';
end;
end;
{$ENDIF}
{$IFDEF LINUX}
var
rs:TResStringRec;
Module:HModule;
begin
Module:=Instance;
rs.Module:=@Module;
with PStrData(Data)^ do begin
rs.Identifier:=Ident;
Str:=System.LoadResString(@rs);
Result:=Str='';
end;
end;
{$ENDIF}
function SysUtilsFindStringResource(Ident: Integer): ansistring;
var
StrData: TStrData;
begin
StrData.Ident := Ident;
StrData.Str := '';
EnumResourceModules(SysUtilsEnumStringModules, @StrData);
Result := StrData.Str;
end;
function SysUtilsLoadStr(Ident: Integer): ansistring;
begin
{$ifdef DXGETTEXTDEBUG}
DefaultInstance.DebugWriteln ('Sysutils.LoadRes('+IntToStr(ident)+') called');
{$endif}
Result := ResourceStringGettext(SysUtilsFindStringResource(Ident));
end;
function SysUtilsFmtLoadStr(Ident: Integer; const Args: array of const): ansistring;
begin
{$ifdef DXGETTEXTDEBUG}
DefaultInstance.DebugWriteln ('Sysutils.FmtLoadRes('+IntToStr(ident)+',Args) called');
{$endif}
FmtStr(Result, SysUtilsFindStringResource(Ident), Args);
Result:=ResourceStringGettext(Result);
end;
function LoadResString(ResStringRec: PResStringRec): widestring;
begin
Result:=DefaultInstance.LoadResString(ResStringRec);
end;
function LoadResStringW(ResStringRec: PResStringRec): widestring;
begin
Result:=DefaultInstance.LoadResString(ResStringRec);
end;
{$endif}
function GetCurrentLanguage:ansistring;
begin
Result:=DefaultInstance.GetCurrentLanguage;
end;
{ TDomain }
procedure TDomain.CloseMoFile;
begin
if mofile<>nil then begin
FileLocator.ReleaseMoFile(mofile);
mofile:=nil;
end;
OpenHasFailedBefore:=False;
end;
destructor TDomain.Destroy;
begin
CloseMoFile;
inherited;
end;
{$ifdef mswindows}
function GetLastWinError:ansistring;
var
errcode:Cardinal;
begin
SetLength (Result,2000);
errcode:=GetLastError();
Windows.FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,errcode,0,PChar(Result),2000,nil);
Result:=StrPas(PChar(Result));
end;
{$endif}
procedure TDomain.OpenMoFile;
var
filename: string;
begin
// Check if it is already open
if mofile<>nil then
exit;
// Check if it has been attempted to open the file before
if OpenHasFailedBefore then
exit;
if SpecificFilename<>'' then
filename:=SpecificFilename
else begin
filename := Directory + curlang + PathDelim + 'LC_MESSAGES' + PathDelim + domain + '.mo';
if (not FileLocator.FileExists(filename)) and (not fileexists(filename)) then
filename := Directory + copy(curlang, 1, 2) + PathDelim + 'LC_MESSAGES' + PathDelim + domain + '.mo';
end;
if (not FileLocator.FileExists(filename)) and (not fileexists(filename)) then begin
OpenHasFailedBefore:=True;
exit;
end;
mofile:=FileLocator.GetMoFile(filename, DebugLogger);
{$ifdef DXGETTEXTDEBUG}
if mofile.isSwappedArchitecture then
DebugLogger ('.mo file is swapped (comes from another CPU architecture)');
{$endif}
// Check, that the contents of the file is utf-8
if pos('CHARSET=UTF-8',string(uppercase(GetTranslationProperty('Content-Type'))))=0 then begin
CloseMoFile;
{$ifdef DXGETTEXTDEBUG}
DebugLogger ('The translation for the language code '+curlang+' (in '+filename+') does not have charset=utf-8 in its Content-Type. Translations are turned off.');
{$endif}
{$ifdef MSWINDOWS}
MessageBox(0,PChar('The translation for the language code '+curlang+' (in '+filename+') does not have charset=utf-8 in its Content-Type. Translations are turned off.'),'Localization problem',MB_OK);
{$endif}
{$ifdef CLR}
{ TODO : A message should be shown here. Find out how to do that with CLR }
{$endif}
{$ifdef LINUX}
writeln (stderr,'The translation for the language code '+curlang+' (in '+filename+') does not have charset=utf-8 in its Content-Type. Translations are turned off.');
{$endif}
Enabled:=False;
end;
end;
function TDomain.GetTranslationProperty(
Propertyname: string): WideString;
var
sl:TStringList;
i:integer;
s:string;
begin
Propertyname:=uppercase(Propertyname)+': ';
sl:=TStringList.Create;
try
{$ifdef CLR}
{ TODO : This has changed - in Delphi 8, sl.Text:= only assigns one string. }
sl.Text:=gettext('');
{$else}
sl.Text:=utf8encode(gettext(''));
{$endif}
for i:=0 to sl.Count-1 do begin
s:=sl.Strings[i];
if uppercase(copy(s,1,length(Propertyname)))=Propertyname then begin
{$ifdef CLR}
Result:=trim(copy(s,length(PropertyName)+1,maxint));
{$else}
Result:=utf8decode(trim(copy(s,length(PropertyName)+1,maxint)));
{$endif}
{$ifdef DXGETTEXTDEBUG}
DebugLogger ('GetTranslationProperty('+PropertyName+') returns '''+Result+'''.');
{$endif}
exit;
end;
end;
finally
FreeAndNil (sl);
end;
Result:='';
{$ifdef DXGETTEXTDEBUG}
DebugLogger ('GetTranslationProperty('+PropertyName+') did not find any value. An empty string is returned.');
{$endif}
end;
procedure TDomain.setDirectory(dir: string);
begin
vDirectory := IncludeTrailingPathDelimiter(dir);
SpecificFilename:='';
CloseMoFile;
end;
procedure AddDomainForResourceString (domain:ansistring);
begin
{$ifdef DXGETTEXTDEBUG}
DefaultInstance.DebugWriteln ('Extra domain for resourcestring: '+domain);
{$endif}
ResourceStringDomainListCS.BeginWrite;
try
if ResourceStringDomainList.IndexOf(domain)=-1 then
ResourceStringDomainList.Add (domain);
finally
ResourceStringDomainListCS.EndWrite;
end;
end;
procedure RemoveDomainForResourceString (domain:ansistring);
var
i:integer;
begin
{$ifdef DXGETTEXTDEBUG}
DefaultInstance.DebugWriteln ('Remove domain for resourcestring: '+domain);
{$endif}
ResourceStringDomainListCS.BeginWrite;
try
i:=ResourceStringDomainList.IndexOf(domain);
if i<>-1 then
ResourceStringDomainList.Delete (i);
finally
ResourceStringDomainListCS.EndWrite;
end;
end;
procedure TDomain.SetLanguageCode(langcode: ansistring);
begin
CloseMoFile;
curlang:=langcode;
end;
function GetPluralForm2EN(Number: Integer): Integer;
begin
Number:=abs(Number);
if Number=1 then Result:=0 else Result:=1;
end;
function GetPluralForm1(Number: Integer): Integer;
begin
Result:=0;
end;
function GetPluralForm2FR(Number: Integer): Integer;
begin
Number:=abs(Number);
if (Number=1) or (Number=0) then Result:=0 else Result:=1;
end;
function GetPluralForm3LV(Number: Integer): Integer;
begin
Number:=abs(Number);
if (Number mod 10=1) and (Number mod 100<>11) then
Result:=0
else
if Number<>0 then Result:=1
else Result:=2;
end;
function GetPluralForm3GA(Number: Integer): Integer;
begin
Number:=abs(Number);
if Number=1 then Result:=0
else if Number=2 then Result:=1
else Result:=2;
end;
function GetPluralForm3LT(Number: Integer): Integer;
var
n1,n2:byte;
begin
Number:=abs(Number);
n1:=Number mod 10;
n2:=Number mod 100;
if (n1=1) and (n2<>11) then
Result:=0
else
if (n1>=2) and ((n2<10) or (n2>=20)) then Result:=1
else Result:=2;
end;
function GetPluralForm3PL(Number: Integer): Integer;
var
n1,n2:byte;
begin
Number:=abs(Number);
n1:=Number mod 10;
n2:=Number mod 100;
if n1=1 then Result:=0
else if (n1>=2) and (n1<=4) and ((n2<10) or (n2>=20)) then Result:=1
else Result:=2;
end;
function GetPluralForm3RU(Number: Integer): Integer;
var
n1,n2:byte;
begin
Number:=abs(Number);
n1:=Number mod 10;
n2:=Number mod 100;
if (n1=1) and (n2<>11) then
Result:=0
else
if (n1>=2) and (n1<=4) and ((n2<10) or (n2>=20)) then Result:=1
else Result:=2;
end;
function GetPluralForm4SL(Number: Integer): Integer;
var
n2:byte;
begin
Number:=abs(Number);
n2:=Number mod 100;
if n2=1 then Result:=0
else
if n2=2 then Result:=1
else
if (n2=3) or (n2=4) then Result:=2
else
Result:=3;
end;
procedure TDomain.GetListOfLanguages(list: TStrings);
var
sr:TSearchRec;
more:boolean;
filename, path, langcode:ansistring;
i, j:integer;
begin
list.Clear;
// Iterate through filesystem
more:=FindFirst (Directory+'*',faAnyFile,sr)=0;
while more do begin
if (sr.Attr and faDirectory<>0) and (sr.name<>'.') and (sr.name<>'..') then begin
filename := Directory + sr.Name + PathDelim + 'LC_MESSAGES' + PathDelim + domain + '.mo';
if fileexists(filename) then begin
langcode:=lowercase(sr.name);
if list.IndexOf(langcode)=-1 then
list.Add(langcode);
end;
end;
more:=FindNext (sr)=0;
end;
// Iterate through embedded files
for i:=0 to FileLocator.filelist.Count-1 do begin
filename:=FileLocator.basedirectory+FileLocator.filelist.Strings[i];
path:=Directory;
{$ifdef MSWINDOWS}
path:=uppercase(path);
filename:=uppercase(filename);
{$endif}
j:=length(path);
if copy(filename,1,j)=path then begin
path:=PathDelim + 'LC_MESSAGES' + PathDelim + domain + '.mo';
{$ifdef MSWINDOWS}
path:=uppercase(path);
{$endif}
if copy(filename,length(filename)-length(path)+1,length(path))=path then begin
langcode:=lowercase(copy(filename,j+1,length(filename)-length(path)-j));
if list.IndexOf(langcode)=-1 then
list.Add(langcode);
end;
end;
end;
end;
procedure TDomain.SetFilename(filename: ansistring);
begin
CloseMoFile;
vDirectory := '';
SpecificFilename:=filename;
end;
function TDomain.gettext(msgid: ansistring): ansistring;
var
found:boolean;
begin
if not Enabled then begin
Result:=msgid;
exit;
end;
if (mofile=nil) and (not OpenHasFailedBefore) then
OpenMoFile;
if mofile=nil then begin
{$ifdef DXGETTEXTDEBUG}
DebugLogger('.mo file is not open. Not translating "'+msgid+'"');
{$endif}
Result := msgid;
end else begin
Result:=mofile.gettext(msgid,found);
{$ifdef DXGETTEXTDEBUG}
if found then
DebugLogger ('Found in .mo ('+Domain+'): "'+utf8encode(msgid)+'"->"'+utf8encode(Result)+'"')
else
DebugLogger ('Translation not found in .mo file ('+Domain+') : "'+utf8encode(msgid)+'"');
{$endif}
end;
end;
constructor TDomain.Create;
begin
inherited Create;
Enabled:=True;
end;
{ TGnuGettextInstance }
procedure TGnuGettextInstance.bindtextdomain(const szDomain,
szDirectory: ansistring);
var
dir:ansistring;
begin
dir:=IncludeTrailingPathDelimiter(szDirectory);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Text domain "'+szDomain+'" is now located at "'+dir+'"');
{$endif}
getdomain(szDomain,DefaultDomainDirectory,CurLang).Directory := dir;
WhenNewDomainDirectory (szDomain, szDirectory);
end;
constructor TGnuGettextInstance.Create;
var
lang: ansistring;
begin
inherited Create;
{$ifndef CLR}
CreatorThread:=GetCurrentThreadId;
{ TODO : Do something about Thread handling if resourcestrings are enabled }
{$endif}
{$ifdef MSWindows}
DesignTimeCodePage:=CP_ACP;
{$endif}
{$ifdef DXGETTEXTDEBUG}
DebugLogCS:=TMultiReadExclusiveWriteSynchronizer.Create;
DebugLog:=TMemoryStream.Create;
DebugWriteln('Debug log started '+DateTimeToStr(Now));
DebugWriteln('');
{$endif}
curGetPluralForm:=GetPluralForm2EN;
Enabled:=True;
curmsgdomain:=DefaultTextDomain;
savefileCS := TMultiReadExclusiveWriteSynchronizer.Create;
domainlist := TStringList.Create;
TP_IgnoreList:=TStringList.Create;
TP_IgnoreList.Sorted:=True;
TP_GlobalClassHandling:=TList.Create;
TP_ClassHandling:=TList.Create;
// Set some settings
DefaultDomainDirectory := IncludeTrailingPathDelimiter(extractfilepath(ExecutableFilename))+'locale';
UseLanguage(lang);
bindtextdomain(DefaultTextDomain, DefaultDomainDirectory);
textdomain(DefaultTextDomain);
// Add default properties to ignore
TP_GlobalIgnoreClassProperty(TComponent,'Name');
TP_GlobalIgnoreClassProperty(TCollection,'PropName');
end;
destructor TGnuGettextInstance.Destroy;
begin
if savememory <> nil then begin
savefileCS.BeginWrite;
try
CloseFile(savefile);
finally
savefileCS.EndWrite;
end;
FreeAndNil(savememory);
end;
FreeAndNil (savefileCS);
FreeAndNil (TP_IgnoreList);
while TP_GlobalClassHandling.Count<>0 do begin
TObject(TP_GlobalClassHandling.Items[0]).Free;
TP_GlobalClassHandling.Delete(0);
end;
FreeAndNil (TP_GlobalClassHandling);
FreeTP_ClassHandlingItems;
FreeAndNil (TP_ClassHandling);
while domainlist.Count <> 0 do begin
domainlist.Objects[0].Free;
domainlist.Delete(0);
end;
FreeAndNil(domainlist);
{$ifdef DXGETTEXTDEBUG}
FreeAndNil (DebugLog);
FreeAndNil (DebugLogCS);
{$endif}
inherited;
end;
{$ifndef DELPHI5OROLDER}
function TGnuGettextInstance.dgettext(const szDomain: ansistring; const szMsgId: ansistring): widestring;
begin
Result:=dgettext(szDomain, ansi2wide(szMsgId));
end;
{$endif}
function TGnuGettextInstance.dgettext(const szDomain: ansistring;
const szMsgId: widestring): widestring;
begin
if not Enabled then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Translation has been disabled. Text is not being translated: '+szMsgid);
{$endif}
Result:=szMsgId;
end else begin
Result:=UTF8Decode(LF2LineBreakA(getdomain(szDomain,DefaultDomainDirectory,CurLang).gettext(StripCR(utf8encode(szMsgId)))));
{$ifdef DXGETTEXTDEBUG}
if (szMsgId<>'') and (Result='') then
DebugWriteln (Format('Error: Translation of %s was an empty string. This may never occur.',[szMsgId]));
{$endif}
end;
end;
function TGnuGettextInstance.GetCurrentLanguage: ansistring;
begin
Result:=curlang;
end;
function TGnuGettextInstance.getcurrenttextdomain: ansistring;
begin
Result := curmsgdomain;
end;
{$ifndef DELPHI5OROLDER}
function TGnuGettextInstance.gettext(
const szMsgId: ansistring): widestring;
begin
Result := dgettext(curmsgdomain, szMsgId);
end;
{$endif}
function TGnuGettextInstance.gettext(
const szMsgId: widestring): widestring;
begin
Result := dgettext(curmsgdomain, szMsgId);
end;
procedure TGnuGettextInstance.textdomain(const szDomain: ansistring);
begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Changed text domain to "'+szDomain+'"');
{$endif}
curmsgdomain := szDomain;
WhenNewDomain (szDomain);
end;
function TGnuGettextInstance.TP_CreateRetranslator : TExecutable;
var
ttpr:TTP_Retranslator;
begin
ttpr:=TTP_Retranslator.Create;
ttpr.Instance:=self;
TP_Retranslator:=ttpr;
Result:=ttpr;
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('A retranslator was created.');
{$endif}
end;
procedure TGnuGettextInstance.TP_GlobalHandleClass(HClass: TClass;
Handler: TTranslator);
var
cm:TClassMode;
i:integer;
begin
for i:=0 to TP_GlobalClassHandling.Count-1 do begin
cm:=TObject(TP_GlobalClassHandling.Items[i]) as TClassMode;
if cm.HClass=HClass then
raise EGGProgrammingError.Create ('You cannot set a handler for a class that has already been assigned otherwise.');
if HClass.InheritsFrom(cm.HClass) then begin
// This is the place to insert this class
cm:=TClassMode.Create;
cm.HClass:=HClass;
cm.SpecialHandler:=Handler;
TP_GlobalClassHandling.Insert(i,cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('A handler was set for class '+HClass.ClassName+'.');
{$endif}
exit;
end;
end;
cm:=TClassMode.Create;
cm.HClass:=HClass;
cm.SpecialHandler:=Handler;
TP_GlobalClassHandling.Add(cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('A handler was set for class '+HClass.ClassName+'.');
{$endif}
end;
procedure TGnuGettextInstance.TP_GlobalIgnoreClass(IgnClass: TClass);
var
cm:TClassMode;
i:integer;
begin
for i:=0 to TP_GlobalClassHandling.Count-1 do begin
cm:=TObject(TP_GlobalClassHandling.Items[i]) as TClassMode;
if cm.HClass=IgnClass then
raise EGGProgrammingError.Create ('You cannot add a class to the ignore list that is already on that list: '+IgnClass.ClassName+'. You should keep all TP_Global functions in one place in your source code.');
if IgnClass.InheritsFrom(cm.HClass) then begin
// This is the place to insert this class
cm:=TClassMode.Create;
cm.HClass:=IgnClass;
TP_GlobalClassHandling.Insert(i,cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Globally, class '+IgnClass.ClassName+' is being ignored.');
{$endif}
exit;
end;
end;
cm:=TClassMode.Create;
cm.HClass:=IgnClass;
TP_GlobalClassHandling.Add(cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Globally, class '+IgnClass.ClassName+' is being ignored.');
{$endif}
end;
procedure TGnuGettextInstance.TP_GlobalIgnoreClassProperty(
IgnClass: TClass; propertyname: ansistring);
var
cm:TClassMode;
i,idx:integer;
begin
propertyname:=uppercase(propertyname);
for i:=0 to TP_GlobalClassHandling.Count-1 do begin
cm:=TObject(TP_GlobalClassHandling.Items[i]) as TClassMode;
if cm.HClass=IgnClass then begin
if Assigned(cm.SpecialHandler) then
raise EGGProgrammingError.Create ('You cannot ignore a class property for a class that has a handler set.');
if not cm.PropertiesToIgnore.Find(propertyname,idx) then
cm.PropertiesToIgnore.Add(propertyname);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Globally, the '+propertyname+' property of class '+IgnClass.ClassName+' is being ignored.');
{$endif}
exit;
end;
if IgnClass.InheritsFrom(cm.HClass) then begin
// This is the place to insert this class
cm:=TClassMode.Create;
cm.HClass:=IgnClass;
cm.PropertiesToIgnore.Add(propertyname);
TP_GlobalClassHandling.Insert(i,cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Globally, the '+propertyname+' property of class '+IgnClass.ClassName+' is being ignored.');
{$endif}
exit;
end;
end;
cm:=TClassMode.Create;
cm.HClass:=IgnClass;
cm.PropertiesToIgnore.Add(propertyname);
TP_GlobalClassHandling.Add(cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Globally, the '+propertyname+' property of class '+IgnClass.ClassName+' is being ignored.');
{$endif}
end;
procedure TGnuGettextInstance.TP_Ignore(AnObject: TObject;
const name: ansistring);
begin
TP_IgnoreList.Add(uppercase(name));
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('On object with class name '+AnObject.ClassName+', ignore is set on '+name);
{$endif}
end;
procedure TGnuGettextInstance.TranslateComponent(AnObject: TComponent;
TextDomain: ansistring);
var
comp:TGnuGettextComponentMarker;
begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('======================================================================');
DebugWriteln ('TranslateComponent() was called for a component with name '+AnObject.Name+'.');
{$endif}
comp:=AnObject.FindComponent('GNUgettextMarker') as TGnuGettextComponentMarker;
if comp=nil then begin
comp:=TGnuGettextComponentMarker.Create (nil);
comp.Name:='GNUgettextMarker';
comp.Retranslator:=TP_CreateRetranslator;
TranslateProperties (AnObject, TextDomain);
AnObject.InsertComponent(comp);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('This is the first time, that this component has been translated. A retranslator component has been created for this component.');
{$endif}
end else begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('This is not the first time, that this component has been translated.');
{$endif}
if comp.LastLanguage<>curlang then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('ERROR: TranslateComponent() was called twice with different languages. This indicates an attempt to switch language at runtime, but by using TranslateComponent every time. This API has changed - please use RetranslateComponent() instead.');
{$endif}
{$ifdef mswindows}
MessageBox (0,'This application tried to switch the language, but in an incorrect way. The programmer needs to replace a call to TranslateComponent with a call to RetranslateComponent(). The programmer should see the changelog of gnugettext.pas for more information.','Error',MB_OK);
{$endif}
{$ifdef CLR}
{ TODO : A message should be shown here. Find out how to do that with CLR }
{$endif}
{$ifdef LINUX}
writeln (stderr,'This application tried to switch the language, but in an incorrect way. The programmer needs to replace a call to TranslateComponent with a call to RetranslateComponent(). The programmer should see the changelog of gnugettext.pas for more information.');
{$endif}
end else begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('ERROR: TranslateComponent has been called twice, but with the same language chosen. This is a mistake, but in order to prevent that the application breaks, no exception is raised.');
{$endif}
end;
end;
comp.LastLanguage:=curlang;
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('======================================================================');
{$endif}
end;
{$ifndef CLR}
procedure TGnuGettextInstance.TranslateProperty (AnObject:TObject; PropInfo:PPropInfo; TodoList:TStrings; TextDomain:ansistring);
var
{$ifdef DELPHI5OROLDER}
ws: ansistring;
old: ansistring;
{$endif}
{$ifndef DELPHI5OROLDER}
ppi:PPropInfo;
ws: WideString;
old: WideString;
{$endif}
obj:TObject;
Propname:ansistring;
begin
PropName:=PropInfo^.Name;
try
// Translate certain types of properties
case PropInfo^.PropType^.Kind of
tkString, tkLString, tkWString:
begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Translating '+AnObject.ClassName+'.'+PropName);
{$endif}
{$ifdef DELPHI5OROLDER}
old := GetStrProp(AnObject, PropName);
{$endif}
{$ifndef DELPHI5OROLDER}
if PropInfo^.PropType^.Kind<>tkWString then
old := ansi2wide(GetStrProp(AnObject, PropName))
else
old := GetWideStrProp(AnObject, PropName);
{$endif}
{$ifdef DXGETTEXTDEBUG}
if old='' then
DebugWriteln ('(Empty, not translated)')
else
DebugWriteln ('Old value: "'+old+'"');
{$endif}
if (old <> '') and (IsWriteProp(PropInfo)) then begin
if TP_Retranslator<>nil then
(TP_Retranslator as TTP_Retranslator).Remember(AnObject, PropName, old);
ws := dgettext(textdomain,old);
if ws <> old then begin
{$ifdef DELPHI5OROLDER}
SetStrProp(AnObject, PropName, ws);
{$endif}
{$ifndef DELPHI5OROLDER}
ppi:=GetPropInfo(AnObject, Propname);
if ppi<>nil then begin
SetWideStrProp(AnObject, ppi, ws);
end else begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('ERROR: Property disappeared: '+Propname+' for object of type '+AnObject.ClassName);
{$endif}
end;
{$endif}
end;
end;
end { case item };
tkClass:
begin
obj:=GetObjectProp(AnObject, PropName);
if obj<>nil then
TodoList.AddObject ('',obj);
end { case item };
end { case };
except
on E:Exception do
raise EGGComponentError.Create ('Property cannot be translated.'+sLineBreak+
'Add TP_GlobalIgnoreClassProperty('+AnObject.ClassName+','''+PropName+''') to your source code or use'+sLineBreak+
'TP_Ignore (self,''.'+PropName+''') to prevent this message.'+sLineBreak+
'Reason: '+e.Message);
end;
end;
{$endif}
procedure TGnuGettextInstance.TranslateProperties(AnObject: TObject; textdomain:ansistring='');
{$ifndef CLR}
var
TodoList:TStringList; // List of Name/TObject's that is to be processed
DoneList:TStringList; // List of hex codes representing pointers to objects that have been done
i, j, Count: integer;
PropList: PPropList;
UPropName: ansistring;
PropInfo: PPropInfo;
comp:TComponent;
cm,currentcm:TClassMode;
ObjectPropertyIgnoreList:TStringList;
objid, Name:ansistring;
{$ifdef DELPHI5OROLDER}
Data:PTypeData;
{$endif}
{$endif}
begin
{$ifndef CLR}
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('----------------------------------------------------------------------');
DebugWriteln ('TranslateProperties() was called for an object of class '+AnObject.ClassName+' with domain "'+textdomain+'".');
{$endif}
if textdomain='' then
textdomain:=curmsgdomain;
if TP_Retranslator<>nil then
(TP_Retranslator as TTP_Retranslator).TextDomain:=textdomain;
DoneList:=TStringList.Create;
TodoList:=TStringList.Create;
ObjectPropertyIgnoreList:=TStringList.Create;
try
TodoList.AddObject('', AnObject);
DoneList.Sorted:=True;
ObjectPropertyIgnoreList.Sorted:=True;
{$ifndef DELPHI5OROLDER}
ObjectPropertyIgnoreList.Duplicates:=dupIgnore;
ObjectPropertyIgnoreList.CaseSensitive:=False;
DoneList.Duplicates:=dupError;
DoneList.CaseSensitive:=True;
{$endif}
while TodoList.Count<>0 do begin
AnObject:=TodoList.Objects[0];
Name:=TodoList.Strings[0];
TodoList.Delete(0);
if (AnObject<>nil) and (AnObject is TPersistent) then begin
// Make sure each object is only translated once
Assert (sizeof(integer)=sizeof(TObject));
objid:=IntToHex(integer(AnObject),8);
if DoneList.Find(objid,i) then begin
continue;
end else begin
DoneList.Add(objid);
end;
ObjectPropertyIgnoreList.Clear;
// Find out if there is special handling of this object
currentcm:=nil;
// First check the local handling instructions
for j:=0 to TP_ClassHandling.Count-1 do begin
cm:=TObject(TP_ClassHandling.Items[j]) as TClassMode;
if AnObject.InheritsFrom(cm.HClass) then begin
if cm.PropertiesToIgnore.Count<>0 then begin
ObjectPropertyIgnoreList.AddStrings(cm.PropertiesToIgnore);
end else begin
// Ignore the entire class
currentcm:=cm;
break;
end;
end;
end;
// Then check the global handling instructions
if currentcm=nil then
for j:=0 to TP_GlobalClassHandling.Count-1 do begin
cm:=TObject(TP_GlobalClassHandling.Items[j]) as TClassMode;
if AnObject.InheritsFrom(cm.HClass) then begin
if cm.PropertiesToIgnore.Count<>0 then begin
ObjectPropertyIgnoreList.AddStrings(cm.PropertiesToIgnore);
end else begin
// Ignore the entire class
currentcm:=cm;
break;
end;
end;
end;
if currentcm<>nil then begin
ObjectPropertyIgnoreList.Clear;
// Ignore or use special handler
if Assigned(currentcm.SpecialHandler) then begin
currentcm.SpecialHandler (AnObject);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Special handler activated for '+AnObject.ClassName);
{$endif}
end else begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Ignoring object '+AnObject.ClassName);
{$endif}
end;
continue;
end;
{$ifdef DELPHI5OROLDER}
if AnObject.ClassInfo=nil then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('ClassInfo=nil encountered for class '+AnObject.ClassName+'. Translation of that component has stopped. You should ignore this object.');
{$endif}
continue;
end;
Data := GetTypeData(AnObject.Classinfo);
Count := Data^.PropCount;
GetMem(PropList, Count * Sizeof(PPropInfo));
{$endif}
{$ifndef DELPHI5OROLDER}
Count := GetPropList(AnObject, PropList);
{$endif}
try
{$ifdef DELPHI5OROLDER}
GetPropInfos(AnObject.ClassInfo, PropList);
{$endif}
for j := 0 to Count - 1 do begin
PropInfo := PropList[j];
UPropName:=uppercase(PropInfo^.Name);
// Ignore properties that are meant to be ignored
if ((currentcm=nil) or (not currentcm.PropertiesToIgnore.Find(UPropName,i))) and
(not TP_IgnoreList.Find(Name+'.'+UPropName,i)) and
(not ObjectPropertyIgnoreList.Find(UPropName,i)) then begin
TranslateProperty (AnObject,PropInfo,TodoList,TextDomain);
end; // if
end; // for
finally
{$ifdef DELPHI5OROLDER}
FreeMem(PropList, Data^.PropCount * Sizeof(PPropInfo));
{$endif}
{$ifndef DELPHI5OROLDER}
if Count<>0 then
FreeMem (PropList);
{$endif}
end;
if AnObject is TStrings then begin
if ((AnObject as TStrings).Text<>'') and (TP_Retranslator<>nil) then
(TP_Retranslator as TTP_Retranslator).Remember(AnObject, 'Text', (AnObject as TStrings).Text);
TranslateStrings (AnObject as TStrings,TextDomain);
end;
// Check for TCollection
if AnObject is TCollection then begin
for i := 0 to (AnObject as TCollection).Count - 1 do
TodoList.AddObject('',(AnObject as TCollection).Items[i]);
end;
if AnObject is TComponent then begin
for i := 0 to TComponent(AnObject).ComponentCount - 1 do begin
comp:=TComponent(AnObject).Components[i];
if (not TP_IgnoreList.Find(uppercase(comp.Name),j)) then begin
TodoList.AddObject(uppercase(comp.Name),comp);
end;
end;
end;
end { if AnObject<>nil };
end { while todolist.count<>0 };
finally
FreeAndNil (todolist);
FreeAndNil (ObjectPropertyIgnoreList);
FreeAndNil (DoneList);
end;
FreeTP_ClassHandlingItems;
TP_IgnoreList.Clear;
TP_Retranslator:=nil;
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('----------------------------------------------------------------------');
{$endif}
{$endif}
end;
procedure TGnuGettextInstance.UseLanguage(LanguageCode: ansistring);
var
i,p:integer;
dom:TDomain;
l2:string[2];
begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln('UseLanguage('''+LanguageCode+'''); called');
{$endif}
if LanguageCode='' then begin
LanguageCode:=GGGetEnvironmentVariable('LANG');
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('LANG env variable is '''+LanguageCode+'''.');
{$endif}
if LanguageCode='' then begin
LanguageCode:=GetOSLanguage;
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Found OS language code to be '''+LanguageCode+'''.');
{$endif}
end;
p:=pos('.',string(LanguageCode));
if p<>0 then
LanguageCode:=copy(LanguageCode,1,p-1);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Language code that will be set is '''+LanguageCode+'''.');
{$endif}
end;
curlang := LanguageCode;
for i:=0 to domainlist.Count-1 do begin
dom:=domainlist.Objects[i] as TDomain;
dom.SetLanguageCode (curlang);
end;
l2:=lowercase(copy(curlang,1,2));
if (l2='en') or (l2='de') then curGetPluralForm:=GetPluralForm2EN else
if (l2='hu') or (l2='ko') or (l2='zh') or (l2='ja') or (l2='tr') then curGetPluralForm:=GetPluralForm1 else
if (l2='fr') or (l2='fa') or (lowercase(curlang)='pt_br') then curGetPluralForm:=GetPluralForm2FR else
if (l2='lv') then curGetPluralForm:=GetPluralForm3LV else
if (l2='ga') then curGetPluralForm:=GetPluralForm3GA else
if (l2='lt') then curGetPluralForm:=GetPluralForm3LT else
if (l2='ru') or (l2='cs') or (l2='sk') or (l2='uk') or (l2='hr') then curGetPluralForm:=GetPluralForm3RU else
if (l2='pl') then curGetPluralForm:=GetPluralForm3PL else
if (l2='sl') then curGetPluralForm:=GetPluralForm4SL else begin
curGetPluralForm:=GetPluralForm2EN;
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Plural form for the language was not found. English plurality system assumed.');
{$endif}
end;
WhenNewLanguage (curlang);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln('');
{$endif}
end;
procedure TGnuGettextInstance.TranslateStrings(sl: TStrings;TextDomain:ansistring);
var
line: ansistring;
i: integer;
s:TStringList;
begin
if sl.Count > 0 then begin
sl.BeginUpdate;
try
s:=TStringList.Create;
try
s.Assign (sl);
for i:=0 to s.Count-1 do begin
line:=s.Strings[i];
if line<>'' then
s.Strings[i]:=dgettext(TextDomain,line);
end;
sl.Assign(s);
finally
FreeAndNil (s);
end;
finally
sl.EndUpdate;
end;
end;
end;
function TGnuGettextInstance.GetTranslatorNameAndEmail: widestring;
begin
Result:=GetTranslationProperty('LAST-TRANSLATOR');
end;
function TGnuGettextInstance.GetTranslationProperty(
Propertyname: ansistring): WideString;
begin
Result:=getdomain(curmsgdomain,DefaultDomainDirectory,CurLang).GetTranslationProperty (Propertyname);
end;
function TGnuGettextInstance.dngettext(const szDomain: ansistring; singular, plural: widestring;
Number: Integer): widestring;
var
org,trans:widestring;
idx:integer;
p:integer;
begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('dngettext translation (domain '+szDomain+', number is '+IntTostr(Number)+') of '+singular+'/'+plural);
{$endif}
org:=singular+#0+plural;
trans:=dgettext(szDomain,org);
if org=trans then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Translation was equal to english version. English plural forms assumed.');
{$endif}
idx:=GetPluralForm2EN(Number)
end else
idx:=curGetPluralForm(Number);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Index '+IntToStr(idx)+' will be used');
{$endif}
while true do begin
p:=pos(#0,string(trans));
if p=0 then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Last translation used: '+utf8encode(trans));
{$endif}
Result:=trans;
exit;
end;
if idx=0 then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Translation found: '+utf8encode(trans));
{$endif}
Result:=copy(trans,1,p-1);
exit;
end;
delete (trans,1,p);
dec (idx);
end;
end;
{$ifndef DELPHI5OROLDER}
function TGnuGettextInstance.ngettext(const singular, plural: ansistring;
Number: Integer): widestring;
begin
Result := dngettext(curmsgdomain, singular, plural, Number);
end;
{$endif}
function TGnuGettextInstance.ngettext(const singular, plural: widestring;
Number: Integer): widestring;
begin
Result := dngettext(curmsgdomain, singular, plural, Number);
end;
procedure TGnuGettextInstance.WhenNewDomain(TextDomain: ansistring);
begin
// This is meant to be empty.
end;
procedure TGnuGettextInstance.WhenNewLanguage(LanguageID: ansistring);
begin
// This is meant to be empty.
end;
procedure TGnuGettextInstance.WhenNewDomainDirectory(TextDomain:ansistring;
Directory: string);
begin
// This is meant to be empty.
end;
procedure TGnuGettextInstance.GetListOfLanguages(domain: ansistring;
list: TStrings);
begin
getdomain(Domain,DefaultDomainDirectory,CurLang).GetListOfLanguages(list);
end;
procedure TGnuGettextInstance.bindtextdomainToFile(const szDomain,
filename: ansistring);
begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Text domain "'+szDomain+'" is now bound to file named "'+filename+'"');
{$endif}
getdomain(szDomain,DefaultDomainDirectory,CurLang).SetFilename (filename);
end;
procedure TGnuGettextInstance.DebugLogPause(PauseEnabled: boolean);
begin
DebugLogOutputPaused:=PauseEnabled;
end;
procedure TGnuGettextInstance.DebugLogToFile(filename: ansistring; append:boolean=false);
var
fs:TFileStream;
marker:ansistring;
begin
// Create the file if needed
if (not fileexists(filename)) or (not append) then
fileclose (filecreate (filename));
// Open file
fs:=TFileStream.Create (filename,fmOpenWrite or fmShareDenyWrite);
if append then
fs.Seek(0,soFromEnd);
// Write header if appending
if fs.Position<>0 then begin
marker:=sLineBreak+'==========================================================================='+sLineBreak;
fs.WriteBuffer(marker[1],length(marker));
end;
// Copy the memorystream contents to the file
DebugLog.Seek(0,soFromBeginning);
fs.CopyFrom(DebugLog,0);
// Make DebugLog point to the filestream
FreeAndNil (DebugLog);
DebugLog:=fs;
end;
procedure TGnuGettextInstance.DebugWriteln(line: ansistring);
Var
Discard: Boolean;
begin
Assert (DebugLogCS<>nil);
Assert (DebugLog<>nil);
DebugLogCS.BeginWrite;
try
if DebugLogOutputPaused then
exit;
if Assigned (fOnDebugLine) then begin
Discard := True;
fOnDebugLine (Self, Line, Discard);
If Discard then Exit;
end;
line:=line+sLineBreak;
// Ensure that memory usage doesn't get too big.
if (DebugLog is TMemoryStream) and (DebugLog.Position>1000000) then begin
line:=sLineBreak+sLineBreak+sLineBreak+sLineBreak+sLineBreak+
'Debug log halted because memory usage grew too much.'+sLineBreak+
'Specify a filename to store the debug log in or disable debug loggin in gnugettext.pas.'+
sLineBreak+sLineBreak+sLineBreak+sLineBreak+sLineBreak;
DebugLogOutputPaused:=True;
end;
DebugLog.WriteBuffer(line[1],length(line));
finally
DebugLogCS.EndWrite;
end;
end;
function TGnuGettextInstance.Getdomain(domain, DefaultDomainDirectory, CurLang: ansistring): TDomain;
// Retrieves the TDomain object for the specified domain.
// Creates one, if none there, yet.
var
idx: integer;
begin
idx := domainlist.IndexOf(Domain);
if idx = -1 then begin
Result := TDomain.Create;
Result.DebugLogger:=DebugWriteln;
Result.Domain := Domain;
Result.Directory := DefaultDomainDirectory;
Result.SetLanguageCode(curlang);
domainlist.AddObject(Domain, Result);
end else begin
Result := domainlist.Objects[idx] as TDomain;
end;
end;
{$ifndef CLR}
function TGnuGettextInstance.LoadResString(
ResStringRec: PResStringRec): widestring;
{$ifdef MSWINDOWS}
var
Len: Integer;
Buffer: array [0..1023] of ansichar;
{$endif}
{$ifdef LINUX }
const
ResStringTableLen = 16;
type
ResStringTable = array [0..ResStringTableLen-1] of LongWord;
var
Handle: TResourceHandle;
Tab: ^ResStringTable;
ResMod: HMODULE;
{$endif}
begin
if ResStringRec=nil then
exit;
if ResStringRec.Identifier>=64*1024 then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('LoadResString was given an invalid ResStringRec.Identifier');
{$endif}
Result:=PChar(ResStringRec.Identifier);
exit;
end else begin
{$ifdef LINUX}
// This works with Unicode if the Linux has utf-8 character set
// Result:=System.LoadResString(ResStringRec);
ResMod:=FindResourceHInstance(ResStringRec^.Module^);
Handle:=FindResource(ResMod,
PChar(ResStringRec^.Identifier div ResStringTableLen), PChar(6)); // RT_STRING
Tab:=Pointer(LoadResource(ResMod, Handle));
if Tab=nil then
Result:=''
else
Result:=PWideChar(PChar(Tab)+Tab[ResStringRec^.Identifier mod ResStringTableLen]);
{$endif}
{$ifdef MSWINDOWS}
if not Win32PlatformIsUnicode then begin
SetString(Result, Buffer,
LoadString(FindResourceHInstance(ResStringRec.Module^),
ResStringRec.Identifier, Buffer, SizeOf(Buffer)))
end else begin
Result := '';
Len := 0;
While Len = Length(Result) do begin
if Length(Result) = 0 then
SetLength(Result, 1024)
else
SetLength(Result, Length(Result) * 2);
Len := LoadStringW(FindResourceHInstance(ResStringRec.Module^),
ResStringRec.Identifier, PWideChar(Result), Length(Result));
end;
SetLength(Result, Len);
end;
{$endif}
end;
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Loaded resourcestring: '+utf8encode(Result));
{$endif}
if CreatorThread<>GetCurrentThreadId then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('LoadResString was called from an invalid thread. Resourcestring was not translated.');
{$endif}
end else
Result:=ResourceStringGettext(Result);
end;
{$endif}
procedure TGnuGettextInstance.RetranslateComponent(AnObject: TComponent;
TextDomain: ansistring);
var
comp:TGnuGettextComponentMarker;
begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('======================================================================');
DebugWriteln ('RetranslateComponent() was called for a component with name '+AnObject.Name+'.');
{$endif}
comp:=AnObject.FindComponent('GNUgettextMarker') as TGnuGettextComponentMarker;
if comp=nil then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Retranslate was called on an object that has not been translated before. An Exception is being raised.');
{$endif}
raise EGGProgrammingError.Create ('Retranslate was called on an object that has not been translated before. Please use TranslateComponent() before RetranslateComponent().');
end else begin
if comp.LastLanguage<>curlang then begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('The retranslator is being executed.');
{$endif}
comp.Retranslator.Execute;
end else begin
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('The language has not changed. The retranslator is not executed.');
{$endif}
end;
end;
comp.LastLanguage:=curlang;
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('======================================================================');
{$endif}
end;
procedure TGnuGettextInstance.TP_IgnoreClass(IgnClass: TClass);
var
cm:TClassMode;
i:integer;
begin
for i:=0 to TP_ClassHandling.Count-1 do begin
cm:=TObject(TP_ClassHandling.Items[i]) as TClassMode;
if cm.HClass=IgnClass then
raise EGGProgrammingError.Create ('You cannot add a class to the ignore list that is already on that list: '+IgnClass.ClassName+'.');
if IgnClass.InheritsFrom(cm.HClass) then begin
// This is the place to insert this class
cm:=TClassMode.Create;
cm.HClass:=IgnClass;
TP_ClassHandling.Insert(i,cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Locally, class '+IgnClass.ClassName+' is being ignored.');
{$endif}
exit;
end;
end;
cm:=TClassMode.Create;
cm.HClass:=IgnClass;
TP_ClassHandling.Add(cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Locally, class '+IgnClass.ClassName+' is being ignored.');
{$endif}
end;
procedure TGnuGettextInstance.TP_IgnoreClassProperty(IgnClass: TClass;
propertyname: ansistring);
var
cm:TClassMode;
i:integer;
begin
propertyname:=uppercase(propertyname);
for i:=0 to TP_ClassHandling.Count-1 do begin
cm:=TObject(TP_ClassHandling.Items[i]) as TClassMode;
if cm.HClass=IgnClass then begin
if Assigned(cm.SpecialHandler) then
raise EGGProgrammingError.Create ('You cannot ignore a class property for a class that has a handler set.');
cm.PropertiesToIgnore.Add(propertyname);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Globally, the '+propertyname+' property of class '+IgnClass.ClassName+' is being ignored.');
{$endif}
exit;
end;
if IgnClass.InheritsFrom(cm.HClass) then begin
// This is the place to insert this class
cm:=TClassMode.Create;
cm.HClass:=IgnClass;
cm.PropertiesToIgnore.Add(propertyname);
TP_ClassHandling.Insert(i,cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Locally, the '+propertyname+' property of class '+IgnClass.ClassName+' is being ignored.');
{$endif}
exit;
end;
end;
cm:=TClassMode.Create;
cm.HClass:=IgnClass;
cm.PropertiesToIgnore.Add(propertyname);
TP_GlobalClassHandling.Add(cm);
{$ifdef DXGETTEXTDEBUG}
DebugWriteln ('Locally, the '+propertyname+' property of class '+IgnClass.ClassName+' is being ignored.');
{$endif}
end;
procedure TGnuGettextInstance.FreeTP_ClassHandlingItems;
begin
while TP_ClassHandling.Count<>0 do begin
TObject(TP_ClassHandling.Items[0]).Free;
TP_ClassHandling.Delete(0);
end;
end;
function TGnuGettextInstance.ansi2wide(s: ansistring): widestring;
{$ifdef MSWindows}
var
len:integer;
{$endif}
begin
{$ifdef MSWindows}
if DesignTimeCodePage=CP_ACP then begin
// No design-time codepage specified. Using runtime codepage instead.
{$endif}
Result:=s;
{$ifdef MSWindows}
end else begin
len:=length(s);
if len=0 then
Result:=''
else begin
SetLength (Result,len);
len:=MultiByteToWideChar(DesignTimeCodePage,0,pchar(s),len,pwidechar(Result),len);
if len=0 then
raise EGGAnsi2WideConvError.Create ('Cannot convert ansistring to widestring:'+sLineBreak+s);
SetLength (Result,len);
end;
end;
{$endif}
end;
{$ifndef DELPHI5OROLDER}
function TGnuGettextInstance.dngettext(const szDomain: ansistring; singular,
plural: ansistring; Number: Integer): widestring;
begin
Result:=dngettext (szDomain, ansi2wide(singular), ansi2wide(plural), Number);
end;
{$endif}
{ TClassMode }
constructor TClassMode.Create;
begin
inherited;
PropertiesToIgnore:=TStringList.Create;
PropertiesToIgnore.Sorted:=True;
PropertiesToIgnore.Duplicates:=dupError;
{$ifndef DELPHI5OROLDER}
PropertiesToIgnore.CaseSensitive:=False;
{$endif}
end;
destructor TClassMode.Destroy;
begin
FreeAndNil (PropertiesToIgnore);
inherited;
end;
{ TFileLocator }
procedure TFileLocator.Analyze;
var
s:ansistring;
i:integer;
offset:int64;
fs:TFileStream;
fi:TEmbeddedFileInfo;
filename:ansistring;
begin
s:='6637DB2E-62E1-4A60-AC19-C23867046A89'#0#0#0#0#0#0#0#0;
s:=copy(s,length(s)-7,8);
offset:=0;
for i:=8 downto 1 do
offset:=offset shl 8+ord(s[i]);
if offset=0 then
exit;
BaseDirectory:=ExtractFilePath(ExecutableFilename);
try
fs:=TFileStream.Create(ExecutableFilename,fmOpenRead or fmShareDenyNone);
try
while true do begin
fs.Seek(offset,soFromBeginning);
offset:=ReadInt64(fs);
if offset=0 then
exit;
fi:=TEmbeddedFileInfo.Create;
try
fi.Offset:=ReadInt64(fs);
fi.Size:=ReadInt64(fs);
SetLength (filename, offset-fs.position);
fs.ReadBuffer (filename[1],offset-fs.position);
filename:=trim(filename);
filelist.AddObject(filename,fi);
except
FreeAndNil (fi);
raise;
end;
end;
finally
FreeAndNil (fs);
end;
except
{$ifdef DXGETTEXTDEBUG}
raise;
{$endif}
end;
end;
constructor TFileLocator.Create;
begin
inherited;
MoFilesCS:=TMultiReadExclusiveWriteSynchronizer.Create;
MoFiles:=TStringList.Create;
filelist:=TStringList.Create;
{$ifdef LINUX}
filelist.Duplicates:=dupError;
filelist.CaseSensitive:=True;
{$endif}
MoFiles.Sorted:=True;
{$ifndef DELPHI5OROLDER}
MoFiles.Duplicates:=dupError;
MoFiles.CaseSensitive:=False;
{$ifdef MSWINDOWS}
filelist.Duplicates:=dupError;
filelist.CaseSensitive:=False;
{$endif}
{$endif}
filelist.Sorted:=True;
end;
destructor TFileLocator.Destroy;
begin
while filelist.count<>0 do begin
filelist.Objects[0].Free;
filelist.Delete (0);
end;
FreeAndNil (filelist);
FreeAndNil (MoFiles);
FreeAndNil (MoFilesCS);
inherited;
end;
function TFileLocator.FileExists(filename: string): boolean;
var
idx:integer;
begin
if copy(filename,1,length(basedirectory))=basedirectory then
filename:=copy(filename,length(basedirectory)+1,maxint);
Result:=filelist.Find(filename,idx);
end;
function TFileLocator.GetMoFile(filename: string; DebugLogger:TDebugLogger): TMoFile;
var
fi:TEmbeddedFileInfo;
idx:integer;
idxname:string;
Offset, Size: Int64;
realfilename:string;
begin
// Find real filename
offset:=0;
size:=0;
realfilename:=filename;
if copy(filename,1,length(basedirectory))=basedirectory then begin
filename:=copy(filename,length(basedirectory)+1,maxint);
idx:=filelist.IndexOf(filename);
if idx<>-1 then begin
fi:=filelist.Objects[idx] as TEmbeddedFileInfo;
realfilename:=ExecutableFilename;
offset:=fi.offset;
size:=fi.size;
{$ifdef DXGETTEXTDEBUG}
DebugLogger ('Instead of '+filename+', using '+realfilename+' from offset '+IntTostr(offset)+', size '+IntToStr(size));
{$endif}
end;
end;
{$ifdef DXGETTEXTDEBUG}
DebugLogger ('Reading .mo data from file '''+filename+'''');
{$endif}
// Find TMoFile object
MoFilesCS.BeginWrite;
try
idxname:=realfilename+#0+IntToStr(offset);
if MoFiles.Find(idxname, idx) then begin
Result:=MoFiles.Objects[idx] as TMoFile;
end else begin
Result:=TMoFile.Create (realfilename, Offset, Size);
MoFiles.AddObject(idxname, Result);
end;
Inc (Result.Users);
finally
MoFilesCS.EndWrite;
end;
end;
function TFileLocator.ReadInt64(str: TStream): int64;
begin
Assert (sizeof(Result)=8);
str.ReadBuffer(Result,8);
end;
procedure TFileLocator.ReleaseMoFile(mofile: TMoFile);
var
i:integer;
begin
Assert (mofile<>nil);
MoFilesCS.BeginWrite;
try
dec (mofile.Users);
if mofile.Users<=0 then begin
i:=MoFiles.Count-1;
while i>=0 do begin
if MoFiles.Objects[i]=mofile then begin
MoFiles.Delete(i);
FreeAndNil (mofile);
break;
end;
dec (i);
end;
end;
finally
MoFilesCS.EndWrite;
end;
end;
{ TTP_Retranslator }
constructor TTP_Retranslator.Create;
begin
inherited;
list:=TList.Create;
end;
destructor TTP_Retranslator.Destroy;
var
i:integer;
begin
for i:=0 to list.Count-1 do
TObject(list.Items[i]).Free;
FreeAndNil (list);
inherited;
end;
procedure TTP_Retranslator.Execute;
var
i:integer;
sl:TStrings;
item:TTP_RetranslatorItem;
newvalue:WideString;
{$ifndef DELPHI5OROLDER}
ppi:PPropInfo;
{$endif}
begin
for i:=0 to list.Count-1 do begin
item:=TObject(list.items[i]) as TTP_RetranslatorItem;
if item.obj is TStrings then begin
// Since we don't know the order of items in sl, and don't have
// the original .Objects[] anywhere, we cannot anticipate anything
// about the current sl.Strings[] and sl.Objects[] values. We therefore
// have to discard both values. We can, however, set the original .Strings[]
// value into the list and retranslate that.
sl:=TStringList.Create;
try
sl.Text:=item.OldValue;
Instance.TranslateStrings(sl,textdomain);
(item.obj as TStrings).BeginUpdate;
try
(item.obj as TStrings).Text:=sl.Text;
finally
(item.obj as TStrings).EndUpdate;
end;
finally
FreeAndNil (sl);
end;
end else begin
newValue:=instance.dgettext(textdomain,item.OldValue);
{$ifdef DELPHI5OROLDER}
SetStrProp(item.obj, item.PropName, newValue);
{$endif}
{$ifndef DELPHI5OROLDER}
ppi:=GetPropInfo(item.obj, item.Propname);
if ppi<>nil then begin
SetWideStrProp(item.obj, ppi, newValue);
end else begin
{$ifdef DXGETTEXTDEBUG}
Instance.DebugWriteln ('ERROR: On retranslation, property disappeared: '+item.Propname+' for object of type '+item.obj.ClassName);
{$endif}
end;
{$endif}
end;
end;
end;
procedure TTP_Retranslator.Remember(obj: TObject; PropName: ansistring;
OldValue: WideString);
var
item:TTP_RetranslatorItem;
begin
item:=TTP_RetranslatorItem.Create;
item.obj:=obj;
item.Propname:=Propname;
item.OldValue:=OldValue;
list.Add(item);
end;
{ TGnuGettextComponentMarker }
destructor TGnuGettextComponentMarker.Destroy;
begin
FreeAndNil (Retranslator);
inherited;
end;
{$ifndef CLR}
{ THook }
constructor THook.Create(OldProcedure, NewProcedure: pointer; FollowJump:boolean=false);
{ Idea and original code from Igor Siticov }
{ Modified by Jacques Garcia Vazquez and Lars Dybdahl }
begin
{$ifndef CPU386}
'This procedure only works on Intel i386 compatible processors.'
{$endif}
oldproc:=OldProcedure;
newproc:=NewProcedure;
Reset (FollowJump);
end;
destructor THook.Destroy;
begin
Shutdown;
inherited;
end;
procedure THook.Disable;
begin
Assert (PatchPosition<>nil,'Patch position in THook was nil when Disable was called');
PatchPosition[0]:=Original[0];
PatchPosition[1]:=Original[1];
PatchPosition[2]:=Original[2];
PatchPosition[3]:=Original[3];
PatchPosition[4]:=Original[4];
end;
procedure THook.Enable;
begin
Assert (PatchPosition<>nil,'Patch position in THook was nil when Enable was called');
PatchPosition[0]:=Patch[0];
PatchPosition[1]:=Patch[1];
PatchPosition[2]:=Patch[2];
PatchPosition[3]:=Patch[3];
PatchPosition[4]:=Patch[4];
end;
procedure THook.Reset(FollowJump: boolean);
var
offset:integer;
{$ifdef LINUX}
p:pointer;
pagesize:integer;
{$endif}
{$ifdef MSWindows}
ov: cardinal;
{$endif}
begin
if PatchPosition<>nil then
Shutdown;
patchPosition := OldProc;
if FollowJump and (Word(OldProc^) = $25FF) then begin
// This finds the correct procedure if a virtual jump has been inserted
// at the procedure address
Inc(Integer(patchPosition), 2); // skip the jump
patchPosition := pChar(Pointer(pointer(patchPosition)^)^);
end;
offset:=integer(NewProc)-integer(pointer(patchPosition))-5;
Patch[0] := ansichar($E9);
Patch[1] := ansichar(offset and 255);
Patch[2] := ansichar((offset shr 8) and 255);
Patch[3] := ansichar((offset shr 16) and 255);
Patch[4] := ansichar((offset shr 24) and 255);
Original[0]:=PatchPosition[0];
Original[1]:=PatchPosition[1];
Original[2]:=PatchPosition[2];
Original[3]:=PatchPosition[3];
Original[4]:=PatchPosition[4];
{$ifdef MSWINDOWS}
if not VirtualProtect(Pointer(PatchPosition), 5, PAGE_EXECUTE_READWRITE, @ov) then
RaiseLastOSError;
{$endif}
{$ifdef LINUX}
pageSize:=sysconf (_SC_PAGE_SIZE);
p:=pointer(PatchPosition);
p:=pointer((integer(p) + PAGESIZE-1) and not (PAGESIZE-1) - pageSize);
if mprotect (p, pageSize, PROT_READ + PROT_WRITE + PROT_EXEC) <> 0 then
RaiseLastOSError;
{$endif}
end;
procedure THook.Shutdown;
begin
Disable;
PatchPosition:=nil;
end;
{$endif}
procedure HookIntoResourceStrings (enabled:boolean=true; SupportPackages:boolean=false);
begin
{$ifndef CLR}
HookLoadResString.Reset (SupportPackages);
HookLoadStr.Reset (SupportPackages);
HookFmtLoadStr.Reset (SupportPackages);
if enabled then begin
HookLoadResString.Enable;
HookLoadStr.Enable;
HookFmtLoadStr.Enable;
end;
{$endif}
end;
{ TMoFile }
constructor TMoFile.Create(filename: ansistring; Offset,Size:int64);
var
i:cardinal;
nn:integer;
{$ifndef windows}
mofile:TFileStream;
{$endif}
begin
inherited Create;
if sizeof(i) <> 4 then
raise EGGProgrammingError.Create('TDomain in gnugettext is written for an architecture that has 32 bit integers.');
// Read the whole file into memory
mofile:=TFileStream.Create (filename, fmOpenRead or fmShareDenyNone);
try
if size=0 then
size:=mofile.Size;
setlength (momemory,size);
mofile.Seek(offset,soFromBeginning);
{$ifdef CLR}
mofile.ReadBuffer(momemory,size);
{$else}
mofile.ReadBuffer(momemory[0],size);
{$endif}
finally
FreeAndNil (mofile);
end;
// Check the magic number
doswap:=False;
i:=CardinalInMem(0);
if (i <> $950412DE) and (i <> $DE120495) then
EGGIOError.Create('This file is not a valid GNU gettext mo file: ' + filename);
doswap := (i = $DE120495);
// Find the positions in the file according to the file format spec
CardinalInMem(4); // Read the version number, but don't use it for anything.
N:=CardinalInMem(8); // Get ansistring count
O:=CardinalInMem(12); // Get offset of original strings
T:=CardinalInMem(16); // Get offset of translated strings
// Calculate start conditions for a binary search
nn := N;
startindex := 1;
while nn <> 0 do begin
nn := nn shr 1;
startindex := startindex shl 1;
end;
startindex := startindex shr 1;
startstep := startindex shr 1;
end;
function TMoFile.CardinalInMem (Offset: Cardinal): Cardinal;
begin
if doswap then begin
Result:=
momemory[Offset]+
(momemory[Offset+1] shl 8)+
(momemory[Offset+2] shl 16)+
(momemory[Offset+3] shl 24);
end else begin
Result:=
(momemory[Offset] shl 24)+
(momemory[Offset+1] shl 16)+
(momemory[Offset+2] shl 8)+
momemory[Offset+3];
end;
end;
function TMoFile.gettext(msgid: ansistring;var found:boolean): ansistring;
var
i, j, step: cardinal;
offset, pos: cardinal;
CompareResult:integer;
msgidptr,a,b:integer;
abidx:integer;
size, msgidsize:integer;
begin
found:=false;
msgidptr:=1;
msgidsize:=length(msgid);
// Do binary search
i:=startindex;
step:=startstep;
while true do begin
// Get string for index i
pos:=O+8*(i-1);
offset:=CardinalInMem (pos+4);
size:=CardinalInMem (pos);
a:=msgidptr;
b:=offset;
abidx:=size;
if msgidsize<abidx then
abidx:=msgidsize;
CompareResult:=0;
while abidx<>0 do begin
CompareResult:=integer(byte(msgid[a]))-integer(momemory[b]);
if CompareResult<>0 then
break;
dec (abidx);
inc (a);
inc (b);
end;
if CompareResult=0 then
CompareResult:=msgidsize-size;
if CompareResult=0 then begin // msgid=s
// Found the msgid
pos:=T+8*(i-1);
offset:=CardinalInMem (pos+4);
size:=CardinalInMem (pos);
SetLength (Result,size);
for j:=0 to size-1 do
Result[j+1]:=ansichar(momemory[offset+j]);
found:=True;
break;
end;
if step=0 then begin
// Not found
Result:=msgid;
break;
end;
if CompareResult<0 then begin // msgid<s
if i < 1+step then
i := 1
else
i := i - step;
step := step shr 1;
end else begin // msgid>s
i := i + step;
if i > N then
i := N;
step := step shr 1;
end;
end;
end;
initialization
{$ifdef DXGETTEXTDEBUG}
{$ifdef MSWINDOWS}
MessageBox (0,'gnugettext.pas debugging is enabled. Turn it off before releasing this piece of software.','Information',MB_OK);
{$endif}
{$ifdef LINUX}
writeln (stderr,'gnugettext.pas debugging is enabled. Turn it off before releasing this piece of software.');
{$endif}
{$endif}
if IsLibrary then begin
// Get DLL/shared object filename
SetLength (ExecutableFilename,300);
{$ifdef MSWINDOWS}
SetLength (ExecutableFilename,GetModuleFileName(HInstance, PChar(ExecutableFilename), length(ExecutableFilename)));
{$endif}
{$ifdef LINUX}
// This line has not been tested on Linux, yet, but should work.
SetLength (ExecutableFilename,GetModuleFileName(0, PChar(ExecutableFilename), length(ExecutableFilename)));
{$endif}
{$ifdef CLR}
{ TODO : Find a way to implement this with CLR }
{$endif}
end else
ExecutableFilename:=Paramstr(0);
FileLocator:=TFileLocator.Create;
FileLocator.Analyze;
ResourceStringDomainList:=TStringList.Create;
ResourceStringDomainList.Add(DefaultTextDomain);
ResourceStringDomainListCS:=TMultiReadExclusiveWriteSynchronizer.Create;
DefaultInstance:=TGnuGettextInstance.Create;
{$ifdef MSWINDOWS}
Win32PlatformIsUnicode := (Win32Platform = VER_PLATFORM_WIN32_NT);
{$endif}
// replace Borlands LoadResString with gettext enabled version:
{$ifndef CLR}
HookLoadResString:=THook.Create (@system.LoadResString, @LoadResStringA);
HookLoadStr:=THook.Create (@sysutils.LoadStr, @SysUtilsLoadStr);
HookFmtLoadStr:=THook.Create (@sysutils.FmtLoadStr, @SysUtilsFmtLoadStr);
HookIntoResourceStrings (AutoCreateHooks,false);
{$endif}
finalization
FreeAndNil (DefaultInstance);
FreeAndNil (ResourceStringDomainListCS);
FreeAndNil (ResourceStringDomainList);
{$ifndef CLR}
FreeAndNil (HookFmtLoadStr);
FreeAndNil (HookLoadStr);
FreeAndNil (HookLoadResString);
{$endif}
FreeAndNil (FileLocator);
end.
|