Welcome to mirror list, hosted at ThFree Co, Russian Federation.

qtluaengine.cpp « qtlua - github.com/torch/qtlua.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6762ee26842e01747cf5210a90ac22694e9d383b (plain)
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
// -*- C++ -*-

#define QTLUAENGINE 1

#include "qtluautils.h"
#include "qtluaengine.h"
#include "lualib.h"

#include <QCoreApplication>
#include <QDebug>
#include <QEvent>
#include <QEventLoop>
#include <QFile>
#include <QList>
#include <QMap>
#include <QMetaMethod>
#include <QMetaObject>
#include <QMetaProperty>
#include <QMetaType>
#include <QMutex>
#include <QMutexLocker>
#include <QPointer>
#include <QSet>
#include <QTimer>
#include <QThread>
#include <QVector>
#include <QWaitCondition>

#include <limits.h>



// ========================================
// Declaration

static int luaQ_pcall(lua_State *L, 
                      int na, int nr, int eh, 
                      QObject *obj, bool async);



/* miscellaneous information */

typedef QVector<int> IntVector;
typedef QVector<void*> PtrVector;
typedef QVector<QVariant> VarVector;

struct QtLuaMethodInfo
{
  struct Detail { 
    int id; 
    PtrVector types;
  };
  const QMetaObject *metaObject;
  QVector<Detail> d;
};

Q_DECLARE_METATYPE(QtLuaMethodInfo)
  
struct QtLuaPropertyInfo
{
  int id;
  const QMetaObject *metaObject;
  QMetaProperty metaProperty;
};

Q_DECLARE_METATYPE(QtLuaPropertyInfo)

Q_DECLARE_METATYPE(QVariant)



// ========================================
// Registry keys


static const char *engineKey = "engine";
static const char *signalKey = "signals";
static const char *objectKey = "objects";
static const char *metaKey = "metatables";
static const char *qtKey = "qt";


// Summary of registry entries:
// _R[engineKey] : pointer to QtLuaEngine::Private.
// _R[qtKey] : qt package.
// _R[qtKey].typename : class for metatype "typename".
// _R[qtKey].classname : class for metaobject "classname".
// _R[metaKey][typeid] : metatable for metatype (by typeid) 
// _R[metaKey][metaobjectptr] : metatable for metaobject (by ptr)
// _R[objectKey][objectptr] : lua value for qobject (weak table)
// _R[signalKey][receiverptr] : closure for signal receiver.
// _R[metatable] : equal to qtKey if this is a qt object.


static void
luaQ_setup(lua_State *L, QtLuaEngine::Private *d)
{
  // metatypes
  qRegisterMetaType<QVariant>("QVariant");
  qRegisterMetaType<QtLuaMethodInfo>("QtLuaMethodInfo");
  qRegisterMetaType<QtLuaPropertyInfo>("QtLuaPropertyInfo");
  qRegisterMetaType<QObjectPointer>("QObjectPointer");
  // engine
  lua_pushlightuserdata(L, (void*)engineKey);
  lua_pushlightuserdata(L, (void*)d);
  lua_rawset(L, LUA_REGISTRYINDEX);
  // metatables
  lua_pushlightuserdata(L, (void*)metaKey);
  lua_createtable(L, 0, 0);
  lua_rawset(L, LUA_REGISTRYINDEX);
  // signals
  lua_pushlightuserdata(L, (void*)signalKey);
  lua_createtable(L, 0, 0);
  lua_rawset(L, LUA_REGISTRYINDEX);
  // objects [weak table]
  lua_pushlightuserdata(L, (void*)objectKey);
  lua_createtable(L, 0, 0); 
  lua_createtable(L, 0, 1); 
  lua_pushliteral(L, "v");
  lua_setfield(L, -2, "__mode");
  lua_setmetatable(L, -2);
  lua_rawset(L, LUA_REGISTRYINDEX);
  // qt
  lua_pushlightuserdata(L, (void*)qtKey);
  lua_createtable(L, 0, 0);
  lua_rawset(L, LUA_REGISTRYINDEX);
  // package.preload["qt"]
  lua_getfield(L, LUA_GLOBALSINDEX, "package");
  if (lua_istable(L, -1)) 
    {
      lua_getfield(L, -1, "preload");
      if (lua_istable(L, -1))
        {
          lua_pushcfunction(L, luaopen_qt);
          lua_setfield(L, -2, "qt");
        }
      lua_pop(L, 1);
    }
  lua_pop(L, 1);
}


static QtLuaEngine::Private *
luaQ_private_noerr(lua_State *L)
{
  QtLuaEngine::Private *d = 0;
  lua_pushlightuserdata(L, (void*)engineKey);
  lua_rawget(L, LUA_REGISTRYINDEX);
  if (lua_islightuserdata(L, -1))
    d = static_cast<QtLuaEngine::Private*>(lua_touserdata(L, -1));
  lua_pop(L, 1);
  return d;
}


static QtLuaEngine::Private *
luaQ_private(lua_State *L)
{
  QtLuaEngine::Private *d = luaQ_private_noerr(L);
  if (! d)
    luaL_error(L, "qtlua: not running inside a QtLuaEngine.");
  return d;
}




// ========================================
// QtLuaEngine::Global

struct QtLuaEngine::Global {
  QMutex mutex;
  QMap<QByteArray,const QMetaObject*> knownMetaObjects;
  void registerMetaObject(const QMetaObject *mo, bool super=true);
  const QMetaObject *findMetaObject(QByteArray className);
};


Q_GLOBAL_STATIC(QtLuaEngine::Global, qtLuaEngineGlobal);


void 
QtLuaEngine::Global::registerMetaObject(const QMetaObject *mo, bool super)
{
  QMutexLocker locker(&mutex);
  knownMetaObjects[mo->className()] = mo;
  while (super && (mo = mo->superClass()))
    knownMetaObjects[mo->className()] = mo;
}


const QMetaObject *
QtLuaEngine::Global::findMetaObject(QByteArray className)
{
  QMutexLocker locker(&mutex);
  if (knownMetaObjects.contains(className))
    return knownMetaObjects[className];
  return 0;
}



// ========================================
// QtLuaEngine::Private basics


struct QtLuaQueuedSignal {
  QPointer<QObject> sender;
  QPointer<QtLuaEngine::Receiver> receiver;
  void *delsignal;
  VarVector args;
};


struct QtLuaEngine::Protector  : public QObject
{
  Q_OBJECT
  Private *d;
  QVariantList saved;
  QMutex mutex;
public:
  Protector(QtLuaEngine::Private *d) : d(d) { }
  bool maybeProtect(const QVariant &var);
  bool protect(const QVariant &var);
  bool event(QEvent *e);
};


struct QtLuaEngine::Private  : public QObject
{
  Q_OBJECT
public:
  Private(QtLuaEngine *parent);
  ~Private();
  QThread *luaThread() const;
  bool isObjectLuaOwned(QObject *obj);
  void makeObjectLuaOwned(QObject *obj);
  bool processQueuedSignals(QMutexLocker &locker);
  void disconnectAllSignals();
  bool stopHelper(bool unwind);
  bool resumeHelper(int retcode);
  static void stopHook(lua_State *L, lua_Debug *ar);
public slots:
  void objectDestroyed(QObject*);
  void readySlot();
  void queueSlot();
  void stopSlot() {}
  void emitStateChanged(State s) { emit stateChanged(s); }
  void emitPauseSignal() { emit stateChanged(QtLuaEngine::Paused); }
  void emitReadySignal() { emit readySignal(); }
  void emitQueueSignal() { emit queueSignal(); }
  void emitErrorMessage(QByteArray m) { emit errorMessage(m); }
  void emitStopSignal() { emit stopSignal(); }
signals:
  void errorMessage(QByteArray message);
  void stateChanged(int s);
  void readySignal();
  void queueSignal();
  void stopSignal();
public:
  QtLuaEngine *q;
  lua_State   *L;
  // locking
  QMutex mutex;
  QWaitCondition condition;
  int lockCount;
  QThread *lockThread;
  bool rflag;
  // hopping
  QWaitCondition hopCondition;
  QEventLoop *hopLoop;
  QEvent *hopEvent;
  int hopNA;
  int hopNR;
  int hopEH;
  // pausing
  QEventLoop *pauseLoop;
  QByteArray lastErrorMessage;
  QList<QByteArray> lastErrorLocation;
  bool printResults;
  bool printErrors;
  bool pauseOnError;
  bool unwindStack;
  bool resumeFlag;
  bool errorHandlerFlag;
  // debugging
  lua_Debug *hookInfo;
  lua_Hook hookFunction;
  int hookMask;
  int hookCount;
  // protector
  Protector *protector;
  // maps
  QMap<QByteArray,const QMetaObject*> knownMetaObjects;
  QMap<QString,QObjectPointer> namedObjectsCache;
  QSet<QObject*> namedObjects;
  QSet<QObject*> luaOwnedObjects;
  QList<QtLuaQueuedSignal> queuedSignals;
};


QtLuaEngine::Private::Private(QtLuaEngine *parent)
  : QObject(parent),
    q(parent),
    L(0),
    lockCount(0),
    lockThread(0),
    rflag(true),
    hopLoop(0),
    hopEvent(0),
    pauseLoop(0),
    printResults(false),
    printErrors(true),
    pauseOnError(false),
    unwindStack(false),
    resumeFlag(false),
    errorHandlerFlag(false),
    hookInfo(0),
    hookFunction(0),
    hookMask(0),
    hookCount(0),
    protector(0)
{
  // setup paths
#if HAVE_LUA_EXECUTABLE_DIR
  QString path = QCoreApplication::applicationFilePath();
  lua_executable_dir(QFile::encodeName(path).constData());
#endif
  // create lua interpreter
  L = luaL_newstate();
  Q_ASSERT(L);
  luaL_openlibs(L);
  luaQ_setup(L, this);
  // delayed connections
  connect(this, SIGNAL(readySignal()), 
          this, SLOT(readySlot()),
          Qt::QueuedConnection );
  connect(this, SIGNAL(queueSignal()), 
          this, SLOT(queueSlot()),
          Qt::QueuedConnection );
  connect(this, SIGNAL(stopSignal()), 
          this, SLOT(stopSlot()),
          Qt::QueuedConnection );
  connect(this, SIGNAL(stateChanged(int)), 
          q, SIGNAL(stateChanged(int)));
  connect(this, SIGNAL(errorMessage(QByteArray)), 
          q, SIGNAL(errorMessage(QByteArray)));
}


QtLuaEngine::Private::~Private()
{
  // close interpreter
  lua_pushlightuserdata(L, (void*)engineKey);
  lua_pushnil(L);
  lua_rawset(L, LUA_REGISTRYINDEX);
  lua_close(L);
  L = 0;
  // destroy protector
  if (protector)
    protector->deleteLater();
  protector = 0;
}


QThread *
QtLuaEngine::Private::luaThread() const
{
  if (lockThread)
    return lockThread;
  return thread();
}


void
QtLuaEngine::Private::objectDestroyed(QObject *obj)
{
  QMutexLocker locker(&mutex);
  if (luaOwnedObjects.contains(obj))
    luaOwnedObjects.remove(obj);
  if (namedObjects.contains(obj))
    namedObjects.remove(obj);
}


