File: Grt.pas

package info (click to toggle)
mysql-query-browser 1.2.5beta-3
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 63,792 kB
  • ctags: 46,485
  • sloc: pascal: 249,299; ansic: 80,111; cpp: 72,467; sh: 25,271; objc: 20,015; yacc: 10,755; java: 9,917; xml: 4,580; php: 2,806; python: 1,566; sql: 1,563; makefile: 1,452; perl: 3
file content (3563 lines) | stat: -rw-r--r-- 114,472 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
unit Grt;

// Copyright (C) 2003, 2004 MySQL AB
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// 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.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

interface

uses
  gnugettext, TntSystem,
  Windows, SysUtils, Classes, TntClasses, Forms, TntSysUtils, Messages,
  myx_public_interface,
  myx_util_public_interface,
//  myx_sql_resultset_public_interface,
  myx_grt_public_interface,
  myx_grt_builtin_module_public_interface,
  UniCodeConsole, SyncObjs, AuxFuncs;

type
  TGrt = class;
  TGrtEngine = class;

  GrtLoaderState =
  (
    GrtLsNotInitialized,
    GrtLsInitialized,
    GrtLsInitializeFailed,
    GrtLsModulesLoaded
  );

  GrtValueType =
  (
    GrtAnyValue = Ord(MYX_ANY_VALUE),
    GrtIntValue = Ord(MYX_INT_VALUE),
    GrtRealValue = Ord(MYX_REAL_VALUE),
    GrtStringValue = Ord(MYX_STRING_VALUE),
    GrtListValue = Ord(MYX_LIST_VALUE),
    GrtDictValue = Ord(MYX_DICT_VALUE)
  );

  GrtValueCallbackReason =
  (
    GrtVcrDelete = Ord(MYX_GVCR_DELETE),
    GrtVcrDictItemChange = Ord(MYX_GVCR_DICT_ITEM_CHANGE)
  );

  IGrtGenericTask = interface;
  
  TGrtProcessOutput = procedure(Text: WideString) of object;
  TGrtProcessMessages = procedure(Messages: TMYX_GRT_MSGS) of object;
  TGrtPerformInput = function(Description: WideString): WideString of object;
  TGrtPerformStatusQuery = function: integer of object;
  TGrtOnShutDown = procedure(Grt: TGrt) of object;
  TGrtTaskFinished = procedure(Task: IGrtGenericTask) of object;

  IGrtValueCallbackListener = interface
    function ValueChange(Value: Pointer; Reason: GrtValueCallbackReason): Integer;
  end;

  IGrtModuleImplementor = interface
    function GrtExecuteModuleFunction(ModuleName: WideString; FunctionName: WideString; arguments: Pointer): Pointer;
  end;

  // Communication interfaces for tasks and their principals.
  IGrtGenericTask = interface
  ['{42C4FCC5-2E9D-4500-AEE7-DE17031B8E6F}']
    function GetAllowNullResult: Boolean;
    function GetDataObj: TObject;
    function GetErrorCode: MYX_GRT_ERROR;
    function GetErrorString: WideString;
    function GetExecutionTime: Cardinal;
    function GetProcessOutputFunction: TGrtProcessOutput;
    function GetTag: Integer;
    function GetTaskFinishedFunction: TGrtTaskFinished;
    function GetTaskID: Integer;
    function GetTimeout: Integer;
    procedure PrepareSynchronization;
    procedure SetErrorCode(const Value: MYX_GRT_ERROR);
    procedure SetErrorString(const Value: WideString);
    procedure SetEvent;
    procedure SetExecutionTime(const Value: Cardinal);
    procedure SetTag(Tag: Integer);
    procedure WaitFor(WithMessages: Boolean);

    property AllowNullResult: Boolean read GetAllowNullResult;
    property DataObj: TObject read GetDataObj;
    property ErrorCode: MYX_GRT_ERROR read GetErrorCode write SetErrorCode;
    property ErrorString: WideString read GetErrorString write SetErrorString;
    property ExecutionTime: Cardinal read GetExecutionTime write SetExecutionTime;
    property TaskID: Integer read GetTaskID;
    property Timeout: Integer read GetTimeout;
    property Tag: Integer read GetTag write SetTag;

    property OnProcessOutput: TGrtProcessOutput read GetProcessOutputFunction;
    property OnTaskFinished: TGrtTaskFinished read GetTaskFinishedFunction;
  end;

  IGrtTask = interface(IGrtGenericTask)
  ['{A995FC94-DE83-4977-B23C-CAC6C9401CA9}']
    function GetDescription: WideString;
    function GetFunctionArgument: Pointer;
    function GetFunctionName: WideString;
    function GetModulName: WideString;
    function GetPerformInputFunction: TGrtPerformInput;
    function GetPerformStatusQueryFunction: TGrtPerformStatusQuery;
    function GetProcessMessagesFunction: TGrtProcessMessages;
    function GetResult: Pointer;
    function GetSearchParent: Boolean;
    procedure SetResult(const Value: Pointer);

    property Description: WideString read GetDescription;
    property FunctionArgument: Pointer read GetFunctionArgument;
    property FunctionName: WideString read GetFunctionName;
    property ModuleName: WideString read GetModulName;
    property Result: Pointer read GetResult write SetResult;
    property SearchParent: Boolean read GetSearchParent;

    property OnPerformInput: TGrtPerformInput read GetPerformInputFunction;
    property OnPerformStatusQuery: TGrtPerformStatusQuery read GetPerformStatusQueryFunction;
    property OnProcessMessages: TGrtProcessMessages read GetProcessMessagesFunction;
  end;

  IGrtShellTask = interface(IGrtGenericTask)
  ['{9FA380B3-8B4D-49F9-961B-E217B8AE82B9}']
    function GetCommand: WideString;
    function GetResult: MYX_GRT_SHELL_COMMAND;
    procedure SetResult(const Value: MYX_GRT_SHELL_COMMAND);

    property Command: WideString read GetCommand;
    property Result: MYX_GRT_SHELL_COMMAND read GetResult write SetResult;
  end;

  // The main Delphi wrapper class to the Generic Runtime library.
  TGrt = class
  private
    FAccessLock: TCriticalSection;
    FNextTaskID: Integer;
    FStructIconsList: TTntStringList;

    FConsole: TUniCodeConsole;

    FVerbose: Boolean;
    FRemoteDebug: Boolean;
    FJvmLibrary: WideString;
    FJvmMaxHeap: WideString;
    FJavaClasspath: WideString;
    FShellInterface: WideString;

    FOnShutDown: TGrtOnShutDown;
  protected
    GrtSyncEvent: TEvent;
    FGrtEngine: TGrtEngine;

    function CreateGrtEngine: TGrtEngine; virtual;

    function GetJavaLoaderState: GrtLoaderState;
    function GetLuaLoaderState: GrtLoaderState;
    function GetBuiltinLoaderState: GrtLoaderState;
    {$ifdef ENABLE_PHP_MODULES}
    function GetPhpLoaderState: GrtLoaderState;
    {$endif}
    function GetUiLoaderState: GrtLoaderState;

    procedure OutputCommandLine(Text: WideString);

    function GrtNativeGrt: Pointer;

    function GetGlobal(const Path: WideString): Pointer;
    procedure SetGlobal(const Path: WideString; NewValue: Pointer);
    function GetGlobalAsString(const Path: WideString): WideString;
    procedure SetGlobalAsString(const Path: WideString; NewValue: WideString);
    function GetGlobalAsInt(const Path: WideString): Integer;
    procedure SetGlobalAsInt(const Path: WideString; NewValue: Integer);
    function GetGlobalAsReal(const Path: WideString): Double;
    procedure SetGlobalAsReal(const Path: WideString; NewValue: Double);
    function GetGlobalRef(const Path: WideString): Pointer;
    procedure SetGlobalRef(const Path: WideString; NewValue: Pointer);

    function GetListItem(const List: Pointer; const I: Integer): Pointer;
    procedure SetListItem(const List: Pointer; const I: Integer; NewValue: Pointer);
    function GetListString(const List: Pointer; const I: Integer): WideString;
    procedure SetListString(const List: Pointer; const I: Integer; NewValue: WideString);
    function GetListRefItem(const List: Pointer; const I: Integer): Pointer;
    procedure SetListRefItem(const List: Pointer; const I: Integer; NewValue: Pointer);
    function GetListItemByObjectName(const List: Pointer; const Name: WideString): Pointer;
    function GetListRefValueByObjectName(const List: Pointer; const Name: WideString): Pointer;

    function GetDictItem(const Dict: Pointer; const Key: WideString): Pointer;
    procedure SetDictItem(const Dict: Pointer; const Key: WideString; NewValue: Pointer);
    function GetDictString(const Dict: Pointer; const Key: WideString): WideString;
    procedure SetDictString(const Dict: Pointer; const Key: WideString; NewValue: WideString);
    function GetDictInt(const Dict: Pointer; const Key: WideString): Integer;
    procedure SetDictInt(const Dict: Pointer; const Key: WideString; NewValue: Integer);
    function GetDictReal(const Dict: Pointer; const Key: WideString): Double;
    procedure SetDictReal(const Dict: Pointer; const Key: WideString; NewValue: Double);
    function GetDictRef(const Dict: Pointer; const Key: WideString): Pointer;
    procedure SetDictRef(const Dict: Pointer; const Key: WideString; NewValue: Pointer);
    function GetDictKey(const Dict: Pointer; const I: Integer): WideString;

    function GetDictStructName(const Dict: Pointer): WideString;
    procedure SetDictStructName(const Dict: Pointer; StructName: WideString);

    function GetValueInt(const Value: Pointer): Integer;
    function GetValueString(const Value: Pointer): WideString;

    function GetOutputBuffer: WideString;
    procedure SetOutputBuffer(OutputBuffer: WideString);

    function GetShellVar(Name: WideString): Pointer;
    procedure SetShellVar(Name: WideString; Value: Pointer);
  public
    constructor Create(Console: TUniCodeConsole);
    destructor Destroy; override;

    property NativeGrt: Pointer read GrtNativeGrt;
    property Console: TUniCodeConsole read FConsole write FConsole;

    property OnShutDown: TGrtOnShutDown read FOnShutDown write FOnShutDown;

    // Options
    property Verbose: Boolean read FVerbose write FVerbose;
    property RemoteDebug: Boolean read FRemoteDebug write FRemoteDebug;
    property JvmLibrary: WideString read FJvmLibrary write FJvmLibrary;
    property JvmMaxHeap: WideString read FJvmMaxHeap write FJvmMaxHeap;
    property ShellInterface: WideString read FShellInterface write FShellInterface;

    // Loaders
    property JavaLoaderState: GrtLoaderState read GetJavaLoaderState;
    property LuaLoaderState: GrtLoaderState read GetLuaLoaderState;
    property BuiltinLoaderState: GrtLoaderState read GetBuiltinLoaderState;
    {$ifdef ENABLE_PHP_MODULES}
    property PhpLoaderState: GrtLoaderState read GetPhpLoaderState;
    {$endif}
    property UiLoaderState: GrtLoaderState read GetUiLoaderState;

    // Access values
    property Global[const Path: WideString]: Pointer read GetGlobal write SetGlobal;
    property GlobalAsString[const Path: WideString]: WideString read GetGlobalAsString write SetGlobalAsString;
    property GlobalAsInt[const Path: WideString]: Integer read GetGlobalAsInt write SetGlobalAsInt;
    property GlobalAsReal[const Path: WideString]: Double read GetGlobalAsReal write SetGlobalAsReal;
    property GlobalRef[const Path: WideString]: Pointer read GetGlobalRef write SetGlobalRef;
    procedure GlobalDel(const Path: WideString; const Key: WideString);

    // Access lists
    property ListItem[const List: Pointer; const I: Integer]: Pointer read GetListItem write SetListItem;
    property ListString[const List: Pointer; const I: Integer]: WideString read GetListString write SetListString;
    property ListRefItem[const List: Pointer; const I: Integer]: Pointer read GetListRefItem write SetListRefItem;
    property ListItemByObjectName[const List: Pointer; const Name: WideString]: Pointer read GetListItemByObjectName;
    property ListRefValueByObjectName[const List: Pointer; const Name: WideString]: Pointer read GetListRefValueByObjectName;

    function ListCount(List: Pointer): Integer;
    procedure ListInsert(List: Pointer; Index: Integer; Value: Pointer; IncreaseRefCount: Boolean = True);
    procedure ListAdd(List: Pointer; Value: Pointer; IncreaseRefCount: Boolean = True);
    procedure ListAddString(List: Pointer; Name: WideString);
    function ListDel(List: Pointer; Index: Integer): Boolean; overload;
    function ListDel(List: Pointer; Value: Pointer): Boolean; overload;
    function ListDelString(List: Pointer; Name: WideString): Boolean;
    function ListDelObject(List: Pointer; Name: WideString): Boolean;
    function ListNew(const ContentType: GrtValueType; const ContentStructName: WideString = ''): Pointer;
    procedure ListClear(List: Pointer);

    // Access dicts
    property DictItem[const Dict: Pointer; const Key: WideString]: Pointer read GetDictItem write SetDictItem;
    property DictString[const Dict: Pointer; const Key: WideString]: WideString read GetDictString write SetDictString;
    property DictInt[const Dict: Pointer; const Key: WideString]: Integer read GetDictInt write SetDictInt;
    property DictReal[const Dict: Pointer; const Key: WideString]: Double read GetDictReal write SetDictReal;
    property DictRef[const Dict: Pointer; const Key: WideString]: Pointer read GetDictRef write SetDictRef;
    property DictStructName[const Dict: Pointer]: WideString read GetDictStructName write SetDictStructName;
    property DictKey[const Dict: Pointer; const I: Integer]: WideString read GetDictKey;
    function DictNew(const StructName: WideString): Pointer;
    function DictNewTyped(const ContentType: GrtValueType;
      const ContentStructName: WideString): Pointer;
    function DictItemCount(const Dict: Pointer): Integer;
    procedure DictDel(const Dict: Pointer; const Key: WideString);

    function ObjectNew(const StructName: WideString;
      Name: WideString; Id: WideString; OwnerId: WideString): Pointer;

    // Simple Values
    property ValueInt[const Value: Pointer]: Integer read GetValueInt;
    property ValueString[const Value: Pointer]: WideString read GetValueString;
    function ValueFromString(S: WideString): Pointer;
    function ValueFromInt(I: Integer): Pointer;

    procedure ValueRetain(Value: Pointer);
    procedure ValueRelease(Value: Pointer);
    function ValueType(Value: Pointer): GrtValueType;
    function ValueDuplicate(Value: Pointer): Pointer;
    function ValueLoadFromFile(FileName: WideString): Pointer;
    procedure ValueSaveToFile(FileName: WideString; Value: Pointer);
    procedure ValueListenerAdd(Value: Pointer; CallbackObject: IGrtValueCallbackListener);
    procedure ValueListenerRemove(Value: Pointer; CallbackObject: IGrtValueCallbackListener);
    function ValueAsLuaCode(Value: Pointer; Indention: Integer): WideString;
    function ValueDiffMake(Source: Pointer; Target: Pointer): Pointer;
    function ValueDiffApply(Value: Pointer; Diff: Pointer): Pointer;
    function ValueReference(Value: Pointer): Pointer; overload;
    function ValueReference(Id: WideString): Pointer; overload;

    function GlobalSetRoot(Value: Pointer): Integer;

    // Structs / Members

    function GetStructCaption(StructName: WideString): WideString;
    function GetStructMemberCount(StructName: WideString): Integer;
    function GetStructMemberName(StructName: WideString; Index: Integer): WideString;
    function GetStructMemberType(StructName: WideString; Index: Integer): GrtValueType; overload;
    function GetStructMemberType(Member: Pointer): GrtValueType; overload;
    function GetStructMemberStructName(StructName: WideString; MemberName: WideString): WideString;
    function GetStructMemberContentType(StructName: WideString; Index: Integer): GrtValueType;
    function GetStructMemberContentStructName(StructName: WideString; MemberName: WideString): WideString; overload;
    function GetStructMemberContentStructName(StructName: WideString; Index: Integer): WideString; overload;
    function StructExists(StructName: WideString): Boolean;
    function StructInheritsFrom(StructName: WideString; ParentStructName: WideString): Boolean;
    function StructIsOrInheritsFrom(StructName: WideString; ParentStructName: WideString): Boolean;

    procedure AddTask(Task: IGrtGenericTask);
    procedure AddTaskAndWait(Task: IGrtGenericTask; ShowError: Boolean);
    procedure AddTaskAndWaitWithMessages(Task: IGrtGenericTask; ShowError: Boolean);
    function CreateStandardTask(Description, ModulName, FunctionName: WideString; FunctionArguments: array of const;
      ProcessOutputFunction: TGrtProcessOutput = nil; ProcessMessagesFunction: TGrtProcessMessages = nil;
      AllowNullAsResult: Boolean = False; SearchParent: Boolean = False; Timeout: Integer = -1;
      PerformInputFunction: TGrtPerformInput = nil; PerformStatusQueryFunction: TGrtPerformStatusQuery = nil;
      TaskFinishedCallback: TGrtTaskFinished = nil; TaskTag: Integer = 0;
      DataObj: TObject = nil): IGrtTask;
    function CreateShellTask(Command: WideString; ProcessOutputFunction: TGrtProcessOutput = nil;
      Timeout: Integer = -1; TaskFinishedCallback: TGrtTaskFinished = nil): IGrtShellTask;
    procedure ExecuteScriptTask(FileName: WideString; ShowError: Boolean; ProcessOutputFunction: TGrtProcessOutput = nil;
      TimeOutMS: Integer = -1);
    function ExecuteStandardTask(Description, ModulName, FunctionName: WideString; FunctionArguments: array of const;
      ShowError: Boolean): Pointer;
    procedure RemoveTask(Task: IGrtGenericTask);

    function GetGlobalAsParam(Path: WideString): WideString;

    procedure AddDelphiModule(ModuleName: WideString; ModuleFunctions: WideString;
      Implementor: IGrtModuleImplementor);
    procedure RemoveDelphiModule(ModuleName: WideString;
      Implementor: IGrtModuleImplementor);

    function FunctionSuccess(Value: Pointer): Pointer;
    function FunctionError(ErrorString: WideString; ErrorDetails: WideString = ''): Pointer;

    property OutputBuffer: WideString read GetOutputBuffer write SetOutputBuffer;

    // Caches
    property StructIconsList: TTntStringList read FStructIconsList;

    // Helper functions
    function BuildGrtParamList(Params: array of const): Pointer;
    function FormatGrtMessagesAsString(Msgs: TMYX_GRT_MSGS): WideString;
    procedure Lock;
    procedure Unlock;
    procedure ScriptInputRead;

    property ShellVar[Name: WideString]: Pointer read GetShellVar write SetShellVar;

    procedure AddObjToReferenceCache(Dict: Pointer);
  end;

  TGrtClass = class of TGrt;

  PCallbackEntry = ^TCallbackEntry;
  TCallbackEntry = record
    Type_: Integer;
    TextForOutput: WideString;
    Messages: TMYX_GRT_MSGS;
  end;

  // The task list is basically a thread safe queue (FIFO) for interfaces.
  // Duplicates are allowed.
  TGrtTaskList = class(TObject)
  private
    FList: TInterfaceList;
    FLock: TRTLCriticalSection;
    function GetEmpty: Boolean;
    procedure SetEmpty(const Value: Boolean);
  public
    constructor Create;
    destructor Destroy; override;

    procedure Clear;
    function  LockList: TInterfaceList;
    function Pop: IGrtGenericTask;
    procedure Push(Task: IGrtGenericTask);
    procedure Remove(Task: IGrtGenericTask);
    procedure UnlockList;

    property Empty: Boolean read GetEmpty write SetEmpty;
  end;

  TGrtEngine = class(TThread)
  private
    FGrt: TGrt;
    FNativeGrt: Pointer;
    FWorkQueue: TGrtTaskList;
    FWorkEvent: TEvent;
    FCurrentTask: IGrtGenericTask;

    FDelphiModuleName,
    FDelphiModuleFunctionName: WideString;
    FDelphiModuleImplementor: IGrtModuleImplementor;
    FDelphiModuleFunctionArgument,
    FDelphiModuleFunctionResult: Pointer;

    FTextForOutput: WideString;
    FStatus: Integer;

    FTextInput: WideString;

    FJavaLoaderState,
    FLuaLoaderState,
    FBuiltinLoaderState,
    {$ifdef ENABLE_PHP_MODULES}
    FPhpLoaderState: GrtLoaderState;
    {$endif}
    FUiLoaderState: GrtLoaderState;
    FDelphiGrtMessages: TMYX_GRT_MSGS;
    FInputBuffer: Array [0 .. 160] of Char;
    FOutputBuffer: WideString;
    FNativeLoader: Pointer;
    FCallbackEntries: TThreadList;
  protected

    procedure ClearCallbackEntries;
    procedure AddCallbackEntry(AType: Integer; OutputText: WideString; Messages: PMYX_GRT_MSGS);
    procedure DoChangeCallback;
    function ApplicationHook(var Message: TMessage): Boolean; virtual;
    procedure Execute; override;

    procedure InitializeGrt;
    procedure InitializeLoadersAndModules; virtual;

    procedure FinalizeGrt;
    procedure FinalizeLoadersAndModules; virtual;

    function GetNativeGrt: Pointer;

    procedure DoOutputText(S: WideString);
    procedure DoProcessMessages(Messages: TMYX_GRT_MSGS);
    procedure DoGrtInputText;
    procedure DoStatusQuery;

    function InitDelphiLoader(Error: PMYX_GRT_ERROR): Pointer;

    procedure ExecuteDelphiFunction;

    procedure OutputModuleStatus(LoaderName: WideString; LoadedModuleCount: Integer; Error: MYX_GRT_ERROR);
    procedure TaskFinished;
  public
    constructor Create(CreateSuspended: Boolean; Grt: TGrt); virtual;
    destructor Destroy; override;

    property Grt: TGrt read FGrt;
    property NativeGrt: Pointer read GetNativeGrt;
    property OutputBuffer: WideString read FOutputBuffer write FOutputBuffer;

    property DelphiGrtMessages: TMYX_GRT_MSGS read FDelphiGrtMessages;

    procedure AddTask(Task: IGrtGenericTask);
    procedure AddTaskAndWait(Task: IGrtGenericTask);
    procedure AddTaskAndWaitWithMessages(Task: IGrtGenericTask);
    procedure RemoveTask(Task: IGrtGenericTask);

    procedure OutputText(S: WideString);
    function ProcessMessages(PMessages: PMYX_GRT_MSGS): Integer;
    function GrtInputText(Caption: WideString; options: MYX_GRT_INPUT_OPTIONS; Text: PPointer): integer;
    function GrtStatusQuery: Integer;

    procedure AddDelphiModule(ModuleName: WideString; ModuleFunctions: WideString;
      Implementor: IGrtModuleImplementor);
    procedure RemoveDelphiModule(ModuleName: WideString;
      Implementor: IGrtModuleImplementor);
  end;

  EGrtError = class(Exception)
  private
    FErrorNumber: Integer;
    FDescription: WideString;
  public
    constructor Create(ErrorNumber: Integer; Description: WideString);

    property ErrorNumber: Integer read FErrorNumber;
    property Description: WideString read FDescription;
  end;

