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
|
{
This file is part of the Free Component Library (FCL)
Copyright (c) 1999-2000 by Michael Van Canneyt and Florian Klaempfl
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**********************************************************************}
{**********************************************************************
* Class implementations are in separate files. *
**********************************************************************}
type
{$ifdef CPU16}
TFilerFlagsInt = Byte;
{$else CPU16}
TFilerFlagsInt = LongInt;
{$endif CPU16}
var
ClassList : TThreadlist;
ClassAliasList : TStringList;
{
Include all message strings
Add a language with IFDEF LANG_NAME
just befor the final ELSE. This way English will always be the default.
}
{$IFDEF LANG_GERMAN}
{$i constsg.inc}
{$ELSE}
{$IFDEF LANG_SPANISH}
{$i constss.inc}
{$ENDIF}
{$ENDIF}
{ Utility routines }
{$i util.inc}
{ TBits implementation }
{$i bits.inc}
{ All streams implementations: }
{ Tstreams THandleStream TFileStream TResourcseStreams TStringStream }
{ TCustomMemoryStream TMemoryStream }
{$i streams.inc}
{ TParser implementation}
{$i parser.inc}
{ TCollection and TCollectionItem implementations }
{$i collect.inc}
{ TList and TThreadList implementations }
{$i lists.inc}
{ TStrings and TStringList implementations }
{$i stringl.inc}
{ TThread implementation }
{ system independend threading code }
var
{ event executed by SychronizeInternal to wake main thread if it sleeps in
CheckSynchronize }
SynchronizeTimeoutEvent: PRtlEvent;
{ the head of the queue containing the entries to be Synchronized - Nil if the
queue is empty }
ThreadQueueHead: TThread.PThreadQueueEntry;
{ the tail of the queue containing the entries to be Synchronized - Nil if the
queue is empty }
ThreadQueueTail: TThread.PThreadQueueEntry;
{ used for serialized access to the queue }
ThreadQueueLock: TRtlCriticalSection;
{ usage counter for ThreadQueueLock }
ThreadQueueLockCounter : longint;
{ this list holds all instances of external threads that need to be freed at
the end of the program }
ExternalThreads: TThreadList;
{ this list signals that the ExternalThreads list is cleared and thus the
thread instances don't need to remove themselves }
ExternalThreadsCleanup: Boolean = False;
{ this must be a global var, otherwise unwanted optimizations might happen in
TThread.SpinWait() }
SpinWaitDummy: LongWord;
{$ifdef FPC_HAS_FEATURE_THREADING}
threadvar
{$else}
var
{$endif}
{ the instance of the current thread; in case of an external thread this is
Nil until TThread.GetCurrentThread was called once (the RTLs need to ensure
that threadvars are initialized with 0!) }
CurrentThreadVar: TThread;
type
{ this type is used if a thread is created using
TThread.CreateAnonymousThread }
TAnonymousThread = class(TThread)
private
fProc: TProcedure;
protected
procedure Execute; override;
public
{ as in TThread aProc needs to be changed to TProc once closures are
supported }
constructor Create(aProc: TProcedure);
end;
procedure TAnonymousThread.Execute;
begin
fProc();
end;
constructor TAnonymousThread.Create(aProc: TProcedure);
begin
{ an anonymous thread is created suspended and with FreeOnTerminate set }
inherited Create(True);
FreeOnTerminate := True;
fProc := aProc;
end;
type
{ this type is used by TThread.GetCurrentThread if the thread does not yet
have a value in CurrentThreadVar (Note: the main thread is also created as
a TExternalThread) }
TExternalThread = class(TThread)
protected
{ dummy method to remove the warning }
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
end;
procedure TExternalThread.Execute;
begin
{ empty }
end;
constructor TExternalThread.Create;
begin
FExternalThread := True;
{ the parameter is unimportant if FExternalThread is True }
inherited Create(False);
with ExternalThreads.LockList do
try
Add(Self);
finally
ExternalThreads.UnlockList;
end;
end;
destructor TExternalThread.Destroy;
begin
inherited;
if not ExternalThreadsCleanup then
with ExternalThreads.LockList do
try
Extract(Self);
finally
ExternalThreads.UnlockList;
end;
end;
function ThreadProc(ThreadObjPtr: Pointer): PtrInt;
var
FreeThread: Boolean;
Thread: TThread absolute ThreadObjPtr;
begin
{ if Suspend checks FSuspended before doing anything, make sure it }
{ knows we're currently not suspended (this flag may have been set }
{ to true if CreateSuspended was true) }
// Thread.FSuspended:=false;
// wait until AfterConstruction has been called, so we cannot
// free ourselves before TThread.Create has finished
// (since that one may check our VTM in case of $R+, and
// will call the AfterConstruction method in all cases)
// Thread.Suspend;
try
{ The thread may be already terminated at this point, e.g. if it was intially
suspended, or if it wasn't ever scheduled for execution for whatever reason.
So bypass user code if terminated. }
if not Thread.Terminated then begin
CurrentThreadVar := Thread;
Thread.Execute;
end;
except
Thread.FFatalException := TObject(AcquireExceptionObject);
end;
FreeThread := Thread.FFreeOnTerminate;
Result := Thread.FReturnValue;
Thread.FFinished := True;
Thread.DoTerminate;
if FreeThread then
Thread.Free;
{$ifdef FPC_HAS_FEATURE_THREADING}
EndThread(Result);
{$endif}
end;
{ system-dependent code }
{$i tthread.inc}
constructor TThread.Create(CreateSuspended: Boolean;
const StackSize: SizeUInt);
begin
inherited Create;
{$ifdef FPC_HAS_FEATURE_THREADING}
InterlockedIncrement(ThreadQueueLockCounter);
{$endif}
if FExternalThread then
{$ifdef FPC_HAS_FEATURE_THREADING}
FThreadID := GetCurrentThreadID
{$else}
FThreadID := 0{GetCurrentThreadID}
{$endif}
else
SysCreate(CreateSuspended, StackSize);
end;
destructor TThread.Destroy;
begin
if not FExternalThread then begin
SysDestroy;
{$ifdef FPC_HAS_FEATURE_THREADING}
if FHandle <> TThreadID(0) then
CloseThread(FHandle);
{$endif}
end;
RemoveQueuedEvents(Self);
DoneSynchronizeEvent;
{$ifdef FPC_HAS_FEATURE_THREADING}
if InterlockedDecrement(ThreadQueueLockCounter)=0 then
DoneCriticalSection(ThreadQueueLock);
{$endif}
{ set CurrentThreadVar to Nil? }
inherited Destroy;
end;
procedure TThread.Start;
begin
{ suspend/resume are now deprecated in Delphi (they also don't work
on most platforms in FPC), so a different method was required
to start a thread if it's create with fSuspended=true -> that's
what this method is for. }
Resume;
end;
function TThread.GetSuspended: Boolean;
begin
GetSuspended:=FSuspended;
end;
Procedure TThread.TerminatedSet;
begin
// Empty, must be overridden.
end;
procedure TThread.AfterConstruction;
begin
inherited AfterConstruction;
// enable for all platforms once http://bugs.freepascal.org/view.php?id=16884
// is fixed for all platforms (in case the fix for non-unix platforms also
// requires this field at least)
{$if defined(unix) or defined(windows) or defined(os2) or defined(hasamiga)}
if not FExternalThread and not FInitialSuspended then
Resume;
{$endif}
end;
procedure ExecuteThreadQueueEntry(aEntry: TThread.PThreadQueueEntry);
begin
if Assigned(aEntry^.Method) then
aEntry^.Method()
// enable once closures are supported
{else
aEntry^.ThreadProc();}
end;
procedure ThreadQueueAppend(aEntry: TThread.PThreadQueueEntry; aQueueIfMain: Boolean);
var
thd: TThread;
issync: Boolean;
begin
{ do we really need a synchronized call? }
{$ifdef FPC_HAS_FEATURE_THREADING}
if (GetCurrentThreadID = MainThreadID) and (not aQueueIfMain or not IsMultiThread) then
{$endif}
begin
try
ExecuteThreadQueueEntry(aEntry);
finally
if not Assigned(aEntry^.SyncEvent) then
Dispose(aEntry);
end;
{$ifdef FPC_HAS_FEATURE_THREADING}
end else begin
{ store thread and whether we're dealing with a synchronized event; the
event record itself might already be freed after the ThreadQueueLock is
released (in case of a Queue() call; for a Synchronize() call the record
will stay valid, thus accessing SyncEvent later on (if issync is true) is
okay) }
thd := aEntry^.Thread;
issync := Assigned(aEntry^.SyncEvent);
System.EnterCriticalSection(ThreadQueueLock);
try
{ add the entry to the thread queue }
if Assigned(ThreadQueueTail) then begin
ThreadQueueTail^.Next := aEntry;
end else
ThreadQueueHead := aEntry;
ThreadQueueTail := aEntry;
finally
System.LeaveCriticalSection(ThreadQueueLock);
end;
{ ensure that the main thread knows that something awaits }
RtlEventSetEvent(SynchronizeTimeoutEvent);
if assigned(WakeMainThread) then
WakeMainThread(thd);
{ is this a Synchronize or Queue entry? }
if issync then begin
RtlEventWaitFor(aEntry^.SyncEvent);
if Assigned(aEntry^.Exception) then
raise aEntry^.Exception;
end;
{$endif def FPC_HAS_FEATURE_THREADING}
end;
end;
procedure TThread.InitSynchronizeEvent;
begin
if Assigned(FSynchronizeEntry) then
Exit;
New(FSynchronizeEntry);
FillChar(FSynchronizeEntry^, SizeOf(TThreadQueueEntry), 0);
FSynchronizeEntry^.Thread := Self;
FSynchronizeEntry^.ThreadID := ThreadID;
{$ifdef FPC_HAS_FEATURE_THREADING}
FSynchronizeEntry^.SyncEvent := RtlEventCreate;
{$else}
FSynchronizeEntry^.SyncEvent := nil{RtlEventCreate};
{$endif}
end;
procedure TThread.DoneSynchronizeEvent;
begin
if not Assigned(FSynchronizeEntry) then
Exit;
{$ifdef FPC_HAS_FEATURE_THREADING}
RtlEventDestroy(FSynchronizeEntry^.SyncEvent);
{$endif}
Dispose(FSynchronizeEntry);
FSynchronizeEntry := Nil;
end;
class procedure TThread.Synchronize(AThread: TThread; AMethod: TThreadMethod);
var
syncentry: PThreadQueueEntry;
thread: TThread;
begin
{$ifdef FPC_HAS_FEATURE_THREADING}
if Assigned(AThread) and (AThread.ThreadID = GetCurrentThreadID) then
{$else}
if Assigned(AThread) then
{$endif}
thread := AThread
else if Assigned(CurrentThreadVar) then
thread := CurrentThreadVar
else begin
thread := Nil;
{ use a local synchronize event }
New(syncentry);
FillChar(syncentry^, SizeOf(TThreadQueueEntry), 0);
{$ifdef FPC_HAS_FEATURE_THREADING}
syncentry^.ThreadID := GetCurrentThreadID;
syncentry^.SyncEvent := RtlEventCreate;
{$else}
syncentry^.ThreadID := 0{GetCurrentThreadID};
syncentry^.SyncEvent := nil{RtlEventCreate};
{$endif}
end;
if Assigned(thread) then begin
{ the Synchronize event is instantiated on demand }
thread.InitSynchronizeEvent;
syncentry := thread.FSynchronizeEntry;
end;
syncentry^.Exception := Nil;
syncentry^.Method := AMethod;
try
ThreadQueueAppend(syncentry, False);
finally
syncentry^.Method := Nil;
syncentry^.Next := Nil;
if not Assigned(thread) then begin
{ clean up again }
{$ifdef FPC_HAS_FEATURE_THREADING}
RtlEventDestroy(syncentry^.SyncEvent);
{$endif}
Dispose(syncentry);
end;
end;
end;
procedure TThread.Synchronize(AMethod: TThreadMethod);
begin
TThread.Synchronize(self,AMethod);
end;
Function PopThreadQueueHead : TThread.PThreadQueueEntry;
begin
Result:=ThreadQueueHead;
if (Result<>Nil) then
begin
{$ifdef FPC_HAS_FEATURE_THREADING}
System.EnterCriticalSection(ThreadQueueLock);
try
{$endif}
Result:=ThreadQueueHead;
if Result<>Nil then
ThreadQueueHead:=ThreadQueueHead^.Next;
if Not Assigned(ThreadQueueHead) then
ThreadQueueTail := Nil;
{$ifdef FPC_HAS_FEATURE_THREADING}
finally
System.LeaveCriticalSection(ThreadQueueLock);
end;
{$endif}
end;
end;
function CheckSynchronize(timeout : longint=0) : boolean;
{ assumes being called from GUI thread }
var
ExceptObj: TObject;
tmpentry: TThread.PThreadQueueEntry;
begin
result:=false;
{ first sanity check }
if Not IsMultiThread then
Exit
{$ifdef FPC_HAS_FEATURE_THREADING}
{ second sanity check }
else if GetCurrentThreadID<>MainThreadID then
raise EThread.CreateFmt(SCheckSynchronizeError,[GetCurrentThreadID]);
if timeout>0 then
RtlEventWaitFor(SynchronizeTimeoutEvent,timeout)
else
RtlEventResetEvent(SynchronizeTimeoutEvent);
tmpentry := PopThreadQueueHead;
while Assigned(tmpentry) do
begin
{ step 2: execute the method }
exceptobj := Nil;
try
ExecuteThreadQueueEntry(tmpentry);
except
exceptobj := TObject(AcquireExceptionObject);
end;
{ step 3: error handling and cleanup }
if Assigned(tmpentry^.SyncEvent) then
begin
{ for Synchronize entries we pass back the Exception and trigger
the event that Synchronize waits in }
tmpentry^.Exception := exceptobj;
RtlEventSetEvent(tmpentry^.SyncEvent)
end
else
begin
{ for Queue entries we dispose the entry and raise the exception }
Dispose(tmpentry);
if Assigned(exceptobj) then
raise exceptobj;
end;
tmpentry := PopThreadQueueHead;
end
{$endif};
end;
class function TThread.GetCurrentThread: TThread;
begin
{ if this is the first time GetCurrentThread is called for an external thread
we need to create a corresponding TExternalThread instance }
Result := CurrentThreadVar;
if not Assigned(Result) then begin
Result := TExternalThread.Create;
CurrentThreadVar := Result;
end;
end;
class function TThread.GetIsSingleProcessor: Boolean;
begin
Result := FProcessorCount <= 1;
end;
procedure TThread.Queue(aMethod: TThreadMethod);
begin
Queue(Self, aMethod);
end;
class procedure TThread.Queue(aThread: TThread; aMethod: TThreadMethod); static;
begin
InternalQueue(aThread, aMethod, False);
end;
class procedure TThread.InternalQueue(aThread: TThread; aMethod: TThreadMethod; aQueueIfMain: Boolean); static;
var
queueentry: PThreadQueueEntry;
begin
New(queueentry);
FillChar(queueentry^, SizeOf(TThreadQueueEntry), 0);
queueentry^.Thread := aThread;
{$ifdef FPC_HAS_FEATURE_THREADING}
queueentry^.ThreadID := GetCurrentThreadID;
{$else}
queueentry^.ThreadID := 0{GetCurrentThreadID};
{$endif}
queueentry^.Method := aMethod;
{ the queueentry is freed by CheckSynchronize (or by RemoveQueuedEvents) }
ThreadQueueAppend(queueentry, aQueueIfMain);
end;
procedure TThread.ForceQueue(aMethod: TThreadMethod);
begin
ForceQueue(Self, aMethod);
end;
class procedure TThread.ForceQueue(aThread: TThread; aMethod: TThreadMethod); static;
begin
InternalQueue(aThread, aMethod, True);
end;
class procedure TThread.RemoveQueuedEvents(aThread: TThread; aMethod: TThreadMethod);
var
entry, tmpentry, lastentry: PThreadQueueEntry;
begin
{ anything to do at all? }
if not Assigned(aThread) and not Assigned(aMethod) then
Exit;
{$ifdef FPC_HAS_FEATURE_THREADING}
System.EnterCriticalSection(ThreadQueueLock);
try
{$endif}
lastentry := Nil;
entry := ThreadQueueHead;
while Assigned(entry) do begin
if
{ only entries not added by Synchronize }
not Assigned(entry^.SyncEvent)
{ check for the thread }
and (not Assigned(aThread) or (entry^.Thread = aThread) or (entry^.ThreadID = aThread.ThreadID))
{ check for the method }
and (not Assigned(aMethod) or
(
(TMethod(entry^.Method).Code = TMethod(aMethod).Code) and
(TMethod(entry^.Method).Data = TMethod(aMethod).Data)
))
then begin
{ ok, we need to remove this entry }
tmpentry := entry;
if Assigned(lastentry) then
lastentry^.Next := entry^.Next;
entry := entry^.Next;
if ThreadQueueHead = tmpentry then
ThreadQueueHead := entry;
if ThreadQueueTail = tmpentry then
ThreadQueueTail := lastentry;
{ only dispose events added by Queue }
if not Assigned(tmpentry^.SyncEvent) then
Dispose(tmpentry);
end else begin
{ leave this entry }
lastentry := entry;
entry := entry^.Next;
end;
end;
{$ifdef FPC_HAS_FEATURE_THREADING}
finally
System.LeaveCriticalSection(ThreadQueueLock);
end;
{$endif}
end;
class procedure TThread.RemoveQueuedEvents(aMethod: TThreadMethod);
begin
RemoveQueuedEvents(Nil, aMethod);
end;
class procedure TThread.RemoveQueuedEvents(aThread: TThread);
begin
RemoveQueuedEvents(aThread, Nil);
end;
class function TThread.CheckTerminated: Boolean;
begin
{ this method only works with threads created by TThread, so we can make a
shortcut here }
if not Assigned(CurrentThreadVar) then
raise EThreadExternalException.Create(SThreadExternal);
Result := CurrentThreadVar.FTerminated;
end;
class procedure TThread.SetReturnValue(aValue: Integer);
begin
{ this method only works with threads created by TThread, so we can make a
shortcut here }
if not Assigned(CurrentThreadVar) then
raise EThreadExternalException.Create(SThreadExternal);
CurrentThreadVar.FReturnValue := aValue;
end;
class function TThread.CreateAnonymousThread(aProc: TProcedure): TThread;
begin
if not Assigned(aProc) then
raise Exception.Create(SNoProcGiven);
Result := TAnonymousThread.Create(aProc);
end;
class procedure TThread.NameThreadForDebugging(aThreadName: UnicodeString; aThreadID: TThreadID);
begin
{$ifdef FPC_HAS_FEATURE_THREADING}
SetThreadDebugName(aThreadID, aThreadName);
{$endif}
end;
class procedure TThread.NameThreadForDebugging(aThreadName: AnsiString; aThreadID: TThreadID);
begin
{$ifdef FPC_HAS_FEATURE_THREADING}
SetThreadDebugName(aThreadID, aThreadName);
{$endif}
end;
class procedure TThread.Yield;
begin
{$ifdef FPC_HAS_FEATURE_THREADING}
ThreadSwitch;
{$endif}
end;
class procedure TThread.Sleep(aMilliseconds: Cardinal);
begin
SysUtils.Sleep(aMilliseconds);
end;
class procedure TThread.SpinWait(aIterations: LongWord);
var
i: LongWord;
begin
{ yes, it's just a simple busy wait to burn some cpu cycles... and as the job
of this loop is to burn CPU cycles we switch off any optimizations that
could interfere with this (e.g. loop unrolling) }
{ Do *NOT* do $PUSH, $OPTIMIZATIONS OFF, <code>, $POP because optimization is
not a local switch, which means $PUSH/POP doesn't affect it, so that turns
off *ALL* optimizations for code below this point. Thanks to this we shipped
large parts of the classes unit with optimizations off between 2012-12-27
and 2014-06-06.
Instead, use a global var for the spinlock, because that is always handled
as volatile, so the access won't be optimized away by the compiler. (KB) }
for i:=1 to aIterations do
begin
Inc(SpinWaitDummy); // SpinWaitDummy *MUST* be global
end;
end;
{$ifndef HAS_TTHREAD_GETSYSTEMTIMES}
class procedure TThread.GetSystemTimes(out aSystemTimes: TSystemTimes);
begin
{ by default we just return a zeroed out record }
FillChar(aSystemTimes, SizeOf(aSystemTimes), 0);
end;
{$endif}
class function TThread.GetTickCount: LongWord;
begin
Result := SysUtils.GetTickCount;
end;
class function TThread.GetTickCount64: QWord;
begin
Result := SysUtils.GetTickCount64;
end;
{ TSimpleThread allows objects to create a threading method without defining
a new thread class }
Type
TSimpleThread = class(TThread)
private
FExecuteMethod: TThreadExecuteHandler;
protected
procedure Execute; override;
public
constructor Create(ExecuteMethod: TThreadExecuteHandler; AOnterminate : TNotifyEvent);
end;
TSimpleStatusThread = class(TThread)
private
FExecuteMethod: TThreadExecuteStatusHandler;
FStatus : String;
FOnStatus : TThreadStatusNotifyEvent;
protected
procedure Execute; override;
Procedure DoStatus;
Procedure SetStatus(Const AStatus : String);
public
constructor Create(ExecuteMethod: TThreadExecuteStatusHandler; AOnStatus : TThreadStatusNotifyEvent; AOnterminate : TNotifyEvent);
end;
TSimpleProcThread = class(TThread)
private
FExecuteMethod: TThreadExecuteCallBack;
FCallOnTerminate : TNotifyCallBack;
FData : Pointer;
protected
Procedure TerminateCallBack(Sender : TObject);
procedure Execute; override;
public
constructor Create(ExecuteMethod: TThreadExecuteCallBack; AData : Pointer; AOnterminate : TNotifyCallBack);
end;
TSimpleStatusProcThread = class(TThread)
private
FExecuteMethod: TThreadExecuteStatusCallBack;
FCallOnTerminate : TNotifyCallBack;
FStatus : String;
FOnStatus : TThreadStatusNotifyCallBack;
FData : Pointer;
protected
procedure Execute; override;
Procedure DoStatus;
Procedure SetStatus(Const AStatus : String);
Procedure TerminateCallBack(Sender : TObject);
public
constructor Create(ExecuteMethod: TThreadExecuteStatusCallBack; AData : Pointer; AOnStatus : TThreadStatusNotifyCallBack; AOnterminate : TNotifyCallBack);
end;
{ TSimpleThread }
constructor TSimpleThread.Create(ExecuteMethod: TThreadExecuteHandler; AOnTerminate: TNotifyEvent);
begin
FExecuteMethod := ExecuteMethod;
OnTerminate := AOnTerminate;
inherited Create(False);
end;
procedure TSimpleThread.Execute;
begin
FreeOnTerminate := True;
FExecuteMethod;
end;
{ TSimpleStatusThread }
constructor TSimpleStatusThread.Create(ExecuteMethod: TThreadExecuteStatusHandler;AOnStatus : TThreadStatusNotifyEvent; AOnTerminate: TNotifyEvent);
begin
FExecuteMethod := ExecuteMethod;
OnTerminate := AOnTerminate;
FOnStatus:=AOnStatus;
FStatus:='';
inherited Create(False);
end;
procedure TSimpleStatusThread.Execute;
begin
FreeOnTerminate := True;
FExecuteMethod(@SetStatus);
end;
procedure TSimpleStatusThread.SetStatus(Const AStatus : String);
begin
If (AStatus=FStatus) then
exit;
FStatus:=AStatus;
If Assigned(FOnStatus) then
Synchronize(@DoStatus);
end;
procedure TSimpleStatusThread.DoStatus;
begin
FOnStatus(Self,FStatus);
end;
{ TSimpleProcThread }
constructor TSimpleProcThread.Create(ExecuteMethod: TThreadExecuteCallBack; AData : Pointer; AOnTerminate: TNotifyCallBack);
begin
FExecuteMethod := ExecuteMethod;
FCallOnTerminate := AOnTerminate;
FData:=AData;
If Assigned(FCallOnTerminate) then
OnTerminate:=@TerminateCallBack;
inherited Create(False);
end;
procedure TSimpleProcThread.Execute;
begin
FreeOnTerminate := True;
FExecuteMethod(FData);
end;
procedure TSimpleProcThread.TerminateCallBack(Sender : TObject);
begin
if Assigned(FCallOnTerminate) then
FCallOnTerminate(Sender,FData);
end;
{ TSimpleStatusProcThread }
constructor TSimpleStatusProcThread.Create(ExecuteMethod: TThreadExecuteStatusCallback; AData : Pointer; AOnStatus : TThreadStatusNotifyCallBack; AOnTerminate: TNotifyCallBack);
begin
FExecuteMethod := ExecuteMethod;
FCallOnTerminate := AOnTerminate;
FData:=AData;
If Assigned(FCallOnTerminate) then
OnTerminate:=@TerminateCallBack;
FOnStatus:=AOnStatus;
FStatus:='';
inherited Create(False);
end;
procedure TSimpleStatusProcThread.Execute;
begin
FreeOnTerminate := True;
FExecuteMethod(FData,@SetStatus);
end;
procedure TSimpleStatusProcThread.SetStatus(Const AStatus : String);
begin
If (AStatus=FStatus) then
exit;
FStatus:=AStatus;
If Assigned(FOnStatus) then
Synchronize(@DoStatus);
end;
procedure TSimpleStatusProcThread.DoStatus;
begin
FOnStatus(Self,FData,FStatus);
end;
procedure TSimpleStatusProcThread.TerminateCallBack(Sender : TObject);
begin
if Assigned(FCallOnTerminate) then
FCallOnTerminate(Sender,FData);
end;
Class Function TThread.ExecuteInThread(AMethod : TThreadExecuteHandler; AOnTerminate : TNotifyEvent = Nil) : TThread;
begin
Result:=TSimpleThread.Create(AMethod,AOnTerminate);
end;
Class Function TThread.ExecuteInThread(AMethod : TThreadExecuteCallback; AData : Pointer; AOnTerminate : TNotifyCallback = Nil) : TThread;
begin
Result:=TSimpleProcThread.Create(AMethod,AData,AOnTerminate);
end;
Class Function TThread.ExecuteInThread(AMethod : TThreadExecuteStatusHandler; AOnStatus : TThreadStatusNotifyEvent; AOnTerminate : TNotifyEvent = Nil) : TThread;
begin
If Not Assigned(AOnStatus) then
Raise EThread.Create(SErrStatusCallBackRequired);
Result:=TSimpleStatusThread.Create(AMethod,AOnStatus,AOnTerminate);
end;
Class Function TThread.ExecuteInThread(AMethod : TThreadExecuteStatusCallback; AOnStatus : TThreadStatusNotifyCallback;AData : Pointer = Nil; AOnTerminate : TNotifyCallBack = Nil) : TThread;
begin
If Not Assigned(AOnStatus) then
Raise EThread.Create(SErrStatusCallBackRequired);
Result:=TSimpleStatusProcThread.Create(AMethod,AData,AOnStatus,AOnTerminate);
end;
{ TPersistent implementation }
{$i persist.inc }
{$i sllist.inc}
{$i resref.inc}
{ TComponent implementation }
{$i compon.inc}
{ TBasicAction implementation }
{$i action.inc}
{ TDataModule implementation }
{$i dm.inc}
{ Class and component registration routines }
{$I cregist.inc}
{ Interface related stuff }
{$I intf.inc}
{**********************************************************************
* Miscellaneous procedures and functions *
**********************************************************************}
function ExtractStrings(Separators, WhiteSpace: TSysCharSet; Content: PChar; Strings: TStrings; AddEmptyStrings : Boolean = False): Integer;
var
b, c : pchar;
procedure SkipWhitespace;
begin
while (c^ in Whitespace) do
inc (c);
end;
procedure AddString;
var
l : integer;
s : string;
begin
l := c-b;
if (l > 0) or AddEmptyStrings then
begin
if assigned(Strings) then
begin
setlength(s, l);
if l>0 then
move (b^, s[1],l*SizeOf(char));
Strings.Add (s);
end;
inc (result);
end;
end;
var
quoted : char;
begin
result := 0;
c := Content;
Quoted := #0;
Separators := Separators + [#13, #10] - ['''','"'];
SkipWhitespace;
b := c;
while (c^ <> #0) do
begin
if (c^ = Quoted) then
begin
if ((c+1)^ = Quoted) then
inc (c)
else
Quoted := #0
end
else if (Quoted = #0) and (c^ in ['''','"']) then
Quoted := c^;
if (Quoted = #0) and (c^ in Separators) then
begin
AddString;
inc (c);
SkipWhitespace;
b := c;
end
else
inc (c);
end;
if (c <> b) then
AddString;
end;
{ Point and rectangle constructors }
function Point(AX, AY: Integer): TPoint;
begin
with Result do
begin
X := AX;
Y := AY;
end;
end;
function SmallPoint(AX, AY: SmallInt): TSmallPoint;
begin
with Result do
begin
X := AX;
Y := AY;
end;
end;
function Rect(ALeft, ATop, ARight, ABottom: Integer): TRect;
begin
with Result do
begin
Left := ALeft;
Top := ATop;
Right := ARight;
Bottom := ABottom;
end;
end;
function Bounds(ALeft, ATop, AWidth, AHeight: Integer): TRect;
begin
with Result do
begin
Left := ALeft;
Top := ATop;
Right := ALeft + AWidth;
Bottom := ATop + AHeight;
end;
end;
function PointsEqual(const P1, P2: TPoint): Boolean; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
begin
{ lazy, but should work }
result:=QWord(P1)=QWord(P2);
end;
function PointsEqual(const P1, P2: TSmallPoint): Boolean; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
begin
{ lazy, but should work }
result:=DWord(P1)=DWord(P2);
end;
function InvalidPoint(X, Y: Integer): Boolean;
begin
result:=(X=-1) and (Y=-1);
end;
function InvalidPoint(const At: TPoint): Boolean;
begin
result:=(At.x=-1) and (At.y=-1);
end;
function InvalidPoint(const At: TSmallPoint): Boolean;
begin
result:=(At.x=-1) and (At.y=-1);
end;
{ Object filing routines }
var
IntConstList: TThreadList;
type
TIntConst = class
IntegerType: PTypeInfo; // The integer type RTTI pointer
IdentToIntFn: TIdentToInt; // Identifier to Integer conversion
IntToIdentFn: TIntToIdent; // Integer to Identifier conversion
constructor Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt;
AIntToIdent: TIntToIdent);
end;
constructor TIntConst.Create(AIntegerType: PTypeInfo; AIdentToInt: TIdentToInt;
AIntToIdent: TIntToIdent);
begin
IntegerType := AIntegerType;
IdentToIntFn := AIdentToInt;
IntToIdentFn := AIntToIdent;
end;
procedure RegisterIntegerConsts(IntegerType: Pointer; IdentToIntFn: TIdentToInt;
IntToIdentFn: TIntToIdent);
begin
IntConstList.Add(TIntConst.Create(IntegerType, IdentToIntFn, IntToIdentFn));
end;
function FindIntToIdent(AIntegerType: Pointer): TIntToIdent;
var
i: Integer;
begin
with IntConstList.LockList do
try
for i := 0 to Count - 1 do
if TIntConst(Items[i]).IntegerType = AIntegerType then
exit(TIntConst(Items[i]).IntToIdentFn);
Result := nil;
finally
IntConstList.UnlockList;
end;
end;
function FindIdentToInt(AIntegerType: Pointer): TIdentToInt;
var
i: Integer;
begin
with IntConstList.LockList do
try
for i := 0 to Count - 1 do
with TIntConst(Items[I]) do
if TIntConst(Items[I]).IntegerType = AIntegerType then
exit(IdentToIntFn);
Result := nil;
finally
IntConstList.UnlockList;
end;
end;
function IdentToInt(const Ident: String; out Int: LongInt;
const Map: array of TIdentMapEntry): Boolean;
var
i: Integer;
begin
for i := Low(Map) to High(Map) do
if CompareText(Map[i].Name, Ident) = 0 then
begin
Int := Map[i].Value;
exit(True);
end;
Result := False;
end;
function IntToIdent(Int: LongInt; var Ident: String;
const Map: array of TIdentMapEntry): Boolean;
var
i: Integer;
begin
for i := Low(Map) to High(Map) do
if Map[i].Value = Int then
begin
Ident := Map[i].Name;
exit(True);
end;
Result := False;
end;
function GlobalIdentToInt(const Ident: String; var Int: LongInt):boolean;
var
i : Integer;
begin
with IntConstList.LockList do
try
for i := 0 to Count - 1 do
if TIntConst(Items[I]).IdentToIntFn(Ident, Int) then
Exit(True);
Result := false;
finally
IntConstList.UnlockList;
end;
end;
{ TPropFixup }
// Tainted. TPropFixup is being removed.
Type
TInitHandler = Class(TObject)
AHandler : TInitComponentHandler;
AClass : TComponentClass;
end;
{$ifndef i8086}
type
TCodePtrList = TList;
{$endif i8086}
Var
InitHandlerList : TList;
FindGlobalComponentList : TCodePtrList;
procedure RegisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent);
begin
if not(assigned(FindGlobalComponentList)) then
FindGlobalComponentList:=TCodePtrList.Create;
if FindGlobalComponentList.IndexOf(CodePointer(AFindGlobalComponent))<0 then
FindGlobalComponentList.Add(CodePointer(AFindGlobalComponent));
end;
procedure UnregisterFindGlobalComponentProc(AFindGlobalComponent: TFindGlobalComponent);
begin
if assigned(FindGlobalComponentList) then
FindGlobalComponentList.Remove(CodePointer(AFindGlobalComponent));
end;
function FindGlobalComponent(const Name: string): TComponent;
var
i : sizeint;
begin
FindGlobalComponent:=nil;
if assigned(FindGlobalComponentList) then
begin
for i:=FindGlobalComponentList.Count-1 downto 0 do
begin
FindGlobalComponent:=TFindGlobalComponent(FindGlobalComponentList[i])(name);
if assigned(FindGlobalComponent) then
break;
end;
end;
end;
procedure RegisterInitComponentHandler(ComponentClass: TComponentClass; Handler: TInitComponentHandler);
Var
I : Integer;
H: TInitHandler;
begin
If (InitHandlerList=Nil) then
InitHandlerList:=TList.Create;
H:=TInitHandler.Create;
H.Aclass:=ComponentClass;
H.AHandler:=Handler;
try
With InitHandlerList do
begin
I:=0;
While (I<Count) and not H.AClass.InheritsFrom(TInitHandler(Items[I]).AClass) do
Inc(I);
{ override? }
if (I<Count) and (TInitHandler(Items[I]).AClass=H.AClass) then
begin
TInitHandler(Items[I]).AHandler:=Handler;
H.Free;
end
else
InitHandlerList.Insert(I,H);
end;
except
H.Free;
raise;
end;
end;
{ all targets should at least include the sysres.inc dummy in the system unit to compile this }
function CreateComponentfromRes(const res : string;Inst : THandle;var Component : TComponent) : Boolean;
var
ResStream : TResourceStream;
begin
result:=true;
if Inst=0 then
Inst:=HInstance;
try
ResStream:=TResourceStream.Create(Inst,res,RT_RCDATA);
try
Component:=ResStream.ReadComponent(Component);
finally
ResStream.Free;
end;
except
on EResNotFound do
result:=false;
end;
end;
function DefaultInitHandler(Instance: TComponent; RootAncestor: TClass): Boolean;
function doinit(_class : TClass) : boolean;
begin
result:=false;
if (_class.ClassType=TComponent) or (_class.ClassType=RootAncestor) then
exit;
result:=doinit(_class.ClassParent);
result:=CreateComponentfromRes(_class.ClassName,0,Instance) or result;
end;
begin
{$ifdef FPC_HAS_FEATURE_THREADING}
GlobalNameSpace.BeginWrite;
try
{$endif}
result:=doinit(Instance.ClassType);
{$ifdef FPC_HAS_FEATURE_THREADING}
finally
GlobalNameSpace.EndWrite;
end;
{$endif}
end;
function InitInheritedComponent(Instance: TComponent; RootAncestor: TClass): Boolean;
Var
I : Integer;
begin
I:=0;
if not Assigned(InitHandlerList) then begin
Result := True;
Exit;
end;
Result:=False;
With InitHandlerList do
begin
I:=0;
// Instance is the normally the lowest one, so that one should be used when searching.
While Not result and (I<Count) do
begin
If (Instance.InheritsFrom(TInitHandler(Items[i]).AClass)) then
Result:=TInitHandler(Items[i]).AHandler(Instance,RootAncestor);
Inc(I);
end;
end;
end;
function InitComponentRes(const ResName: String; Instance: TComponent): Boolean;
begin
Result:=ReadComponentRes(ResName,Instance)=Instance;
end;
function SysReadComponentRes(HInstance : THandle; const ResName: String; Instance: TComponent): TComponent;
Var
H : TFPResourceHandle;
begin
{ Windows unit also has a FindResource function, use the one from
system unit here. }
H:=system.FindResource(HInstance,ResName,RT_RCDATA);
if (PtrInt(H)=0) then
Result:=Nil
else
With TResourceStream.Create(HInstance,ResName,RT_RCDATA) do
try
Result:=ReadComponent(Instance);
Finally
Free;
end;
end;
function ReadComponentRes(const ResName: String; Instance: TComponent): TComponent;
begin
Result:=SysReadComponentRes(Hinstance,Resname,Instance);
end;
function ReadComponentResEx(HInstance: THandle; const ResName: String): TComponent;
begin
Result:=SysReadComponentRes(Hinstance,ResName,Nil);
end;
function ReadComponentResFile(const FileName: String; Instance: TComponent): TComponent;
var
FileStream: TStream;
begin
FileStream := TFileStream.Create(FileName, fmOpenRead {!!!:or fmShareDenyWrite});
try
Result := FileStream.ReadComponentRes(Instance);
finally
FileStream.Free;
end;
end;
procedure WriteComponentResFile(const FileName: String; Instance: TComponent);
var
FileStream: TStream;
begin
FileStream := TFileStream.Create(FileName, fmCreate);
try
FileStream.WriteComponentRes(Instance.ClassName, Instance);
finally
FileStream.Free;
end;
end;
Function FindNestedComponent(Root : TComponent; APath : String; CStyle : Boolean = True) : TComponent;
Function GetNextName : String; {$ifdef CLASSESINLINE} inline; {$endif CLASSESINLINE}
Var
P : Integer;
CM : Boolean;
begin
P:=Pos('.',APath);
CM:=False;
If (P=0) then
begin
If CStyle then
begin
P:=Pos('->',APath);
CM:=P<>0;
end;
If (P=0) Then
P:=Length(APath)+1;
end;
Result:=Copy(APath,1,P-1);
Delete(APath,1,P+Ord(CM));
end;
Var
C : TComponent;
S : String;
begin
If (APath='') then
Result:=Nil
else
begin
Result:=Root;
While (APath<>'') And (Result<>Nil) do
begin
C:=Result;
S:=Uppercase(GetNextName);
Result:=C.FindComponent(S);
If (Result=Nil) And (S='OWNER') then
Result:=C;
end;
end;
end;
{$ifdef FPC_HAS_FEATURE_THREADING}
threadvar
{$else}
var
{$endif}
GlobalLoaded, GlobalLists: TFpList;
procedure BeginGlobalLoading;
begin
if not Assigned(GlobalLists) then
GlobalLists := TFpList.Create;
GlobalLists.Add(GlobalLoaded);
GlobalLoaded := TFpList.Create;
end;
{ Notify all global components that they have been loaded completely }
procedure NotifyGlobalLoading;
var
i: Integer;
begin
for i := 0 to GlobalLoaded.Count - 1 do
TComponent(GlobalLoaded[i]).Loaded;
end;
procedure EndGlobalLoading;
begin
{ Free the memory occupied by BeginGlobalLoading }
GlobalLoaded.Free;
GlobalLoaded := TFpList(GlobalLists.Last);
GlobalLists.Delete(GlobalLists.Count - 1);
if GlobalLists.Count = 0 then
begin
GlobalLists.Free;
GlobalLists := nil;
end;
end;
function CollectionsEqual(C1, C2: TCollection): Boolean;
begin
// !!!: Implement this
CollectionsEqual:=false;
end;
function CollectionsEqual(C1, C2: TCollection; Owner1, Owner2: TComponent): Boolean;
procedure stream_collection(s : tstream;c : tcollection;o : tcomponent);
var
w : twriter;
begin
w:=twriter.create(s,4096);
try
w.root:=o;
w.flookuproot:=o;
w.writecollection(c);
finally
w.free;
end;
end;
var
s1,s2 : tmemorystream;
begin
result:=false;
if (c1.classtype<>c2.classtype) or
(c1.count<>c2.count) then
exit;
if c1.count = 0 then
begin
result:= true;
exit;
end;
s1:=tmemorystream.create;
try
s2:=tmemorystream.create;
try
stream_collection(s1,c1,owner1);
stream_collection(s2,c2,owner2);
result:=(s1.size=s2.size) and (CompareChar(s1.memory^,s2.memory^,s1.size)=0);
finally
s2.free;
end;
finally
s1.free;
end;
end;
{ Object conversion routines }
type
CharToOrdFuncty = Function(var charpo: Pointer): Cardinal;
function CharToOrd(var P: Pointer): Cardinal;
begin
result:= ord(pchar(P)^);
inc(pchar(P));
end;
function WideCharToOrd(var P: Pointer): Cardinal;
begin
result:= ord(pwidechar(P)^);
inc(pwidechar(P));
end;
function Utf8ToOrd(var P:Pointer): Cardinal;
begin
// Should also check for illegal utf8 combinations
Result := Ord(PChar(P)^);
Inc(P);
if (Result and $80) <> 0 then
if (Ord(Result) and %11100000) = %11000000 then begin
Result := ((Result and %00011111) shl 6)
or (ord(PChar(P)^) and %00111111);
Inc(P);
end else if (Ord(Result) and %11110000) = %11100000 then begin
Result := ((Result and %00011111) shl 12)
or ((ord(PChar(P)^) and %00111111) shl 6)
or (ord((PChar(P)+1)^) and %00111111);
Inc(P,2);
end else begin
Result := ((ord(Result) and %00011111) shl 18)
or ((ord(PChar(P)^) and %00111111) shl 12)
or ((ord((PChar(P)+1)^) and %00111111) shl 6)
or (ord((PChar(P)+2)^) and %00111111);
Inc(P,3);
end;
end;
procedure ObjectBinaryToText(Input, Output: TStream; Encoding: TObjectTextEncoding);
procedure OutStr(s: String);
begin
if Length(s) > 0 then
Output.Write(s[1], Length(s));
end;
procedure OutLn(s: String);
begin
OutStr(s + LineEnding);
end;
procedure Outchars(P, LastP : Pointer; CharToOrdFunc: CharToOrdFuncty;
UseBytes: boolean = false);
var
res, NewStr: String;
w: Cardinal;
InString, NewInString: Boolean;
begin
if p = nil then begin
res:= '''''';
end
else
begin
res := '';
InString := False;
while P < LastP do
begin
NewInString := InString;
w := CharToOrdfunc(P);
if w = ord('''') then
begin //quote char
if not InString then
NewInString := True;
NewStr := '''''';
end
else if (Ord(w) >= 32) and ((Ord(w) < 127) or (UseBytes and (Ord(w)<256))) then
begin //printable ascii or bytes
if not InString then
NewInString := True;
NewStr := char(w);
end
else
begin //ascii control chars, non ascii
if InString then
NewInString := False;
NewStr := '#' + IntToStr(w);
end;
if NewInString <> InString then
begin
NewStr := '''' + NewStr;
InString := NewInString;
end;
res := res + NewStr;
end;
if InString then
res := res + '''';
end;
OutStr(res);
end;
procedure OutString(s: String);
begin
OutChars(Pointer(S),PChar(S)+Length(S),@CharToOrd,Encoding=oteLFM);
end;
procedure OutWString(W: WideString);
begin
OutChars(Pointer(W),pwidechar(W)+Length(W),@WideCharToOrd);
end;
procedure OutUString(W: UnicodeString);
begin
OutChars(Pointer(W),pwidechar(W)+Length(W),@WideCharToOrd);
end;
procedure OutUtf8Str(s: String);
begin
if Encoding=oteLFM then
OutChars(Pointer(S),PChar(S)+Length(S),@CharToOrd)
else
OutChars(Pointer(S),PChar(S)+Length(S),@Utf8ToOrd);
end;
function ReadWord : word; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
begin
Result:=Input.ReadWord;
Result:=LEtoN(Result);
end;
function ReadDWord : longword; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
begin
Result:=Input.ReadDWord;
Result:=LEtoN(Result);
end;
function ReadQWord : qword; {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
begin
Input.ReadBuffer(Result,sizeof(Result));
Result:=LEtoN(Result);
end;
{$ifndef FPUNONE}
{$IFNDEF FPC_HAS_TYPE_EXTENDED}
function ExtendedToDouble(e : pointer) : double;
var mant : qword;
exp : smallint;
sign : boolean;
d : qword;
begin
move(pbyte(e)[0],mant,8); //mantissa : bytes 0..7
move(pbyte(e)[8],exp,2); //exponent and sign: bytes 8..9
mant:=LEtoN(mant);
exp:=LetoN(word(exp));
sign:=(exp and $8000)<>0;
if sign then exp:=exp and $7FFF;
case exp of
0 : mant:=0; //if denormalized, value is too small for double,
//so it's always zero
$7FFF : exp:=2047 //either infinity or NaN
else
begin
dec(exp,16383-1023);
if (exp>=-51) and (exp<=0) then //can be denormalized
begin
mant:=mant shr (-exp);
exp:=0;
end
else
if (exp<-51) or (exp>2046) then //exponent too large.
begin
Result:=0;
exit;
end
else //normalized value
mant:=mant shl 1; //hide most significant bit
end;
end;
d:=word(exp);
d:=d shl 52;
mant:=mant shr 12;
d:=d or mant;
if sign then d:=d or $8000000000000000;
Result:=pdouble(@d)^;
end;
{$ENDIF}
{$endif}
function ReadInt(ValueType: TValueType): Int64;
begin
case ValueType of
vaInt8: Result := ShortInt(Input.ReadByte);
vaInt16: Result := SmallInt(ReadWord);
vaInt32: Result := LongInt(ReadDWord);
vaInt64: Result := Int64(ReadQWord);
end;
end;
function ReadInt: Int64;
begin
Result := ReadInt(TValueType(Input.ReadByte));
end;
{$ifndef FPUNONE}
function ReadExtended : extended;
{$IFNDEF FPC_HAS_TYPE_EXTENDED}
var ext : array[0..9] of byte;
{$ENDIF}
begin
{$IFNDEF FPC_HAS_TYPE_EXTENDED}
Input.ReadBuffer(ext[0],10);
Result:=ExtendedToDouble(@(ext[0]));
{$ELSE}
Input.ReadBuffer(Result,sizeof(Result));
{$ENDIF}
end;
{$endif}
function ReadSStr: String;
var
len: Byte;
begin
len := Input.ReadByte;
SetLength(Result, len);
if (len > 0) then
Input.ReadBuffer(Result[1], len);
end;
function ReadLStr: String;
var
len: DWord;
begin
len := ReadDWord;
SetLength(Result, len);
if (len > 0) then
Input.ReadBuffer(Result[1], len);
end;
function ReadWStr: WideString;
var
len: DWord;
{$IFDEF ENDIAN_BIG}
i : integer;
{$ENDIF}
begin
len := ReadDWord;
SetLength(Result, len);
if (len > 0) then
begin
Input.ReadBuffer(Pointer(@Result[1])^, len*2);
{$IFDEF ENDIAN_BIG}
for i:=1 to len do
Result[i]:=widechar(SwapEndian(word(Result[i])));
{$ENDIF}
end;
end;
function ReadUStr: UnicodeString;
var
len: DWord;
{$IFDEF ENDIAN_BIG}
i : integer;
{$ENDIF}
begin
len := ReadDWord;
SetLength(Result, len);
if (len > 0) then
begin
Input.ReadBuffer(Pointer(@Result[1])^, len*2);
{$IFDEF ENDIAN_BIG}
for i:=1 to len do
Result[i]:=widechar(SwapEndian(word(Result[i])));
{$ENDIF}
end;
end;
procedure ReadPropList(indent: String);
procedure ProcessValue(ValueType: TValueType; Indent: String);
procedure ProcessBinary;
var
ToDo, DoNow, i: LongInt;
lbuf: array[0..31] of Byte;
s: String;
begin
ToDo := ReadDWord;
OutLn('{');
while ToDo > 0 do begin
DoNow := ToDo;
if DoNow > 32 then DoNow := 32;
Dec(ToDo, DoNow);
s := Indent + ' ';
Input.ReadBuffer(lbuf, DoNow);
for i := 0 to DoNow - 1 do
s := s + IntToHex(lbuf[i], 2);
OutLn(s);
end;
OutLn(indent + '}');
end;
var
s: String;
{ len: LongInt; }
IsFirst: Boolean;
{$ifndef FPUNONE}
ext: Extended;
{$endif}
begin
case ValueType of
vaList: begin
OutStr('(');
IsFirst := True;
while True do begin
ValueType := TValueType(Input.ReadByte);
if ValueType = vaNull then break;
if IsFirst then begin
OutLn('');
IsFirst := False;
end;
OutStr(Indent + ' ');
ProcessValue(ValueType, Indent + ' ');
end;
OutLn(Indent + ')');
end;
vaInt8: OutLn(IntToStr(ShortInt(Input.ReadByte)));
vaInt16: OutLn( IntToStr(SmallInt(ReadWord)));
vaInt32: OutLn(IntToStr(LongInt(ReadDWord)));
vaInt64: OutLn(IntToStr(Int64(ReadQWord)));
{$ifndef FPUNONE}
vaExtended: begin
ext:=ReadExtended;
Str(ext,S);// Do not use localized strings.
OutLn(S);
end;
{$endif}
vaString: begin
OutString(ReadSStr);
OutLn('');
end;
vaIdent: OutLn(ReadSStr);
vaFalse: OutLn('False');
vaTrue: OutLn('True');
vaBinary: ProcessBinary;
vaSet: begin
OutStr('[');
IsFirst := True;
while True do begin
s := ReadSStr;
if Length(s) = 0 then break;
if not IsFirst then OutStr(', ');
IsFirst := False;
OutStr(s);
end;
OutLn(']');
end;
vaLString:
begin
OutString(ReadLStr);
OutLn('');
end;
vaWString:
begin
OutWString(ReadWStr);
OutLn('');
end;
vaUString:
begin
OutWString(ReadWStr);
OutLn('');
end;
vaNil:
OutLn('nil');
vaCollection: begin
OutStr('<');
while Input.ReadByte <> 0 do begin
OutLn(Indent);
Input.Seek(-1, soFromCurrent);
OutStr(indent + ' item');
ValueType := TValueType(Input.ReadByte);
if ValueType <> vaList then
OutStr('[' + IntToStr(ReadInt(ValueType)) + ']');
OutLn('');
ReadPropList(indent + ' ');
OutStr(indent + ' end');
end;
OutLn('>');
end;
{vaSingle: begin OutLn('!!Single!!'); exit end;
vaCurrency: begin OutLn('!!Currency!!'); exit end;
vaDate: begin OutLn('!!Date!!'); exit end;}
vaUTF8String: begin
OutUtf8Str(ReadLStr);
OutLn('');
end;
else
Raise EReadError.CreateFmt(SErrInvalidPropertyType,[Ord(ValueType)]);
end;
end;
begin
while Input.ReadByte <> 0 do begin
Input.Seek(-1, soFromCurrent);
OutStr(indent + ReadSStr + ' = ');
ProcessValue(TValueType(Input.ReadByte), Indent);
end;
end;
procedure ReadObject(indent: String);
var
b: Byte;
ObjClassName, ObjName: String;
ChildPos: LongInt;
begin
// Check for FilerFlags
b := Input.ReadByte;
if (b and $f0) = $f0 then begin
if (b and 2) <> 0 then ChildPos := ReadInt;
end else begin
b := 0;
Input.Seek(-1, soFromCurrent);
end;
ObjClassName := ReadSStr;
ObjName := ReadSStr;
OutStr(Indent);
if (b and 1) <> 0 then OutStr('inherited')
else
if (b and 4) <> 0 then OutStr('inline')
else OutStr('object');
OutStr(' ');
if ObjName <> '' then
OutStr(ObjName + ': ');
OutStr(ObjClassName);
if (b and 2) <> 0 then OutStr('[' + IntToStr(ChildPos) + ']');
OutLn('');
ReadPropList(indent + ' ');
while Input.ReadByte <> 0 do begin
Input.Seek(-1, soFromCurrent);
ReadObject(indent + ' ');
end;
OutLn(indent + 'end');
end;
type
PLongWord = ^LongWord;
const
signature: PChar = 'TPF0';
begin
if Input.ReadDWord <> PLongWord(Pointer(signature))^ then
raise EReadError.Create('Illegal stream image' {###SInvalidImage});
ReadObject('');
end;
procedure ObjectBinaryToText(Input, Output: TStream);
begin
ObjectBinaryToText(Input,Output,oteDFM);
end;
procedure ObjectTextToBinary(Input, Output: TStream);
var
parser: TParser;
procedure WriteWord(w : word); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
begin
w:=NtoLE(w);
Output.WriteWord(w);
end;
procedure WriteDWord(lw : longword); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
begin
lw:=NtoLE(lw);
Output.WriteDWord(lw);
end;
procedure WriteQWord(qw : qword); {$ifdef CLASSESINLINE}inline;{$endif CLASSESINLINE}
begin
qw:=NtoLE(qw);
Output.WriteBuffer(qw,sizeof(qword));
end;
{$ifndef FPUNONE}
{$IFNDEF FPC_HAS_TYPE_EXTENDED}
procedure DoubleToExtended(d : double; e : pointer);
var mant : qword;
exp : smallint;
sign : boolean;
begin
mant:=(qword(d) and $000FFFFFFFFFFFFF) shl 12;
exp :=(qword(d) shr 52) and $7FF;
sign:=(qword(d) and $8000000000000000)<>0;
case exp of
0 : begin
if mant<>0 then //denormalized value: hidden bit is 0. normalize it
begin
exp:=16383-1022;
while (mant and $8000000000000000)=0 do
begin
dec(exp);
mant:=mant shl 1;
end;
dec(exp); //don't shift, most significant bit is not hidden in extended
end;
end;
2047 : exp:=$7FFF //either infinity or NaN
else
begin
inc(exp,16383-1023);
mant:=(mant shr 1) or $8000000000000000; //unhide hidden bit
end;
end;
if sign then exp:=exp or $8000;
mant:=NtoLE(mant);
exp:=NtoLE(word(exp));
move(mant,pbyte(e)[0],8); //mantissa : bytes 0..7
move(exp,pbyte(e)[8],2); //exponent and sign: bytes 8..9
end;
{$ENDIF}
procedure WriteExtended(e : extended);
{$IFNDEF FPC_HAS_TYPE_EXTENDED}
var ext : array[0..9] of byte;
{$ENDIF}
begin
{$IFNDEF FPC_HAS_TYPE_EXTENDED}
DoubleToExtended(e,@(ext[0]));
Output.WriteBuffer(ext[0],10);
{$ELSE}
Output.WriteBuffer(e,sizeof(e));
{$ENDIF}
end;
{$endif}
procedure WriteString(s: String);
var size : byte;
begin
if length(s)>255 then size:=255
else size:=length(s);
Output.WriteByte(size);
if Length(s) > 0 then
Output.WriteBuffer(s[1], size);
end;
procedure WriteLString(Const s: String);
begin
WriteDWord(Length(s));
if Length(s) > 0 then
Output.WriteBuffer(s[1], Length(s));
end;
procedure WriteWString(Const s: WideString);
var len : longword;
{$IFDEF ENDIAN_BIG}
i : integer;
ws : widestring;
{$ENDIF}
begin
len:=Length(s);
WriteDWord(len);
if len > 0 then
begin
{$IFDEF ENDIAN_BIG}
setlength(ws,len);
for i:=1 to len do
ws[i]:=widechar(SwapEndian(word(s[i])));
Output.WriteBuffer(ws[1], len*sizeof(widechar));
{$ELSE}
Output.WriteBuffer(s[1], len*sizeof(widechar));
{$ENDIF}
end;
end;
procedure WriteInteger(value: Int64);
begin
if (value >= -128) and (value <= 127) then begin
Output.WriteByte(Ord(vaInt8));
Output.WriteByte(byte(value));
end else if (value >= -32768) and (value <= 32767) then begin
Output.WriteByte(Ord(vaInt16));
WriteWord(word(value));
end else if (value >= -2147483648) and (value <= 2147483647) then begin
Output.WriteByte(Ord(vaInt32));
WriteDWord(longword(value));
end else begin
Output.WriteByte(ord(vaInt64));
WriteQWord(qword(value));
end;
end;
procedure ProcessWideString(const left : widestring);
var ws : widestring;
begin
ws:=left+parser.TokenWideString;
while parser.NextToken = '+' do
begin
parser.NextToken; // Get next string fragment
if not (parser.Token in [toString,toWString]) then
parser.CheckToken(toWString);
ws:=ws+parser.TokenWideString;
end;
Output.WriteByte(Ord(vaWstring));
WriteWString(ws);
end;
procedure ProcessProperty; forward;
procedure ProcessValue;
var
{$ifndef FPUNONE}
flt: Extended;
{$endif}
s: String;
stream: TMemoryStream;
begin
case parser.Token of
toInteger:
begin
WriteInteger(parser.TokenInt);
parser.NextToken;
end;
{$ifndef FPUNONE}
toFloat:
begin
Output.WriteByte(Ord(vaExtended));
flt := Parser.TokenFloat;
WriteExtended(flt);
parser.NextToken;
end;
{$endif}
toString:
begin
s := parser.TokenString;
while parser.NextToken = '+' do
begin
parser.NextToken; // Get next string fragment
case parser.Token of
toString : s:=s+parser.TokenString;
toWString : begin
ProcessWideString(WideString(s));
exit;
end
else parser.CheckToken(toString);
end;
end;
if (length(S)>255) then
begin
Output.WriteByte(Ord(vaLString));
WriteLString(S);
end
else
begin
Output.WriteByte(Ord(vaString));
WriteString(s);
end;
end;
toWString:
ProcessWideString('');
toSymbol:
begin
if CompareText(parser.TokenString, 'True') = 0 then
Output.WriteByte(Ord(vaTrue))
else if CompareText(parser.TokenString, 'False') = 0 then
Output.WriteByte(Ord(vaFalse))
else if CompareText(parser.TokenString, 'nil') = 0 then
Output.WriteByte(Ord(vaNil))
else
begin
Output.WriteByte(Ord(vaIdent));
WriteString(parser.TokenComponentIdent);
end;
Parser.NextToken;
end;
// Set
'[':
begin
parser.NextToken;
Output.WriteByte(Ord(vaSet));
if parser.Token <> ']' then
while True do
begin
parser.CheckToken(toSymbol);
WriteString(parser.TokenString);
parser.NextToken;
if parser.Token = ']' then
break;
parser.CheckToken(',');
parser.NextToken;
end;
Output.WriteByte(0);
parser.NextToken;
end;
// List
'(':
begin
parser.NextToken;
Output.WriteByte(Ord(vaList));
while parser.Token <> ')' do
ProcessValue;
Output.WriteByte(0);
parser.NextToken;
end;
// Collection
'<':
begin
parser.NextToken;
Output.WriteByte(Ord(vaCollection));
while parser.Token <> '>' do
begin
parser.CheckTokenSymbol('item');
parser.NextToken;
// ConvertOrder
Output.WriteByte(Ord(vaList));
while not parser.TokenSymbolIs('end') do
ProcessProperty;
parser.NextToken; // Skip 'end'
Output.WriteByte(0);
end;
Output.WriteByte(0);
parser.NextToken;
end;
// Binary data
'{':
begin
Output.WriteByte(Ord(vaBinary));
stream := TMemoryStream.Create;
try
parser.HexToBinary(stream);
WriteDWord(stream.Size);
Output.WriteBuffer(Stream.Memory^, stream.Size);
finally
stream.Free;
end;
parser.NextToken;
end;
else
parser.Error(SInvalidProperty);
end;
end;
procedure ProcessProperty;
var
name: String;
begin
// Get name of property
parser.CheckToken(toSymbol);
name := parser.TokenString;
while True do begin
parser.NextToken;
if parser.Token <> '.' then break;
parser.NextToken;
parser.CheckToken(toSymbol);
name := name + '.' + parser.TokenString;
end;
WriteString(name);
parser.CheckToken('=');
parser.NextToken;
ProcessValue;
end;
procedure ProcessObject;
var
Flags: Byte;
ObjectName, ObjectType: String;
ChildPos: Integer;
begin
if parser.TokenSymbolIs('OBJECT') then
Flags :=0 { IsInherited := False }
else begin
if parser.TokenSymbolIs('INHERITED') then
Flags := 1 { IsInherited := True; }
else begin
parser.CheckTokenSymbol('INLINE');
Flags := 4;
end;
end;
parser.NextToken;
parser.CheckToken(toSymbol);
ObjectName := '';
ObjectType := parser.TokenString;
parser.NextToken;
if parser.Token = ':' then begin
parser.NextToken;
parser.CheckToken(toSymbol);
ObjectName := ObjectType;
ObjectType := parser.TokenString;
parser.NextToken;
if parser.Token = '[' then begin
parser.NextToken;
ChildPos := parser.TokenInt;
parser.NextToken;
parser.CheckToken(']');
parser.NextToken;
Flags := Flags or 2;
end;
end;
if Flags <> 0 then begin
Output.WriteByte($f0 or Flags);
if (Flags and 2) <> 0 then
WriteInteger(ChildPos);
end;
WriteString(ObjectType);
WriteString(ObjectName);
// Convert property list
while not (parser.TokenSymbolIs('END') or
parser.TokenSymbolIs('OBJECT') or
parser.TokenSymbolIs('INHERITED') or
parser.TokenSymbolIs('INLINE')) do
ProcessProperty;
Output.WriteByte(0); // Terminate property list
// Convert child objects
while not parser.TokenSymbolIs('END') do ProcessObject;
parser.NextToken; // Skip end token
Output.WriteByte(0); // Terminate property list
end;
const
signature: PChar = 'TPF0';
begin
parser := TParser.Create(Input);
try
Output.WriteBuffer(signature[0], 4);
ProcessObject;
finally
parser.Free;
end;
end;
procedure ObjectResourceToText(Input, Output: TStream);
begin
Input.ReadResHeader;
ObjectBinaryToText(Input, Output);
end;
procedure ObjectTextToResource(Input, Output: TStream);
var
StartPos, FixupInfo: LongInt;
parser: TParser;
name: String;
begin
// Get form type name
StartPos := Input.Position;
parser := TParser.Create(Input);
try
if not parser.TokenSymbolIs('OBJECT') then parser.CheckTokenSymbol('INHERITED');
parser.NextToken;
parser.CheckToken(toSymbol);
parser.NextToken;
parser.CheckToken(':');
parser.NextToken;
parser.CheckToken(toSymbol);
name := parser.TokenString;
finally
parser.Free;
Input.Position := StartPos;
end;
name := UpperCase(name);
Output.WriteResourceHeader(name,FixupInfo); // Write resource header
ObjectTextToBinary(Input, Output); // Convert the stuff!
Output.FixupResourceHeader(FixupInfo); // Insert real resource data size
end;
{ Utility routines }
function LineStart(Buffer, BufPos: PChar): PChar;
begin
Result := BufPos;
while Result > Buffer do begin
Dec(Result);
if Result[0] = #10 then break;
end;
end;
procedure CommonInit;
begin
{$ifdef FPC_HAS_FEATURE_THREADING}
SynchronizeTimeoutEvent:=RtlEventCreate;
InterlockedIncrement(ThreadQueueLockCounter);
InitCriticalSection(ThreadQueueLock);
MainThreadID:=GetCurrentThreadID;
{$else}
MainThreadID:=0{GetCurrentThreadID};
{$endif}
ExternalThreads := TThreadList.Create;
{$ifdef FPC_HAS_FEATURE_THREADING}
InitCriticalsection(ResolveSection);
TThread.FProcessorCount := CPUCount;
{$else}
TThread.FProcessorCount := 1{CPUCount};
{$endif}
InitHandlerList:=Nil;
FindGlobalComponentList:=nil;
IntConstList := TThreadList.Create;
ClassList := TThreadList.Create;
ClassAliasList := nil;
{ on unix this maps to a simple rw synchornizer }
GlobalNameSpace := TMultiReadExclusiveWriteSynchronizer.Create;
RegisterInitComponentHandler(TComponent,@DefaultInitHandler);
end;
procedure CommonCleanup;
var
i: Integer;
tmpentry: TThread.PThreadQueueEntry;
begin
{$ifdef FPC_HAS_FEATURE_THREADING}
GlobalNameSpace.BeginWrite;
{$endif}
with IntConstList.LockList do
try
for i := 0 to Count - 1 do
TIntConst(Items[I]).Free;
finally
IntConstList.UnlockList;
end;
IntConstList.Free;
ClassList.Free;
ClassAliasList.Free;
RemoveFixupReferences(nil, '');
{$ifdef FPC_HAS_FEATURE_THREADING}
DoneCriticalsection(ResolveSection);
{$endif}
GlobalLists.Free;
ComponentPages.Free;
FreeAndNil(NeedResolving);
{ GlobalNameSpace is an interface so this is enough }
GlobalNameSpace:=nil;
if (InitHandlerList<>Nil) then
for i := 0 to InitHandlerList.Count - 1 do
TInitHandler(InitHandlerList.Items[I]).Free;
InitHandlerList.Free;
InitHandlerList:=Nil;
FindGlobalComponentList.Free;
FindGlobalComponentList:=nil;
ExternalThreadsCleanup:=True;
with ExternalThreads.LockList do
try
for i := 0 to Count - 1 do
TThread(Items[i]).Free;
finally
ExternalThreads.UnlockList;
end;
FreeAndNil(ExternalThreads);
{$ifdef FPC_HAS_FEATURE_THREADING}
RtlEventDestroy(SynchronizeTimeoutEvent);
try
System.EnterCriticalSection(ThreadQueueLock);
{$endif}
{ clean up the queue, but keep in mind that the entries used for Synchronize
are owned by the corresponding TThread }
while Assigned(ThreadQueueHead) do begin
tmpentry := ThreadQueueHead;
ThreadQueueHead := tmpentry^.Next;
if not Assigned(tmpentry^.SyncEvent) then
Dispose(tmpentry);
end;
{ We also need to reset ThreadQueueTail }
ThreadQueueTail := nil;
{$ifdef FPC_HAS_FEATURE_THREADING}
finally
System.LeaveCriticalSection(ThreadQueueLock);
end;
if InterlockedDecrement(ThreadQueueLockCounter)=0 then
DoneCriticalSection(ThreadQueueLock);
{$endif}
end;
{ TFiler implementation }
{$i filer.inc}
{ TReader implementation }
{$i reader.inc}
{ TWriter implementations }
{$i writer.inc}
{$i twriter.inc}
|