bool 
QtLuaEngine::Private::isObjectLuaOwned(QObject *obj)
{
  QMutexLocker locker(&mutex);
  return luaOwnedObjects.contains(obj);
}


void 
QtLuaEngine::Private::makeObjectLuaOwned(QObject *obj)
{
  if (obj)
    {
      connect(obj, SIGNAL(destroyed(QObject*)),
              this, SLOT(objectDestroyed(QObject*)),
              Qt::DirectConnection );
      QMutexLocker locker(&mutex);
      luaOwnedObjects += obj;
    }
}


static void
queue_sub(QtLuaEngine::Private *d, QMutexLocker &locker)
{
  QThread *mythread = QThread::currentThread();
  Q_ASSERT(mythread == d->thread());
  Q_ASSERT(!d->lockCount && !d->hopEvent && !d->hopLoop);
  d->lockCount = 1;
  d->lockThread = mythread;
  d->processQueuedSignals(locker); 
  if (! d->queuedSignals.isEmpty())
    d->emitQueueSignal();
  d->lockCount = 0;
  d->lockThread = 0;
  d->condition.wakeOne();
}


void 
QtLuaEngine::Private::readySlot()
{
  QMutexLocker locker(&mutex);
  if (!lockCount && !hopLoop && !hopEvent && !pauseLoop)
    queue_sub(this, locker);
  bool stateChanged = rflag;
  hookInfo = 0;
  unwindStack = false;
  rflag = false;
  if (lua_gethook(L) == stopHook)
    lua_sethook(L, hookFunction, hookMask, hookCount);
  locker.unlock();
  if (stateChanged)
    emit q->stateChanged(QtLuaEngine::Ready);
}


void 
QtLuaEngine::Private::queueSlot()
{
  QMutexLocker locker(&mutex);
  if (pauseLoop && ! hookInfo)
    {
      Q_ASSERT(rflag);
      QEventLoop *savedLoop = pauseLoop; 
      lua_Debug *savedInfo = hookInfo;
      pauseLoop = 0;
      hookInfo = 0;
      rflag = false;
      resumeFlag = false;
      queue_sub(this, locker);
      bool stateChanged = rflag;
      pauseLoop = savedLoop;
      hookInfo = savedInfo;
      rflag = true;
      locker.unlock();
      if (stateChanged)
        emit q->stateChanged(QtLuaEngine::Paused);
      if (pauseLoop && unwindStack)
        pauseLoop->exit(1);
      else if (pauseLoop && resumeFlag)
        pauseLoop->exit(0);
    }
  else if (!lockCount && !lockThread && !hopEvent && !pauseLoop)
    {
      queue_sub(this, locker);
      bool stateChanged = rflag;
      hookInfo = 0;
      unwindStack = false;
      rflag = false;
      if (lua_gethook(L) == stopHook)
        lua_sethook(L, hookFunction, hookMask, hookCount);
      locker.unlock();
      if (stateChanged)
        emit q->stateChanged(QtLuaEngine::Ready);    
    }
}




// ========================================
// QtLuaEngine state



/*! Returns the engine state. */

QtLuaEngine::State 
QtLuaEngine::state() const
{
  QMutexLocker locker(&d->mutex);
  if (d->pauseLoop)
    return Paused;
  else if (d->rflag)
    return Running;
  else
    return Ready;
}

/*! \fn QtLuaEngine::isReady()
  Returns \a true if the engine is in ready state. */

/*! \fn QtLuaEngine::isRunning()
  Returns \a true if the engine is in running state. */

/*! \fn QtLuaEngine::isPaused()
  Returns \a true if the engine is in paused state. */


/*! Returns true if the engine is paused because an error has occured */

bool
QtLuaEngine::isPausedOnError() const
{
  QMutexLocker locker(&d->mutex);
  if (d->pauseLoop && d->errorHandlerFlag)
    return true;
  return false;
}


/*! \signal stateChanged(State state)
  Posted when the engine state changes.
  When this message is received, 
  the engine state might have changed again! */


/*! \signal errorMessage(QByteArray message)
  Posted when a lua error is signalled. */



// ========================================
// QtLuaLocker


/*! \class QtLuaLocker
  This class safely locks a \a QtLuaEngine.
  The constructor acquires the lock 
  and the destructor releases the lock.
  The \a lua_State can then be safely 
  accessed by casting an instance of this class. */


QtLuaLocker::~QtLuaLocker()
{
  if (engine && count)
    {
      QtLuaEngine::Private *d = engine->d;
      d->mutex.lock();
      count = d->lockCount - 1;
      if (! count)
        {
          if (d->hopEvent)
            {
              d->hopCondition.wakeOne(); // mostly for async eval
            }
          else
            {
              d->lockThread = 0;
              d->emitReadySignal();
              d->condition.wakeOne();
            }
        }
      d->lockCount = count;
      d->mutex.unlock();
    }
}


/*! Constructor. 
  This constructor acquires a lock,
  waiting as long as necessary. */

QtLuaLocker::QtLuaLocker(QtLuaEngine *engine)
  : engine(engine), count(0)
{
  QtLuaEngine::Private *d = engine->d;
  QThread *mythread = QThread::currentThread();
  QMutexLocker locker(&d->mutex);
  for(;;)
    {
      if (d->lockCount > 0 && d->lockThread == mythread)
        break;
      if (d->lockCount == 0 && d->lockThread == 0)
        break;
      d->condition.wait(&d->mutex);
    }
  d->lockCount += 1;
  d->lockThread = mythread;
  count = d->lockCount;
}



/*! Alternate constructor. 
  This constructor attempts to acquire a lock
  waiting at most \a timeOut milliseconds.
  To see if the lock has been acquired, 
  use the \a lua_State* conversion operator
  or use the \a isReady() function. */

QtLuaLocker::QtLuaLocker(QtLuaEngine *engine, int timeOut)
  : engine(engine), count(0)
{
  QtLuaEngine::Private *d = engine->d;
  QThread *mythread = QThread::currentThread();
  QMutexLocker locker(&d->mutex);
  for(;;)
    {
      if (d->lockCount > 0 && d->lockThread == mythread)
        break;
      if (d->lockCount == 0 && d->lockThread == 0)
        break;
      if (! d->condition.wait(&d->mutex, timeOut))
        return;
    }
  d->lockCount += 1;
  d->lockThread = mythread;
  count = d->lockCount;
}


/*! \fn bool isReady()
  Returns true if the locking operation was 
  successful and the interpreter is in ready state. 
  Note that locking and state are distinct concepts.
  It is possible to lock a running interpreter
  while it is waiting for other events.
  The \a eval and \a evaluate functions use this test
  to decide whether to run a command. */


/*! \fn operator lua_State*
  Accesses the \a lua_State underlying the locked engine.
  This provides the only safe way to access 
  the \a lua_State variable. */


/*! Calling this function after a successful lock 
  causes the engine to transition to state \a Running.
  The engine will return to state \a Ready after
  the destruction of the last \a QtLuaLocker object 
  and the execution of the command queue.
  Temporary releasing the lock with \a unlock() 
  keeps the engine in state \a Running. */

void 
QtLuaLocker::setRunning()
{
  bool stateChanged = false;
  QtLuaEngine::Private *d = engine->d;
  if (count > 0)
    {
      QMutexLocker locker(&d->mutex);
      stateChanged = !d->rflag;
      d->rflag = true;
    }
  if (stateChanged)
    d->emitStateChanged(QtLuaEngine::Running);
}







// ========================================
// QtLuaEngine basics


/*! \class QtLuaEngine
  Class \a QtLuaEngine represents a Lua interpreter.
  This object can be used to add a Lua interpreter 
  to any Qt application with capabilities 
  comparable to those of the QtScript language
  and additional support for multi-threaded execution.

  Instances of this class can be in one of three state.
  State \a QtLuaEngine::Ready indicates that the interpreter
  is ready to accept new Lua commands.
  State \a QtLuaEngine::Running indicates that the interpreter
  is currently executing a Lua program.
  State \a QtLuaEngine::Paused indicates that the interpreter
  was suspended while executing a Lua program. One can then
  use the Lua debug library to investigage the Lua state.

  Class \a QtLuaEngine provides member functions to 
  submit Lua strings to the interpreter and to collect 
  the evaluation results.  If these functions are invoked
  from the thread owning the Lua engine object,
  the Lua code is executed right away. 
  Otherwise a thread hopping operation with \a luaQ_pcall
  ensures that the execution of a Lua program happens 
  in the thread owning the Lua engine object. */


QtLuaEngine::~QtLuaEngine()
{
  Q_ASSERT(QThread::currentThread() == thread());
  // make as silent as possible
  setPrintResults(false);
  setPauseOnError(false);
  disconnect(d, 0, this, 0);
  d->disconnectAllSignals();
  // stop lua
  QMutexLocker locker(&d->mutex);
  while (d->lockCount || d->lockThread || d->hopEvent)
    {
      locker.unlock();
      resume(true);
      stop(true);
      QEventLoop loop;
      loop.processEvents(QEventLoop::ExcludeUserInputEvents, 100);
      locker.relock();
      d->unwindStack = true;
    }
  // delete children and owned objects
  QObject *obj;
  QList<QObjectPointer> family;
  foreach(obj, d->luaOwnedObjects)
    family << obj;
  foreach(obj, children())
    family << obj;
  d->luaOwnedObjects.clear();
  foreach(QObjectPointer objptr, family)
    if ((obj = objptr) && (obj != d))
      obj->deleteLater();
  // disconnect protector
  if (d->protector)
    QCoreApplication::instance()->removeEventFilter(d->protector);
}


/*! Basic constructor. */

QtLuaEngine::QtLuaEngine(QObject *parent)
  : QObject(parent),
    d(new Private(this)),
    L(d->L)
{
  d->protector = new QtLuaEngine::Protector(d);
  d->protector->moveToThread(QCoreApplication::instance()->thread());
  QCoreApplication::instance()->installEventFilter(d->protector);
}


/*! Registering a metaobject allows the engine 
  to recognize qobject classes by name in method 
  and signal arguments. This happens automatically 
  when a qobject is translated into a lua userdata,
  or, more generally, whenever \a luaQ_pushmeta is called.
  In rare occasions, it may be necessary to manually 
  register a meta object, for instance when a scriptable 
  method returns a qobject whose class has not been previously
  registered and is not a superclass of the current class,
  or when one connects a signal whose arguments are
  qobjects whose class has not been previously registered. */

void 
QtLuaEngine::registerMetaObject(const QMetaObject *mo)
{
  qtLuaEngineGlobal()->registerMetaObject(mo);
}


/*! Make a \a QObject accessible to the interpreter by name.
  Use the Qt object name when string \a name is not provided. 
  The lua engine keeps tracking the object when its name
  is reset or changed. */

void 
QtLuaEngine::nameObject(QObject *object, QString name)
{
  if (object)
    {
      if (! name.isEmpty())
        object->setObjectName(name);
      name = object->objectName();
      QMutexLocker locker(&d->mutex);
      d->namedObjects += object;
      if (! name.isEmpty())
        d->namedObjectsCache[name] = object;
      connect(object, SIGNAL(destroyed(QObject*)),
              d, SLOT(objectDestroyed(QObject*)),
              Qt::DirectConnection );
    }
}


/*! Returns a \a QObject by name. */