function GetListMemberCount(Grt: Pointer; StructName: WideString; OnlyCheck: Boolean): Integer;
function GetListMember(Grt: Pointer; StructName: WideString; Index: Integer): Pointer;
function FormatGrtMessagesAsString(Msgs: TMYX_GRT_MSGS): WideString;
function GetGrtFunctionArgumentAsString(Argument: Pointer): WideString;

function RuntimeEnvironment: TGrt;
procedure SetGrtClass(AClass: TGrtClass);

procedure InitThreads;

//----------------------------------------------------------------------------------------------------------------------

implementation

var
  GrtClass: TGrtClass;        // Determines which actual class to use for the runtime environment.
  InternalGrtInstance: TGrt;

const
  WM_PROCESS_CALLBACK = WM_APP + 10001;

type
  TGrtGenericTask = class(TInterfacedObject, IGrtGenericTask)
  private
    FGrt: TGrt;
    FTaskID: Integer;
    FTimeOut: Integer;
    FExecutionTime: Cardinal; // Execution time in milliseconds.
    FWaitEvent: TEvent;
    FAllowNullResult: Boolean;
    FErrorString: WideString;
    FErrorCode: MYX_GRT_ERROR;
    FTag: Integer;
    FDataObj: TObject;

    FOnProcessOutput: TGrtProcessOutput;
    FOnTaskFinished: TGrtTaskFinished;

    function GetAllowNullResult: Boolean;
    function GetDataObj: TObject;
    function GetErrorCode: MYX_GRT_ERROR;
    function GetErrorString: WideString;
    function GetExecutionTime: Cardinal;
    function GetProcessOutputFunction: TGrtProcessOutput;
    function GetTag: Integer;
    function GetTaskFinishedFunction: TGrtTaskFinished;
    function GetTaskID: Integer;
    function GetTimeout: Integer;
    procedure SetErrorCode(const Value: MYX_GRT_ERROR);
    procedure SetErrorString(const Value: WideString);
    procedure SetEvent;
    procedure SetExecutionTime(const Value: Cardinal);
    procedure SetTag(Tag: Integer);
  public
    destructor Destroy; override;

    procedure WaitFor(WithMessages: Boolean);
    procedure PrepareSynchronization;
  end;

  TGrtTask = class(TGrtGenericTask, IGrtTask)
  private
    FDescription: WideString;
    FModulName: WideString;
    FFunctionName: WideString;
    FFunctionArguments: Pointer;
    FSearchParent: Boolean;
    FResult: Pointer;

    FONProcessMessages: TGrtProcessMessages;
    FOnPerformInput: TGrtPerformInput;
    FOnPerformStatusQuery: TGrtPerformStatusQuery;

    function GetDescription: WideString;
    function GetFunctionArgument: Pointer;
    function GetFunctionName: WideString;
    function GetModulName: WideString;
    function GetPerformInputFunction: TGrtPerformInput;
    function GetPerformStatusQueryFunction: TGrtPerformStatusQuery;
    function GetProcessMessagesFunction: TGrtProcessMessages;
    function GetResult: Pointer;
    function GetSearchParent: Boolean;
    procedure SetResult(const Value: Pointer);
  public
    destructor Destroy; override;
  end;

  TGrtShellTask = class(TGrtGenericTask, IGrtShellTask)
  private
    FCommand: WideString;
    FResult: MYX_GRT_SHELL_COMMAND;

    FOnProcessOutput: TGrtProcessOutput;

    function GetCommand: WideString; 
    function GetResult: MYX_GRT_SHELL_COMMAND;
    procedure SetResult(const Value: MYX_GRT_SHELL_COMMAND);
  end;