QObject *
QtLuaEngine::namedObject(QString name)
{
  QObject *obj;
  QMutexLocker locker(&d->mutex);
  if (d->namedObjectsCache.contains(name))
    {
      obj = d->namedObjectsCache[name];
      if (obj && obj->objectName() == name)
        return obj;
      d->namedObjectsCache.remove(name);
    }
  foreach(obj, d->namedObjects)
    if (obj->objectName() == name)
      {
        d->namedObjectsCache[name] = obj;
        return obj;
      }
  return 0;
}


/*! Return the list of all named objects. */

QList<QObjectPointer> 
QtLuaEngine::allNamedObjects() 
{
  QObject *obj;
  QList<QObjectPointer> list;
  foreach(obj, d->namedObjects)
    list += obj;
  return list;
}


/*! \property QtLuaEngine::lastErrorMessage
  Contains the last error message
  reported with signal \a errorMessage. */

QByteArray
QtLuaEngine::lastErrorMessage() const
{
  return d->lastErrorMessage;
}


/*! \property QtLuaEngine::lastErrorLocation
  Contains the location associated with the 
  last error message reported with signal \a errorMessage.
  When the location corresponds to a file, 
  this string has the format "@filename:linenumber". */

QStringList 
QtLuaEngine::lastErrorLocation() const
{
  QStringList list;
  foreach(QByteArray b, d->lastErrorLocation)
    list << QString::fromLocal8Bit(b);
  return list;
}




/*! \property QtLuaEngine::printResults
  Indicates whether the results of an \a eval()
  must be printed on the standard output. */

bool 
QtLuaEngine::printResults() const
{
  return d->printResults;
}


void 
QtLuaEngine::setPrintResults(bool b)
{
  d->printResults = b;
}


/*! \property QtLuaEngine::printErrors
  Indicates whether error messages
  must be printed on the standard output. */

bool 
QtLuaEngine::printErrors() const
{
  return d->printErrors;
}


void 
QtLuaEngine::setPrintErrors(bool b)
{
  d->printErrors = b;
}



/*! \property QtLuaEngine::pauseOnError
  Indicates whether the default error handler
  should pause execution when an error occurs
  as if \a pause() had been called from 
  the error handler. */

bool 
QtLuaEngine::pauseOnError() const
{
  return d->pauseOnError;
}


void 
QtLuaEngine::setPauseOnError(bool b)
{
  d->pauseOnError = b;
}


/*! \property QtLuaEngine::runSignalHandlers
  This property is true when the Lua interpreter
  honors the signal handler invokations immediately 
  instead of queuing them for further processing. */

bool 
QtLuaEngine::runSignalHandlers() const
{
  QMutexLocker locker(&d->mutex);
  if (! d->rflag)
    return true;
  if (d->pauseLoop && ! d->hookInfo)
    return true;
  return false;
}




// ========================================
// Stopping, Resuming, Evaluating


static bool
lua_pause_sub(lua_State *L, QtLuaEngine::Private *d, QMutexLocker &locker)
{
  // must be called with a message on the stack
  if (!d->pauseLoop && d->rflag && !d->unwindStack)
    {
      int savedLockCount = d->lockCount;
      QThread *savedLockThread = d->lockThread;
      QEventLoop loop;
      d->pauseLoop = &loop;
      d->lockCount = 0;
      d->lockThread = 0;
      d->condition.wakeOne();
      locker.unlock();
      // make sure we enter the loop before signalling.
      QTimer::singleShot(0, d, SLOT(emitPauseSignal()));
      if (loop.exec())
        d->unwindStack = true;
      locker.relock();
      d->lockThread = savedLockThread;
      d->lockCount = savedLockCount;
      d->pauseLoop = 0;
      return true;
    }
  return false;
}


void
QtLuaEngine::Private::stopHook(lua_State *L, lua_Debug *ar)
{
  QtLuaEngine::Private *d = luaQ_private_noerr(L);
  lua_sethook(L, 0, 0, 0);
  lua_pushliteral(L, "stop");
  luaQ_tracebackskip(L, 1);
  bool stateChanged = false;
  if (d) 
    {
      QMutexLocker locker(&d->mutex);
      lua_Debug *savedInfo = d->hookInfo;
      d->hookInfo = ar;
      lua_sethook(L, d->hookFunction, d->hookMask, d->hookCount);
      if (! d->unwindStack)
        stateChanged = lua_pause_sub(L, d, locker);
      d->hookInfo = savedInfo;
    }
  if (d && stateChanged)
    d->emitStateChanged(QtLuaEngine::Running);
  lua_pop(L, 1);
  if (d && !d->unwindStack)
    return;
  lua_pushliteral(L, "stop");
  lua_error(L);
}


static QList<QByteArray>
find_error_location(lua_State *L, QByteArray &message)
{
  QByteArray loc;
  QList<QByteArray> list;
  // parse locations in message
  const char *m = message.constData();
  for(const char *s = m; *s && *s != '\n'; s++)
    {
      // search ":[0-9]+: +"
      if (*s != ':')
        continue;
      char *e;
      QByteArray location(m, s-m);
      int lineno = (int)strtol(++s, &e, 10);
      if (lineno <= 0 || e <= s || *e != ':')
        continue;
      s = e;
      while (s[1] && s[1] == ' ')
        s += 1;
      m = s + 1;
      // append
      if (location.startsWith("[string \"") && location.endsWith("\"]"))
        location = location.mid(9, location.length()-11);
      else
        location = "@" + location;
      loc = location + ":" + QByteArray::number(lineno);
      if (list.isEmpty() || list.first() != loc)
        list.prepend(loc);
    }
  message = QByteArray(m);
  // parse locations in top ten stack elements
  int maxlevel = 8;
  int level = 0;
  lua_Debug ar;
  while (level < maxlevel && lua_getstack(L, level++, &ar)) 
    {
      lua_getinfo(L, "Snl", &ar);
      if (ar.currentline > 0)
        {
          loc = QByteArray(ar.source) + ":" + 
            QByteArray::number(ar.currentline);
          if (list.isEmpty() || list.last() != loc)
            list.append(loc);
        }
    }
  return list;
}


static int
lua_error_handler(lua_State *L)
{
  QtLuaEngine::Private *d = luaQ_private_noerr(L);
  const char *m = lua_tostring(L, -1);
  if (m && strstr(m, "\nstack traceback:\n\t"))
    return 1;  // hack alert (see lua/src/ldblib.c) 
  luaQ_tracebackskip(L, 1);
  QByteArray message = lua_tostring(L, -1);
  QList<QByteArray> location = find_error_location(L, message);
  bool stateChanged = false;
  if (d)
    {
      d->lastErrorLocation = location;
      d->lastErrorMessage = message;
      d->emitErrorMessage(d->lastErrorMessage);
      QMutexLocker locker(&d->mutex);
      d->errorHandlerFlag = true;
      if (d->pauseOnError && !d->unwindStack)
        stateChanged = lua_pause_sub(L, d, locker);
      d->errorHandlerFlag = false;
    }
  if (stateChanged)
    d->emitStateChanged(QtLuaEngine::Running);
  return 1;
}



bool 
QtLuaEngine::Private::stopHelper(bool unwind)
{
  unwindStack |= unwind;
  lua_Hook hf = lua_gethook(L);
  if (hf != stopHook)
    {
      hookFunction = lua_gethook(L);
      hookMask = lua_gethookmask(L);
      hookCount = lua_gethookcount(L);
    }
  lua_sethook(L, stopHook, LUA_MASKCOUNT|LUA_MASKRET, 1);
  emitStopSignal(); // just to make sure luaQ_doevents() is stopped!
  return true;
}

bool 
QtLuaEngine::Private::resumeHelper(int retcode)
{
  if (pauseLoop)
    pauseLoop->exit(retcode);
  return true;
}


/*! Stops the lua execution as soon as practicable.
  If flag \a nopause if false, the interpreter
  will transition to the paused state until someone
  calls \a resume(). Otherwise  the interpreter stops 
  executing, unwinds the stack, and returns to ready state. */

bool
QtLuaEngine::stop(bool nopause)
{
  QMutexLocker locker(&d->mutex);
  if (d->pauseLoop && nopause)
    return d->resumeHelper(1);
  if (d->rflag && !d->pauseLoop)
    return d->stopHelper(nopause);
  return false;
}


/*! Resume execution after a \a pause().
  Returns \a false when called when the engine is not in paused state. 
  When argument \a nocontinue is true, the interpreter
  stops executing, unwinds the stack, and returns to ready state. */

bool 
QtLuaEngine::resume(bool nocontinue)
{
  QMutexLocker locker(&d->mutex);
  if (d->pauseLoop)
    return d->resumeHelper(nocontinue ? 1 : 0);
  if (d->rflag && !d->pauseLoop && nocontinue)
    return d->stopHelper(true);
  return false;
}


static int
lua_eval_func(lua_State *L)
{
  QtLuaEngine::Private *d = luaQ_private_noerr(L);
  d->errorHandlerFlag = false;
  lua_pushcfunction(L, lua_error_handler);
  int error = luaL_loadstring(L, lua_tostring(L, 1));
  if (! error)
    error = lua_pcall(L, 0, LUA_MULTRET, -2);
  if (!d || d->printResults || (error && d->printErrors))
    luaQ_print(L, lua_gettop(L) - 2);
  if (error)
    lua_error(L);
  return lua_gettop(L) - 2;
}


/*! Evaluate the expression in string \a s.
  This function returns \a true if the evaluation
  was performed without error. It immediately
  returns \a false if the \a QtLuaEngine instance
  state is not "ready" or when one requests
  an asynchronous call from the engine thread.
  Evaluation takes place in the thread 
  owning the \a QtLuaEngine instance.
  Synchronous calls are performed by setting
  flag \a async is \a false. The function waits 
  until the evaluation terminates regardless of 
  the thread from which it is called.
  Asynchronous calls are performed by setting
  flag \a async to \a true and calling this
  function from a thread other than the thread
  owning the \a QtLuaEngine instance. */

bool 
QtLuaEngine::eval(QByteArray s, bool async)
{
  QtLuaLocker lua(this);
  if (! lua.isReady())
    return false;
  if (async && QThread::currentThread() == thread())
    return false;
  lua_settop(L, 0);
  lua_pushcfunction(L, lua_eval_func);
  lua_pushstring(L, s.constData());
  int status = luaQ_pcall(L, 1, 0, 0, this, async);
  return (status == 0);
}


/*! \overload */

bool
QtLuaEngine::eval(QString s, bool async)
{
  return eval(s.toLocal8Bit(), async);
}


/*! Synchronously evaluate string \a s and returns the result.
  This function returns an empty \a QVariantList if
  called when the engine is not in ready state.
  If an error occurs during evaluation, it returns a list
  whose first element is \a QVariant(false) and whose
  second element is the error message. 
  Otherwise is returns a list whose first element is
  \a QVariant(true) and whose remaining elements
  are the evaluation results.
*/

QVariantList 
QtLuaEngine::evaluate(QByteArray s)
{
  QVariantList results;
  QtLuaLocker lua(this);
  if (! lua.isReady())
    return results;
  lua_settop(L, 0);
  lua_pushcfunction(L, lua_eval_func);
  lua_pushstring(L, s.constData());
  int status = luaQ_pcall(L, 1, LUA_MULTRET, 0, this);
  if (status)
    results << QVariant(false);
  else
    results << QVariant(true);
  for (int i = 1; i <= lua_gettop(L); i++)
    results << luaQ_toqvariant(L, i);
  return results;
}


/*! \overload */

QVariantList 
QtLuaEngine::evaluate(QString s)
{
  return evaluate(s.toLocal8Bit());
}




// ========================================
// Calls


struct QtLuaEngine::Catcher : public QObject
{
  Q_OBJECT
public:
  QtLuaEngine::Private *d;
  Catcher(QtLuaEngine::Private *d) : d(d) { }
  virtual bool event(QEvent *e);
public slots:
  void destroy() { delete this; }
};
  

bool
QtLuaEngine::Catcher::event(QEvent *e)
{
  if (e->type() != QEvent::User)
    return false;
  QMutexLocker locker(&d->mutex);
  Q_ASSERT(e == d->hopEvent);
  while (d->lockCount > 0)
    d->hopCondition.wait(&d->mutex);
  // lock
  d->lockThread = QThread::currentThread();
  d->lockCount = 1;
  d->hopEvent = 0;
  bool rflag = d->rflag;
  int stacktop = lua_gettop(d->L);
  int status = LUA_ERRRUN;
  if (d->unwindStack)  
    {
      lua_pushliteral(d->L, "stop (unwinding stack)");
    }
  else try 
    { 
      d->rflag = true;
      locker.unlock();
      if (! rflag)
        d->emitStateChanged(QtLuaEngine::Running);
      status = lua_pcall(d->L, d->hopNA, d->hopNR, d->hopEH);
      locker.relock();
    } 
  catch(...) 
    {
      lua_settop(d->L, stacktop);
      lua_pushliteral(d->L, "uncaught c++ exception");
    }
  d->lockCount = 0;
  if (d->hopLoop) 
    d->hopLoop->exit(status);
  else
    d->emitReadySignal();
  // We use a timer because calling 'delete this' 
  // in an event handler is not supported and 
  // because 'deleteLater' waits until the
  // current eventloop returns...
  QTimer::singleShot(0, this, SLOT(destroy()));
  return true;
}


struct QtLuaEngine::Unlocker : public QObject
{
  Q_OBJECT
public:
  QtLuaEngine::Private *d;
  Unlocker(QtLuaEngine::Private *d) : d(d) {}
  virtual bool event(QEvent *e);
};


bool 
QtLuaEngine::Unlocker::event(QEvent *e) 
{ 
  if (e->type() != QEvent::User)
    return false;
  d->mutex.lock();
  d->lockCount = 0;
  d->hopCondition.wakeOne();
  d->mutex.unlock();
  return true;
}


static int
luaQ_pcall(lua_State *L, int na, int nr, int eh, QObject *obj, bool async)
{
  int status;
  // obtain lua engine
  QtLuaEngine::Private *d = luaQ_private(L);
  d->mutex.lock();
  if (! obj)
    obj = QCoreApplication::instance();
  if (obj->thread() == QThread::currentThread())
    {
      bool rflag = d->rflag;
      d->rflag = true;
      d->mutex.unlock();
      if (! rflag)
        d->emitStateChanged(QtLuaEngine::Running);
      status = lua_pcall(L, na, nr, eh);
    }
  else
    {
      QEvent *event = new QEvent(QEvent::User);
      d->hopEvent = event;
      d->hopNA = na;
      d->hopNR = nr;
      d->hopEH = eh;
      QThread *thread = obj->thread();
      QtLuaEngine::Catcher *catcher = new QtLuaEngine::Catcher(d);
      catcher->moveToThread(thread);
      QCoreApplication::postEvent(catcher, event);
      if (async)
        {
          // This should only be used for async eval.
          // Freeing the last lua locker will wake
          // the catcher waiting on hopCondition
          Q_ASSERT(! d->rflag);
          d->mutex.unlock();
          return 0;
        }
      else
        {
          QEventLoop *savedHopLoop = d->hopLoop;
          int savedLockCount = d->lockCount;
          QThread *savedLockThread = d->lockThread;
          QEventLoop loop;
          d->hopLoop = &loop;
          // The catcher will soon get the hopEvent message
          // and run lua_pcall() in the receiving thread.
          // Then it calls exit() causing us to leave the 
          // event loop and resume execution in this thread.
          // For this to happen we need to unlock the engine
          // and signal hopCondition. But we cannot do it right now
          // because the other thread might complete even before 
          // we call loop.exec(). Posting a message to the Unlocker
          // object ensures that unlock happens after exec() has started.
          // This is not very high-performance :-(.
          QtLuaEngine::Unlocker unlocker(d);
          QEvent *unlockEvent = new QEvent(QEvent::User);
          QCoreApplication::postEvent(&unlocker, unlockEvent);
          d->mutex.unlock();
          status = loop.exec();
          d->mutex.lock();
          d->lockCount = savedLockCount;
          d->lockThread = savedLockThread;
          d->hopLoop = savedHopLoop;
          d->mutex.unlock();
        }
    }
  return status;
}


/*! Thread hopping version of \a lua_pcall().
  This function is similar to \a lua_pcall() but
  arranges the execution to happen in the
  thread of the Qt object \a obj. 
  This only works if the target thread is running an event loop. 
  The current thread then runs an event loop until 
  being notified of the call results.  
  When \a obj is null, the application object
  is assumed (ensuring the code runs in the gui thread). */

int
luaQ_pcall(lua_State *L, int na, int nr, int eh, QObject *obj)
{
  return luaQ_pcall(L, na, nr, eh, obj, false);
}


/*! Convenience function.
    Same as "luaQ_pcall(L,na,nr,0,obj) || lua_error(L)". 
    Unlike \a lua_call() this function calls
    the function with the default error handler
    instead of the current error handler. */

void
luaQ_call(lua_State *L, int na, int nr, QObject *obj)
{
  int base = lua_gettop(L) - na;
  Q_ASSERT(base > 0);
  lua_pushcfunction(L, lua_error_handler);
  lua_insert(L, base);
  int status = luaQ_pcall(L, na, nr, base, obj);
  lua_remove(L, base);
  if (status)
    lua_error(L);
}




static int
call_in_obj_thread(lua_State *L)
{
  int narg = lua_gettop(L);
  // object
  lua_pushvalue(L, lua_upvalueindex(2));
  QObject *obj = luaQ_toqobject(L, -1);
  lua_pop(L, 1); 
  // function
  lua_pushvalue(L, lua_upvalueindex(1));
  Q_ASSERT(lua_isfunction(L, -1));
  lua_insert(L, 1); // function
  // call
  luaQ_call(L, narg, LUA_MULTRET, obj);
  return lua_gettop(L);
}


static int
call_in_arg_thread(lua_State *L)
{
  int narg = lua_gettop(L);
  // object
  QObject *obj = luaQ_toqobject(L, 1);
  if (! obj) 
    luaL_typerror(L, 1, "qobject");
  // function
  lua_pushvalue(L, lua_upvalueindex(1));
  Q_ASSERT(lua_isfunction(L, -1));
  lua_insert(L, 1);
  // call
  luaQ_call(L, narg, LUA_MULTRET, obj);
  return lua_gettop(L);
}



/*! Register functions to be called in the thread of object \a obj.
  If argument \a obj is null, the functions will be called
  in the thread of their first argument (which must be a qobject).
  This is handy to define methods in metaclasses. */

void 
luaQ_register(lua_State *L, const luaL_Reg *l, QObject *obj)
{
  while (l->name)
    {
      lua_pushcfunction(L, l->func);
      if (obj) {
        luaQ_pushqt(L, obj);
        lua_pushcclosure(L, call_in_obj_thread, 2);
      } else
        lua_pushcclosure(L, call_in_arg_thread, 1);
      lua_setfield(L, -2, l->name);
      l += 1;
    }
}





// ========================================
// Bindings


/*! Returns the engine for the current interpreter. */

QtLuaEngine *
luaQ_engine(lua_State *L)
{
  QtLuaEngine::Private *d = luaQ_private(L);
  return d->q;
}


/*! Pushes the qt package table on the stack. */

void
luaQ_pushqt(lua_State *L)
{
  lua_pushlightuserdata(L, (void*)qtKey);
  lua_rawget(L, LUA_REGISTRYINDEX);
  Q_ASSERT(lua_istable(L, -1));
}


/* conversions and tests */

static QVariant *
luaQ_toqvariantp(lua_State *L, int index)
{
  QVariant *vp = 0;
  if (lua_isuserdata(L, index) && 
      lua_getmetatable(L, index))
    {
      lua_rawget(L, LUA_REGISTRYINDEX);
      void *v = lua_touserdata(L, -1);
      lua_pop(L, 1);
      if (v == (void*)qtKey)
        vp = static_cast<QVariant*>(lua_touserdata(L, index));
    }
  return vp;
}


static inline bool
qvariant_has_object_type(const QVariant *vp)
{
  int type = vp->userType();
  return (type == qMetaTypeId<QObjectPointer>() ||
          type == QMetaType::QObjectStar ||
          type == QMetaType::QWidgetStar );
}


static inline QObject *
qvariant_to_object(const QVariant *vp)
{
  int type = vp->userType();
  if (type == qMetaTypeId<QObjectPointer>())
    return *static_cast<QObjectPointer const *>(vp->constData());
  if (type == QMetaType::QObjectStar)
    return *static_cast<QObject * const *>(vp->constData());
  return 0;
}


static inline QObject *
qvariant_to_object(const QVariant *vp, const QMetaObject *mo)
{
  QObject *obj = qvariant_to_object(vp);
  if (obj && mo)
    {
      const QMetaObject *m = obj->metaObject();
      while (m && m != mo)
        m = m->superClass();
      if (m != mo)
        obj = 0;
    }
  return obj;
}


/*! Extract \a QVariant from the lua value located 
  at position \a index in the stack. 
  Standard lua types are converted to \a QVariant
  as needed. */

QVariant 
luaQ_toqvariant(lua_State *L, int index, int type)
{
  QVariant v;
  switch (lua_type(L, index))
    {
    case LUA_TBOOLEAN:
      v = QVariant((bool)lua_toboolean(L, index));
      break;
    case LUA_TNUMBER:
      v = QVariant((double)lua_tonumber(L, index));
      break;
    case LUA_TUSERDATA: {
      const QVariant *vp = 0;
      if (! (vp = luaQ_toqvariantp(L, index)))
        break;
      if (qvariant_has_object_type(vp) && !qvariant_to_object(vp))
        break;
      v = *vp;
      break; }
    case LUA_TSTRING: {
      size_t l; 
      const char *s = lua_tolstring(L, index, &l);
      v = QVariant(QByteArray(s, l)); 
      break; }
    default:
      break;
    }
  if  (type)
    {
      int vtype = v.userType();
      if (type == vtype)
        return v;
      else if (type == QVariant::ByteArray && vtype == QVariant::String)
        v = v.toString().toLocal8Bit();
      else if (type == QVariant::String && vtype == QVariant::ByteArray)
        v = QString::fromLocal8Bit(v.toByteArray().constData());
      else if (! v.convert(QVariant::Type(type)))
        v = QVariant();
    }
  return v;
}


/*! Returns true if the lua value at position \a index
  points to a \a QObject that inherits from the class
  identified by metaobject \a mo. */