//----------------------------------------------------------------------------------------------------------------------

procedure InitThreads;

begin
  myx_grt_init_threads();
end;

//----------------------------------------------------------------------------------------------------------------------

function RuntimeEnvironment: TGrt;

begin
  if (InternalGrtInstance = nil) then
    InternalGrtInstance := GrtClass.Create(nil);

  Result := InternalGrtInstance;
end;

//----------------------------------------------------------------------------------------------------------------------

function GrtValueCallback(grt: Pointer; value: Pointer; reason: MYX_GRT_VALUE_CALLBACK_REASON; user_data: Pointer): Integer; cdecl;

var
  Obj: IGrtValueCallbackListener;

begin
  Obj := IGrtValueCallbackListener(user_data);

  Result := Obj.ValueChange(value, GrtValueCallbackReason(reason));
end;

//----------------------------------------------------------------------------------------------------------------------

procedure ProcessGrtOutput(text: PChar; userdata: Pointer) cdecl;

var
  GrtEngine: TGrtEngine;
  S: WideString;

begin
  GrtEngine := userdata;
  S := UTF8Decode(text);

  GrtEngine.OutputText(S);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure ProcessGrtMessages(PMessages: PMYX_GRT_MSGS; userdata: Pointer) cdecl;

var
  GrtEngine: TGrtEngine;

begin
  GrtEngine := userdata;

  GrtEngine.ProcessMessages(PMessages);
end;

//----------------------------------------------------------------------------------------------------------------------

function ProcessInput(caption: PChar; options: MYX_GRT_INPUT_OPTIONS; text: PPointer; user_data: Pointer): Integer cdecl;

var
  GrtEngine: TGrtEngine;
  S: WideString;

begin
  GrtEngine := user_data;
  S := UTF8Decode(caption);

  Result := GrtEngine.GrtInputText(S, options, text);
end;

//----------------------------------------------------------------------------------------------------------------------

function ProcessStatusQuery(user_data: Pointer): Integer cdecl;

var
  GrtEngine: TGrtEngine;

begin
  GrtEngine := user_data;

  Result := GrtEngine.GrtStatusQuery();
end;

//----------------------------------------------------------------------------------------------------------------------

constructor TGrt.Create(Console: TUniCodeConsole);

var
  TimeStart: TDateTime;
  TimeOut: Boolean;
  TimeOutInterval: TDateTime;
  WaitResult: Cardinal;
  WaitHandle: THandle;
  I: Integer;
  InitScriptFile: WideString;

begin
  inherited Create;

  FStructIconsList := TTntStringList.Create;
  FAccessLock := TCriticalSection.Create;
  FOnShutDown := nil;

  I := 1;

  // get startup arguments from command line
  Verbose := False;
  RemoteDebug := False;
  JvmLibrary := '';
  InitScriptFile := '';
  FShellInterface := 'lua';
  FJavaClasspath := 'java';
  JvmMaxHeap := '';

  while (I <= WideParamCount) do
  begin
    if (WideSameText(WideParamStr(I), '-verbose')) then
      FVerbose := True
    else
      if (WideSameText(WideParamStr(I), '-debug')) then
        FRemoteDebug := True
      else
        if (WideSameText(WideParamStr(I), '-py')) then
          FShellInterface := 'python'
        else
          if (WideSameText(WideParamStr(i), '-jvm')) and
            (i < WideParamCount) then
          begin
            FJvmLibrary := WideParamStr(i + 1);
            inc(i);
          end
          else
            if (WideSameText(WideParamStr(i), '-classpath')) and
              (i < WideParamCount) then
            begin
              FJavaClasspath := WideExcludeTrailingPathDelimiter(
                WideParamStr(i + 1));
              inc(i);
            end
            else
              if (WideSameText(WideParamStr(i), '-initscript')) and (i < ParamCount) then
              begin
                InitScriptFile := WideParamStr(i + 1);
                inc(i);
              end
              else
                if (Length(WideParamStr(i)) > 4) and
                  (WideSameText(Copy(WideParamStr(i), 1, 4), '-Xmx')) then
                begin
                  JvmMaxHeap := WideParamStr(i);
                end
                else
                  if (WideSameText(WideParamStr(i), '-Xmx')) and
                    (i < WideParamCount) then
                  begin
                    JvmMaxHeap := '-Xmx' + WideParamStr(i + 1);
                    inc(i);
                  end;

    inc(I);
  end;

  FConsole := Console;

  GrtSyncEvent := TEvent.Create(nil, False, False, '');

  FGrtEngine := CreateGrtEngine;
  FGrtEngine.FreeOnTerminate := False;

  // Wait for 20 sek
  TimeOut := False;
  TimeStart := Now;
  TimeOutInterval := (1 / 86400) * 20 * 10 * (1 * 10000);
  WaitHandle := GrtSyncEvent.Handle;

  while (not (TimeOut)) do
  begin
    // Wait for the initialisation to finish but every
    // 100 milliseonds check if the timeout value has been reached.
    // Process any incomming message while we wait.
    WaitResult := MsgWaitForMultipleObjects(
      1, WaitHandle, false, 100, QS_ALLEVENTS);
    if WaitResult = WAIT_OBJECT_0 then
      Break;

    Application.ProcessMessages;

    if (Now - TimeStart > TimeOutInterval) then
      TimeOut := True;
  end;

  if (TimeOut) then
    raise Exception.Create(_('Could not initialize the GRT Environment. ' +
      'A timeout occured during the initalization.'));

  GrtSyncEvent.Free;
  GrtSyncEvent := nil;

  if (InitScriptFile <> '') and (FGrtEngine.NativeGrt <> nil) then
    myx_grt_shell_run_file(FGrtEngine.NativeGrt, InitScriptFile, 1);
end;

//----------------------------------------------------------------------------------------------------------------------

destructor TGrt.Destroy;

var
  I: Integer;

begin
  if (Assigned(FOnShutDown)) then
    FOnShutDown(self);

  //myx_grt_value_release(myx_grt_get_root(NativeGrt));

  // Free FGrtStructIconsList
  for I := 0 to FStructIconsList.Count - 1 do
    FStructIconsList.Objects[I].Free;
  FStructIconsList.Free;

  FGrtEngine.Terminate;
  FGrtEngine.WaitFor;
  FGrtEngine.Free;
  FAccessLock.Free;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.CreateGrtEngine: TGrtEngine;

begin
  Result := TGrtEngine.Create(False, self);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetJavaLoaderState: GrtLoaderState;

begin
  Result := FGrtEngine.FJavaLoaderState;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetLuaLoaderState: GrtLoaderState;

begin
  Result := FGrtEngine.FLuaLoaderState;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetBuiltinLoaderState: GrtLoaderState;

begin
  Result := FGrtEngine.FBuiltinLoaderState;
end;

//----------------------------------------------------------------------------------------------------------------------

{$ifdef ENABLE_PHP_MODULES}
function TGrt.GetPhpLoaderState: GrtLoaderState;

begin
  Result := FGrtEngine.FUiLoaderState;
end;
{$endif}

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetUiLoaderState: GrtLoaderState;

begin
  Result := FGrtEngine.FUiLoaderState;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.OutputCommandLine(Text: WideString);