QObject*
luaQ_toqobject(lua_State *L, int index, const QMetaObject *mo)
{
  const QVariant *vp = luaQ_toqvariantp(L, index);
  return (vp) ? qvariant_to_object(vp, mo) : 0;
}



/* This part of the protector makes sure that
   certain implicit shared objects are
   destroyed in the gui thread instead
   of the thread that destroys the variant.
   Yes this is tricky. */

bool 
QtLuaEngine::Protector::maybeProtect(const QVariant &var)
{
  if (QThread::currentThread() == QCoreApplication::instance()->thread())
    return false;
  int type = var.userType();
  switch(type)
    {
    case QMetaType::QPixmap:
    case QMetaType::QBrush:
    case QMetaType::QPen:
      return protect(var);
    default:
      return false;
    }
}

bool 
QtLuaEngine::Protector::protect(const QVariant &var)
{
  QMutexLocker lock(&mutex);
  int size = saved.size();
  saved.append(var);
  if (! size)
    QCoreApplication::postEvent(this, new QEvent(QEvent::User));
  return true;
}

bool 
QtLuaEngine::Protector::event(QEvent *e)
{
  if (e->type() == QEvent::User)
    {
      QMutexLocker lock(&mutex);
      saved.clear(); // possible actual deletion 
      return true;
    }
  return QObject::event(e);
}



/* metatable material */

static int
luaQ_m__gc(lua_State *L)
{
  QtLuaEngine::Private *d = luaQ_private_noerr(L);
  QObject *obj = luaQ_toqobject(L, 1);
  if (obj && d && d->isObjectLuaOwned(obj))
    obj->deleteLater();
  QVariant *vp = luaQ_toqvariantp(L, 1);
  if (vp && d && d->protector)
    d->protector->maybeProtect(*vp);
  if (vp)
    vp->QVariant::~QVariant();
  return 0;
}


static int
luaQ_m__type(lua_State *L)
{
  // LUA: "_val_:type()"
  // Returns a string describing the type of a qt value.
  // Returns nil if _val_ is not a qt value.
  if (lua_isuserdata(L, 1) && 
      lua_getmetatable(L, 1))
    {
      lua_pushliteral(L, "__typename");
      lua_rawget(L, -2);
      if (lua_isstring(L, -1))
        return 1;
    }
  lua_pushstring(L, luaL_typename(L, 1));
  return 1;
}


static int
luaQ_m__isa(lua_State *L)
{
  // LUA: "_val_:isa(_str_)"
  // Returns true is _val_ is an instance of class _str_.
  // In the case of objects, the classname may or may not
  // have a final star.
  bool b = false;
  QObject *obj;
  const QVariant *vp = luaQ_toqvariantp(L, 1);
  const char *t = luaL_checkstring(L, 2);
  if (! vp)
    b = (!strcmp(t, lua_typename(L, lua_type(L, 1))));
  else if (! qvariant_has_object_type(vp))
    b = (!strcmp(t, QMetaType::typeName(vp->userType())) ||
         !strcmp(t, vp->typeName()) );
  else if ((obj = luaQ_toqobject(L, 1)))
    {
      const QMetaObject *mo = obj->metaObject();
      int tlen = strlen(t);
      if (tlen>0 && t[tlen-1]=='*')    
        tlen -= 1;
      while (mo && !b)
        {
          const char *c = mo->className();
          b = (!strncmp(t, c, tlen) && c[tlen]==0);
          mo = mo->superClass();
        }
    }
  lua_pushboolean(L, b);
  return 1;
}


static int
luaQ_m__eq(lua_State *L)
{
  // __eq in metatable
  const QVariant *vp1 = luaQ_toqvariantp(L, 1);
  const QVariant *vp2 = luaQ_toqvariantp(L, 2);
  bool ok = false;
  if (*vp1 == *vp2)
    ok = true;
  else if (qvariant_has_object_type(vp1) &&
           qvariant_has_object_type(vp2) &&
           qvariant_to_object(vp1) == qvariant_to_object(vp2) )
    ok = true;
  lua_pushboolean(L, ok);
  return 1;
}


static int
luaQ_m__tostring(lua_State *L)
{
  // LUA: "_val_:tostring()"
  // Converts a qt value to a nice printable string.
  // Returns nil if _val_ is not a qt value.
  const QVariant *vp = luaQ_toqvariantp(L, 1);
  if (! vp)
    lua_pushnil(L);
  else if (qvariant_has_object_type(vp))
    {
      QObject *obj = qvariant_to_object(vp);
      if (obj)
        lua_pushfstring(L, "qt.%s (%p)", obj->metaObject()->className(), obj);
      else
        lua_pushliteral(L, "qt.zombie");
    }
  else
    {
      int type = vp->userType();
      const void *ptr = vp->constData();
      QVariant var = *vp;
      if (var.type() == QVariant::String)
        lua_pushstring(L, var.toString().toLocal8Bit().constData());
      else if (var.convert(QVariant::ByteArray))
        lua_pushstring(L, var.toByteArray().constData());
      else
        lua_pushfstring(L, "qt.%s (%p)", QMetaType::typeName(type), ptr);
    }
  return 1;
}


static int
luaQ_m__tonumber(lua_State *L)
{
  // LUA: "_val_:tonumber()"
  // Converts a qt value to a number.
  // Returns nil if the conversion is impossible
  QVariant var = luaQ_toqvariant(L, 1);
  if (var.convert(QVariant::Double))
    lua_pushnumber(L, var.toDouble());
  else
    lua_pushnil(L);
  return 1;
}


static int
luaQ_m__tobool(lua_State *L)
{
  // LUA: "_val_:tobool()"
  // Converts a qt value to a boolean.
  const QVariant *vp = luaQ_toqvariantp(L, 1);
  if (! vp)
    lua_pushnil(L);
  else if (qvariant_has_object_type(vp))
    lua_pushboolean(L, !!qvariant_to_object(vp));
  else
    lua_pushboolean(L, !vp->isNull());
  return 1;
}


static int
luaQ_m__call(lua_State *L)
{
  luaL_checktype(L, 1, LUA_TTABLE);
  lua_pushliteral(L, "new");
  lua_rawget(L, 1);
  if (!lua_isfunction(L, -1))
    luaL_error(L, "constructor 'new' not found");
  lua_replace(L, 1);
  lua_call(L, lua_gettop(L)-1, LUA_MULTRET);
  return lua_gettop(L);
}


/* metatable material: get/set property */

static int
luaQ_m__getsetproperty(lua_State *L)
{
  const QVariant* vp = luaQ_toqvariantp(L, lua_upvalueindex(1));
  if (vp->userType() != qMetaTypeId<QtLuaPropertyInfo>())
    luaL_error(L, "internal error while accessing property");
  const QtLuaPropertyInfo *info =
    static_cast<const QtLuaPropertyInfo*>(vp->constData());
  const QMetaProperty &mp = info->metaProperty;
  QObject *obj = luaQ_toqobject(L, 1, info->metaObject);
  if (! obj)
    luaL_typerror(L, 0, info->metaObject->className());
  if (! mp.isScriptable(obj))
    luaL_error(L, "property " LUA_QS " is not scriptable", mp.name());
  if (lua_gettop(L) == 1)
    {
      if (! mp.isReadable())
        luaL_error(L, "property " LUA_QS " is not readable", mp.name());
      // get property
      QVariant v = mp.read(obj);
      // convert enum codes into enum names
      QByteArray n;
      if (mp.isFlagType() && v.canConvert(QVariant::Int))
        v = mp.enumerator().valueToKeys(v.toInt());
      else if (mp.isEnumType() && v.canConvert(QVariant::Int))
        v = mp.enumerator().valueToKey(v.toInt());
      // return
      luaQ_pushqt(L, v);
      return 1;
    }
  else
    {
      QVariant v = luaQ_toqvariant(L, 2);
      if (! mp.isWritable())
        luaL_error(L, "property " LUA_QS " is not writable", mp.name());
      // string conversion
      if (mp.type() == QVariant::String && v.type() == QVariant::ByteArray)
        v = QString::fromLocal8Bit(v.toByteArray());
      // enum and flags conversion
      if (mp.isFlagType() && v.type() == QVariant::ByteArray)
        {
          QMetaEnum me = mp.enumerator();
          int n = me.keysToValue(v.toByteArray().constData());
          if (n == -1)
            luaL_error(L, "unrecognized flag for " LUA_QS, me.name());
          v = QVariant(n);
        }
      else if (mp.isEnumType() && v.type() == QVariant::ByteArray)
        {
          QMetaEnum me = mp.enumerator();
          int n = me.keyToValue(v.toByteArray().constData());
          if (n == -1)
            luaL_error(L, "unrecognized enum for " LUA_QS, me.name());
          v = QVariant(n);
        }
      // check types
      if (! mp.write(obj, v))
        luaL_error(L, "cannot convert value for property '%s'", mp.name());
    }
  return 0;
}


/* metatable material: invoking methods */

static void *
make_argtype(QByteArray type)
{
  int tid = QMetaType::type(type);
  if (type.endsWith("*"))
    {
      type.chop(1);
      const QMetaObject *mo = qtLuaEngineGlobal()->findMetaObject(type);
      if (mo)
        return (void*)mo;
      else if (!tid)
        tid = QMetaType::VoidStar;
    }
  if (tid)
    return (void*)((((size_t)tid)<<1)|1);
  return 0;
}


static inline int
v_to_type(void *v)
{
  return (((size_t)v)&1) ? (((size_t)v)>>1) : 0;
}


static inline const QMetaObject *
v_to_metaobject(void *v)
{
  return (((size_t)v)&1) ? 0 : static_cast<const QMetaObject*>(v);
}


static const char *
v_to_name(void *v)
{
  int type = v_to_type(v);
  if (type)
    return QMetaType::typeName(type);
  else if (v)
    return v_to_metaobject(v)->className();
  else
    return "void";
}


static void *
construct_arg(QVariant &var, void *vtype)
{
  int type = v_to_type(vtype);
  const QMetaObject *mo = v_to_metaobject(vtype);
  QObject *obj;
  if (type == QVariant::String && var.type() == QVariant::ByteArray)
    var = QString::fromLocal8Bit(var.toByteArray());
  if (type == qMetaTypeId<QVariant>())
    return static_cast<void*>(new QVariant(var));
  else if (type && (var.userType() == type || var.convert(QVariant::Type(type))))
    return QMetaType::construct(type, var.constData());
  else if (mo && (obj = qvariant_to_object(&var)))
    return static_cast<void*>(new QObject*(obj));
  return 0;
}


static void
destroy_arg(void *arg,  void *vtype)
{
  int type = v_to_type(vtype);
  const QMetaObject *mo = v_to_metaobject(vtype);
  if (! arg)
    return;
  else if (type == qMetaTypeId<QVariant>())
    delete static_cast<QVariant*>(arg);
  else if (type)
    QMetaType::destroy(type, arg);
  else if (mo)
    delete static_cast<QObject**>(arg);
}


static void *
construct_retval(void *vtype)
{
  int type = v_to_type(vtype);
  const QMetaObject *mo = v_to_metaobject(vtype);
  if (mo)
    return static_cast<void*>(new QObject*(0));
  else if (type == QMetaType::Void)
    return 0;
  else if (type == qMetaTypeId<QVariant>())
    return static_cast<void*>(new QVariant());
  else if (type)
    return QMetaType::construct(type);
  return 0;
}


static int
luaQ_p_push_retval(lua_State *L, void *arg, void *vtype)
{
  int type = v_to_type(vtype);
  const QMetaObject *mo = v_to_metaobject(vtype);
  if (! arg)
    return 0;
  if (type == qMetaTypeId<QVariant>())
    luaQ_pushqt(L, *static_cast<QVariant*>(arg));
  else if (type)
    luaQ_pushqt(L, QVariant(type, arg));
  else if (mo)
    luaQ_pushqt(L, *static_cast<QObject**>(arg));
  else
    return 0;
  return 1;
}


static inline int
type_class(int type)
{
  switch(type)
    {
    case QMetaType::Double:
    case QMetaType::Float:
    case QMetaType::Char:
    case QMetaType::Short:
    case QMetaType::Int:
    case QMetaType::Long:
    case QMetaType::LongLong:
    case QMetaType::UChar:
    case QMetaType::UShort:
    case QMetaType::UInt:
    case QMetaType::ULong:
    case QMetaType::ULongLong:
      return -1; // numerical
    case QMetaType::QByteArray:
    case QMetaType::QString:
      return -2; // string
    default:
      return type;
    }
}


static int
select_overload(VarVector &vars, const QtLuaMethodInfo *info)
{
  // fast path when single method
  int overloads = info->d.size();
  if (overloads == 1)
    return 0;
  // fast path when single method with right number of args
  int i;
  int b = -1;
  int bn = 0;
  int narg = vars.size(); 
  for (i=0; i<overloads; i++)
    if (narg == info->d[i].types.size())
      { b = i; bn += 1; }
  if (b >= 0 && bn == 1)
    return b;
  // match types
  b = -1;
  bn = 0;
  int bs = INT_MAX;
  for (i=0; i<overloads; i++)
    if (narg == info->d[i].types.size())
      {
        int j;
        int s = 0;
        const QtLuaMethodInfo::Detail &d = info->d[i];
        for (j=1; j<narg; j++)
          {
            int type = v_to_type(d.types[j]);
            int argtype = vars[j].userType();
            const QMetaObject *mo = v_to_metaobject(d.types[j]);
            if (type == qMetaTypeId<QVariant>())
              continue;
            if (type && type == argtype)
              continue;
            if (mo && qvariant_to_object(&vars[j], mo))
              continue;
            s += 1;
            if (type && type_class(type) == type_class(argtype))
              continue;
            s += 10;
            QVariant var = vars[j];
            if (var.canConvert(QVariant::Type(type)))
              continue;
            s += INT_MAX / 2;
            break;
          }
        if (j < narg)
          continue;
        if (s == bs)
          bn += 1;
        else if (s < bs)
          { b = i; bs = s; bn = 1; }
      }
  if (b >= 0 && bn == 1)
    return b;
  return -1;
}


static int
luaQ_m__invokemethod(lua_State *L)
{
  int i;
  const int narg = lua_gettop(L) - 1;
  const QVariant* vp = luaQ_toqvariantp(L, narg  + 1);
  if (vp->userType() != qMetaTypeId<QtLuaMethodInfo>())
    luaL_error(L, "internal error while invoking method");
  const QtLuaMethodInfo *info 
    = static_cast<const QtLuaMethodInfo*>(vp->constData());
  QObject *obj = luaQ_toqobject(L, 1, info->metaObject);
  if (! obj)
    luaL_error(L, "bad 'self' argument (%s expected)", 
               info->metaObject->className());
  VarVector vargs(narg);
  for (i=1; i<narg; i++)
    vargs[i] = luaQ_toqvariant(L, i+1);
  int m = select_overload(vargs, info);
  if (m < 0)
    luaL_error(L, "cannot resolve ambiguous overload");
  const QtLuaMethodInfo::Detail &d = info->d[m];
  PtrVector pargs(narg);
  int arg = 0;
  int errarg = -1;
  int nret = 0;
  try
    {
      pargs[arg++] = construct_retval(d.types[0]);
      for (int i=1; i<narg; i++)
        if (! (pargs[arg++] = construct_arg(vargs[i], d.types[i])))
          { errarg = i; break ; }
      // invoke
      if (errarg < 0)
        {
          obj->qt_metacall(QMetaObject::InvokeMetaMethod, d.id, pargs.data());
          nret = luaQ_p_push_retval(L, pargs[0], d.types[0]);
        }
      // deallocate
      while (--arg >= 0)
        destroy_arg(pargs[arg], d.types[arg]);
      // diagnosis
      if (errarg >= 0)
        luaL_error(L, "bad argument #%d (%s expected)", 
                   errarg, v_to_name(d.types[errarg]) );
    }
  catch(...)
    {
      while (--arg >= 0)
        destroy_arg(pargs[arg], d.types[arg]);
      throw;
    }
  return nret;
}


static int
luaQ_m__call_invokemethod(lua_State *L)
{
  QObject *obj = luaQ_toqobject(L, 1);
  if (! obj)
    luaL_error(L, "bad 'self' argument (not a qobject)");
  int narg = lua_gettop(L);
  lua_pushcfunction(L, luaQ_m__invokemethod);
  lua_insert(L, 1);
  lua_pushvalue(L, lua_upvalueindex(1));
  luaQ_call(L, narg + 1, LUA_MULTRET, obj);
  return lua_gettop(L);
}


/* metatable material: index/newindex */

static int
luaQ_m__index(lua_State *L)
{
  // __index in metatable
  // Check arguments
  QObject *obj = luaQ_checkqobject<QObject>(L, 1);
  if (lua_getmetatable(L, 1)) 
    {
      lua_pushliteral(L, "__metatable");
      lua_rawget(L, -2);
      // ..stack: object key metatable metaclass
      // Search metaclass
      if (lua_istable(L, -1))
        {
          lua_pushvalue(L, 2);
          lua_gettable(L, -2);
          // ..stack: object key metatable metaclass value
          const QVariant *vp = luaQ_toqvariantp(L, -1);
          int type = (vp) ? vp->userType() : QMetaType::Void;
          if (type == qMetaTypeId<QtLuaMethodInfo>())
            {
              lua_pushcclosure(L, luaQ_m__call_invokemethod, 1);
              return 1;
            }
          else if (type == qMetaTypeId<QtLuaPropertyInfo>())
            {
              lua_pushcclosure(L, luaQ_m__getsetproperty, 1);
              lua_pushvalue(L, 1);
              luaQ_call(L, 1, 1, obj);
              return 1;
            }
          else if (! lua_isnil(L, -1))
            return 1;
          lua_pop(L, 1);
        }
      lua_pop(L, 2);
    }
  // ..stack: object key
  // Search children
  const char *key = luaL_checkstring(L, 2);
  QString name = QString::fromLocal8Bit(key);
  foreach (QObject *o, obj->children())
    if (o->objectName() == name)
      {
        luaQ_pushqt(L, o);
        return 1;
      }
  QObject *o = qFindChild<QObject*>(obj, QString::fromLocal8Bit(key));
  if (o)
    {
      luaQ_pushqt(L, o);
      return 1;
    }
  // Failed
  lua_pushnil(L);
  return 1;
}


static int
luaQ_m__newindex(lua_State *L)
{
  // __newindex in metatables
  // ..stack: object key value
  QObject *obj = luaQ_checkqobject<QObject>(L, 1);
  if (lua_getmetatable(L, 1))
    {
      lua_pushliteral(L, "__metatable"); 
      lua_rawget(L, -2);
      // ..stack: object key value metatable metaclass
      // Search property
      if (lua_istable(L, -1))
        {
          lua_pushvalue(L, 2);
          lua_gettable(L, -2);
          // ..stack: object key value metatable metaclass curval
          const QVariant *vp = luaQ_toqvariantp(L, -1);
          int type = (vp) ? vp->userType() : QMetaType::Void;
          if (type == qMetaTypeId<QtLuaPropertyInfo>())
            {
              lua_pushcclosure(L, luaQ_m__getsetproperty, 1);
              lua_pushvalue(L, 1);
              lua_pushvalue(L, 3);
              luaQ_call(L, 2, 0, obj);
              return 0;
            }
          lua_pop(L, 1);
        }
      lua_pop(L, 2);
    }
  // Failed
  const char *key = luaL_checkstring(L, 2);
  luaL_error(L, "cannot set unrecognized property '%s'", key);
  return 0;
}


/* metaclasses */

static const luaL_Reg qtval_lib[] = {
  { "tostring", luaQ_m__tostring },
  { "tonumber", luaQ_m__tonumber },
  { "tobool", luaQ_m__tobool },
  { "type", luaQ_m__type },
  { "isa", luaQ_m__isa },
  {NULL, NULL}
};


void
luaQ_buildmetaclass(lua_State *L, int type)
{
  // Create table
  lua_createtable(L, 0, 0); 
  // Fill table
  lua_pushvalue(L, -1);
  lua_setfield(L, -2, "__index");
  lua_pushcfunction(L, luaQ_m__call);
  lua_setfield(L, -2, "__call");
  if (type != QMetaType::Void)
    {
      luaQ_pushmeta(L,  QMetaType::Void);
      lua_pushliteral(L, "__metatable");
      lua_rawget(L, -2);
      Q_ASSERT(lua_istable(L, -1));
      // stack: class metasuper classsuper
      lua_setmetatable(L, -3);
      lua_pop(L, 1);
    }
  else
    {
      // Standard methods
      luaL_register(L, 0, qtval_lib);
    }
  // Insert class into qt package
  lua_pushlightuserdata(L, (void*)qtKey);
  lua_rawget(L, LUA_REGISTRYINDEX); 
  Q_ASSERT(lua_istable(L, -1));
  lua_pushstring(L, QMetaType::typeName(type));
  lua_pushvalue(L, -3);
  // ..stack: metaclass qtkeytable typename metaclass
  lua_rawset(L, -3);
  lua_pop(L, 1);
}


static PtrVector 
make_argtypes(QMetaMethod method)
{
  PtrVector types;
  QList<QByteArray> typeNames = method.parameterTypes();
  types += make_argtype(method.typeName());
  foreach(QByteArray b, typeNames)
    types += make_argtype(b);
  types.squeeze();
  return types;
}