begin
  if Assigned(FConsole) then
    FConsole.AddOutput(Text + #13#10);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GrtNativeGrt: Pointer;

begin
  Result := FGrtEngine.NativeGrt;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.AddTask(Task: IGrtGenericTask);

// Adds the given task to the task list of the underlying Grt engine.
// It is allowed to add the same task more than once.

begin
  FGrtEngine.AddTask(Task);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.AddTaskAndWait(Task: IGrtGenericTask; ShowError: Boolean);

// Works like AddTask except that the caller is blocked until the task is finished.
// The value given as Timeout during task creation can be used to either block undefinedly (-1) or a certain amount.

var
  StandardTask: IGrtTask;

begin
  FGrtEngine.AddTaskAndWait(Task);

  if ShowError and ((Task.ErrorCode <> MYX_GRT_NO_ERROR) or (Task.ErrorString <> '')) then
    if Supports(Task, IGrtTask, StandardTask) then
      raise EGrtError.Create(Ord(Task.ErrorCode), StandardTask.ModuleName + '.' + StandardTask.FunctionName + ' :' +
        Task.ErrorString)
    else
      raise EGrtError.Create(Ord(Task.ErrorCode), Task.ErrorString);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.AddTaskAndWaitWithMessages(Task: IGrtGenericTask; ShowError: Boolean);

// Works like AddTaskAndWait except that the applications can process its messages.
// This is a potential reentrancy problem and therefor this method should only be used by old code.
// Instead use the asynchronous way to wait for a task to finish.

var
  StandardTask: IGrtTask;

begin
  FGrtEngine.AddTaskAndWaitWithMessages(Task);

  if ShowError and ((Task.ErrorCode <> MYX_GRT_NO_ERROR) or (Task.ErrorString <> '')) then
    if Supports(Task, IGrtTask, StandardTask) then
      raise EGrtError.Create(Ord(Task.ErrorCode), StandardTask.ModuleName + '.' + StandardTask.FunctionName + ' :' +
        Task.ErrorString)
    else
      raise EGrtError.Create(Ord(Task.ErrorCode), Task.ErrorString);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.CreateStandardTask(Description, ModulName, FunctionName: WideString; FunctionArguments: array of const;
      ProcessOutputFunction: TGrtProcessOutput; ProcessMessagesFunction: TGrtProcessMessages;
      AllowNullAsResult: Boolean; SearchParent: Boolean; Timeout: Integer; PerformInputFunction: TGrtPerformInput;
      PerformStatusQueryFunction: TGrtPerformStatusQuery; TaskFinishedCallback: TGrtTaskFinished;
      TaskTag: Integer; DataObj: TObject): IGrtTask;

// Creates a new task entry filled with the given values. The task is not yet added to the internal task list
// of the underlying GRT engine thread. Use AddTask for this.

var
  Task: TGrtTask;

begin
  Task := TGrtTask.Create;
  Task.FGrt := Self;

  Lock;
  Task.FTaskID := FNextTaskID;
  Inc(FNextTaskID);
  Unlock;

  Task.FDescription := Description;
  Task.FExecutionTime := 0;
  Task.FModulName := ModulName;
  Task.FFunctionName := FunctionName;
  Task.FFunctionArguments := BuildGrtParamList(FunctionArguments);
  Task.FSearchParent := SearchParent;
  Task.FTimeOut := TimeOut;
  Task.FAllowNullResult := AllowNullAsResult;

  Task.FOnProcessOutput := ProcessOutputFunction;
  Task.FOnProcessMessages := ProcessMessagesFunction;
  Task.FOnPerformInput := PerformInputFunction;
  Task.FOnPerformStatusQuery := PerformStatusQueryFunction;
  Task.FOnTaskFinished := TaskFinishedCallback;
  Task.FTag := TaskTag;
  Task.FDataObj := DataObj;

  Task.FResult := nil;
  Result := Task; // Returns the interface, sets the current ref count to 1 and starts so the life cycle of the task.
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.CreateShellTask(Command: WideString; ProcessOutputFunction: TGrtProcessOutput;
  Timeout: Integer; TaskFinishedCallback: TGrtTaskFinished): IGrtShellTask;

// Creates a new task entry filled with the given values. The task is not yet added to the internal task list
// of the underlying GRT engine thread. Use AddTask for this.
// This method is especially for shell tasks as they need fewer parameters.

var
  Task: TGrtShellTask;

begin
  Task := TGrtShellTask.Create;
  with Task do
  begin
    FGrt := Self;

    Lock;
    FTaskID := FNextTaskID;
    Inc(FNextTaskID);
    Unlock;

    FExecutionTime := 0;
    FTimeOut := TimeOut;
    FCommand := Command;

    FOnProcessOutput := ProcessOutputFunction;
    FOnTaskFinished := TaskFinishedCallback;

    FResult := MYX_GRT_SHELL_COMMAND_UNKNOWN;
  end;
  Result := Task; // Returns the interface, sets the current ref count to 1 and starts so the life cycle of the task.
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ExecuteScriptTask(FileName: WideString; ShowError: Boolean; ProcessOutputFunction: TGrtProcessOutput;
  TimeOutMS: Integer);

var
  Script: TTntStringList;
  Task: IGrtShellTask;
  
begin
  if WideFileExists(FileName) then
  begin
    Script := TTntStringList.Create;
    try
      Script.LoadFromFile(FileName);
      if Script.Count > 0 then
      begin
        Task := CreateShellTask(Script.Text, ProcessOutputFunction, TimeOutMS);
        AddTaskAndWait(Task, ShowError);
      end;
    finally
      Script.Free;
    end;
  end
  else
    ShowModalDialog(_('Script file not found'), Format(_('The script file %s cannot be found.'), [FileName]),
      myx_mtError);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ExecuteStandardTask(Description, ModulName, FunctionName: WideString; FunctionArguments: array of const;
  ShowError: Boolean): Pointer;

// Simplified task creation and execution function to be used for tasks without callbacks/events.
// This method always waits until the task is finished.

var
  Task: IGrtTask;

begin
  Task := CreateStandardTask(Description, ModulName, FunctionName, FunctionArguments);
  AddTaskAndWait(Task, ShowError);
  Result := Task.Result;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.RemoveTask(Task: IGrtGenericTask);

// Removes the given task from the task list of the underlying GRT engine thread.
// It does not harm if the task is not in that list.

begin
  FGrtEngine.RemoveTask(Task);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.BuildGrtParamList(Params: array of const): Pointer;

var
  ParamList: Pointer;
  Param: Pointer;
  I: Integer;

begin
  ParamList := myx_grt_list_new(MYX_ANY_VALUE, '');

  for I := 0 to High(Params) do
  begin
    with Params[I] do
      case VType of
        vtInteger:
          Param := myx_grt_value_from_int(VInteger);
        vtExtended:
          Param := myx_grt_value_from_real(VExtended^);
        vtWideString:
          Param := myx_grt_value_from_string(WideString(VWideString));
        vtString:
          Param := myx_grt_value_from_string(VString^);
        vtAnsiString:
          Param := myx_grt_value_from_string(string(VAnsiString));
        vtChar:
          Param := myx_grt_value_from_string(VChar);
        vtPChar:
          Param := myx_grt_value_from_string(VPChar);
        vtPointer:
          Param := VPointer;
        vtObject:
          Param := VObject;
      else
        raise EInOutError.Create(_('BuildGrtParamList called with unsupported parameter type.'));
      end;

    myx_grt_list_item_add(ParamList, Param);

    if not (Params[I].VType in [vtPointer, vtObject]) then
      ValueRelease(Param);
  end;

  Result := ParamList;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.AddDelphiModule(ModuleName: WideString; ModuleFunctions: WideString;
  Implementor: IGrtModuleImplementor);

begin
  FGrtEngine.AddDelphiModule(ModuleName, ModuleFunctions, Implementor);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.RemoveDelphiModule(ModuleName: WideString;
  Implementor: IGrtModuleImplementor);

begin
  FGrtEngine.RemoveDelphiModule(ModuleName, Implementor);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.FunctionSuccess(Value: Pointer): Pointer;

begin
  Result := DictNew('');

  DictItem[Result, 'value'] := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.FunctionError(ErrorString: WideString; ErrorDetails: WideString): Pointer;

begin
  Result := DictNew('');

  DictItem[Result, 'error'] := ValueFromString(ErrorString);
  if (ErrorDetails <> '') then
    DictItem[Result, 'detail'] := ValueFromString(ErrorDetails);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetGlobal(const Path: WideString): Pointer;

begin
  Result := myx_grt_dict_item_get_by_path(NativeGrt, myx_grt_get_root(NativeGrt), Path);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetGlobal(const Path: WideString; NewValue: Pointer);

begin
  if (myx_grt_dict_item_set_by_path(myx_grt_get_root(NativeGrt), Path, NewValue) <> 0) then
    raise Exception.Create(Format(_('The value %s cannot be set.'), [Path]));
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetGlobalAsString(const Path: WideString): WideString;

var
  PValue: Pointer;

begin
  PValue := Global[Path];

  if (PValue <> nil) then
  begin
    if (myx_grt_value_get_type(PValue) <> MYX_STRING_VALUE) then
      raise Exception.Create(Format(
        _('The value %s is not a string value.'),
        [Path]));

    Result := myx_grt_value_as_string(PValue);
  end
  else
    Result := '';
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetGlobalAsString(const Path: WideString; NewValue: WideString);

begin
  Global[Path] := myx_grt_value_from_string(NewValue);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetGlobalAsInt(const Path: WideString): Integer;

var
  PValue: Pointer;

begin
  PValue := Global[Path];

  if (PValue <> nil) then
  begin
    if (myx_grt_value_get_type(PValue) <> MYX_INT_VALUE) then
      raise Exception.Create(Format(
        _('The value %s is not a int value.'),
        [Path]));

    Result := myx_grt_value_as_int(PValue);
  end
  else
    Result := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetGlobalAsInt(const Path: WideString; NewValue: Integer);

begin
  Global[Path] := myx_grt_value_from_int(NewValue);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetGlobalAsReal(const Path: WideString): Double;

var
  PValue: Pointer;

begin
  PValue := Global[Path];

  if (PValue <> nil) then
  begin
    if (myx_grt_value_get_type(PValue) <> MYX_INT_VALUE) then
      raise Exception.Create(Format(
        _('The value %s is not a real value.'),
        [Path]));

    Result := myx_grt_value_as_real(PValue);
  end
  else
    Result := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetGlobalAsReal(const Path: WideString; NewValue: Double);

begin
  Global[Path] := myx_grt_value_from_real(NewValue);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetGlobalRef(const Path: WideString): Pointer;

var
  Id: WideString;

begin
  Result := nil;

  Id := GetGlobalAsString(Path);
  if (Id <> '') then
    Result := myx_grt_reference_cache_lookup(NativeGrt, Id);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetGlobalRef(const Path: WideString; NewValue: Pointer);

begin
  Global[Path] := DictItem[NewValue, '_id'];
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.GlobalDel(const Path: WideString; const Key: WideString);

var
  Value: Pointer;

begin
  Value := myx_grt_dict_item_get_by_path(NativeGrt, myx_grt_get_root(NativeGrt), Path);

  if (ValueType(Value) = GrtDictValue) then
    myx_grt_dict_item_del(Value, Key)
  else
    if (ValueType(Value) = GrtListValue) then
      myx_grt_list_item_del(Value, StrToInt(Key));
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueType(Value: Pointer): GrtValueType;

begin
  Result := GrtValueType(myx_grt_value_get_type(Value));
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueDuplicate(Value: Pointer): Pointer;

begin
  Result := myx_grt_value_dup(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueLoadFromFile(FileName: WideString): Pointer;

begin
  Result := myx_grt_retrieve_from_file(NativeGrt, FileName);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ValueSaveToFile(FileName: WideString; Value: Pointer);

var
  Error: MYX_GRT_ERROR;

begin
  Error := myx_grt_store_to_file(NativeGrt, Value, FileName);

  if (Error <> MYX_GRT_NO_ERROR) then
    raise Exception.CreateFmt(
      _('The following error occured. Error Nr. %d'), [Ord(Error)]);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ValueListenerAdd(Value: Pointer; CallbackObject: IGrtValueCallbackListener);
begin
  myx_grt_value_listener_add(NativeGrt, Value, Pointer(CallbackObject), @GrtValueCallback);

  // Add a reference because a pointer to the interfaces is store in the GRT
  CallbackObject._AddRef;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ValueListenerRemove(Value: Pointer; CallbackObject: IGrtValueCallbackListener);

begin
  myx_grt_value_listener_remove(Value, Pointer(CallbackObject), @GrtValueCallback);

  // Release refcount since the interface ref is now no longer stored in the GRT
  CallbackObject._Release;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GlobalSetRoot(Value: Pointer): Integer;

begin
  Result := Ord(myx_grt_set_root(NativeGrt, Value));
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ValueRetain(Value: Pointer);

begin
  myx_grt_value_retain(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ValueRelease(Value: Pointer);

begin
  myx_grt_value_release(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetStructMemberCount(StructName: WideString): Integer;

var
  Struct: Pointer;

begin
  Struct := myx_grt_struct_get(NativeGrt, StructName);

  if (Struct <> nil) then
    Result := myx_grt_struct_get_member_count_total(NativeGrt, Struct)
  else
    Result := -1;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetStructMemberName(StructName: WideString; Index: Integer): WideString;

var
  Struct,
  Member: Pointer;

begin
  Result := '';

  Struct := myx_grt_struct_get(NativeGrt, StructName);

  if (Struct <> nil) then
  begin
    Member := myx_grt_struct_get_member_by_index_total(NativeGrt, Struct, Index);

    if (Member <> nil) then
      Result := myx_grt_struct_get_member_name(Member);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetStructMemberType(StructName: WideString; Index: Integer): GrtValueType;

var
  Struct,
  Member: Pointer;

begin
  Result := GrtAnyValue;

  Struct := myx_grt_struct_get(NativeGrt, StructName);

  if (Struct <> nil) then
  begin
    Member := myx_grt_struct_get_member_by_index_total(NativeGrt, Struct, Index);

    if (Member <> nil) then
      Result := GrtValueType(myx_grt_struct_member_get_type(Member));
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetStructMemberType(Member: Pointer): GrtValueType;

begin
  Result := GrtAnyValue;

  if (Member <> nil) then
    Result := GrtValueType(myx_grt_struct_member_get_type(Member));
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetStructMemberContentType(StructName: WideString; Index: Integer): GrtValueType;

var
  Struct,
  Member: Pointer;

begin
  Result := GrtAnyValue;

  Struct := myx_grt_struct_get(NativeGrt, StructName);

  if (Struct <> nil) then
  begin
    Member := myx_grt_struct_get_member_by_index_total(NativeGrt, Struct, Index);

    if (Member <> nil) then
      Result := GrtValueType(myx_grt_struct_member_get_content_type(Member));
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetStructMemberStructName(StructName: WideString; MemberName: WideString): WideString;

var
  Struct,
  Member: Pointer;

begin
  Result := '';

  Struct := myx_grt_struct_get(NativeGrt, StructName);

  if (Struct <> nil) then
  begin
    Member := myx_grt_struct_get_member_by_name(NativeGrt, Struct, MemberName, 1);

    if (Member <> nil) then
      Result := myx_grt_struct_member_get_struct_name(Member);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetStructMemberContentStructName(StructName: WideString; MemberName: WideString): WideString;

var
  Struct,
  Member: Pointer;

begin
  Result := '';

  Struct := myx_grt_struct_get(NativeGrt, StructName);

  if (Struct <> nil) then
  begin
    Member := myx_grt_struct_get_member_by_name(NativeGrt, Struct, MemberName, 1);

    if (Member <> nil) then
      Result := myx_grt_struct_member_get_content_struct_name(Member);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetStructMemberContentStructName(StructName: WideString; Index: Integer): WideString;

var
  Struct,
  Member: Pointer;

begin
  Result := '';

  Struct := myx_grt_struct_get(NativeGrt, StructName);

  if (Struct <> nil) then
  begin
    Member := myx_grt_struct_get_member_by_index_total(NativeGrt, Struct, Index);

    if (Member <> nil) then
      Result := myx_grt_struct_member_get_content_struct_name(Member);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetStructCaption(StructName: WideString): WideString;

var
  Struct: PMYX_GRT_STRUCT;
  InheritedCaption: Integer;

begin
  Struct := myx_grt_struct_get(NativeGrt, StructName);

  Result := myx_grt_struct_get_caption(NativeGrt, Struct, @InheritedCaption);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.StructExists(StructName: WideString): Boolean;

begin
  Result := (myx_grt_struct_get(NativeGrt, StructName) <> nil);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.StructInheritsFrom(StructName: WideString; ParentStructName: WideString): Boolean;

begin
  Result := (myx_grt_struct_inherits_from(NativeGrt, StructName, ParentStructName) = 1);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.StructIsOrInheritsFrom(StructName: WideString; ParentStructName: WideString): Boolean;

begin
  Result := (myx_grt_struct_is_or_inherits_from(NativeGrt, StructName, ParentStructName) = 1);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.FormatGrtMessagesAsString(Msgs: TMYX_GRT_MSGS): WideString;

begin
  Result := FormatGrtMessagesAsString(Msgs);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ListCount(List: Pointer): Integer;

begin
  Result := myx_grt_list_item_count(List);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetListItem(const List: Pointer; const I: Integer): Pointer;

begin
  Result := myx_grt_list_item_get(List, I);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetListItem(const List: Pointer; const I: Integer; NewValue: Pointer);

begin
  myx_grt_list_item_set(List, I, NewValue);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetListString(const List: Pointer; const I: Integer): WideString;

begin
  Result := myx_grt_list_item_get_as_string(List, I);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetListString(const List: Pointer; const I: Integer; NewValue: WideString);

var
  Value: Pointer;
  OrgValue: Pointer;
  ValueType: MYX_GRT_VALUE_TYPE;
  
begin
  // Check what the original value's type is and auto-convert the given string to a native type if possible.
  OrgValue := myx_grt_list_item_get(List, I);
  ValueType := myx_grt_value_get_type(OrgValue);
  case ValueType of
    MYX_INT_VALUE:
      try
        Value := myx_grt_value_from_int(StrToInt(NewValue));
      except
        raise Exception.Create(Format(_('The string %s cannot be converted to an integer value.'), [NewValue]));
      end;
    MYX_REAL_VALUE:
      try
        Value := myx_grt_value_from_real(StrToFloat(NewValue));
      except
        raise Exception.Create(Format(_('The string %s cannot be converted to a float value.'), [NewValue]));
      end;
  else
    // Everything else.
    Value := myx_grt_value_from_string(NewValue);
  end;
  myx_grt_list_item_set(List, I, Value);
  myx_grt_value_release(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetListRefItem(const List: Pointer; const I: Integer): Pointer;

begin
  Result := myx_grt_list_item_get_reference_value(NativeGrt, List, I);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetListRefItem(const List: Pointer; const I: Integer; NewValue: Pointer);

var
  Value: Pointer;

begin
  Value := myx_grt_value_from_string(DictString[NewValue, '_id']);

  myx_grt_list_item_set(List, I, Value);

  myx_grt_value_release(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetListItemByObjectName(const List: Pointer; const Name: WideString): Pointer;

begin
  Result := myx_grt_list_item_get_by_object_name(List, Name);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetListRefValueByObjectName(const List: Pointer; const Name: WideString): Pointer;

begin
  Result := myx_grt_list_item_get_reference_value_by_object_name(NativeGrt, List, Name);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ListAdd(List: Pointer; Value: Pointer; IncreaseRefCount: Boolean);

begin
  myx_grt_list_item_add(List, Value);

  // as myx_grt_list_item_add increases refcount,
  // release it one time if it should not be increased
  if (not (IncreaseRefCount)) then
    myx_grt_value_release(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ListAddString(List: Pointer; Name: WideString);

var
  Value: Pointer;

begin
  Value := ValueFromString(Name);

  ListAdd(List, Value, False);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ListInsert(List: Pointer; Index: Integer; Value: Pointer; IncreaseRefCount: Boolean);

begin
  myx_grt_list_item_insert(List, Index, Value);

  // as myx_grt_list_item_insert increases refcount,
  // release it one time if it should not be increased
  if (not (IncreaseRefCount)) then
    myx_grt_value_release(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ListDel(List: Pointer; Index: Integer): Boolean;

begin
  Result := (myx_grt_list_item_del(List, Index) = 0);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ListDel(List: Pointer; Value: Pointer): Boolean;

begin
  Result := (myx_grt_list_item_del_value(List, Value) = 0);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ListDelString(List: Pointer; Name: WideString): Boolean;

begin
  Result := (myx_grt_list_item_del_as_string(List, Name) = 0);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ListDelObject(List: Pointer; Name: WideString): Boolean;

begin
  Result := (myx_grt_list_del_by_object_name(List, Name) = 0);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ListNew(const ContentType: GrtValueType;
  const ContentStructName: WideString = ''): Pointer;

begin
  Result := myx_grt_list_new(MYX_GRT_VALUE_TYPE(ContentType),
    ContentStructName);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ListClear(List: Pointer);

begin
  myx_grt_list_clear(List);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetDictItem(const Dict: Pointer; const Key: WideString): Pointer;

begin
  Result := myx_grt_dict_item_get_value(Dict, Key);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetDictItem(const Dict: Pointer; const Key: WideString; NewValue: Pointer);

begin
  myx_grt_dict_item_set_value(Dict, Key, NewValue);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetDictString(const Dict: Pointer; const Key: WideString): WideString;

begin
  if (Dict <> nil) then
    Result := myx_grt_dict_item_get_as_string(Dict, Key)
  else
    Result := '';
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetDictString(const Dict: Pointer; const Key: WideString; NewValue: WideString);

var
  Value: Pointer;
  OrgValue: Pointer;
  ValueType: MYX_GRT_VALUE_TYPE;

begin
  // Check what the original value's type is and auto-convert the given string to a native type if possible.
  OrgValue := myx_grt_dict_item_get_value(Dict, Key);
  ValueType := myx_grt_value_get_type(OrgValue);
  case ValueType of
    MYX_INT_VALUE:
      try
        Value := myx_grt_value_from_int(StrToInt(NewValue));
      except
        raise Exception.Create(Format(_('The string %s cannot be converted to an integer value.'), [NewValue]));
      end;
    MYX_REAL_VALUE:
      try
        Value := myx_grt_value_from_real(StrToFloat(NewValue));
      except
        raise Exception.Create(Format(_('The string %s cannot be converted to a float value.'), [NewValue]));
      end;
  else
    // Everything else.
    Value := myx_grt_value_from_string(NewValue);
  end;

  myx_grt_dict_item_set_value(Dict, Key, Value);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetDictInt(const Dict: Pointer; const Key: WideString): Integer;

begin
  Result := myx_grt_dict_item_get_as_int(Dict, Key);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetDictInt(const Dict: Pointer; const Key: WideString; NewValue: Integer);

begin
  myx_grt_dict_item_set_value_from_int(Dict, Key, NewValue);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetDictReal(const Dict: Pointer; const Key: WideString): Double;

begin
  Result := myx_grt_dict_item_get_as_real(Dict, Key);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetDictReal(const Dict: Pointer; const Key: WideString; NewValue: Double);

begin
  myx_grt_dict_item_set_value_from_real(Dict, Key, NewValue);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetDictRef(const Dict: Pointer; const Key: WideString): Pointer;

begin
  Result := myx_grt_dict_item_get_reference_value(FGrtEngine.NativeGrt, Dict, Key);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetDictRef(const Dict: Pointer; const Key: WideString; NewValue: Pointer);

begin
  myx_grt_dict_item_set_value_from_string(Dict, Key,
    DictString[NewValue, '_id']);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetDictStructName(const Dict: Pointer): WideString;

begin
  Result := myx_grt_dict_struct_get_name(Dict);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetDictStructName(const Dict: Pointer; StructName: WideString);

begin
  myx_grt_dict_struct_set_name(NativeGrt, Dict, StructName);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.DictNew(const StructName: WideString): Pointer;

begin
  Result := myx_grt_dict_new(NativeGrt, StructName);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.DictNewTyped(const ContentType: GrtValueType;
  const ContentStructName: WideString): Pointer;

begin
  Result := myx_grt_dict_new_typed(MYX_GRT_VALUE_TYPE(ContentType),
    ContentStructName);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ObjectNew(const StructName: WideString;
  Name: WideString; Id: WideString; OwnerId: WideString): Pointer;

begin
  Result := myx_grt_dict_new_obj(NativeGrt, StructName, Name, Id, OwnerId);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetValueInt(const Value: Pointer): Integer;

begin
  Result := myx_grt_value_as_int(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetValueString(const Value: Pointer): WideString;

begin
  Result := myx_grt_value_as_string(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueFromString(S: WideString): Pointer;

begin
  Result := myx_grt_value_from_string(S);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueFromInt(I: Integer): Pointer;

begin
  Result := myx_grt_value_from_int(I);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueAsLuaCode(Value: Pointer; Indention: Integer): WideString;

begin
  Result := myx_grt_value_as_lua_code(Value, Indention);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueDiffMake(Source: Pointer; Target: Pointer): Pointer;

begin
  Result := myx_grt_value_diff_make(NativeGrt, Source, Target);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueDiffApply(Value: Pointer; Diff: Pointer): Pointer;

begin
  Result := myx_grt_value_diff_apply(NativeGrt, Value, Diff);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueReference(Value: Pointer): Pointer;

begin
  Result := myx_grt_reference_cache_lookup(NativeGrt,
    ValueString[Value]);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.ValueReference(Id: WideString): Pointer;

begin
  Result := myx_grt_reference_cache_lookup(NativeGrt,
    PWideChar(Id));
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.Lock;

// Sets a lock on the GRT class for the calling thread or holds it if another thread already has a lock.

begin
  FAccessLock.Acquire;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.Unlock;

// Releases the lock for the calling thread, set previously with Lock.

begin
  FAccessLock.Release;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.ScriptInputRead;

begin
  if (GrtSyncEvent <> nil) then
    GrtSyncEvent.SetEvent;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetOutputBuffer: WideString;

begin
  Result := FGrtEngine.OutputBuffer;

  FGrtEngine.OutputBuffer := '';
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetOutputBuffer(OutputBuffer: WideString);

begin
  FGrtEngine.OutputBuffer := OutputBuffer;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetShellVar(Name: WideString): Pointer;

begin
  Result := myx_grt_shell_get_global_var(NativeGrt, Name);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.SetShellVar(Name: WideString; Value: Pointer);

begin
  myx_grt_shell_set_global_var(NativeGrt, Name, Value);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetGlobalAsParam(Path: WideString): WideString;

begin
  Result := 'global::' + Path;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.DictItemCount(const Dict: Pointer): Integer;

begin
  Result := myx_grt_dict_item_count(Dict);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.DictDel(const Dict: Pointer; const Key: WideString);

begin
  myx_grt_dict_item_del(Dict, Key);
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrt.GetDictKey(const Dict: Pointer; const I: Integer): WideString;

begin
  Result := myx_grt_dict_item_key_by_index(Dict, I);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrt.AddObjToReferenceCache(Dict: Pointer);

begin
  myx_grt_reference_cache_add(NativeGrt, Dict);
end;


//----------------------------------------------------------------------------------------------------------------------
// Grt Engine
//----------------------------------------------------------------------------------------------------------------------

constructor TGrtEngine.Create(CreateSuspended: Boolean; Grt: TGrt);

begin
  inherited Create(CreateSuspended);

  FGrt := Grt;
  FNativeGrt := nil;

  FWorkQueue := TGrtTaskList.Create;

  FCallbackEntries := TThreadList.Create;

  FJavaLoaderState := GrtLsNotInitialized;
  FLuaLoaderState := GrtLsNotInitialized;
  FBuiltinLoaderState := GrtLsNotInitialized;
  {$ifdef ENABLE_PHP_MODULES}
  FPhpLoaderState := GrtLsNotInitialized;
  {$endif}
  FUiLoaderState := GrtLsNotInitialized;

  FWorkEvent := TEvent.Create(nil, False, False, '');

  FDelphiGrtMessages := TMYX_GRT_MSGS.Create;
  Application.HookMainWindow(ApplicationHook);
end;

//----------------------------------------------------------------------------------------------------------------------

destructor TGrtEngine.Destroy;

begin
  Application.UnhookMainWindow(ApplicationHook);

  FWorkQueue.Free;

  ClearCallbackEntries;
  FCallbackEntries.Free;

  if FNativeGrt <> nil then
    myx_grt_finalize(FNativeGrt);

  FWorkEvent.Free;

  FDelphiGrtMessages.Free;

  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.Execute;

var
  ErrorDetails: TMYX_STRINGLIST;
  GrtOptions: Integer;
  StandardTask: IGrtTask;
  ShellTask: IGrtShellTask;
  StartTicks: Cardinal;
  Error: MYX_GRT_ERROR;
  Result: Pointer;

begin
  GrtOptions := 0;
  if (FGrt.Verbose) then
    GrtOptions := GrtOptions + Ord(MYX_GRT_VERBOSE);
  if (FGrt.RemoteDebug) then
    GrtOptions := GrtOptions + Ord(MYX_GRT_REMOTE_DEBUG);

  FNativeGrt := myx_grt_initialize(GrtOptions);

  InitializeGrt;

  while not Terminated do
  begin
    // Wait at most one second it there is no work to do.
    // Check if the thread is being shut down and continue loop if not.
    if FWorkEvent.WaitFor(1000) = wrSignaled then
    begin
      // New work has arrived. Get it from the work queue. Check once more we really have work.
      if FWorkQueue.Empty then
        Continue;

      FCurrentTask := FWorkQueue.Pop;

      // Immediately set the work event if the work queue is not empty so we continously
      // execute all tasks until our work queue is empty.
      if not FWorkQueue.Empty then
        FWorkEvent.SetEvent;

      StartTicks := GetTickCount;
      try
        try
          if Supports(FCurrentTask, IGrtTask, StandardTask) then
          begin
            StandardTask.Result := nil;

            // Execute a standard task and check its result.
            Result := myx_grt_function_get_and_call(FNativeGrt, StandardTask.ModuleName, StandardTask.FunctionName,
              Ord(StandardTask.SearchParent), StandardTask.FunctionArgument, @Error);

            // Check the result for error keys.
            FCurrentTask.ErrorCode := Error;
            FCurrentTask.ErrorString := myx_grt_function_check_error(Result, Ord(FCurrentTask.AllowNullResult));

            // Release result if there was an error.
            if (Error <> MYX_GRT_NO_ERROR) or (FCurrentTask.ErrorString <> '') and Assigned(Result) then
            begin
              myx_grt_value_release(Result);
              Result := nil;
            end;

            // If there was no error we have a value key. Return the contents of that key as result.
            if Assigned(Result) then
            begin
              StandardTask.Result := myx_grt_dict_item_get_value(Result, 'value');
              myx_grt_value_retain(StandardTask.Result);

              // Release result wrapper dict.
              myx_grt_value_release(Result);
            end;
          end
          else
            if Supports(FCurrentTask, IGrtShellTask, ShellTask) then
            begin
              // A shell task is to be executed. Extract the shell result afterwards.
              ShellTask.Result := myx_grt_shell_execute(FNativeGrt,
                Tnt_WideStringReplace(ShellTask.Command, #13#10, #10,[rfReplaceAll]));
            end;

        finally
          FCurrentTask.ExecutionTime := GetTickCount - StartTicks;
          FCurrentTask.SetEvent;
          if Assigned(FCurrentTask.OnTaskFinished) then
            Synchronize(TaskFinished);
        end;
      except
        on X: Exception do
        begin
          ErrorDetails := TMYX_STRINGLIST.Create;
          try
            if Assigned(StandardTask) then
              ErrorDetails.strings.Text := Format(_('The call to the function %s:%s returned with an exception.'),
                [StandardTask.ModuleName, StandardTask.FunctionName])
            else
              if Assigned(ShellTask) then
                ErrorDetails.strings.Text := Format(_('Exception encountered while executing the shell command: "%s"'),
                  [ShellTask.Command])
              else
                ErrorDetails.strings.Text := _('An unknown error occured during execution of a GRT function.');
            myx_grt_messages_stack_add(FNativeGrt, 1, X.Message, ErrorDetails.get_record_pointer, 1, -1);
            myx_grt_messages_stack_flush(FNativeGrt, 0);
          finally
            ErrorDetails.Free;
          end;
        end;
      end;

      // Process pending text/msg output
      Application.ProcessMessages;
    end;
  end;
  FinalizeGrt;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.FinalizeGrt;

begin
  FGrt.ScriptInputRead;

  FinalizeLoadersAndModules;
end;

procedure TGrtEngine.FinalizeLoadersAndModules;

begin
  FGrt.ScriptInputRead;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.InitializeGrt;

var
  Error: MYX_GRT_ERROR;
  I: integer;

begin
  myx_grt_catch_glib_messages(FNativeGrt, 1);

  // setup shell
  if (FGrt.ShellInterface = 'python') then
    myx_grt_setup_shell(FNativeGrt, MYX_GRT_SHELL_PYTHON)
  else
    myx_grt_setup_shell(FNativeGrt, MYX_GRT_SHELL_LUA);

  // Register print output function
  myx_grt_set_output_callback(FNativeGrt, self, @ProcessGrtOutput);

  // Register message processing function
  myx_grt_set_message_callback(FNativeGrt, self, @ProcessGrtMessages);

  // Register input function
  myx_grt_set_input_callback(FNativeGrt, self, @ProcessInput);

  // Register status query function
  myx_grt_set_status_query_callback(FNativeGrt, self, @ProcessStatusQuery);

  myx_grt_shell_print_welcome(FNativeGrt);

  OutputText('');

  // -------------------------------------------------
  // Load Structs

  I := myx_grt_scan_for_structs(FNativeGrt, './xml', @Error);
  if (Error <> MYX_GRT_NO_ERROR) then
    OutputText('  ' + Format(
      _('Error while loading struct definitions (%d).') + #13#10,
      [Ord(Error)]))
  else
    if (I = 1) then
      OutputText(
        _('Registered 1 struct definition file.') + #13#10)
    else
      OutputText(Format(
        _('Registered %d struct definition files.') + #13#10,
        [I]));


  InitializeLoadersAndModules;


  OutputText(#13#10);

  //Init shell
  myx_grt_shell_init(FNativeGrt);

  FGrt.GrtSyncEvent.SetEvent;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.InitializeLoadersAndModules;

var
  Loader: Pointer;
  Error: MYX_GRT_ERROR;
  I: integer;

begin
  // -------------------------------------------------
  // Initialized Loaders

  // Init Delphi loader
  OutputText(_('Initializing native loader...') + #13#10);
  FUiLoaderState := GrtLsInitializeFailed;
  FNativeLoader := InitDelphiLoader(@Error);
  if (FNativeLoader <> nil) then
  begin
    if (myx_grt_register_module_loader(FNativeGrt, FNativeLoader) <> MYX_GRT_NO_ERROR) then
      OutputText('  ' + _('Could not register Delphi modules.') + #13#10)
    else
      FUiLoaderState := GrtLsInitialized;
  end
  else
    OutputText('  ' + Format(
      _('Error initializing Delphi modules (%d)') + #13#10,
      [Ord(error)]));

  // Init Java loader
  if (WideDirectoryExists(FGrt.FJavaClasspath)) then
  begin
    OutputText(_('Initializing Java loader...') + #13#10);
    if (FGrt.Verbose) then
      OutputText(#13#10);

    FJavaLoaderState := GrtLsInitializeFailed;

    Loader := myx_java_init_loader_advanced(FNativeGrt, FGrt.FJavaClasspath, @Error,
      FGrt.JvmLibrary, FGrt.FJavaClasspath, FGrt.JvmMaxHeap);

    if (Loader <> nil) then
    begin
      FJavaLoaderState := GrtLsInitialized;

      if (myx_grt_register_module_loader(FNativeGrt, Loader) <> MYX_GRT_NO_ERROR) then
        OutputText('  ' + _('Could not register Java module loader.') + #13#10)
      else
        FJavaLoaderState := GrtLsInitialized;
    end
    else
      OutputText('  ' + Format(
        _('Error initializing Java module loader (%d). ' +
          'Please check the .\java and .\java\lib directories.') + #13#10,
        [Ord(error)]));
  end;

  {$ifdef ENABLE_PHP_MODULES}
  // Init PHP loader
  if (WideDirectoryExists(GetApplDir + 'php')) then
  begin
    OutputText(_('Initializing PHP loader...') + #13#10);
    FPhpLoaderState := GrtLsInitializeFailed;

    Loader := myx_php_init_loader(FNativeGrt, @Error);
    if (Loader <> nil) then
    begin
      if (myx_grt_register_module_loader(FNativeGrt, Loader) <> MYX_GRT_NO_ERROR) then
        OutputText('  ' + _('Could not register PHP module loader.') + #13#10)
      else
        FPhpLoaderState := GrtLsInitialized;
    end
    else
      OutputText('  ' + Format(
        _('Error initializing PHP module loader (%d)') + #13#10,
        [Ord(error)]));
  end;
  {$endif}
  
  // Init lua loader
  OutputText(_('Initializing Lua loader...') + #13#10);
  FLuaLoaderState := GrtLsInitializeFailed;
  Loader := myx_lua_init_loader(FNativeGrt, @Error, './lua');
  if (Loader <> nil) then
  begin
    if (myx_grt_register_module_loader(FNativeGrt, Loader) <> MYX_GRT_NO_ERROR) then
      OutputText('  ' + _('Could not register Lua module loader.') + #13#10)
    else
      FLuaLoaderState := GrtLsInitialized;
  end
  else
    OutputText('  ' + Format(
      _('Error initializing Lua module loader (%d)') + #13#10,
      [Ord(error)]));

  // Init python loader
  OutputText(_('Initializing Python loader...') + #13#10);
  FLuaLoaderState := GrtLsInitializeFailed;
  Loader := myx_python_init_loader(FNativeGrt, @Error, './python');
  if (Loader <> nil) then
  begin
    if (myx_grt_register_module_loader(FNativeGrt, Loader) <> MYX_GRT_NO_ERROR) then
      OutputText('  ' + _('Could not register Python module loader.') + #13#10)
    else
      FLuaLoaderState := GrtLsInitialized;
  end
  else
    OutputText('  ' + Format(
      _('Error initializing Python module loader (%d)') + #13#10,
      [Ord(error)]));

  // -------------------------------------------------
  // Load modules

  //Load builtin modules
  FBuiltinLoaderState := GrtLsInitializeFailed;
  if (myx_register_builtin_grt_module_base(FNativeGrt) <> nil) and
    (myx_register_builtin_grt_module_reverse_engineer_mysql(FNativeGrt) <> nil) and
    (myx_register_builtin_grt_module_transformation_mysql(FNativeGrt) <> nil) {and
    (myx_register_builtin_grt_module_query_mysql(FNativeGrt) <> nil) and
    (myx_register_builtin_grt_module_result_set(FNativeGrt) <> nil)} then
  begin
    FBuiltinLoaderState := GrtLsModulesLoaded;

    OutputModuleStatus('builtin', 5, MYX_GRT_NO_ERROR);
  end;

  // Java modules
  if (FJavaLoaderState = GrtLsInitialized) then
  begin
    if (FGrt.Verbose) then
      OutputText(#13#10);

    //Scan for Java plugins
    I := myx_grt_scan_for_modules(FNativeGrt, FGrt.FJavaClasspath + '/com/mysql/grt/modules', @Error);
    OutputModuleStatus('Java', I, Error);

    FJavaLoaderState := GrtLsModulesLoaded;
  end;

  {$ifdef ENABLE_PHP_MODULES}
  // Php modules
  if (FPhpLoaderState = GrtLsInitialized) then
  begin
    //Scan for PHP plugins
    I := myx_grt_scan_for_modules(FNativeGrt, './php/modules', @Error);
    OutputModuleStatus('PHP', I, Error);
  end;
  {$endif}

  // Lua modules
  if (FLuaLoaderState = GrtLsInitialized) and
    (WideDirectoryExists(GetApplDir + 'lua')) then
  begin
    //Scan for Lua plugins
    I := myx_grt_scan_for_modules(FNativeGrt, './lua', @Error);
    OutputModuleStatus('Lua', I, Error);
  end;
end;


//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.OutputModuleStatus(LoaderName: WideString; LoadedModuleCount: Integer; Error: MYX_GRT_ERROR);

begin
  if (Error <> MYX_GRT_NO_ERROR) then
    OutputText(Format(
      _('Error while loading %s modules (%d).') + #13#10,
      [LoaderName, Ord(Error)]))
  else
    if (LoadedModuleCount = 1) then
      OutputText(Format(
        _('Registered 1 %s module.') + #13#10, [LoaderName]))
    else
      if (LoadedModuleCount > 0) then
        OutputText(Format(
          _('Registered %d %s modules.') + #13#10, [LoadedModuleCount, LoaderName]))
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.TaskFinished;

begin
  FCurrentTask.OnTaskFinished(FCurrentTask);
  FCurrentTask := nil;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtEngine.GetNativeGrt: Pointer;

begin
  Result := FNativeGrt;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.AddTask(Task: IGrtGenericTask);

// Adds the given task to the work queue and returns immediately.
// Once the task was executed its OnTaskFinished callback is called to notify the principal.

begin
  FWorkQueue.Push(Task);
  FWorkEvent.SetEvent;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.AddTaskAndWait(Task: IGrtGenericTask);

// Similar to AddTask, however the method does not return until the task is finished, the given timeout is reached
// or the application is being terminated.

begin
  Task.PrepareSynchronization;
  FWorkQueue.Push(Task);
  FWorkEvent.SetEvent;
  Task.WaitFor(False);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.AddTaskAndWaitWithMessages(Task: IGrtGenericTask);

// Works like AddTaskAndWait except that the applications can process its messages.
// This is a potential reentrancy problem and therefor this method should only be used by old code.
// Instead use the asynchronous way to wait for a task to finish.

begin
  Task.PrepareSynchronization;
  FWorkQueue.Push(Task);
  FWorkEvent.SetEvent;
  Task.WaitFor(True);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.RemoveTask(Task: IGrtGenericTask);

// Removes the given task from the work queue.
// If this task is currently being executed then removing it has no effect.

begin
  FWorkQueue.Remove(Task);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.OutputText(S: WideString);

begin
  AddCallbackEntry(0, S, nil);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.DoOutputText(S: WideString);

begin
  if Assigned(FCurrentTask) and
    (Assigned(FCurrentTask.OnProcessOutput)) then
    FCurrentTask.OnProcessOutput(S)
  else
  begin
    if Assigned(FGrt.FConsole) then
    begin
      FGrt.Console.AddOutput(S);
      FGrt.Console.Invalidate;
    end
    else
      FOutputBuffer := FOutputBuffer + S;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtEngine.ProcessMessages(PMessages: PMYX_GRT_MSGS): Integer;

begin
  AddCallbackEntry(1, '', PMessages);
  Result := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.DoProcessMessages(Messages: TMYX_GRT_MSGS);

var
  StandardTask: IGrtTask;

begin
  if Assigned(FCurrentTask) then
  begin
    if not Supports(FCurrentTask, IGrtTask, StandardTask) then
      StandardTask := nil;
    if Assigned(StandardTask) and Assigned(StandardTask.OnProcessMessages) then
      StandardTask.OnProcessMessages(Messages)
    else
    begin
      // print the message
      DoOutputText(FormatGrtMessagesAsString(Messages));
    end;
  end
  else
  begin
    // print the message
    DoOutputText(FormatGrtMessagesAsString(Messages));
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtEngine.GrtInputText(Caption: WideString; options: MYX_GRT_INPUT_OPTIONS; Text: PPointer): integer;

var
  Input: string;

begin
  FTextForOutput := Caption;

  // This text is changed in the following input call if there is an input function assigned to the task.
  FTextInput := '@~@';
  Synchronize(DoGrtInputText);

  if FTextInput <> '@~@' then
    Input := UTF8Encode(FTextInput)
  else
  begin
    // Wait till user input is finished
    FGrt.GrtSyncEvent := TEvent.Create(nil, False, False, '');
    try
      FGrt.GrtSyncEvent.WaitFor(10000000);

      Input := UTF8Encode(FGrt.Console.ConsoleCommand);
      Input := Copy(Input, 0, Length(Input) - 2);
    finally
      FGrt.Console.ReadScriptInput := False;
      FGrt.GrtSyncEvent.Free;
      FGrt.GrtSyncEvent := nil;
    end;
  end;

  StrLCopy(FInputBuffer, PChar(Input), 160);

  Text^ := @FInputBuffer;

  Result := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.DoGrtInputText;

var
  StandardTask: IGrtTask;

begin
  StandardTask := nil;
  if Assigned(FCurrentTask) then
  begin
    if not Supports(FCurrentTask, IGrtTask, StandardTask) then
      StandardTask := nil;
  end;
  if Assigned(StandardTask) and Assigned(StandardTask.OnPerformInput) then
    FTextInput := StandardTask.OnPerformInput(FTextForOutput)
  else
  begin
    FGrt.Console.ReadScriptInput := True;
    FGrt.Console.ConsolePrompt := FTextForOutput;
    FGrt.Console.Content.DeleteLine(FGrt.Console.Content.Count - 1);
    FGrt.Console.PrepareNextConsoleCommand;
  end
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtEngine.GrtStatusQuery: Integer;

begin
  Synchronize(DoStatusQuery);
  Result := FStatus;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.DoStatusQuery;

var
  StandardTask: IGrtTask;

begin
  StandardTask := nil;
  if Assigned(FCurrentTask) then
    if not Supports(FCurrentTask, IGrtTask, StandardTask) then
      StandardTask := nil;
  if Assigned(StandardTask) and Assigned(StandardTask.OnPerformStatusQuery) then
    FStatus := StandardTask.OnPerformStatusQuery
  else
    FStatus := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.ExecuteDelphiFunction;

begin
  FDelphiModuleFunctionResult :=
    FDelphiModuleImplementor.GrtExecuteModuleFunction(
    FDelphiModuleName, FDelphiModuleFunctionName, FDelphiModuleFunctionArgument);
end;

//----------------------------------------------------------------------------------------------------------------------

function DelphiGrtCallFunction(func: PMYX_GRT_FUNCTION; argument: Pointer; retval: PPointer): MYX_GRT_ERROR cdecl;

var
  GrtEngine: TGrtEngine;

begin
  Result := MYX_GRT_NO_ERROR;

  GrtEngine := func.module.priv;

  retval^ := nil;

  try
    GrtEngine.FDelphiModuleImplementor := IGrtModuleImplementor(func.priv);
    GrtEngine.FDelphiModuleName := UTF8Decode(func.module.name);
    GrtEngine.FDelphiModuleFunctionName := UTF8Decode(func.name);
    GrtEngine.FDelphiModuleFunctionArgument := argument;

    // Call function synchronized
    GrtEngine.Synchronize(GrtEngine.ExecuteDelphiFunction);

    GrtEngine.FDelphiModuleImplementor := nil;

    retval^ := GrtEngine.FDelphiModuleFunctionResult;
  except
    on x: Exception do
    begin
      // Log error
      GrtEngine.DelphiGrtMessages.msgs.Add(
        TMYX_GRT_MSG.Create(1, x.Message, -1, nil));
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtEngine.InitDelphiLoader(Error: PMYX_GRT_ERROR): Pointer;

begin
  Result := myx_grt_module_loader_create(FNativeGrt,
    MYX_DELPHI_MODULE_TYPE, nil,
    nil, @DelphiGrtCallFunction,
    self);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.AddDelphiModule(ModuleName: WideString; ModuleFunctions: WideString;
  Implementor: IGrtModuleImplementor);

var
  PModule: PMYX_GRT_MODULE;
  I: Integer;
  FuncList: TTntStringList;
  Impl: Pointer;

begin
  PModule := myx_grt_module_create(FNativeLoader, ModuleName, '', '', self);

  FuncList := TTntStringList.Create;
  try
    FuncList.Text := ModuleFunctions;

    Impl := Pointer(Implementor);

    for I := 0 to FuncList.Count - 1 do
      myx_grt_module_add_function(PModule, FuncList[I], '', '',
        Impl);

    // Add a reference because a pointer to the interfaces is store in the GRT
    Implementor._AddRef;

    myx_grt_add_module(NativeGrt, PModule);
  finally
    FuncList.Free;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.RemoveDelphiModule(ModuleName: WideString;
  Implementor: IGrtModuleImplementor);

begin
  // Release refcount since the interface ref is now no longer stored in the GRT
  Implementor._Release;
end;

//----------------------------------------------------------------------------------------------------------------------

constructor EGrtError.Create(ErrorNumber: Integer; Description: WideString);

begin
  FErrorNumber := ErrorNumber;
  FDescription := Description;

  if (FErrorNumber <> 0) then
    Message := FDescription + ' Error Nr.' + IntToStr(FErrorNumber)
  else
    Message := FDescription;
end;

//----------------------------------------------------------------------------------------------------------------------

function GetListMemberCount(Grt: Pointer; StructName: WideString; OnlyCheck: Boolean): Integer;

var
  PStruct,
    PMember: Pointer;
  i,
    count: integer;

begin
  PStruct := myx_grt_struct_get(Grt, StructName);

  count := 0;
  for i := 0 to myx_grt_struct_get_member_count_total_excluding_struct(
    Grt, PStruct, 'db.DatabaseObject') - 1 do
  begin
    PMember := myx_grt_struct_get_member_by_index_total(
      Grt, PStruct, i);

    if (myx_grt_struct_member_get_type(PMember) = MYX_LIST_VALUE) and
      (myx_grt_struct_member_get_content_type(PMember) = MYX_DICT_VALUE) then
    begin
      inc(count);

      if (OnlyCheck) then
        break;
    end;
  end;

  Result := count;
end;

//----------------------------------------------------------------------------------------------------------------------

function GetListMember(Grt: Pointer; StructName: WideString; Index: Integer): Pointer;

var
  PStruct: Pointer;
  i,
  Count: integer;

begin
  Result := nil;
  PStruct := myx_grt_struct_get(Grt, StructName);

  count := 0;
  for i := 0 to myx_grt_struct_get_member_count_total(Grt, PStruct) - 1 do
  begin
    Result := myx_grt_struct_get_member_by_index_total(
      Grt, PStruct, i);

    if (myx_grt_struct_member_get_type(Result) = MYX_LIST_VALUE) and
      (myx_grt_struct_member_get_content_type(Result) = MYX_DICT_VALUE) then
    begin
      inc(Count);

      if (Index = Count - 1) then
        break;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function FormatGrtMessagesAsString(Msgs: TMYX_GRT_MSGS): WideString;

var
  S: WideString;
  I,
  J: Integer;

begin
  S := '';

  for I := 0 to Msgs.msgs.Count - 1 do
  begin
    // do not log progress messages
    if (Msgs.msgs[I].msg_type = 2) then
      Continue;

    if (Msgs.msgs[I].msg_type = 1) then
      S := S + 'ERROR: ';

    S := S +
      Tnt_WideStringReplace(
      Tnt_WideStringReplace(
      Msgs.msgs[I].msg, #13#10, #10, [rfReplaceAll], False),
      #10, #13#10, [rfReplaceAll], False) +
      #13#10;

    if (Msgs.msgs[I].msg_detail <> nil) then
    begin
      for j := 0 to Msgs.msgs[I].msg_detail.strings.Count - 1 do
      begin
        S := S +
          Tnt_WideStringReplace(
          Tnt_WideStringReplace(
          Msgs.msgs[I].msg_detail.strings[J], #13#10, #10, [rfReplaceAll], False),
          #10, #13#10, [rfReplaceAll], False) +
          #13#10;
      end;
    end;
  end;

  Result := S;
end;

//----------------------------------------------------------------------------------------------------------------------

function GetGrtFunctionArgumentAsString(Argument: Pointer): WideString;

var
  ValueType: MYX_GRT_VALUE_TYPE;
  Value: Pointer;

begin
  Result := '';

  ValueType := myx_grt_value_get_type(Argument);

  if (ValueType = MYX_STRING_VALUE) then
    Result := myx_grt_value_as_string(Argument)
  else
    if (ValueType = MYX_LIST_VALUE) then
    begin
      Value := myx_grt_list_item_get(Argument, 0);
      ValueType := myx_grt_value_get_type(Value);

      if (ValueType = MYX_STRING_VALUE) then
        Result := myx_grt_value_as_string(Value)
    end;

  if (ValueType <> MYX_STRING_VALUE) then
    raise Exception.Create('A wrong argument was passed to the function.');
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtEngine.ApplicationHook(var Message: TMessage): Boolean;

begin
  Result := False;
  case Message.Msg of
    WM_PROCESS_CALLBACK:
      begin
        DoChangeCallback;
        Result := True;
      end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.ClearCallbackEntries;

var
  I: Integer;
  Entry: PCallbackEntry;

begin
  with FCallbackEntries, LockList do
  try
    for I := 0 to Count - 1 do
    begin
      Entry := Items[I];
      Entry.Messages.Free;
      Dispose(Entry);
    end;
    Clear;
  finally
    UnlockList;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtEngine.AddCallbackEntry(AType: Integer; OutputText: WideString; Messages: PMYX_GRT_MSGS);

var
  Entry: PCallbackEntry;

begin
  with FCallbackEntries, LockList do
  try
    New(Entry);
    Entry.Type_ := AType;
    Entry.TextForOutput := OutputText;
    Entry.Messages := TMYX_GRT_MSGS.Create(Messages);
    FCallbackEntries.Add(Entry);
  finally
    UnlockList;
  end;

  PostMessage(Application.Handle, WM_PROCESS_CALLBACK, 0, 0);
end;

// -----------------------------------------------------------------------------

procedure TGrtEngine.DoChangeCallback;

var
  Entry: PCallbackEntry;

begin
  repeat
    with FCallbackEntries, LockList do
    begin
      if Count > 0 then
      begin
        Entry := First;
        Remove(Entry);
      end
      else
        Entry := nil;
      UnlockList;
    end;

    if Entry = nil then
      Break;

    case Entry.Type_ of
      0:
        DoOutputText(Entry.TextForOutput);
      1:
       begin
          DoProcessMessages(Entry.Messages);
          Entry.Messages.Free;
       end;
    end;
    Dispose(Entry);
  until False;
end;

//----------------- TGrtTaskList ---------------------------------------------------------------------------------------

constructor TGrtTaskList.Create;

begin
  inherited Create;

  InitializeCriticalSection(FLock);
  FList := TInterfaceList.Create;
end;

//----------------------------------------------------------------------------------------------------------------------

destructor TGrtTaskList.Destroy;

begin
  LockList;    // Make sure nobody else is inside the list.
  try
    FList.Free;
    inherited Destroy;
  finally
    UnlockList;
    DeleteCriticalSection(FLock);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTaskList.GetEmpty: Boolean;

begin
  LockList;    // Make sure nobody else is inside the list.
  try
    Result := FList.Count = 0;
  finally
    UnlockList;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtTaskList.SetEmpty(const Value: Boolean);

begin
  if Value then
    Clear;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtTaskList.Clear;

begin
  LockList;
  try
    FList.Clear;
  finally
    UnlockList;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTaskList.LockList: TInterfaceList;

begin
  EnterCriticalSection(FLock);
  Result := FList;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTaskList.Pop: IGrtGenericTask;

begin
  LockList;
  try
    Result := IGrtGenericTask(FList[0]);
    FList.Delete(0);
  finally
    UnlockList;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtTaskList.Push(Task: IGrtGenericTask);

begin
  LockList;
  try
    FList.Add(Task);
  finally
    UnlockList;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtTaskList.Remove(Task: IGrtGenericTask);

begin
  LockList;
  try
    FList.Remove(Task);
  finally
    UnlockList;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtTaskList.UnlockList;

begin
  LeaveCriticalSection(FLock);
end;

//-----------------TGrtGenericTask ------------------------------------------------------------------------------------

destructor TGrtGenericTask.Destroy;

begin
  FWaitEvent.Free;
  
  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetAllowNullResult: Boolean;

begin
  Result := FAllowNullResult;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetDataObj: TObject;

begin
  Result := FDataObj;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetErrorCode: MYX_GRT_ERROR;

begin
  Result := FErrorCode;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetErrorString: WideString;

begin
  Result := FErrorString;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetExecutionTime: Cardinal;

begin
  Result := FExecutionTime;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetProcessOutputFunction: TGrtProcessOutput;

begin
  Result := FOnProcessOutput;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetTag: Integer;

begin
  Result := FTag;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetTaskFinishedFunction: TGrtTaskFinished;

begin
  Result := FOnTaskFinished;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetTaskID: Integer;

begin
  Result := FTaskID;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtGenericTask.GetTimeout: Integer;

begin
  Result := FTimeout;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtGenericTask.PrepareSynchronization;

// Prepares the task for a following WaitFor call.

begin
  // The creation call is not synchronized against multiple use of the task by different threads.
  // A task should be "owned" only by one thread at a time. However it can be executed multiple times.
  if FWaitEvent = nil then
    FWaitEvent := TEvent.Create(nil, True, False, '');
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtGenericTask.SetErrorCode(const Value: MYX_GRT_ERROR);

begin
  FErrorCode := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtGenericTask.SetErrorString(const Value: WideString);

begin
  FErrorString := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtGenericTask.SetEvent;

// Signals any waiting thread that this task is finished.

begin
  if Assigned(FWaitEvent) then
    FWaitEvent.SetEvent;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtGenericTask.SetExecutionTime(const Value: Cardinal);

begin
  FExecutionTime := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtGenericTask.SetTag(Tag: Integer);

begin
  FTag := Tag;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtGenericTask.WaitFor(WithMessages: Boolean);

// Waits for the task to be finished by locking the calling thread. The task must have been prepared by a
// PrepareSynchronization call. The timeout value stored in FTimeout is used to limit the wait call to
// a maximum time. If this timeout value is -1, which means to wait forever, then the termination state of the application
// is checked each second and the WaitFor call is ended in case the application is about to be terminated.
// The parameter tells the method whether to process application messages while it waits. This is a potential reentrancy
// problem and therefor this method should only be used by old code. Instead use the asynchronous way to wait for a
// task to finish.

var
  WaitTime: Integer;

begin
  if FTimeout = -1 then
  begin
    if WithMessages then
      WaitTime := 20
    else
      WaitTime := 1000;
    while not Application.Terminated do
      if FWaitEvent.WaitFor(WaitTime) = wrSignaled then
        Break
      else
        if WithMessages then
          Application.ProcessMessages;
  end
  else
    FWaitEvent.WaitFor(FTimeout);
end;

//----------------- TGrtTask -------------------------------------------------------------------------------------------

destructor TGrtTask.Destroy;

begin
  if FFunctionArguments <> nil then
    FGrt.ValueRelease(FFunctionArguments);
    
  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTask.GetDescription: WideString;

begin
  Result := FDescription;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTask.GetFunctionArgument: Pointer;

begin
  Result := FFunctionArguments;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTask.GetFunctionName: WideString;

begin
  Result := FFunctionName;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTask.GetModulName: WideString;

begin
  Result := FModulName;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTask.GetPerformInputFunction: TGrtPerformInput;

begin
  Result := FOnPerformInput;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTask.GetPerformStatusQueryFunction: TGrtPerformStatusQuery;

begin
  Result := FOnPerformStatusQuery;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTask.GetProcessMessagesFunction: TGrtProcessMessages;

begin
  Result := FOnProcessMessages;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTask.GetResult: Pointer;

begin
  Result := FResult;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtTask.GetSearchParent: Boolean;

begin
  Result := FSearchParent;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtTask.SetResult(const Value: Pointer);

begin
  FResult := Value;
end;

//----------------- TGrtShellTask --------------------------------------------------------------------------------------

function TGrtShellTask.GetCommand: WideString;

begin
  Result := FCommand;
end;

//----------------------------------------------------------------------------------------------------------------------

function TGrtShellTask.GetResult: MYX_GRT_SHELL_COMMAND;

begin
  Result := FResult;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TGrtShellTask.SetResult(const Value: MYX_GRT_SHELL_COMMAND);

begin
  FResult := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure SetGrtClass(AClass: TGrtClass);

begin
  if GrtClass <> AClass then
  begin
    FreeAndNil(InternalGrtInstance);
    GrtClass := AClass;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

initialization
  SetGrtClass(TGrt);
end.