void
luaQ_buildmetaclass(lua_State *L, const QMetaObject *mo)
{
  // Create table
  lua_createtable(L, 0, 0);
  // Fill table
  lua_pushvalue(L, -1);
  lua_setfield(L, -2, "__index");
  lua_pushcfunction(L, luaQ_m__call);
  lua_setfield(L, -2, "__call");
  const QMetaObject *super = mo->superClass();
  if (super)
    {
      // Plug superclass into index
      luaQ_pushmeta(L, super);
      lua_pushliteral(L, "__metatable");
      lua_rawget(L, -2);
      Q_ASSERT(lua_istable(L, -1));
      // stack: class metasuper classsuper
      lua_setmetatable(L, -3);
      lua_pop(L, 1);
    }
  else
    {
      // Standard methods
      luaL_register(L, 0, qtval_lib);
    }
  // Slots and invokable method
  QMap<QByteArray,QtLuaMethodInfo> overloads;
  int fm = mo->methodOffset();
  int lm = mo->methodCount();
  for  (int i=fm; i<lm; i++)
    {
      QMetaMethod method = mo->method(i);
      QByteArray sig = method.signature();
      if (method.access() != QMetaMethod::Private)
        {
          QtLuaMethodInfo::Detail d;
          d.id = i;
          d.types = make_argtypes(method);
          QtLuaMethodInfo info;
          info.metaObject = mo;
          info.d += d;
          info.d.squeeze();
          lua_pushstring(L, sig.constData());
          luaQ_pushqt(L, qVariantFromValue(info));
          // stack: class signature methodinfo
          lua_rawset(L, -3);
          // record overloads
          int len = sig.indexOf('(');
          if (len > 0)
            {
              sig = sig.left(len);
              if (! overloads.contains(sig))
                overloads[sig] = info;
              else {
                QtLuaMethodInfo &oinfo = overloads[sig];
                oinfo.d += d;
              }
            }
        }
    }
  // Overloaded methods
  QMap<QByteArray,QtLuaMethodInfo>::const_iterator it;
  for (it = overloads.constBegin(); it != overloads.constEnd(); ++it)
    {
      QtLuaMethodInfo info = it.value();
      info.d.squeeze();
      lua_pushstring(L, it.key().constData());
      luaQ_pushqt(L, qVariantFromValue(info));
      lua_rawset(L, -3);
    }
  // Properties
  int fp = mo->propertyOffset();
  int lp = mo->propertyCount();
  for  (int j=fp; j<lp; j++)
    {
      QtLuaPropertyInfo info;
      info.id = j;
      info.metaObject = mo;
      info.metaProperty = mo->property(j);
      lua_pushstring(L, info.metaProperty.name());
      luaQ_pushqt(L, qVariantFromValue(info));
      // stack: class name propinfo
      lua_rawset(L, -3);
    }
  // Insert class into qt package
  lua_pushlightuserdata(L, (void*)qtKey);
  lua_rawget(L, LUA_REGISTRYINDEX); 
  Q_ASSERT(lua_istable(L, -1));
  lua_pushstring(L, mo->className());
  lua_pushvalue(L, -3);
  // ..stack: metaclass qtkeytable classname metaclass
  lua_rawset(L, -3);
  lua_pop(L, 1);
}


static const luaL_Reg qtmeta_lib[] = {
  { "__tostring", luaQ_m__tostring },
  { "__eq", luaQ_m__eq },
  { "__gc", luaQ_m__gc },
  {NULL, NULL}
};


void
luaQ_fillmetatable(lua_State *L, int type, const QMetaObject *mo)
{
  // Fill common entries
  luaL_register(L, 0, qtmeta_lib);
  // Fill distinct entries
  if (mo)
    {
      luaQ_buildmetaclass(L, mo);
      lua_setfield(L, -2, "__metatable");
      lua_pushcfunction(L, luaQ_m__index);
      lua_setfield(L, -2, "__index");
      lua_pushcfunction(L, luaQ_m__newindex);
      lua_setfield(L, -2, "__newindex");
      lua_pushfstring(L, "%s*", mo->className());
      lua_setfield(L, -2, "__typename");
    }
  else
    {
      luaQ_buildmetaclass(L, type);
      lua_pushvalue(L, -1);
      lua_setfield(L, -3, "__index");
      lua_setfield(L, -2, "__metatable");
      lua_pushstring(L, QMetaType::typeName(type));
      lua_setfield(L, -2, "__typename");
    }
}


/*! Pushes the metatable for qt values with type id \a type. */

void 
luaQ_pushmeta(lua_State *L, int type)
{
  lua_pushlightuserdata(L, (void*)metaKey);
  lua_rawget(L, LUA_REGISTRYINDEX);
  Q_ASSERT(lua_istable(L, -1));
  lua_pushlightuserdata(L, (void*)((((size_t)type)<<1)|1));
  lua_rawget(L, -2);
  // stack: metakeytable metatable
  if (lua_istable(L,-1))
    {
      lua_remove(L, -2);
    }
  else
    {
      lua_createtable(L, 0, 6);
      // stack: metakeytable nil metatable
      lua_pushlightuserdata(L, (void*)((((size_t)type)<<1)|1));
      lua_pushvalue(L, -2);
      lua_rawset(L, -5);
      lua_pushvalue(L, -1);
      lua_pushlightuserdata(L, (void*)qtKey);
      lua_rawset(L, LUA_REGISTRYINDEX);
      // fill metatable
      luaQ_fillmetatable(L, type, 0);
      lua_replace(L, -3);
      lua_pop(L, 1);
    }
}


/*! Pushes the metatable for qt objects with meta object \a mo. */

void 
luaQ_pushmeta(lua_State *L, const QMetaObject *mo)
{
  lua_pushlightuserdata(L, (void*)metaKey);
  lua_rawget(L, LUA_REGISTRYINDEX);
  Q_ASSERT(lua_istable(L, -1));
  lua_pushlightuserdata(L, (void*)mo);
  lua_rawget(L, -2);
  // ..stack: metakeytable metatable
  if (lua_istable(L,-1))
    {
      lua_remove(L, -2);
    }
  else
    {
      // record metaobject name
      qtLuaEngineGlobal()->registerMetaObject(mo, false);
      // create metatable
      lua_createtable(L, 0, 6);
     // stack: metakeytable maybehook metatable
      lua_pushlightuserdata(L, (void*)mo);
      lua_pushvalue(L, -2);
      lua_rawset(L, -5);
      lua_pushvalue(L, -1);
      lua_pushlightuserdata(L, (void*)qtKey);
      lua_rawset(L, LUA_REGISTRYINDEX);
      // fill metatable
      luaQ_fillmetatable(L, 0, mo);
      lua_replace(L, -3);
      lua_pop(L, 1);
    }
}


/*! Pushes the metatable for qobject \a o. */

void 
luaQ_pushmeta(lua_State *L, const QObject *o)
{
  luaQ_pushmeta(L, o->metaObject());
}


/*! Pushes value \a var onto the stack.
  Common variant types are converted 
  to standard lua types when applicable. */

void 
luaQ_pushqt(lua_State *L, const QVariant &var)
{
  switch(var.userType())
    {
    case QVariant::Invalid:
      lua_pushnil(L);
      break;
    case QVariant::Bool:
      lua_pushboolean(L, var.toBool());
      break;
    case QVariant::Double:
    case QVariant::Int:
    case QVariant::ULongLong:
    case QVariant::UInt:
    case QMetaType::Float:
    case QMetaType::Char:
    case QMetaType::Short:
    case QMetaType::Long:
    case QMetaType::UChar:
    case QMetaType::UShort:
    case QMetaType::ULong:
      lua_pushnumber(L, var.toDouble());
      break;
    case QVariant::ByteArray:
      {
        QByteArray b = var.toByteArray();
        lua_pushlstring(L, b.constData(), b.size());
        break; 
      }
    default: 
      if (qvariant_has_object_type(&var))
        {
          luaQ_pushqt(L, qvariant_to_object(&var));
        }
      else
        {
          void *v = lua_newuserdata(L, sizeof(QVariant));
          new (v) QVariant(var);
          luaQ_pushmeta(L, var.userType());
          lua_setmetatable(L, -2);
          break; 
        }
    }
}


/*! Pushes qobject \obj onto the stack.
  Flag \a owned indicates whether the object should
  be deleted when lua deallocates the object descriptor.
  Null object pointers are converted to lua \a nil value. */

void 
luaQ_pushqt(lua_State *L, QObject *obj, bool owned)
{
  if (! obj)
    {
      lua_pushnil(L);
    }
  else
    {
      // Search already created objects
      lua_pushlightuserdata(L, (void*)objectKey);
      lua_rawget(L, LUA_REGISTRYINDEX);
      Q_ASSERT(lua_istable(L, -1));
      lua_pushlightuserdata(L, (void*)obj);
      lua_rawget(L, -2);
      // ..stack: objecttable object
      if (lua_isuserdata(L, -1))
        {
          lua_remove(L, -2);
        }
      else
        {
          lua_pop(L, 1);
          // ..stack: objecttable
          // Make new userdata for object
          QObjectPointer objp = obj;
          QVariant objv = qVariantFromValue(objp);
          void *v = lua_newuserdata(L, sizeof(QVariant));
          new (v) QVariant(objv);
          // Fill object
          luaQ_pushmeta(L, obj->metaObject());
          lua_setmetatable(L, -2);
          // ..stack: objecttable object
          // Record object
          lua_pushlightuserdata(L, (void*)obj);
          lua_pushvalue(L, -2);
          // ..stack: objecttable object ud object
          lua_rawset(L, -4);
          // ..stack: objecttable object
          lua_remove(L, -2);
          // ..stack: object
          if (owned)
            {
              QtLuaEngine::Private *d = luaQ_private(L);
              if (d) 
                d->makeObjectLuaOwned(obj);
            }
        }
    }
}



// ========================================
// Signal interception


struct QtLuaEngine::Receiver : public QObject
{
  Q_OBJECT
public:
  virtual ~Receiver();
  Receiver(QtLuaEngine *q) : 
    QObject(q), d(q->d), sender(0), direct(false), args(0) {}
public slots:
  void universal();
  void disconnect();
  bool connect(QObject *sender, const char *signal, bool direct);
public:
  QPointer<QtLuaEngine::Private> d;
  QPointer<QObject> sender;
  QByteArray signature;
  PtrVector types;
  bool direct;
protected:
  void **args;
};


struct QtLuaEngine::Receiver2
#ifndef Q_MOC_RUN
  : public QtLuaEngine::Receiver
#endif
{
  Receiver2(QtLuaEngine *engine) : QtLuaEngine::Receiver(engine) {}
  virtual int qt_metacall(QMetaObject::Call, int, void**);
};


int 
QtLuaEngine::Receiver2::qt_metacall(QMetaObject::Call c, int id, void **a)
{
  void **old = args;
  args = a;
  id = Receiver::qt_metacall(c,id,a);
  args = old;
  return id;
}


QtLuaEngine::Receiver::~Receiver()
{
  if (d && sender)
    {
      QtLuaQueuedSignal q;
      q.delsignal = (void*)this;
      QMutexLocker locker(&d->mutex);
      d->queuedSignals += q;
    }
}


void
QtLuaEngine::Receiver::disconnect()
{
  if (sender)
    QObject::disconnect(sender, 0, this, 0);
}


bool
QtLuaEngine::Receiver::connect(QObject *obj, const char *sig, bool d)
{
  Q_ASSERT(sig);
  Q_ASSERT(obj);
  const QMetaObject *m = obj->metaObject();
  Q_ASSERT(m);
  if (sender)
    return false;
  // search signal
  if (sig[0]>= '0' && sig[0]<='3')
    sig = sig + 1;
  signature = sig;
  int i = m->indexOfSignal(signature.constData());
  if (i < 0)
    {
      signature = QMetaObject::normalizedSignature(sig);
      i = m->indexOfSignal(signature.constData());
      if (i < 0)
        return false;
    }
  // metamethod
  QMetaMethod method = m->method(i);
  if (method.methodType() != QMetaMethod::Signal)
    return false;
  // setup
  sender = obj;
  types = make_argtypes(m->method(i));
  signature.prepend('0' + QSIGNAL_CODE);
#if QT_VERSION >= 0x040800
  const int sigIndex = i;
  const int memberOffset = QObject::staticMetaObject.methodCount();
  bool okay = QMetaObject::connect(obj, sigIndex, this, memberOffset,
                                   Qt::DirectConnection, 0);
#else
  bool okay = QObject::connect(obj, signature.constData(), this,
                               SLOT(universal()), Qt::DirectConnection);
#endif
  if (okay)
    {
      QObject::connect(obj, SIGNAL(destroyed(QObject*)), 
                       this, SLOT(deleteLater()) );
      direct = d;
      return true;
    }
  else
    {
      sender = 0;
      signature.clear();
      types.clear();
      return false;
    }
}


void
QtLuaEngine::Receiver::universal()
{
  bool queueSignal = false;
  QThread *mythread = QThread::currentThread();
  QMutexLocker locker(&d->mutex);
  if (d && direct && !d->hopEvent && 
      d->lockCount>0 && d->lockThread == mythread)
    {
      // find closure
      lua_State *L = d->L;
      int base = lua_gettop(L);
      lua_pushlightuserdata(L, (void*)signalKey);
      lua_rawget(L, LUA_REGISTRYINDEX);
      if (lua_istable(L, -1))
        {
          lua_pushlightuserdata(L, (void*)this);
          lua_rawget(L, -2);
          lua_remove(L, -2);
          if (lua_isfunction(L, -1))
            {
              for (int i=1; i<types.size(); i++)
                luaQ_p_push_retval(L, args[i], types[i]);
              bool oldRflag = d->rflag;
              d->rflag = true;
              locker.unlock();
              if (! oldRflag)
                emit d->q->stateChanged(QtLuaEngine::Running);
              if (lua_pcall(L, types.size()-1, 0, 0))
                if (!d || d->printErrors)
                  luaQ_print(L, 1);
            }
        }
      lua_settop(L, base);
    }
  else if (d)
    {
      // prepare queued signals
      QtLuaQueuedSignal q;
      q.sender = sender;
      q.receiver = this;
      q.delsignal = 0;
      for (int i=1; i<types.size(); i++)
        {
          int type = v_to_type(types[i]);
          const QMetaObject *mo = v_to_metaobject(types[i]);
          if (type == qMetaTypeId<QVariant>())
            q.args += *static_cast<QVariant*>(args[i]);
          else if (type)
            q.args += QVariant(type, args[i]);
          else if (mo) {
            QObjectPointer p = *static_cast<QObject**>(args[i]);
            q.args += qVariantFromValue(p);
          } else
            q.args += QVariant();
        }
      // queue signals for later invocation
      if (d->queuedSignals.isEmpty())
        queueSignal = true;
      d->queuedSignals += q;
      locker.unlock();
    }
  if (queueSignal)
    d->emitQueueSignal();
}


void
QtLuaEngine::Private::disconnectAllSignals()
{
  Receiver *r;
  foreach(QObject *obj, children())
    if ((obj) && (r = qobject_cast<Receiver*>(obj)))
      r->disconnect();
  QMutexLocker locker(&mutex);
  queuedSignals.clear();
}


bool 
QtLuaEngine::Private::processQueuedSignals(QMutexLocker &locker)
{
  bool processed = false;
  QList<QtLuaQueuedSignal> qs = queuedSignals;
  queuedSignals.clear();
  while (qs.size() > 0)
    {
      QtLuaQueuedSignal q = qs.takeFirst();
      if (q.delsignal)
        {
          // delete closure associated with this signal
          lua_pushlightuserdata(L, (void*)signalKey);
          lua_rawget(L, LUA_REGISTRYINDEX);
          if (lua_istable(L, -1))
            {
              lua_pushlightuserdata(L, (void*)this);
              lua_pushnil(L);
              lua_rawset(L, -3);
            }
          lua_pop(L, 1);
        }
      else if (q.sender && q.receiver && !pauseLoop && !unwindStack)
        {
          bool stateChanged = ! rflag;
          rflag = true;
          locker.unlock();
          if (stateChanged)
            emitStateChanged(QtLuaEngine::Running);
          // call closure
          int base = lua_gettop(L);
          lua_pushcfunction(L, lua_error_handler);
          lua_pushlightuserdata(L, (void*)signalKey);
          lua_rawget(L, LUA_REGISTRYINDEX);
          if (lua_istable(L, -1))
            {
              QtLuaEngine::Receiver *receiver = q.receiver;
              lua_pushlightuserdata(L, (void*)receiver);
              lua_rawget(L, -2);
              lua_remove(L, -2);
              if (lua_isfunction(L, -1))
                {
                  processed = true;
                  for (int i=0; i<q.args.size(); i++)
                    luaQ_pushqt(L, q.args[i]);
                  if (lua_pcall(L, q.args.size(), 0, -2-q.args.size()))
                    if (printErrors)
                      luaQ_print(L, 1);
                }
            }
          lua_settop(L, base);
          locker.relock();
        }
    }
  return processed;
}


/*! This function processes all pending events in the running thread.
  It also processed queued signals connected to a lua function or closure.
  This implies that these lua functions or closure are called from
  within the luaQ_doevents function. 
  The optional flag \a wait indicates if one should wait 
  until receiving at least one event. */

void 
luaQ_doevents(lua_State *L, bool wait)
{
  QtLuaEngine::Private *d = luaQ_private(L);
  QMutexLocker locker(&d->mutex);
  QEventLoop *saved_loop = d->pauseLoop;
  bool saved_rflag = d->rflag;
  // process events (state unchanged. should we pause on wait?)
  QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents;
  if (wait && d->queuedSignals.isEmpty())
    flags |= QEventLoop::WaitForMoreEvents;
  locker.unlock();
  QCoreApplication::processEvents(flags);
  locker.relock();
  // run signals (possibly going into Running state)
  d->pauseLoop = 0;
  if (saved_loop)
    d->rflag = false;
  while(d->processQueuedSignals(locker))
    {
      locker.unlock();
      QCoreApplication::processEvents();
      locker.relock();
    }
  // restore initial state
  bool new_rflag = d->rflag;
  d->rflag = saved_rflag;
  d->pauseLoop = saved_loop;
  locker.unlock();
  if (saved_loop && new_rflag)
    emit d->emitStateChanged(QtLuaEngine::Paused);
  else if (!saved_rflag && new_rflag)
    emit d->emitStateChanged(QtLuaEngine::Ready);
}


void 
luaQ_doevents(lua_State *L)
{
  return luaQ_doevents(L, false);
}


void
luaQ_pause(lua_State *L)
{
  QtLuaEngine::Private *d = luaQ_private(L);
  d->emitQueueSignal();
  lua_pushliteral(L, "pause");
  QMutexLocker locker(&d->mutex);
  bool stateChanged = lua_pause_sub(L, d, locker);
  locker.unlock();
  if (stateChanged)
    d->emitStateChanged(QtLuaEngine::Running);
  lua_pop(L, 1);
  if (d && !d->unwindStack)
    return;
  lua_pushliteral(L, "stop");
  lua_error(L);
}


void
luaQ_resume(lua_State *L, bool nocontinue)
{
  QtLuaEngine::Private *d = luaQ_private(L);
  QMutexLocker locker(&d->mutex);
  if (d->pauseLoop)
    return;
  if (nocontinue)
    d->unwindStack = true;
  else
    d->resumeFlag = true;
}



/* create a receiver2 (receiver2, not receiver!) */

static int
luaQ_p_create_receiver(lua_State *L)
{
  QtLuaEngine::Private *d = luaQ_private(L);
  QtLuaEngine::Receiver *r = new QtLuaEngine::Receiver2(d->q);
  luaQ_pushqt(L, qVariantFromValue<void*>(static_cast<void*>(r)));
  return 1;
}


/*! Connects signal \a sig of Qt object \a obj to the 
  function located at stack position \a findex.
  Returns false if the signal does not exist. */

bool
luaQ_connect(lua_State *L, QObject *obj, 
             const char *sig, int findex, bool direct)
{
  bool success = false;
  QtLuaEngine::Private *d = luaQ_private(L);
  if (! lua_isfunction(L, findex))
    luaL_error(L, "luaQ_connect: function expected");
  // create receiver
  lua_pushcfunction(L, luaQ_p_create_receiver);
  luaQ_call(L, 0, 1, d->q);
  QVariant *vp = luaQ_toqvariantp(L, -1);
  void *v = (vp) ? qVariantValue<void*>(luaQ_toqvariant(L, -1)) : 0;
  QtLuaEngine::Receiver *r = static_cast<QtLuaEngine::Receiver*>(v);
  lua_pop(L, 1);
  if (! r)
    luaL_error(L, "luaQ_connect: cannot create receiver");
  // push closure
  lua_pushvalue(L, findex);
  lua_pushlightuserdata(L, (void*)signalKey);
  lua_rawget(L, LUA_REGISTRYINDEX);
  if (lua_istable(L, -1))
    {
      lua_pushlightuserdata(L, (void*)r);
      // ..stack: function signaltable receiveraddress
      lua_pushvalue(L, -3);
      lua_rawset(L, -3);
      success = r->connect(obj, sig, direct);
      if (! success)
        r->deleteLater();
    }
  lua_pop(L, 2);
  return success;
}


/*! Disconnects the connection matching the provided arguments.
  Arguments \a sig of \a findex can be zero to indicate
  that any signature or any closure should match. 
  Returns a boolean indicating if any such signals were found. */

bool
luaQ_disconnect(lua_State *L, QObject *obj, const char *sig, int findex)
{
  QtLuaEngine::Private *d = luaQ_private(L);
  if (sig && sig[0] == '0' + QSIGNAL_CODE)
    sig = sig + 1;
  else if (sig && sig[0] >= '0' && sig[0] <= '3')
    return false;
  if (findex && !lua_isfunction(L, findex))
    return false;
  QByteArray nsig = QMetaObject::normalizedSignature(sig);
  nsig.prepend('0' + QSIGNAL_CODE);
  lua_pushlightuserdata(L, (void*)signalKey);
  lua_rawget(L, LUA_REGISTRYINDEX);
  if (findex)
    lua_pushvalue(L, findex);
  else 
    lua_pushnil(L);
  // ..stack: function sigtable ...
  // select receviers
  QList<QtLuaEngine::Receiver*> chosen;
  QMutexLocker locker(&d->mutex);
  QtLuaEngine::Receiver *r;
  foreach(QObject *o, d->q->children())
    if ((r = qobject_cast<QtLuaEngine::Receiver*>(o)))
      {
        if (obj && r->sender != obj)
          continue;
        if (sig && r->signature != nsig)
          continue;
        if (findex && lua_istable(L, -2))
          {
            lua_pushlightuserdata(L, (void*)r);
            lua_rawget(L, -3);
            // ..stack: sigfunc function sigtable
            bool eq = lua_equal(L, -1, -2);
            lua_pop(L, 1);
            if (! eq)
              continue;
          }
        chosen += r;
      }
  // now disconnect and destroy the chosen receivers
  locker.unlock();
  foreach(r, chosen)
    {
      r->disconnect();
      lua_pushlightuserdata(L, (void*)r);
      lua_pushnil(L);
      lua_rawset(L, -4);
      r->deleteLater();
    }
  // return
  lua_pop(L, 2);
  return chosen.size() > 0;
}




// ========================================
// MOC

#include "qtluaengine.moc"




/* -------------------------------------------------------------
   Local Variables:
   c++-font-lock-extra-types: ("\\sw+_t" "\\(lua_\\)?[A-Z]\\sw*[a-z]\\sw*")
   End:
   ------------------------------------------------------------- */