summaryrefslogtreecommitdiffstats
path: root/src/activeqt/control/qaxserverbase.cpp
blob: a2f9579753b0c80dab9a95e4964e6d15d11ac8f8 (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
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the ActiveQt framework of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

#define QT_NO_CAST_TO_ASCII

#ifndef QT_NO_WIN_ACTIVEQT

#include <qabstracteventdispatcher.h>
#include <qapplication.h>
#include <qbuffer.h>
#include <qdatastream.h>
#include <qdebug.h>
#include <qevent.h>
#include <qeventloop.h>
#include <qfile.h>
#include <qpointer.h>
#include <qhash.h>
#include <qmap.h>
#include <qmenubar.h>
#include <qmenu.h>
#include <qmetaobject.h>
#include <qpixmap.h>
#include <qstatusbar.h>
#include <qwhatsthis.h>
#include <ocidl.h>
#include <olectl.h>
#include <private/qcoreapplication_p.h>

#include "qaxfactory.h"
#include "qaxbindable.h"
#include "qaxaggregated.h"

#include "../shared/qaxtypes.h"

#if defined Q_CC_GNU
#   include <w32api.h>
#endif

#ifndef Q_OS_WIN64
#define ULONG_PTR DWORD
#endif

QT_BEGIN_NAMESPACE

extern HHOOK qax_hhook;

// in qaxserver.cpp
extern ITypeLib *qAxTypeLibrary;
extern QAxFactory *qAxFactory();
extern unsigned long qAxLock();
extern unsigned long qAxUnlock();
extern HANDLE qAxInstance;
extern bool qAxOutProcServer;

static int invokeCount = 0;

#ifdef QT_DEBUG
unsigned long qaxserverbase_instance_count = 0;
#endif

// in qaxserverdll.cpp
extern bool qax_ownQApp;

struct QAxExceptInfo
{
    QAxExceptInfo(int c, const QString &s, const QString &d, const QString &x)
	: code(c), src(s), desc(d), context(x)
    {
    }
    int code;
    QString src;
    QString desc;
    QString context;
};


bool qt_sendSpontaneousEvent(QObject*, QEvent*);

/*
    \class QAxServerBase
    \brief The QAxServerBase class is an ActiveX control hosting a QWidget.

    \internal
*/
class QAxServerBase :
    public QObject,
    public IAxServerBase,
    public IDispatch,
    public IOleObject,
    public IOleControl,
#if defined Q_CC_GNU
#   if (__W32API_MAJOR_VERSION < 2 || (__W32API_MAJOR_VERSION == 2 && __W32API_MINOR_VERSION < 5))
    public IViewObject, // this should not be needed as IViewObject2 is meant to inherit from this,
                        // untill the mingw headers are fixed this will need to stay.
#   endif
#endif
    public IViewObject2,
    public IOleInPlaceObject,
    public IOleInPlaceActiveObject,
    public IProvideClassInfo2,
    public IConnectionPointContainer,
    public IPersistStream,
    public IPersistStreamInit,
    public IPersistStorage,
    public IPersistPropertyBag,
    public IPersistFile,
    public IDataObject
{
public:
    typedef QMap<QUuid,IConnectionPoint*> ConnectionPoints;
    typedef QMap<QUuid,IConnectionPoint*>::Iterator ConnectionPointsIterator;

    QAxServerBase(const QString &classname, IUnknown *outerUnknown);
    QAxServerBase(QObject *o);

    void init();

    ~QAxServerBase();

// Window creation
    HWND create(HWND hWndParent, RECT& rcPos);
    HMENU createPopup(QMenu *popup, HMENU oldMenu = 0);
    void createMenu(QMenuBar *menuBar);
    void removeMenu();

    static LRESULT QT_WIN_CALLBACK ActiveXProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

// Object registration with OLE
    void registerActiveObject(IUnknown *object);
    void revokeActiveObject();

// IUnknown
    unsigned long WINAPI AddRef()
    {
	if (m_outerUnknown)
	    return m_outerUnknown->AddRef();

	EnterCriticalSection(&refCountSection);
	unsigned long r = ++ref;
	LeaveCriticalSection(&refCountSection);

	return r;
    }
    unsigned long WINAPI Release()
    {
    	if (m_outerUnknown)
	    return m_outerUnknown->Release();

	EnterCriticalSection(&refCountSection);
	unsigned long r = --ref;
	LeaveCriticalSection(&refCountSection);

	if (!r) {
	    delete this;
	    return 0;
	}
	return r;
    }
    HRESULT WINAPI QueryInterface(REFIID iid, void **iface);
    HRESULT InternalQueryInterface(REFIID iid, void **iface);

// IAxServerBase
    IUnknown *clientSite() const
    {
	return m_spClientSite;
    }

    void emitPropertyChanged(const char*);
    bool emitRequestPropertyChange(const char*);
    QObject *qObject() const
    {
	return theObject;
    }
    void ensureMetaData();
    bool isPropertyExposed(int index);

    void reportError(int code, const QString &src, const QString &desc, const QString &context)
    {
        if (exception)
            delete exception;
        exception = new QAxExceptInfo(code, src, desc, context);
    }

// IDispatch
    STDMETHOD(GetTypeInfoCount)(UINT* pctinfo);
    STDMETHOD(GetTypeInfo)(UINT itinfo, LCID lcid, ITypeInfo** pptinfo);
    STDMETHOD(GetIDsOfNames)(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid);
    STDMETHOD(Invoke)(DISPID dispidMember, REFIID riid,
		LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult,
		EXCEPINFO* pexcepinfo, UINT* puArgErr);

// IProvideClassInfo
    STDMETHOD(GetClassInfo)(ITypeInfo** pptinfo);

// IProvideClassInfo2
    STDMETHOD(GetGUID)(DWORD dwGuidKind, GUID* pGUID);

// IOleObject
    STDMETHOD(Advise)(IAdviseSink* pAdvSink, DWORD* pdwConnection);
    STDMETHOD(Close)(DWORD dwSaveOption);
    STDMETHOD(DoVerb)(LONG iVerb, LPMSG lpmsg, IOleClientSite* pActiveSite, LONG lindex, HWND hwndParent, LPCRECT lprcPosRect);
    STDMETHOD(EnumAdvise)(IEnumSTATDATA** ppenumAdvise);
    STDMETHOD(EnumVerbs)(IEnumOLEVERB** ppEnumOleVerb);
    STDMETHOD(GetClientSite)(IOleClientSite** ppClientSite);
    STDMETHOD(GetClipboardData)(DWORD dwReserved, IDataObject** ppDataObject);
    STDMETHOD(GetExtent)(DWORD dwDrawAspect, SIZEL* psizel);
    STDMETHOD(GetMiscStatus)(DWORD dwAspect, DWORD *pdwStatus);
    STDMETHOD(GetMoniker)(DWORD dwAssign, DWORD dwWhichMoniker, IMoniker** ppmk);
    STDMETHOD(GetUserClassID)(CLSID* pClsid);
    STDMETHOD(GetUserType)(DWORD dwFormOfType, LPOLESTR *pszUserType);
    STDMETHOD(InitFromData)(IDataObject* pDataObject, BOOL fCreation, DWORD dwReserved);
    STDMETHOD(IsUpToDate)();
    STDMETHOD(SetClientSite)(IOleClientSite* pClientSite);
    STDMETHOD(SetColorScheme)(LOGPALETTE* pLogPal);
    STDMETHOD(SetExtent)(DWORD dwDrawAspect, SIZEL* psizel);
    STDMETHOD(SetHostNames)(LPCOLESTR szContainerApp, LPCOLESTR szContainerObj);
    STDMETHOD(SetMoniker)(DWORD dwWhichMoniker, IMoniker* ppmk);
    STDMETHOD(Unadvise)(DWORD dwConnection);
    STDMETHOD(Update)();

// IViewObject
    STDMETHOD(Draw)(DWORD dwAspect, LONG lIndex, void *pvAspect, DVTARGETDEVICE *ptd,
		    HDC hicTargetDevice, HDC hdcDraw, LPCRECTL lprcBounds, LPCRECTL lprcWBounds,
		    BOOL(__stdcall*pfnContinue)(ULONG_PTR), ULONG_PTR dwContinue);
    STDMETHOD(GetColorSet)(DWORD dwDrawAspect, LONG lindex, void *pvAspect, DVTARGETDEVICE *ptd,
		    HDC hicTargetDev, LOGPALETTE **ppColorSet);
    STDMETHOD(Freeze)(DWORD dwAspect, LONG lindex, void *pvAspect, DWORD *pdwFreeze);
    STDMETHOD(Unfreeze)(DWORD dwFreeze);
    STDMETHOD(SetAdvise)(DWORD aspects, DWORD advf, IAdviseSink *pAdvSink);
    STDMETHOD(GetAdvise)(DWORD *aspects, DWORD *advf, IAdviseSink **pAdvSink);

// IViewObject2
    STDMETHOD(GetExtent)(DWORD dwAspect, LONG lindex, DVTARGETDEVICE *ptd, LPSIZEL lpsizel);

// IOleControl
    STDMETHOD(FreezeEvents)(BOOL);
    STDMETHOD(GetControlInfo)(LPCONTROLINFO);
    STDMETHOD(OnAmbientPropertyChange)(DISPID);
    STDMETHOD(OnMnemonic)(LPMSG);

// IOleWindow
    STDMETHOD(GetWindow)(HWND *pHwnd);
    STDMETHOD(ContextSensitiveHelp)(BOOL fEnterMode);

// IOleInPlaceObject
    STDMETHOD(InPlaceDeactivate)();
    STDMETHOD(UIDeactivate)();
    STDMETHOD(SetObjectRects)(LPCRECT lprcPosRect, LPCRECT lprcClipRect);
    STDMETHOD(ReactivateAndUndo)();

// IOleInPlaceActiveObject
    STDMETHOD(TranslateAcceleratorW)(MSG *pMsg);
    STDMETHOD(TranslateAcceleratorA)(MSG *pMsg);
    STDMETHOD(OnFrameWindowActivate)(BOOL);
    STDMETHOD(OnDocWindowActivate)(BOOL fActivate);
    STDMETHOD(ResizeBorder)(LPCRECT prcBorder, IOleInPlaceUIWindow *pUIWindow, BOOL fFrameWindow);
    STDMETHOD(EnableModeless)(BOOL);

// IConnectionPointContainer
    STDMETHOD(EnumConnectionPoints)(IEnumConnectionPoints**);
    STDMETHOD(FindConnectionPoint)(REFIID, IConnectionPoint**);

// IPersist
    STDMETHOD(GetClassID)(GUID*clsid)
    {
	*clsid = qAxFactory()->classID(class_name);
	return S_OK;
    }

// IPersistStreamInit
    STDMETHOD(InitNew)(VOID);
    STDMETHOD(IsDirty)();
    STDMETHOD(Load)(IStream *pStm);
    STDMETHOD(Save)(IStream *pStm, BOOL fClearDirty);
    STDMETHOD(GetSizeMax)(ULARGE_INTEGER *pcbSize);

// IPersistPropertyBag
    STDMETHOD(Load)(IPropertyBag *, IErrorLog *);
    STDMETHOD(Save)(IPropertyBag *, BOOL, BOOL);

// IPersistStorage
    STDMETHOD(InitNew)(IStorage *pStg);
    STDMETHOD(Load)(IStorage *pStg);
    STDMETHOD(Save)(IStorage *pStg, BOOL fSameAsLoad);
    STDMETHOD(SaveCompleted)(IStorage *pStgNew);
    STDMETHOD(HandsOffStorage)();

// IPersistFile
    STDMETHOD(SaveCompleted)(LPCOLESTR fileName);
    STDMETHOD(GetCurFile)(LPOLESTR *currentFile);
    STDMETHOD(Load)(LPCOLESTR fileName, DWORD mode);
    STDMETHOD(Save)(LPCOLESTR fileName, BOOL fRemember);

// IDataObject
    STDMETHOD(GetData)(FORMATETC *pformatetcIn, STGMEDIUM *pmedium);
    STDMETHOD(GetDataHere)(FORMATETC* /* pformatetc */, STGMEDIUM* /* pmedium */);
    STDMETHOD(QueryGetData)(FORMATETC* /* pformatetc */);
    STDMETHOD(GetCanonicalFormatEtc)(FORMATETC* /* pformatectIn */,FORMATETC* /* pformatetcOut */);
    STDMETHOD(SetData)(FORMATETC* /* pformatetc */, STGMEDIUM* /* pmedium */, BOOL /* fRelease */);
    STDMETHOD(EnumFormatEtc)(DWORD /* dwDirection */, IEnumFORMATETC** /* ppenumFormatEtc */);
    STDMETHOD(DAdvise)(FORMATETC *pformatetc, DWORD advf, IAdviseSink *pAdvSink, DWORD *pdwConnection);
    STDMETHOD(DUnadvise)(DWORD dwConnection);
    STDMETHOD(EnumDAdvise)(IEnumSTATDATA **ppenumAdvise);

// QObject
    int qt_metacall(QMetaObject::Call, int index, void **argv);

    bool eventFilter(QObject *o, QEvent *e);
private:
    void update();
    void resize(const QSize &newSize);
    void updateGeometry();
    void updateMask();
    bool internalCreate();
    void internalBind();
    void internalConnect();
    HRESULT internalActivate();

    friend class QAxBindable;
    friend class QAxPropertyPage;

    QAxAggregated *aggregatedObject;
    ConnectionPoints points;

    union {
	QWidget *widget;
	QObject *object;
    } qt;
    QPointer<QObject> theObject;
    unsigned isWidget		:1;
    unsigned ownObject		:1;
    unsigned initNewCalled	:1;
    unsigned dirtyflag		:1;
    unsigned hasStockEvents	:1;
    unsigned stayTopLevel	:1;
    unsigned isInPlaceActive	:1;
    unsigned isUIActive		:1;
    unsigned wasUIActive	:1;
    unsigned inDesignMode	:1;
    unsigned canTakeFocus	:1;
    short freezeEvents;

    HWND m_hWnd;

    HMENU hmenuShared;
    HOLEMENU holemenu;
    HWND hwndMenuOwner;
    QMap<HMENU, QMenu*> menuMap;
    QMap<UINT, QAction*> actionMap;
    QPointer<QMenuBar> menuBar;
    QPointer<QStatusBar> statusBar;
    QPointer<QMenu> currentPopup;
    QAxExceptInfo *exception;

    CRITICAL_SECTION refCountSection;
    CRITICAL_SECTION createWindowSection;

    unsigned long ref;
    unsigned long ole_ref;

    QString class_name;
    QString currentFileName;

    QHash<long, int> indexCache;
    QHash<int,DISPID> signalCache;

    IUnknown *m_outerUnknown;
    IAdviseSink *m_spAdviseSink;
    QList<STATDATA> adviseSinks;
    IOleClientSite *m_spClientSite;
    IOleInPlaceSiteWindowless *m_spInPlaceSite;
    IOleInPlaceFrame *m_spInPlaceFrame;
    ITypeInfo *m_spTypeInfo;
    IStorage *m_spStorage;
    QSize m_currentExtent;
};

class QAxServerAggregate : public IUnknown
{
public:
    QAxServerAggregate(const QString &className, IUnknown *outerUnknown)
	: m_outerUnknown(outerUnknown), ref(0)
    {
	object = new QAxServerBase(className, outerUnknown);
	object->registerActiveObject(this);

	InitializeCriticalSection(&refCountSection);
	InitializeCriticalSection(&createWindowSection);
    }
    ~QAxServerAggregate()
    {
	DeleteCriticalSection(&refCountSection);
	DeleteCriticalSection(&createWindowSection);

	delete object;
    }

// IUnknown
    unsigned long WINAPI AddRef()
    {
	EnterCriticalSection(&refCountSection);
	unsigned long r = ++ref;
	LeaveCriticalSection(&refCountSection);

	return r;
    }
    unsigned long WINAPI Release()
    {
	EnterCriticalSection(&refCountSection);
	unsigned long r = --ref;
	LeaveCriticalSection(&refCountSection);

	if (!r) {
	    delete this;
	    return 0;
	}
	return r;
    }
    HRESULT WINAPI QueryInterface(REFIID iid, void **iface)
    {
	*iface = 0;

	HRESULT res = E_NOINTERFACE;
	if (iid == IID_IUnknown) {
	    *iface = (IUnknown*)this;
	    AddRef();
	    return S_OK;
	}
	return object->InternalQueryInterface(iid, iface);
    }

private:
    QAxServerBase *object;
    IUnknown *m_outerUnknown;
    unsigned long ref;

    CRITICAL_SECTION refCountSection;
    CRITICAL_SECTION createWindowSection;
};

bool QAxFactory::createObjectWrapper(QObject *object, IDispatch **wrapper)
{
    *wrapper = 0;
    QAxServerBase *obj = new QAxServerBase(object);
    obj->QueryInterface(IID_IDispatch, (void**)wrapper);
    if (*wrapper)
	return true;

    delete obj;
    return false;
}


/*
    Helper class to enumerate all supported event interfaces.
*/
class QAxSignalVec : public IEnumConnectionPoints
{
public:
    QAxSignalVec(const QAxServerBase::ConnectionPoints &points)
	: cpoints(points), ref(0)
    {
	InitializeCriticalSection(&refCountSection);
	for (QAxServerBase::ConnectionPointsIterator i = cpoints.begin(); i != cpoints.end(); ++i)
	    (*i)->AddRef();
    }
    QAxSignalVec(const QAxSignalVec &old)
    {
	InitializeCriticalSection(&refCountSection);
	ref = 0;
	cpoints = old.cpoints;
	for (QAxServerBase::ConnectionPointsIterator i = cpoints.begin(); i != cpoints.end(); ++i)
	    (*i)->AddRef();
	it = old.it;
    }
    ~QAxSignalVec()
    {
	for (QAxServerBase::ConnectionPointsIterator i = cpoints.begin(); i != cpoints.end(); ++i)
	    (*i)->Release();

	DeleteCriticalSection(&refCountSection);
    }

    unsigned long __stdcall AddRef()
    {
	EnterCriticalSection(&refCountSection);
	unsigned long r = ++ref;
	LeaveCriticalSection(&refCountSection);
	return ++r;
    }
    unsigned long __stdcall Release()
    {
	EnterCriticalSection(&refCountSection);
	unsigned long r = --ref;
	LeaveCriticalSection(&refCountSection);

	if (!r) {
	    delete this;
	    return 0;
	}
	return r;
    }
    STDMETHOD(QueryInterface)(REFIID iid, void **iface)
    {
	*iface = 0;
	if (iid == IID_IUnknown)
	    *iface = this;
	else if (iid == IID_IEnumConnectionPoints)
	    *iface = this;
	else
	    return E_NOINTERFACE;

	AddRef();
	return S_OK;
    }
    STDMETHOD(Next)(ULONG cConnections, IConnectionPoint **cpoint, ULONG *pcFetched)
    {
	unsigned long i;
	for (i = 0; i < cConnections; i++) {
	    if (it == cpoints.end())
		break;
	    IConnectionPoint *cp = *it;
	    cp->AddRef();
	    cpoint[i] = cp;
	    ++it;
	}
	*pcFetched = i;
	return i == cConnections ? S_OK : S_FALSE;
    }
    STDMETHOD(Skip)(ULONG cConnections)
    {
	while (cConnections) {
	    ++it;
	    --cConnections;
	    if (it == cpoints.end())
		return S_FALSE;
	}
	return S_OK;
    }
    STDMETHOD(Reset)()
    {
	it = cpoints.begin();

	return S_OK;
    }
    STDMETHOD(Clone)(IEnumConnectionPoints **ppEnum)
    {
	*ppEnum = new QAxSignalVec(*this);
	(*ppEnum)->AddRef();

	return S_OK;
    }

    QAxServerBase::ConnectionPoints cpoints;
    QAxServerBase::ConnectionPointsIterator it;

private:
    CRITICAL_SECTION refCountSection;

    unsigned long ref;
};

/*
    Helper class to store and enumerate all connected event listeners.
*/
class QAxConnection : public IConnectionPoint,
		      public IEnumConnections
{
public:
    typedef QList<CONNECTDATA> Connections;
    typedef QList<CONNECTDATA>::Iterator Iterator;

    QAxConnection(QAxServerBase *parent, const QUuid &uuid)
	: that(parent), iid(uuid), ref(1)
    {
	InitializeCriticalSection(&refCountSection);
    }
    QAxConnection(const QAxConnection &old)
    {
	InitializeCriticalSection(&refCountSection);
	ref = 0;
	connections = old.connections;
	it = old.it;
	that = old.that;
	iid = old.iid;
	QList<CONNECTDATA>::Iterator it = connections.begin();
	while (it != connections.end()) {
	    CONNECTDATA connection = *it;
	    ++it;
	    connection.pUnk->AddRef();
	}
    }
    ~QAxConnection()
    {
	DeleteCriticalSection(&refCountSection);
    }

    unsigned long __stdcall AddRef()
    {
	EnterCriticalSection(&refCountSection);
	unsigned long r = ++ref;
	LeaveCriticalSection(&refCountSection);
	return r;
    }
    unsigned long __stdcall Release()
    {
	EnterCriticalSection(&refCountSection);
	unsigned long r = --ref;
	LeaveCriticalSection(&refCountSection);

	if (!r) {
	    delete this;
	    return 0;
	}
	return r;
    }
    STDMETHOD(QueryInterface)(REFIID iid, void **iface)
    {
	*iface = 0;
	if (iid == IID_IUnknown)
	    *iface = (IConnectionPoint*)this;
	else if (iid == IID_IConnectionPoint)
	    *iface = this;
	else if (iid == IID_IEnumConnections)
	    *iface = this;
	else
	    return E_NOINTERFACE;

	AddRef();
	return S_OK;
    }
    STDMETHOD(GetConnectionInterface)(IID *pIID)
    {
	*pIID = iid;
	return S_OK;
    }
    STDMETHOD(GetConnectionPointContainer)(IConnectionPointContainer **ppCPC)
    {
	return that->QueryInterface(IID_IConnectionPointContainer, (void**)ppCPC);
    }
    STDMETHOD(Advise)(IUnknown*pUnk, DWORD *pdwCookie)
    {
	{
	    IDispatch *checkImpl = 0;
	    pUnk->QueryInterface(iid, (void**)&checkImpl);
	    if (!checkImpl)
		return CONNECT_E_CANNOTCONNECT;
	    checkImpl->Release();
	}

	CONNECTDATA cd;
	cd.dwCookie = connections.count()+1;
	cd.pUnk = pUnk;
	cd.pUnk->AddRef();
	connections.append(cd);

	*pdwCookie = cd.dwCookie;
	return S_OK;
    }
    STDMETHOD(Unadvise)(DWORD dwCookie)
    {
	QList<CONNECTDATA>::Iterator it = connections.begin();
	while (it != connections.end()) {
	    CONNECTDATA cd = *it;
	    if (cd.dwCookie == dwCookie) {
		cd.pUnk->Release();
		connections.erase(it);
		return S_OK;
	    }
	    ++it;
	}
	return CONNECT_E_NOCONNECTION;
    }
    STDMETHOD(EnumConnections)(IEnumConnections **ppEnum)
    {
	*ppEnum = this;
	AddRef();

	return S_OK;
    }
    STDMETHOD(Next)(ULONG cConnections, CONNECTDATA *cd, ULONG *pcFetched)
    {
	unsigned long i;
	for (i = 0; i < cConnections; i++) {
	    if (it == connections.end())
		break;
	    cd[i] = *it;
	    cd[i].pUnk->AddRef();
	    ++it;
	}
	if (pcFetched)
	    *pcFetched = i;
	return i == cConnections ? S_OK : S_FALSE;
    }
    STDMETHOD(Skip)(ULONG cConnections)
    {
	while (cConnections) {
	    ++it;
	    --cConnections;
	    if (it == connections.end())
		return S_FALSE;
	}
	return S_OK;
    }
    STDMETHOD(Reset)()
    {
	it = connections.begin();

	return S_OK;
    }
    STDMETHOD(Clone)(IEnumConnections **ppEnum)
    {
	*ppEnum = new QAxConnection(*this);
	(*ppEnum)->AddRef();

	return S_OK;
    }

private:
    QAxServerBase *that;
    QUuid iid;
    Connections connections;
    Iterator it;

    CRITICAL_SECTION refCountSection;
    unsigned long ref;
};

// callback for DLL server to hook into non-Qt eventloop
LRESULT QT_WIN_CALLBACK axs_FilterProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (qApp && !invokeCount)
        qApp->sendPostedEvents();

    return CallNextHookEx(qax_hhook, nCode, wParam, lParam);
}

// filter for executable case to hook into Qt eventloop
// for DLLs the client calls TranslateAccelerator
bool qax_winEventFilter(void *message)
{
    MSG *pMsg = (MSG*)message;
    if (pMsg->message < WM_KEYFIRST || pMsg->message > WM_KEYLAST)
	return false;

    bool ret = false;
    QWidget *aqt = QWidget::find(pMsg->hwnd);
    if (!aqt)
	return ret;

    HWND baseHwnd = ::GetParent(aqt->winId());
    QAxServerBase *axbase = 0;
    while (!axbase && baseHwnd) {
#ifdef GWLP_USERDATA
        axbase = (QAxServerBase*)GetWindowLongPtr(baseHwnd, GWLP_USERDATA);
#else
        axbase = (QAxServerBase*)GetWindowLong(baseHwnd, GWL_USERDATA);
#endif

	baseHwnd = ::GetParent(baseHwnd);
    }
    if (!axbase)
	return ret;

    HRESULT hres = axbase->TranslateAcceleratorW(pMsg);
    return hres == S_OK;
}

extern void qWinMsgHandler(QtMsgType t, const char* str);

// COM Factory class, mapping COM requests to ActiveQt requests.
// One instance of this class for each ActiveX the server can provide.
class QClassFactory : public IClassFactory2
{
public:
    QClassFactory(CLSID clsid)
	: ref(0), licensed(false)
    {
	InitializeCriticalSection(&refCountSection);

	// COM only knows the CLSID, but QAxFactory is class name based...
	QStringList keys = qAxFactory()->featureList();
	for (QStringList::Iterator  key = keys.begin(); key != keys.end(); ++key) {
	    if (qAxFactory()->classID(*key) == clsid) {
		className = *key;
		break;
	    }
	}

	const QMetaObject *mo = qAxFactory()->metaObject(className);
	if (mo) {
	    classKey = QLatin1String(mo->classInfo(mo->indexOfClassInfo("LicenseKey")).value());
	    licensed = !classKey.isEmpty();
	}
    }

    ~QClassFactory()
    {
	DeleteCriticalSection(&refCountSection);
    }

    // IUnknown
    unsigned long WINAPI AddRef()
    {
	EnterCriticalSection(&refCountSection);
	unsigned long r = ++ref;
	LeaveCriticalSection(&refCountSection);
	return ++r;
    }
    unsigned long WINAPI Release()
    {
	EnterCriticalSection(&refCountSection);
	unsigned long r = --ref;
	LeaveCriticalSection(&refCountSection);

	if (!r) {
	    delete this;
	    return 0;
	}
	return r;
    }
    HRESULT WINAPI QueryInterface(REFIID iid, LPVOID *iface)
    {
	*iface = 0;
	if (iid == IID_IUnknown)
	    *iface = (IUnknown*)this;
	else if (iid == IID_IClassFactory)
	    *iface = (IClassFactory*)this;
	else if (iid == IID_IClassFactory2 && licensed)
	    *iface = (IClassFactory2*)this;
	else
	    return E_NOINTERFACE;

	AddRef();
	return S_OK;
    }

    HRESULT WINAPI CreateInstanceHelper(IUnknown *pUnkOuter, REFIID iid, void **ppObject)
    {
	if (pUnkOuter) {
	    if (iid != IID_IUnknown)
		return CLASS_E_NOAGGREGATION;
	    const QMetaObject *mo = qAxFactory()->metaObject(className);
	    if (mo && !qstricmp(mo->classInfo(mo->indexOfClassInfo("Aggregatable")).value(), "no"))
		return CLASS_E_NOAGGREGATION;
	}

    	// Make sure a QApplication instance is present (inprocess case)
        if (!qApp) {
            qInstallMsgHandler(qWinMsgHandler);
            qax_ownQApp = true;
            int argc = 0;
            QApplication *app = new QApplication(argc, 0);
        }
        qApp->setQuitOnLastWindowClosed(false);

        if (qAxOutProcServer)
            QAbstractEventDispatcher::instance()->setEventFilter(qax_winEventFilter);
        else
            QApplication::instance()->d_func()->in_exec = true;

        // hook into eventloop; this allows a server to create his own QApplication object
        if (!qax_hhook && qax_ownQApp) {
            qax_hhook = SetWindowsHookEx(WH_GETMESSAGE, axs_FilterProc, 0, GetCurrentThreadId());
        }

	HRESULT res;
	// Create the ActiveX wrapper - aggregate if requested
	if (pUnkOuter) {
	    QAxServerAggregate *aggregate = new QAxServerAggregate(className, pUnkOuter);
	    res = aggregate->QueryInterface(iid, ppObject);
	    if (FAILED(res))
		delete aggregate;
	} else {
	    QAxServerBase *activeqt = new QAxServerBase(className, pUnkOuter);
	    res = activeqt->QueryInterface(iid, ppObject);
	    if (FAILED(res))
		delete activeqt;
	    else
		activeqt->registerActiveObject((IUnknown*)(IDispatch*)activeqt);
	}
	return res;
    }

    // IClassFactory
    HRESULT WINAPI CreateInstance(IUnknown *pUnkOuter, REFIID iid, void **ppObject)
    {
	// class is licensed
	if (licensed && !qAxFactory()->validateLicenseKey(className, QString()))
	    return CLASS_E_NOTLICENSED;

	return CreateInstanceHelper(pUnkOuter, iid, ppObject);
    }
    HRESULT WINAPI LockServer(BOOL fLock)
    {
	if (fLock)
	    qAxLock();
	else
	    qAxUnlock();

	return S_OK;
    }

    // IClassFactory2
    HRESULT WINAPI RequestLicKey(DWORD, BSTR *pKey)
    {
	if (!pKey)
	    return E_POINTER;
	*pKey = 0;

	// This of course works only on fully licensed machines
	if (!qAxFactory()->validateLicenseKey(className, QString()))
	    return CLASS_E_NOTLICENSED;

	*pKey = QStringToBSTR(classKey);
	return S_OK;
    }

    HRESULT WINAPI GetLicInfo(LICINFO *pLicInfo)
    {
	if (!pLicInfo)
	    return E_POINTER;
	pLicInfo->cbLicInfo = sizeof(LICINFO);

	// class specific license key?
	const QMetaObject *mo = qAxFactory()->metaObject(className);
	const char *key = mo->classInfo(mo->indexOfClassInfo("LicenseKey")).value();
	pLicInfo->fRuntimeKeyAvail = key && key[0];

	// machine fully licensed?
	pLicInfo->fLicVerified = qAxFactory()->validateLicenseKey(className, QString());

	return S_OK;
    }

    HRESULT WINAPI CreateInstanceLic(IUnknown *pUnkOuter, IUnknown *pUnkReserved, REFIID iid, BSTR bKey, PVOID *ppObject)
    {
        QString licenseKey = QString::fromWCharArray(bKey);
	if (!qAxFactory()->validateLicenseKey(className, licenseKey))
	    return CLASS_E_NOTLICENSED;
	return CreateInstanceHelper(pUnkOuter, iid, ppObject);
    }

    QString className;

protected:
    CRITICAL_SECTION refCountSection;
    unsigned long ref;
    bool licensed;
    QString classKey;
};

// Create a QClassFactory object for class \a iid
HRESULT GetClassObject(REFIID clsid, REFIID iid, void **ppUnk)
{
    QClassFactory *factory = new QClassFactory(clsid);
    if (!factory)
	return E_OUTOFMEMORY;
    if (factory->className.isEmpty()) {
	delete factory;
	return E_NOINTERFACE;
    }
    HRESULT res = factory->QueryInterface(iid, ppUnk);
    if (res != S_OK)
	delete factory;
    return res;
}


/*!
    Constructs a QAxServerBase object wrapping the QWidget \a
    classname into an ActiveX control.

    The constructor is called by the QClassFactory object provided by
    the COM server for the respective CLSID.
*/
QAxServerBase::QAxServerBase(const QString &classname, IUnknown *outerUnknown)
: aggregatedObject(0), ref(0), ole_ref(0), class_name(classname),
  m_hWnd(0), hmenuShared(0), hwndMenuOwner(0),
  m_outerUnknown(outerUnknown)
{
    init();

    internalCreate();
}

/*!
    Constructs a QAxServerBase object wrapping \a o.
*/
QAxServerBase::QAxServerBase(QObject *o)
: aggregatedObject(0), ref(0), ole_ref(0),
  m_hWnd(0), hmenuShared(0), hwndMenuOwner(0),
  m_outerUnknown(0)
{
    init();

    qt.object = o;
    if (o) {
	theObject = o;
	isWidget = false;
	class_name = QLatin1String(o->metaObject()->className());
    }
    internalBind();
    internalConnect();
}

/*!
    Initializes data members.
*/
void QAxServerBase::init()
{
    qt.object = 0;
    isWidget		= false;
    ownObject		= false;
    initNewCalled	= false;
    dirtyflag		= false;
    hasStockEvents	= false;
    stayTopLevel	= false;
    isInPlaceActive	= false;
    isUIActive		= false;
    wasUIActive		= false;
    inDesignMode	= false;
    canTakeFocus	= false;
    freezeEvents = 0;
    exception = 0;

    m_spAdviseSink = 0;
    m_spClientSite = 0;
    m_spInPlaceSite = 0;
    m_spInPlaceFrame = 0;
    m_spTypeInfo = 0;
    m_spStorage = 0;

    InitializeCriticalSection(&refCountSection);
    InitializeCriticalSection(&createWindowSection);

#ifdef QT_DEBUG
    EnterCriticalSection(&refCountSection);
    ++qaxserverbase_instance_count;
    LeaveCriticalSection(&refCountSection);
#endif

    qAxLock();

    points[IID_IPropertyNotifySink] = new QAxConnection(this, IID_IPropertyNotifySink);
}

/*!
    Destroys the QAxServerBase object, releasing all allocated
    resources and interfaces.
*/
QAxServerBase::~QAxServerBase()
{
#ifdef QT_DEBUG
    EnterCriticalSection(&refCountSection);
    --qaxserverbase_instance_count;
    LeaveCriticalSection(&refCountSection);
#endif

    revokeActiveObject();

    for (QAxServerBase::ConnectionPointsIterator it = points.begin(); it != points.end(); ++it) {
	if (it.value())
	    (*it)->Release();
    }
    delete aggregatedObject;
    aggregatedObject = 0;
    if (theObject) {
	qt.object->disconnect(this);
	QObject *aqt = qt.object;
	qt.object = 0;
	if (ownObject)
	    delete aqt;
    }

    if (m_spAdviseSink) m_spAdviseSink->Release();
    m_spAdviseSink = 0;
    for (int i = 0; i < adviseSinks.count(); ++i) {
        adviseSinks.at(i).pAdvSink->Release();
    }
    if (m_spClientSite) m_spClientSite->Release();
    m_spClientSite = 0;
    if (m_spInPlaceFrame) m_spInPlaceFrame->Release();
    m_spInPlaceFrame = 0;
    if (m_spInPlaceSite) m_spInPlaceSite->Release();
    m_spInPlaceSite = 0;
    if (m_spTypeInfo) m_spTypeInfo->Release();
    m_spTypeInfo = 0;
    if (m_spStorage) m_spStorage->Release();
    m_spStorage = 0;

    DeleteCriticalSection(&refCountSection);
    DeleteCriticalSection(&createWindowSection);

    qAxUnlock();
}

/*
    Registering with OLE
*/
void QAxServerBase::registerActiveObject(IUnknown *object)
{
    if (ole_ref || !qt.object || !qAxOutProcServer)
	return;

    const QMetaObject *mo = qt.object->metaObject();
    if (!qstricmp(mo->classInfo(mo->indexOfClassInfo("RegisterObject")).value(), "yes"))
	RegisterActiveObject(object, qAxFactory()->classID(class_name), ACTIVEOBJECT_WEAK, &ole_ref);
}

void QAxServerBase::revokeActiveObject()
{
    if (!ole_ref)
	return;

    RevokeActiveObject(ole_ref, 0);
    ole_ref = 0;
}

/*
    QueryInterface implementation.
*/
HRESULT WINAPI QAxServerBase::QueryInterface(REFIID iid, void **iface)
{
    if (m_outerUnknown)
	return m_outerUnknown->QueryInterface(iid, iface);

    return InternalQueryInterface(iid, iface);
}

HRESULT QAxServerBase::InternalQueryInterface(REFIID iid, void **iface)
{
    *iface = 0;

    if (iid == IID_IUnknown) {
	*iface = (IUnknown*)(IDispatch*)this;
    } else {
	HRESULT res = S_OK;
	if (aggregatedObject)
	    res = aggregatedObject->queryInterface(iid, iface);
	if (*iface)
	    return res;
    }

    if (!(*iface)) {
	if (iid == qAxFactory()->interfaceID(class_name))
	    *iface = (IDispatch*)this;
	if (iid == IID_IDispatch)
	    *iface = (IDispatch*)this;
	else if (iid == IID_IAxServerBase)
	    *iface = (IAxServerBase*)this;
	else if (iid == IID_IOleObject)
	    *iface = (IOleObject*)this;
	else if (iid == IID_IConnectionPointContainer)
	    *iface = (IConnectionPointContainer*)this;
	else if (iid == IID_IProvideClassInfo)
	    *iface = (IProvideClassInfo*)this;
	else if (iid == IID_IProvideClassInfo2)
	    *iface = (IProvideClassInfo2*)this;
	else if (iid == IID_IPersist)
	    *iface = (IPersist*)(IPersistStream*)this;
	else if (iid == IID_IPersistStream)
	    *iface = (IPersistStream*)this;
	else if (iid == IID_IPersistStreamInit)
	    *iface = (IPersistStreamInit*)this;
	else if (iid == IID_IPersistStorage)
	    *iface = (IPersistStorage*)this;
	else if (iid == IID_IPersistPropertyBag)
	    *iface = (IPersistPropertyBag*)this;
        else if (iid == IID_IPersistFile &&
            qAxFactory()->metaObject(class_name)->indexOfClassInfo("MIME") != -1)
            *iface = (IPersistFile*)this;
	else if (iid == IID_IViewObject)
	    *iface = (IViewObject*)this;
	else if (iid == IID_IViewObject2)
	    *iface = (IViewObject2*)this;
	else if (isWidget) {
	    if (iid == IID_IOleControl)
		*iface = (IOleControl*)this;
	    else if (iid == IID_IOleWindow)
		*iface = (IOleWindow*)(IOleInPlaceObject*)this;
	    else if (iid == IID_IOleInPlaceObject)
		*iface = (IOleInPlaceObject*)this;
	    else if (iid == IID_IOleInPlaceActiveObject)
		*iface = (IOleInPlaceActiveObject*)this;
	    else if (iid == IID_IDataObject)
		*iface = (IDataObject*)this;
	}
    }
    if (!*iface)
	return E_NOINTERFACE;

    AddRef();
    return S_OK;
}

/*!
    Detects and initilaizes implementation of QAxBindable in objects.
*/
void QAxServerBase::internalBind()
{
    QAxBindable *axb = (QAxBindable*)qt.object->qt_metacast("QAxBindable");
    if (axb) {
	// no addref; this is aggregated
	axb->activex = this;
	if (!aggregatedObject)
	    aggregatedObject = axb->createAggregate();
	if (aggregatedObject) {
	    aggregatedObject->controlling_unknown = (IUnknown*)(IDispatch*)this;
	    aggregatedObject->the_object = qt.object;
	}
    }
}

/*!
    Connects object signals to event dispatcher.
*/
void QAxServerBase::internalConnect()
{
    QUuid eventsID = qAxFactory()->eventsID(class_name);
    if (!eventsID.isNull()) {
	if (!points[eventsID])
	    points[eventsID] = new QAxConnection(this, eventsID);

	// connect the generic slot to all signals of qt.object
	const QMetaObject *mo = qt.object->metaObject();
        for (int isignal = mo->methodCount()-1; isignal >= 0; --isignal) {
            if (mo->method(isignal).methodType() == QMetaMethod::Signal)
	        QMetaObject::connect(qt.object, isignal, this, isignal);
        }
    }
}

/*!
    Creates the QWidget for the classname passed to the c'tor.

    All signals of the widget class are connected to the internal event mapper.
    If the widget implements QAxBindable, stock events are also connected.
*/
bool QAxServerBase::internalCreate()
{
    if (qt.object)
	return true;

    qt.object = qAxFactory()->createObject(class_name);
    Q_ASSERT(qt.object);
    if (!qt.object)
	return false;

    theObject = qt.object;
    ownObject = true;
    isWidget = qt.object->isWidgetType();
    hasStockEvents = qAxFactory()->hasStockEvents(class_name);
    stayTopLevel = qAxFactory()->stayTopLevel(class_name);

    internalBind();
    if (isWidget) {
        if (!stayTopLevel) {
            QEvent e(QEvent::EmbeddingControl);
            QApplication::sendEvent(qt.widget, &e);
            ::SetWindowLong(qt.widget->winId(), GWL_STYLE, WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
        }
        qt.widget->setAttribute(Qt::WA_QuitOnClose, false);
        qt.widget->move(0, 0);

        // initialize to sizeHint, but don't set resized flag so that container has a chance to override
        bool wasResized = qt.widget->testAttribute(Qt::WA_Resized);
        updateGeometry();
        if (!wasResized && qt.widget->testAttribute(Qt::WA_Resized)
            && qt.widget->sizePolicy() != QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)) {
            qt.widget->setAttribute(Qt::WA_Resized, false);
        }
    }

    internalConnect();
    // install an event filter for stock events
    if (isWidget) {
        qt.object->installEventFilter(this);
        const QList<QWidget*> children = qt.object->findChildren<QWidget*>();
        QList<QWidget*>::ConstIterator it = children.constBegin();
        while (it != children.constEnd()) {
            (*it)->installEventFilter(this);
            ++it;
        }
    }
    return true;
}

/*
class HackMenuData : public QMenuData
{
    friend class QAxServerBase;
};
*/

class HackWidget : public QWidget
{
    friend class QAxServerBase;
};
/*
    Message handler. \a hWnd is always the ActiveX widget hosting the Qt widget.
    \a uMsg is handled as follows
    \list
    \i WM_CREATE The ActiveX control is created
    \i WM_DESTROY The QWidget is destroyed
    \i WM_SHOWWINDOW The QWidget is parented into the ActiveX window
    \i WM_PAINT The QWidget is updated
    \i WM_SIZE The QWidget is resized to the new size
    \i WM_SETFOCUS and
    \i WM_KILLFOCUS The client site is notified about the focus transfer
    \i WM_MOUSEACTIVATE The ActiveX is activated
    \endlist

    The semantics of \a wParam and \a lParam depend on the value of \a uMsg.
*/
LRESULT QT_WIN_CALLBACK QAxServerBase::ActiveXProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if (uMsg == WM_CREATE) {
        CREATESTRUCT *cs = (CREATESTRUCT*)lParam;
        QAxServerBase *that = (QAxServerBase*)cs->lpCreateParams;

#ifdef GWLP_USERDATA
        SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)that);
#else
        SetWindowLong(hWnd, GWL_USERDATA, (LONG)that);
#endif

        that->m_hWnd = hWnd;

        return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
    }

    QAxServerBase *that = 0;

#ifdef GWLP_USERDATA
    that = (QAxServerBase*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
#else
    that = (QAxServerBase*)GetWindowLong(hWnd, GWL_USERDATA);
#endif

    if (that) {
        int width = that->qt.widget ? that->qt.widget->width() : 0;
        int height = that->qt.widget ? that->qt.widget->height() : 0;
        RECT rcPos = {0, 0, width + 1, height + 1};

        switch (uMsg) {
        case WM_NCDESTROY:
	    that->m_hWnd = 0;
	    break;

        case WM_QUERYENDSESSION:
        case WM_DESTROY:
            // save the window handle
            if (that->qt.widget) {
                that->qt.widget->hide();
                ::SetParent(that->qt.widget->winId(), 0);
            }
	    break;

        case WM_SHOWWINDOW:
	    if(wParam) {
	        that->internalCreate();
	        if (!that->stayTopLevel) {
		    ::SetParent(that->qt.widget->winId(), that->m_hWnd);
		    that->qt.widget->raise();
		    that->qt.widget->move(0, 0);
	        }
	        that->qt.widget->show();
	    } else if (that->qt.widget) {
	        that->qt.widget->hide();
	    }
	    break;

        case WM_ERASEBKGND:
	    that->updateMask();
	    break;

        case WM_SIZE:
            that->resize(QSize(LOWORD(lParam), HIWORD(lParam)));
	    break;

        case WM_SETFOCUS:
	    if (that->isInPlaceActive && that->m_spClientSite && !that->inDesignMode && that->canTakeFocus) {
	        that->DoVerb(OLEIVERB_UIACTIVATE, NULL, that->m_spClientSite, 0, that->m_hWnd, &rcPos);
	        if (that->isUIActive) {
		    IOleControlSite *spSite = 0;
		    that->m_spClientSite->QueryInterface(IID_IOleControlSite, (void**)&spSite);
		    if (spSite) {
		        spSite->OnFocus(true);
		        spSite->Release();
		    }
                    QWidget *candidate = that->qt.widget;
                    while (!(candidate->focusPolicy() & Qt::TabFocus)) {
                        candidate = candidate->nextInFocusChain();
                        if (candidate == that->qt.widget) {
                            candidate = 0;
                            break;
                        }
                    }
                    if (candidate) {
                        candidate->setFocus();
                        HackWidget *widget = (HackWidget*)that->qt.widget;
                        if (::GetKeyState(VK_SHIFT) < 0)
                            widget->focusNextPrevChild(false);
                    }
	        }
	    }
	    break;

        case WM_KILLFOCUS:
	    if (that->isInPlaceActive && that->isUIActive && that->m_spClientSite) {
	        IOleControlSite *spSite = 0;
	        that->m_spClientSite->QueryInterface(IID_IOleControlSite, (void**)&spSite);
	        if (spSite) {
		    if (!::IsChild(that->m_hWnd, ::GetFocus()))
		        spSite->OnFocus(false);
		    spSite->Release();
	        }
	    }
	    break;

        case WM_MOUSEACTIVATE:
	    that->DoVerb(OLEIVERB_UIACTIVATE, NULL, that->m_spClientSite, 0, that->m_hWnd, &rcPos);
	    break;

        case WM_INITMENUPOPUP:
	    if (that->qt.widget) {
	        that->currentPopup = that->menuMap[(HMENU)wParam];
	        if (!that->currentPopup)
		    break;
	        const QMetaObject *mo = that->currentPopup->metaObject();
	        int index = mo->indexOfSignal("aboutToShow()");
	        if (index < 0)
		    break;

	        that->currentPopup->qt_metacall(QMetaObject::InvokeMetaMethod, index, 0);
	        that->createPopup(that->currentPopup, (HMENU)wParam);
	        return 0;
	    }
	    break;

        case WM_MENUSELECT:
        case WM_COMMAND:
	    if (that->qt.widget) {
	        QMenuBar *menuBar = that->menuBar;
	        if (!menuBar)
		    break;

                QObject *menuObject = 0;
	        bool menuClosed = false;

                if (uMsg == WM_COMMAND) {
		    menuObject = that->actionMap.value(wParam);
                } else if (!lParam) {
		    menuClosed = true;
                    menuObject = that->currentPopup;
                } else {
                    menuObject = that->actionMap.value(LOWORD(wParam));
                }

	        if (menuObject) {
		    const QMetaObject *mo = menuObject->metaObject();
		    int index = -1;

		    if (uMsg == WM_COMMAND)
		        index = mo->indexOfSignal("activated()");
		    else if (menuClosed)
		        index = mo->indexOfSignal("aboutToHide()");
		    else
		        index = mo->indexOfSignal("hovered()");

		    if (index < 0)
		        break;

		    menuObject->qt_metacall(QMetaObject::InvokeMetaMethod, index, 0);
                    if (menuClosed || uMsg == WM_COMMAND)
                        that->currentPopup = 0;
		    return 0;
	        }
	    }
	    break;

        default:
	    break;
        }
    }

    return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
}

/*!
    Creates the window hosting the QWidget.
*/
HWND QAxServerBase::create(HWND hWndParent, RECT& rcPos)
{
    Q_ASSERT(isWidget && qt.widget);

    static ATOM atom = 0;
    HINSTANCE hInst = (HINSTANCE)qAxInstance;
    EnterCriticalSection(&createWindowSection);
    QString cn(QLatin1String("QAxControl"));
    cn += QString::number((quintptr)ActiveXProc);
    if (!atom) {
        WNDCLASS wcTemp;
        wcTemp.style = CS_DBLCLKS;
        wcTemp.cbClsExtra = 0;
        wcTemp.cbWndExtra = 0;
        wcTemp.hbrBackground = 0;
        wcTemp.hCursor = 0;
        wcTemp.hIcon = 0;
        wcTemp.hInstance = hInst;
        wcTemp.lpszClassName = (wchar_t*)cn.utf16();
        wcTemp.lpszMenuName = 0;
        wcTemp.lpfnWndProc = ActiveXProc;

        atom = RegisterClass(&wcTemp);
    }
    LeaveCriticalSection(&createWindowSection);
    if (!atom  && GetLastError() != ERROR_CLASS_ALREADY_EXISTS)
	return 0;

    Q_ASSERT(!m_hWnd);
    HWND hWnd = ::CreateWindow((wchar_t*)cn.utf16(), 0,
                               WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
                               rcPos.left, rcPos.top, rcPos.right - rcPos.left,
                               rcPos.bottom - rcPos.top, hWndParent, 0, hInst, this);

    Q_ASSERT(m_hWnd == hWnd);

    updateMask();
    EnableWindow(m_hWnd, qt.widget->isEnabled());

    return hWnd;
}

/*
    Recoursively creates Win32 submenus.
*/
HMENU QAxServerBase::createPopup(QMenu *popup, HMENU oldMenu)
{
    HMENU popupMenu = oldMenu ? oldMenu : CreatePopupMenu();
    menuMap.insert(popupMenu, popup);

    if (oldMenu) while (GetMenuItemCount(oldMenu)) {
	DeleteMenu(oldMenu, 0, MF_BYPOSITION);
    }

    const QList<QAction*> actions = popup->actions();
    for (int i = 0; i < actions.count(); ++i) {
        QAction *action = actions.at(i);

        uint flags = action->isEnabled() ? MF_ENABLED : MF_GRAYED;
        if (action->isSeparator())
            flags |= MF_SEPARATOR;
        else if (action->menu())
            flags |= MF_POPUP;
        else
            flags |= MF_STRING;
        if (action->isChecked())
            flags |= MF_CHECKED;

	ushort itemId;
        if (flags & MF_POPUP) {
            itemId = static_cast<ushort>(
                reinterpret_cast<quintptr>(createPopup(action->menu()))
            );
        } else {
            itemId = static_cast<ushort>(reinterpret_cast<quintptr>(action));
            actionMap.remove(itemId);
            actionMap.insert(itemId, action);
        }
        AppendMenu(popupMenu, flags, itemId, (const wchar_t *)action->text().utf16());
    }
    if (oldMenu)
        DrawMenuBar(hwndMenuOwner);
    return popupMenu;
}

/*!
    Creates a Win32 menubar.
*/
void QAxServerBase::createMenu(QMenuBar *menuBar)
{
    hmenuShared = ::CreateMenu();

    int edit = 0;
    int object = 0;
    int help = 0;

    const QList<QAction*> actions = menuBar->actions();
    for (int i = 0; i < actions.count(); ++i) {
        QAction *action = actions.at(i);

        uint flags = action->isEnabled() ? MF_ENABLED : MF_GRAYED;
	if (action->isSeparator())
	    flags |= MF_SEPARATOR;
	else if (action->menu())
	    flags |= MF_POPUP;
	else
	    flags |= MF_STRING;

	if (action->text() == QCoreApplication::translate(qt.widget->metaObject()->className(), "&Edit"))
	    edit++;
	else if (action->text() == QCoreApplication::translate(qt.widget->metaObject()->className(), "&Help"))
	    help++;
	else
	    object++;

	ushort itemId;
        if (flags & MF_POPUP) {
            itemId = static_cast<ushort>(
                reinterpret_cast<quintptr>(createPopup(action->menu()))
            );
        } else {
            itemId = static_cast<ushort>(reinterpret_cast<quintptr>(action));
            actionMap.insert(itemId, action);
        }
        AppendMenu(hmenuShared, flags, itemId, (const wchar_t *)action->text().utf16());
    }

    OLEMENUGROUPWIDTHS menuWidths = {0,edit,0,object,0,help};
    HRESULT hres = m_spInPlaceFrame->InsertMenus(hmenuShared, &menuWidths);
    if (FAILED(hres)) {
	::DestroyMenu(hmenuShared);
	hmenuShared = 0;
	return;
    }

    m_spInPlaceFrame->GetWindow(&hwndMenuOwner);

    holemenu = OleCreateMenuDescriptor(hmenuShared, &menuWidths);
    hres = m_spInPlaceFrame->SetMenu(hmenuShared, holemenu, m_hWnd);
    if (FAILED(hres)) {
	::DestroyMenu(hmenuShared);
	hmenuShared = 0;
	OleDestroyMenuDescriptor(holemenu);
    }
}

/*!
    Remove the Win32 menubar.
*/
void QAxServerBase::removeMenu()
{
    if (hmenuShared)
	m_spInPlaceFrame->RemoveMenus(hmenuShared);
    holemenu = 0;
    m_spInPlaceFrame->SetMenu(0, 0, m_hWnd);
    if (hmenuShared) {
	DestroyMenu(hmenuShared);
	hmenuShared = 0;
	menuMap.clear();
    }
    hwndMenuOwner = 0;
}

extern bool ignoreSlots(const char *test);
extern bool ignoreProps(const char *test);

/*!
    Makes sure the type info is loaded
*/
void QAxServerBase::ensureMetaData()
{
    if (!m_spTypeInfo) {
	qAxTypeLibrary->GetTypeInfoOfGuid(qAxFactory()->interfaceID(class_name), &m_spTypeInfo);
	m_spTypeInfo->AddRef();
    }
}

/*!
    \internal
    Returns true if the property \a index is exposed to COM and should
    be saved/loaded.
*/
bool QAxServerBase::isPropertyExposed(int index)
{
    if (!theObject)
	return false;

    bool result = false;
    const QMetaObject *mo = theObject->metaObject();

    int qtProps = 0;
    if (theObject->isWidgetType())
	qtProps = QWidget::staticMetaObject.propertyCount();
    QMetaProperty property = mo->property(index);
    if (index <= qtProps && ignoreProps(property.name()))
	return result;

    BSTR bstrNames = QStringToBSTR(QLatin1String(property.name()));
    DISPID dispId;
    GetIDsOfNames(IID_NULL, (BSTR*)&bstrNames, 1, LOCALE_USER_DEFAULT, &dispId);
    result = dispId != DISPID_UNKNOWN;
    SysFreeString(bstrNames);

    return result;
}


/*!
    \internal
    Updates the view, or asks the client site to do so.
*/
void QAxServerBase::update()
{
    if (isInPlaceActive) {
	if (m_hWnd)
	    ::InvalidateRect(m_hWnd, 0, true);
	else if (m_spInPlaceSite)
	    m_spInPlaceSite->InvalidateRect(NULL, true);
    } else if (m_spAdviseSink) {
        m_spAdviseSink->OnViewChange(DVASPECT_CONTENT, -1);
        for (int i = 0; i < adviseSinks.count(); ++i) {
	    adviseSinks.at(i).pAdvSink->OnViewChange(DVASPECT_CONTENT, -1);
        }
    }
}

/*!
    Resizes the control, faking a QResizeEvent if required
*/
void QAxServerBase::resize(const QSize &size)
{
    if (!isWidget || !qt.widget || !size.isValid() || size == QSize(0, 0))
        return;

    QSize oldSize = qt.widget->size();
    qt.widget->resize(size);
    QSize newSize = qt.widget->size();
    // make sure we get a resize event even if not embedded as a control
    if (!m_hWnd && !qt.widget->isVisible() && newSize != oldSize) {
        QResizeEvent resizeEvent(newSize, oldSize);
#ifndef QT_DLL // import from static library
        extern bool qt_sendSpontaneousEvent(QObject*,QEvent*);
#endif
        qt_sendSpontaneousEvent(qt.widget, &resizeEvent);
    }
    m_currentExtent = qt.widget->size();
}

/*!
    \internal

    Updates the internal size values.
*/
void QAxServerBase::updateGeometry()
{
    if (!isWidget || !qt.widget)
	return;

    const QSize sizeHint = qt.widget->sizeHint();
    const QSize size = qt.widget->size();
    if (sizeHint.isValid()) { // if provided, adjust to sizeHint
        QSize newSize = size;
        if (!qt.widget->testAttribute(Qt::WA_Resized)) {
            newSize = sizeHint;
        } else { // according to sizePolicy rules if already resized
            QSizePolicy sizePolicy = qt.widget->sizePolicy();
            if (sizeHint.width() > size.width() && !(sizePolicy.horizontalPolicy() & QSizePolicy::ShrinkFlag))
	        newSize.setWidth(sizeHint.width());
            if (sizeHint.width() < size.width() && !(sizePolicy.horizontalPolicy() & QSizePolicy::GrowFlag))
                newSize.setWidth(sizeHint.width());
            if (sizeHint.height() > size.height() && !(sizePolicy.verticalPolicy() & QSizePolicy::ShrinkFlag))
	        newSize.setHeight(sizeHint.height());
            if (sizeHint.height() < size.height() && !(sizePolicy.verticalPolicy() & QSizePolicy::GrowFlag))
                newSize.setHeight(sizeHint.height());
        }
        resize(newSize);

    // set an initial size suitable for embedded controls
    } else if (!qt.widget->testAttribute(Qt::WA_Resized)) {
        resize(QSize(100, 100));
        qt.widget->setAttribute(Qt::WA_Resized, false);
    }
}

/*!
    \internal

    Updates the mask of the widget parent.
*/
void QAxServerBase::updateMask()
{
    if (!isWidget || !qt.widget || qt.widget->mask().isEmpty())
	return;

    QRegion rgn = qt.widget->mask();
    HRGN hrgn = rgn.handle();

    // Since SetWindowRegion takes ownership
    HRGN wr = CreateRectRgn(0,0,0,0);
    CombineRgn(wr, hrgn, 0, RGN_COPY);
    SetWindowRgn(m_hWnd, wr, true);
}

static bool checkHRESULT(HRESULT hres)
{
    const char *name = 0;
    switch(hres) {
    case S_OK:
	return true;
    case DISP_E_BADPARAMCOUNT:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Bad parameter count", name);
#endif
	return false;
    case DISP_E_BADVARTYPE:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Bad variant type", name);
#endif
	return false;
    case DISP_E_EXCEPTION:
#if defined(QT_CHECK_STATE)
	    qWarning("QAxBase: Error calling IDispatch member %s: Exception thrown by server", name);
#endif
	return false;
    case DISP_E_MEMBERNOTFOUND:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Member not found", name);
#endif
	return false;
    case DISP_E_NONAMEDARGS:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: No named arguments", name);
#endif
	return false;
    case DISP_E_OVERFLOW:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Overflow", name);
#endif
	return false;
    case DISP_E_PARAMNOTFOUND:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Parameter not found", name);
#endif
	return false;
    case DISP_E_TYPEMISMATCH:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Type mismatch", name);
#endif
	return false;
    case DISP_E_UNKNOWNINTERFACE:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Unknown interface", name);
#endif
	return false;
    case DISP_E_UNKNOWNLCID:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Unknown locale ID", name);
#endif
	return false;
    case DISP_E_PARAMNOTOPTIONAL:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Non-optional parameter missing", name);
#endif
	return false;
    default:
#if defined(QT_CHECK_STATE)
	qWarning("QAxBase: Error calling IDispatch member %s: Unknown error", name);
#endif
	return false;
    }
}

static inline QByteArray paramType(const QByteArray &ptype, bool *out)
{
    *out = ptype.endsWith('&') || ptype.endsWith("**");
    if (*out) {
        QByteArray res(ptype);
	res.truncate(res.length() - 1);
        return res;
    }

    return ptype;
}

/*!
    Catches all signals emitted by the Qt widget and fires the respective COM event.

    \a isignal is the Qt Meta Object index of the received signal, and \a _o the
    signal parameters.
*/
int QAxServerBase::qt_metacall(QMetaObject::Call call, int index, void **argv)
{
    Q_ASSERT(call == QMetaObject::InvokeMetaMethod);

    if (index == -1) {
        if (sender() && m_spInPlaceFrame) {
            if (qobject_cast<QStatusBar*>(sender()) != statusBar)
                return true;

            if (statusBar->isHidden()) {
                QString message = *(QString*)argv[1];
                m_spInPlaceFrame->SetStatusText(QStringToBSTR(message));
            }
        }
        return true;
    }

    if (freezeEvents || inDesignMode)
        return true;

    ensureMetaData();

    // get the signal information.
    const QMetaObject *mo = qt.object->metaObject();
    QMetaMethod signal;
    DISPID eventId = index;
    int pcount = 0;
    QByteArray type;
    QList<QByteArray> ptypes;

    switch(index) {
    case DISPID_KEYDOWN:
    case DISPID_KEYUP:
        pcount = 2;
        ptypes << "int&" << "int";
        break;
    case DISPID_KEYPRESS:
        pcount = 1;
        ptypes << "int&";
        break;
    case DISPID_MOUSEDOWN:
    case DISPID_MOUSEMOVE:
    case DISPID_MOUSEUP:
        pcount = 4;
        ptypes << "int" << "int" << "int" << "int";
        break;
    case DISPID_CLICK:
        pcount = 0;
        break;
    case DISPID_DBLCLICK:
        pcount = 0;
        break;
    default:
        {
            signal = mo->method(index);
            Q_ASSERT(signal.methodType() == QMetaMethod::Signal);
            type = signal.typeName();
            QByteArray signature(signal.signature());
            QByteArray name(signature);
            name.truncate(name.indexOf('('));

            eventId = signalCache.value(index, -1);
            if (eventId == -1) {
                ITypeInfo *eventInfo = 0;
                qAxTypeLibrary->GetTypeInfoOfGuid(qAxFactory()->eventsID(class_name), &eventInfo);
                if (eventInfo) {
                    QString uni_name = QLatin1String(name);
                    const OLECHAR *olename = reinterpret_cast<const OLECHAR *>(uni_name.utf16());
                    eventInfo->GetIDsOfNames((OLECHAR**)&olename, 1, &eventId);
                    eventInfo->Release();
                }
            }

            signature = signature.mid(name.length() + 1);
            signature.truncate(signature.length() - 1);

            if (!signature.isEmpty())
                ptypes = signature.split(',');

            pcount = ptypes.count();
        }
        break;
    }
    if (pcount && !argv) {
        qWarning("QAxServerBase::qt_metacall: Missing %d arguments", pcount);
        return false;
    }
    if (eventId == -1)
        return false;

    // For all connected event sinks...
    IConnectionPoint *cpoint = 0;
    GUID IID_QAxEvents = qAxFactory()->eventsID(class_name);
    FindConnectionPoint(IID_QAxEvents, &cpoint);
    if (cpoint) {
        IEnumConnections *clist = 0;
        cpoint->EnumConnections(&clist);
        if (clist) {
            clist->Reset();
            ULONG cc = 1;
            CONNECTDATA c[1];
            clist->Next(cc, (CONNECTDATA*)&c, &cc);
            if (cc) {
                // setup parameters
                unsigned int argErr = 0;
                DISPPARAMS dispParams;
                dispParams.cArgs = pcount;
                dispParams.cNamedArgs = 0;
                dispParams.rgdispidNamedArgs = 0;
                dispParams.rgvarg = 0;

                if (pcount) // Use malloc/free for eval package compatibility
                    dispParams.rgvarg = (VARIANTARG*)malloc(pcount * sizeof(VARIANTARG));
                int p = 0;
                for (p = 0; p < pcount; ++p) {
                    VARIANT *arg = dispParams.rgvarg + (pcount - p - 1);
                    VariantInit(arg);

                    bool out;
                    QByteArray ptype = paramType(ptypes.at(p), &out);
                    QVariant variant;
                    if (mo->indexOfEnumerator(ptype) != -1) {
                        // convert enum values to int
                        variant = QVariant(*reinterpret_cast<int *>(argv[p+1]));
                    } else {
                        QVariant::Type vt = QVariant::nameToType(ptype);
                        if (vt == QVariant::UserType) {
                            if (ptype.endsWith('*')) {
                                variant = QVariant(QMetaType::type(ptype), (void**)argv[p+1]);
                                // variant.setValue(*(void**)(argv[p + 1]), ptype);
                            } else {
                                variant = QVariant(QMetaType::type(ptype), argv[p+1]);
                                // variant.setValue(argv[p + 1], ptype);
                            }
                        } else {
                            variant = QVariant(vt, argv[p + 1]);
                        }
                    }

                    QVariantToVARIANT(variant, *arg, type, out);
                }

                VARIANT retval;
                VariantInit(&retval);
                VARIANT *pretval = 0;
                if (!type.isEmpty())
                    pretval = &retval;

                // call listeners (through IDispatch)
                while (cc) {
                    if (c->pUnk) {
                        IDispatch *disp = 0;
                        c->pUnk->QueryInterface(IID_QAxEvents, (void**)&disp);
                        if (disp) {
                            disp->Invoke(eventId, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispParams, pretval, 0, &argErr);

                            // update out-parameters and return value
                            if (index > 0) {
                                for (p = 0; p < pcount; ++p) {
                                    bool out;
                                    QByteArray ptype = paramType(ptypes.at(p), &out);
                                    if (out)
                                        QVariantToVoidStar(VARIANTToQVariant(dispParams.rgvarg[pcount - p - 1], ptype), argv[p+1], ptype);
                                }
                                if (pretval)
                                    QVariantToVoidStar(VARIANTToQVariant(retval, type), argv[0], type);
                            }
                            disp->Release();
                        }
                        c->pUnk->Release(); // AddRef'ed by clist->Next implementation
                    }
                    clist->Next(cc, (CONNECTDATA*)&c, &cc);
                }

                // clean up
                for (p = 0; p < pcount; ++p)
                    clearVARIANT(dispParams.rgvarg+p);
                free(dispParams.rgvarg);
            }
            clist->Release();
        }
        cpoint->Release();
    }

    return true;
}

/*!
    Call IPropertyNotifySink of connected clients.
    \a dispId specifies the ID of the property that changed.
*/
bool QAxServerBase::emitRequestPropertyChange(const char *property)
{
    long dispId = -1;

    IConnectionPoint *cpoint = 0;
    FindConnectionPoint(IID_IPropertyNotifySink, &cpoint);
    if (cpoint) {
	IEnumConnections *clist = 0;
	cpoint->EnumConnections(&clist);
	if (clist) {
	    clist->Reset();
	    ULONG cc = 1;
	    CONNECTDATA c[1];
	    clist->Next(cc, (CONNECTDATA*)&c, &cc);
	    if (cc) {
		if (dispId == -1) {
		    BSTR bstr = QStringToBSTR(QLatin1String(property));
		    GetIDsOfNames(IID_NULL, &bstr, 1, LOCALE_USER_DEFAULT, &dispId);
		    SysFreeString(bstr);
		}
		if (dispId != -1) while (cc) {
		    if (c->pUnk) {
			IPropertyNotifySink *sink = 0;
			c->pUnk->QueryInterface(IID_IPropertyNotifySink, (void**)&sink);
			bool disallows = sink && sink->OnRequestEdit(dispId) == S_FALSE;
			sink->Release();
			c->pUnk->Release();
			if (disallows) { // a client disallows the property to change
			    clist->Release();
			    cpoint->Release();
			    return false;
			}
		    }
		    clist->Next(cc, (CONNECTDATA*)&c, &cc);
		}
	    }
	    clist->Release();
	}
	cpoint->Release();
    }
    dirtyflag = true;
    return true;
}

/*!
    Call IPropertyNotifySink of connected clients.
    \a dispId specifies the ID of the property that changed.
*/
void QAxServerBase::emitPropertyChanged(const char *property)
{
    long dispId = -1;

    IConnectionPoint *cpoint = 0;
    FindConnectionPoint(IID_IPropertyNotifySink, &cpoint);
    if (cpoint) {
	IEnumConnections *clist = 0;
	cpoint->EnumConnections(&clist);
	if (clist) {
	    clist->Reset();
	    ULONG cc = 1;
	    CONNECTDATA c[1];
	    clist->Next(cc, (CONNECTDATA*)&c, &cc);
	    if (cc) {
		if (dispId == -1) {
		    BSTR bstr = QStringToBSTR(QLatin1String(property));
		    GetIDsOfNames(IID_NULL, &bstr, 1, LOCALE_USER_DEFAULT, &dispId);
		    SysFreeString(bstr);
		}
		if (dispId != -1) while (cc) {
		    if (c->pUnk) {
			IPropertyNotifySink *sink = 0;
			c->pUnk->QueryInterface(IID_IPropertyNotifySink, (void**)&sink);
			if (sink) {
			    sink->OnChanged(dispId);
			    sink->Release();
			}
			c->pUnk->Release();
		    }
		    clist->Next(cc, (CONNECTDATA*)&c, &cc);
		}
	    }
	    clist->Release();
	}
	cpoint->Release();
    }
    dirtyflag = true;
}

//**** IProvideClassInfo
/*
    Provide the ITypeInfo implementation for the COM class.
*/
HRESULT WINAPI QAxServerBase::GetClassInfo(ITypeInfo** pptinfo)
{
    if (!pptinfo)
	return E_POINTER;

    *pptinfo = 0;
    if (!qAxTypeLibrary)
	return DISP_E_BADINDEX;

    return qAxTypeLibrary->GetTypeInfoOfGuid(qAxFactory()->classID(class_name), pptinfo);
}

//**** IProvideClassInfo2
/*
    Provide the ID of the event interface.
*/
HRESULT WINAPI QAxServerBase::GetGUID(DWORD dwGuidKind, GUID* pGUID)
{
    if (!pGUID)
	return E_POINTER;

    if (dwGuidKind == GUIDKIND_DEFAULT_SOURCE_DISP_IID) {
	*pGUID = qAxFactory()->eventsID(class_name);
	return S_OK;
    }
    *pGUID = GUID_NULL;
    return E_FAIL;
}

//**** IDispatch
/*
    Returns the number of class infos for this IDispatch.
*/
HRESULT WINAPI QAxServerBase::GetTypeInfoCount(UINT* pctinfo)
{
    if (!pctinfo)
	return E_POINTER;

    *pctinfo = qAxTypeLibrary ? 1 : 0;
    return S_OK;
}

/*
    Provides the ITypeInfo for this IDispatch implementation.
*/
HRESULT WINAPI QAxServerBase::GetTypeInfo(UINT itinfo, LCID /*lcid*/, ITypeInfo** pptinfo)
{
    if (!pptinfo)
	return E_POINTER;

    if (!qAxTypeLibrary)
	return DISP_E_BADINDEX;

    ensureMetaData();

    *pptinfo = m_spTypeInfo;
    (*pptinfo)->AddRef();

    return S_OK;
}

/*
    Provides the names of the methods implemented in this IDispatch implementation.
*/
HRESULT WINAPI QAxServerBase::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames,
				     LCID /*lcid*/, DISPID* rgdispid)
{
    if (!rgszNames || !rgdispid)
	return E_POINTER;

    if (!qAxTypeLibrary)
	return DISP_E_UNKNOWNNAME;

    ensureMetaData();
    if (!m_spTypeInfo)
	return DISP_E_UNKNOWNNAME;

    return m_spTypeInfo->GetIDsOfNames(rgszNames, cNames, rgdispid);
}

/*
    Map the COM call to the Qt slot/property for \a dispidMember.
*/
HRESULT WINAPI QAxServerBase::Invoke(DISPID dispidMember, REFIID riid,
		  LCID /*lcid*/, WORD wFlags, DISPPARAMS* pDispParams, VARIANT* pvarResult,
		  EXCEPINFO* pexcepinfo, UINT* puArgErr)
{
    if (riid != IID_NULL)
	return DISP_E_UNKNOWNINTERFACE;
    if (!theObject)
	return E_UNEXPECTED;

    HRESULT res = DISP_E_MEMBERNOTFOUND;

    bool uniqueIndex = wFlags == DISPATCH_PROPERTYGET || wFlags == DISPATCH_PROPERTYPUT || wFlags == DISPATCH_METHOD;

    int index = uniqueIndex ? indexCache.value(dispidMember, -1) : -1;
    QByteArray name;
    if (index == -1) {
	ensureMetaData();

        // This property or method is invoked when an ActiveX client specifies
        // the object name without a property or method. We only support property.
        if (dispidMember == DISPID_VALUE && (wFlags == DISPATCH_PROPERTYGET || wFlags == DISPATCH_PROPERTYPUT)) {
            const QMetaObject *mo = qt.object->metaObject();
            index = mo->indexOfClassInfo("DefaultProperty");
            if (index != -1) {
                name  = mo->classInfo(index).value();
                index = mo->indexOfProperty(name);
            }
        } else {
	    BSTR bname;
	    UINT cname = 0;
	    if (m_spTypeInfo)
	        m_spTypeInfo->GetNames(dispidMember, &bname, 1, &cname);
	    if (!cname)
	        return res;

            name = QString::fromWCharArray(bname).toLatin1();
	    SysFreeString(bname);
        }
    }

    const QMetaObject *mo = qt.object->metaObject();
    QSize oldSizeHint;
    if (isWidget)
	oldSizeHint = qt.widget->sizeHint();

    switch (wFlags) {
    case DISPATCH_PROPERTYGET|DISPATCH_METHOD:
    case DISPATCH_PROPERTYGET:
	{
	    if (index == -1) {
		index = mo->indexOfProperty(name);
		if (index == -1 && wFlags == DISPATCH_PROPERTYGET)
		    return res;
	    }

	    QMetaProperty property;
            if (index < mo->propertyCount())
                property = mo->property(index);

	    if (property.isReadable()) {
		if (!pvarResult)
		    return DISP_E_PARAMNOTOPTIONAL;
		if (pDispParams->cArgs ||
		     pDispParams->cNamedArgs)
		    return DISP_E_BADPARAMCOUNT;

		QVariant var = qt.object->property(property.name());
		if (!var.isValid())
		    res =  DISP_E_MEMBERNOTFOUND;
		else if (!QVariantToVARIANT(var, *pvarResult))
		    res = DISP_E_TYPEMISMATCH;
		else
		    res = S_OK;
		break;
	    } else if (wFlags == DISPATCH_PROPERTYGET) {
		break;
	    }
	}
	// FALLTHROUGH if wFlags == DISPATCH_PROPERTYGET|DISPATCH_METHOD AND not a property.
    case DISPATCH_METHOD:
	{
            int nameLength = 0;
	    if (index == -1) {
	        nameLength = name.length();
	        name += '(';
		// no parameter - shortcut
		if (!pDispParams->cArgs)
		    index = mo->indexOfSlot((name + ')'));
		// search
		if (index == -1) {
		    for (int i = 0; i < mo->methodCount(); ++i) {
                        const QMetaMethod slot(mo->method(i));
                        if (slot.methodType() == QMetaMethod::Slot && QByteArray(slot.signature()).startsWith(name)) {
			    index = i;
			    break;
			}
		    }
                    // resolve overloads
                    if (index == -1) {
                        QRegExp regexp(QLatin1String("_([0-9])\\("));
                        if (regexp.lastIndexIn(QString::fromLatin1(name.constData())) != -1) {
                            name = name.left(name.length() - regexp.cap(0).length()) + '(';
                            int overload = regexp.cap(1).toInt() + 1;

                            for (int s = 0; s < qt.object->metaObject()->methodCount(); ++s) {
                                QMetaMethod slot = qt.object->metaObject()->method(s);
                                if (slot.methodType() == QMetaMethod::Slot && QByteArray(slot.signature()).startsWith(name)) {
                                    if (!--overload) {
                                        index = s;
                                        break;
                                    }
                                }
                            }
                        }
                    }
		    if (index == -1)
			return res;
		}
	    }

            int lookupIndex = index;

	    // get slot info
	    QMetaMethod slot(mo->method(index));
            Q_ASSERT(slot.methodType() == QMetaMethod::Slot);
	    QByteArray type = slot.typeName();
	    name = slot.signature();
            nameLength = name.indexOf('(');
	    QByteArray prototype = name.mid(nameLength + 1);
	    prototype.truncate(prototype.length() - 1);
	    QList<QByteArray> ptypes;
	    if (!prototype.isEmpty())
		ptypes = prototype.split(',');
	    int pcount = ptypes.count();

	    // verify parameter count
            if (pcount > pDispParams->cArgs) {
                // count cloned slots immediately following the real thing
                int defArgs = 0;
                while (index < mo->methodCount()) {
                    ++index;
                    slot = mo->method(index);
                    if (!(slot.attributes() & QMetaMethod::Cloned))
                        break;
                    --pcount;
                    // found a matching overload. ptypes still valid
                    if (pcount <= pDispParams->cArgs)
                        break;
                }
                // still wrong :(
                if (pcount > pDispParams->cArgs)
		    return DISP_E_PARAMNOTOPTIONAL;
            } else if (pcount < pDispParams->cArgs) {
		return DISP_E_BADPARAMCOUNT;
            }

	    // setup parameters (pcount + return)
	    bool ok = true;
            void *static_argv[QAX_NUM_PARAMS + 1];
            QVariant static_varp[QAX_NUM_PARAMS + 1];
            void *static_argv_pointer[QAX_NUM_PARAMS + 1];

            int totalParam = pcount;
            if (!type.isEmpty())
                ++totalParam;

	    void **argv = 0; // the actual array passed into qt_metacall
            void **argv_pointer = 0; // in case we need an additional level of indirection
	    QVariant *varp = 0; // QVariants to hold the temporary Qt data object for us

            if (totalParam) {
                if (totalParam <= QAX_NUM_PARAMS) {
                    argv = static_argv;
                    argv_pointer = static_argv_pointer;
                    varp = static_varp;
                } else {
                    argv = new void*[pcount + 1];
                    argv_pointer = new void*[pcount + 1];
                    varp = new QVariant[pcount + 1];
                }

                argv_pointer[0] = 0;
            }

	    for (int p = 0; p < pcount; ++p) {
		// map the VARIANT to the void*
		bool out;
		QByteArray ptype = paramType(ptypes.at(p), &out);
		varp[p + 1] = VARIANTToQVariant(pDispParams->rgvarg[pcount - p - 1], ptype);
                argv_pointer[p + 1] = 0;
		if (varp[p + 1].isValid()) {
                    if (varp[p + 1].type() == QVariant::UserType) {
                        argv[p + 1] = varp[p + 1].data();
                    } else if (ptype == "QVariant") {
                        argv[p + 1] = varp + p + 1;
                    } else {
                        argv[p + 1] = const_cast<void*>(varp[p + 1].constData());
                        if (ptype.endsWith('*')) {
                            argv_pointer[p + 1] = argv[p + 1];
                            argv[p + 1] = argv_pointer + p + 1;
                        }
                    }
                } else if (ptype == "QVariant") {
                    argv[p + 1] = varp + p + 1;
		} else {
		    if (puArgErr)
			*puArgErr = pcount-p-1;
		    ok = false;
		}
	    }

            // return value
	    if (!type.isEmpty()) {
                QVariant::Type vt = QVariant::nameToType(type);
                if (vt == QVariant::UserType)
                    vt = QVariant::Invalid;
                varp[0] = QVariant(vt);
                if (varp[0].type() == QVariant::Invalid && mo->indexOfEnumerator(slot.typeName()) != -1)
                    varp[0] = QVariant(QVariant::Int);

                if (varp[0].type() == QVariant::Invalid) {
                    if (type == "QVariant")
                        argv[0] = varp;
                    else
                        argv[0] = 0;
                } else {
                    argv[0] = const_cast<void*>(varp[0].constData());
                }
                if (type.endsWith('*')) {
                    argv_pointer[0] = argv[0];
                    argv[0] = argv_pointer;
                }
	    }

	    // call the slot if everthing went fine.
	    if (ok) {
            ++invokeCount;
            qt.object->qt_metacall(QMetaObject::InvokeMetaMethod, index, argv);
            if (--invokeCount < 0)
                invokeCount = 0;

		// update reference parameters and return value
		for (int p = 0; p < pcount; ++p) {
		    bool out;
		    QByteArray ptype = paramType(ptypes.at(p), &out);
		    if (out) {
			if (!QVariantToVARIANT(varp[p + 1], pDispParams->rgvarg[pcount - p - 1], ptype, out))
			    ok = false;
		    }
		}
                if (!type.isEmpty() && pvarResult) {
                    if (!varp[0].isValid() && type != "QVariant")
                        varp[0] = QVariant(QMetaType::type(type), argv_pointer);
//                        varp[0].setValue(argv_pointer[0], type);
		    ok = QVariantToVARIANT(varp[0], *pvarResult, type);
                }
	    }
            if (argv && argv != static_argv) {
                delete []argv;
                delete []argv_pointer;
                delete []varp;
            }

	    res = ok ? S_OK : DISP_E_TYPEMISMATCH;

            // reset in case index changed for default-arg handling
            index = lookupIndex;
	}
	break;
    case DISPATCH_PROPERTYPUT:
    case DISPATCH_PROPERTYPUT|DISPATCH_PROPERTYPUTREF:
	{
            if (index == -1) {
                index = mo->indexOfProperty(name);
                if (index == -1)
                    return res;
            }

            QMetaProperty property;
            if (index < mo->propertyCount())
                property = mo->property(index);
            if (!property.isWritable())
                return DISP_E_MEMBERNOTFOUND;
            if (!pDispParams->cArgs)
                return DISP_E_PARAMNOTOPTIONAL;
            if (pDispParams->cArgs != 1 ||
                pDispParams->cNamedArgs != 1 ||
                *pDispParams->rgdispidNamedArgs != DISPID_PROPERTYPUT)
                return DISP_E_BADPARAMCOUNT;

            QVariant var = VARIANTToQVariant(*pDispParams->rgvarg, property.typeName(), property.type());
            if (!var.isValid()) {
                if (puArgErr)
                    *puArgErr = 0;
                return DISP_E_BADVARTYPE;
            }
            if (!qt.object->setProperty(property.name(), var)) {
                if (puArgErr)
                    *puArgErr = 0;
                return DISP_E_TYPEMISMATCH;
            }

            res = S_OK;
	}
	break;

    default:
	break;
    }

    // maybe calling a setter? Notify client about changes
    switch(wFlags) {
    case DISPATCH_METHOD:
    case DISPATCH_PROPERTYPUT:
    case DISPATCH_PROPERTYPUT|DISPATCH_PROPERTYPUTREF:
        if (m_spAdviseSink || adviseSinks.count()) {
            FORMATETC fmt;
            fmt.cfFormat = 0;
            fmt.ptd = 0;
            fmt.dwAspect = DVASPECT_CONTENT;
            fmt.lindex = -1;
            fmt.tymed = TYMED_NULL;

            STGMEDIUM stg;
            stg.tymed = TYMED_NULL;
            stg.pUnkForRelease = 0;
            stg.hBitmap = 0; // initializes the whole union

            if (m_spAdviseSink) {
                m_spAdviseSink->OnViewChange(DVASPECT_CONTENT, -1);
                m_spAdviseSink->OnDataChange(&fmt, &stg);
            }
            for (int i = 0; i < adviseSinks.count(); ++i) {
                adviseSinks.at(i).pAdvSink->OnDataChange(&fmt, &stg);
            }
        }

        dirtyflag = true;
        break;
    default:
        break;
    }

    if (index != -1 && uniqueIndex)
	indexCache.insert(dispidMember, index);

    if (exception) {
	if (pexcepinfo) {
	    memset(pexcepinfo, 0, sizeof(EXCEPINFO));

	    pexcepinfo->wCode = exception->code;
	    if (!exception->src.isNull())
		pexcepinfo->bstrSource = QStringToBSTR(exception->src);
	    if (!exception->desc.isNull())
		pexcepinfo->bstrDescription = QStringToBSTR(exception->desc);
	    if (!exception->context.isNull()) {
		QString context = exception->context;
		int contextID = 0;
		int br = context.indexOf(QLatin1Char('['));
		if (br != -1) {
		    context = context.mid(br+1);
		    context = context.left(context.length() - 1);
		    contextID = context.toInt();

		    context = exception->context;
		    context = context.left(br-1);
		}
		pexcepinfo->bstrHelpFile = QStringToBSTR(context);
		pexcepinfo->dwHelpContext = contextID;
	    }
	}
	delete exception;
	exception = 0;
	return DISP_E_EXCEPTION;
    } else if (isWidget) {
	QSize sizeHint = qt.widget->sizeHint();
	if (oldSizeHint != sizeHint) {
	    updateGeometry();
	    if (m_spInPlaceSite) {
                RECT rect = {0, 0, sizeHint.width(), sizeHint.height()};
		m_spInPlaceSite->OnPosRectChange(&rect);
	    }
	}
	updateMask();
    }

    return res;
}

//**** IConnectionPointContainer
/*
    Provide the IEnumConnectionPoints implemented in the QAxSignalVec class.
*/
HRESULT WINAPI QAxServerBase::EnumConnectionPoints(IEnumConnectionPoints **epoints)
{
    if (!epoints)
	return E_POINTER;
    *epoints = new QAxSignalVec(points);
    (*epoints)->AddRef();
    return S_OK;
}

/*
    Provide the IConnectionPoint implemented in the QAxConnection for \a iid.
*/
HRESULT WINAPI QAxServerBase::FindConnectionPoint(REFIID iid, IConnectionPoint **cpoint)
{
    if (!cpoint)
	return E_POINTER;

    IConnectionPoint *cp = points[iid];
    *cpoint = cp;
    if (cp) {
	cp->AddRef();
	return S_OK;
    }
    return CONNECT_E_NOCONNECTION;
}

//**** IPersistStream
/*
    \reimp

    See documentation of IPersistStorage::IsDirty.
*/
HRESULT WINAPI QAxServerBase::IsDirty()
{
    return dirtyflag ? S_OK : S_FALSE;
}

HRESULT WINAPI QAxServerBase::Load(IStream *pStm)
{
    STATSTG stat;
    HRESULT hres = pStm->Stat(&stat, STATFLAG_DEFAULT);
    bool openAsText = false;
    QByteArray qtarray;
    if (hres == S_OK) {
        QString streamName = QString::fromWCharArray(stat.pwcsName);
        CoTaskMemFree(stat.pwcsName);
        openAsText = streamName == QLatin1String("SomeStreamName");
	if (stat.cbSize.HighPart) // more than 4GB - too large!
	    return S_FALSE;

	qtarray.resize(stat.cbSize.LowPart);
        ULONG read;
	pStm->Read(qtarray.data(), stat.cbSize.LowPart, &read);
    } else if (hres == E_NOTIMPL) {
        ULONG read = 0;
        while (hres != S_FALSE) {
            QByteArray arrayRead;
            arrayRead.resize(4098);
            hres = pStm->Read(arrayRead.data(), arrayRead.size(), &read);
            if (hres != S_OK && hres != S_FALSE) {
                qtarray.resize(0);
                break;
            } else if (read == 0)
                break;
            qtarray.append(arrayRead);
        }
    }
    const QMetaObject *mo = qt.object->metaObject();

    QBuffer qtbuffer(&qtarray);
    QByteArray mimeType = mo->classInfo(mo->indexOfClassInfo("MIME")).value();
    if (!mimeType.isEmpty()) {
        mimeType = mimeType.left(mimeType.indexOf(':')); // first type
        QAxBindable *axb = (QAxBindable*)qt.object->qt_metacast("QAxBindable");
        if (axb && axb->readData(&qtbuffer, QString::fromLatin1(mimeType)))
            return S_OK;
    }

    qtbuffer.close(); // resets
    qtbuffer.open(openAsText ? (QIODevice::ReadOnly | QIODevice::Text) : QIODevice::ReadOnly);

    QDataStream qtstream(&qtbuffer);
    int version;
    qtstream >> version;
    qtstream.setVersion(version);
    int more = 0;
    qtstream >> more;

    while (!qtbuffer.atEnd() && more) {
	QString propname;
	QVariant value;
	qtstream >> propname;
	if (propname.isEmpty())
	    break;
	qtstream >> value;
	qtstream >> more;

	int idx = mo->indexOfProperty(propname.toLatin1());
	QMetaProperty property = mo->property(idx);
	if (property.isWritable())
	    qt.object->setProperty(propname.toLatin1(), value);
    }
    return S_OK;
}

HRESULT WINAPI QAxServerBase::Save(IStream *pStm, BOOL clearDirty)
{
    const QMetaObject *mo = qt.object->metaObject();

    QBuffer qtbuffer;
    bool saved = false;
    QByteArray mimeType = mo->classInfo(mo->indexOfClassInfo("MIME")).value();
    if (!mimeType.isEmpty()) {
        QAxBindable *axb = (QAxBindable*)qt.object->qt_metacast("QAxBindable");
        saved = axb && axb->writeData(&qtbuffer);
        qtbuffer.close();
    }

    if (!saved) {
        qtbuffer.open(QIODevice::WriteOnly);
        QDataStream qtstream(&qtbuffer);
        qtstream << qtstream.version();

        for (int prop = 0; prop < mo->propertyCount(); ++prop) {
	    if (!isPropertyExposed(prop))
	        continue;
	    QMetaProperty metaprop = mo->property(prop);
            if (QByteArray(metaprop.typeName()).endsWith('*'))
                continue;
	    QString property = QLatin1String(metaprop.name());
	    QVariant qvar = qt.object->property(metaprop.name());
	    if (qvar.isValid()) {
	        qtstream << int(1);
	        qtstream << property;
	        qtstream << qvar;
	    }
        }

        qtstream << int(0);
        qtbuffer.close();
    }

    QByteArray qtarray = qtbuffer.buffer();
    ULONG written = 0;
    const char *data = qtarray.constData();
    ULARGE_INTEGER newsize;
    newsize.HighPart = 0;
    newsize.LowPart = qtarray.size();
    pStm->SetSize(newsize);
    pStm->Write(data, qtarray.size(), &written);
    pStm->Commit(STGC_ONLYIFCURRENT);

    if (clearDirty)
        dirtyflag = false;
    return S_OK;
}

HRESULT WINAPI QAxServerBase::GetSizeMax(ULARGE_INTEGER *pcbSize)
{
    const QMetaObject *mo = qt.object->metaObject();

    int np = mo->propertyCount();
    pcbSize->HighPart = 0;
    pcbSize->LowPart = np * 50;

    return S_OK;
}

//**** IPersistStorage

HRESULT WINAPI QAxServerBase::InitNew(IStorage *pStg)
{
    if (initNewCalled)
	return CO_E_ALREADYINITIALIZED;

    dirtyflag = false;
    initNewCalled = true;

    m_spStorage = pStg;
    if (m_spStorage)
	m_spStorage->AddRef();
    return S_OK;
}

HRESULT WINAPI QAxServerBase::Load(IStorage *pStg)
{
    if (InitNew(pStg) != S_OK)
	return CO_E_ALREADYINITIALIZED;

    IStream *spStream = 0;
    QString streamName = QLatin1String(qt.object->metaObject()->className());
    streamName.replace(QLatin1Char(':'), QLatin1Char('.'));
    /* Also invalid, but not relevant
    streamName.replace(QLatin1Char('/'), QLatin1Char('_'));
    streamName.replace(QLatin1Char('\\'), QLatin1Char('_'));
    */
    streamName += QLatin1String("_Stream4.2");

    pStg->OpenStream((const wchar_t *)streamName.utf16(), 0, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &spStream);
    if (!spStream) // support for streams saved with 4.1 and earlier
        pStg->OpenStream(L"SomeStreamName", 0, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &spStream);
    if (!spStream)
	return E_FAIL;

    Load(spStream);
    spStream->Release();

    return S_OK;
}

HRESULT WINAPI QAxServerBase::Save(IStorage *pStg, BOOL fSameAsLoad)
{
    IStream *spStream = 0;
    QString streamName = QLatin1String(qt.object->metaObject()->className());
    streamName.replace(QLatin1Char(':'), QLatin1Char('.'));
    /* Also invalid, but not relevant
    streamName.replace(QLatin1Char('/'), QLatin1Char('_'));
    streamName.replace(QLatin1Char('\\'), QLatin1Char('_'));
    */
    streamName += QLatin1String("_Stream4.2");

    pStg->CreateStream((const wchar_t *)streamName.utf16(), STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &spStream);
    if (!spStream)
	return E_FAIL;

    Save(spStream, true);

    spStream->Release();
    return S_OK;
}

HRESULT WINAPI QAxServerBase::SaveCompleted(IStorage *pStgNew)
{
    if (pStgNew) {
	if (m_spStorage)
	    m_spStorage->Release();
	m_spStorage = pStgNew;
	m_spStorage->AddRef();
    }
    return S_OK;
}

HRESULT WINAPI QAxServerBase::HandsOffStorage()
{
    if (m_spStorage) m_spStorage->Release();
    m_spStorage = 0;

    return S_OK;
}

//**** IPersistPropertyBag
/*
    Initialize the properties of the Qt widget.
*/
HRESULT WINAPI QAxServerBase::InitNew()
{
    if (initNewCalled)
	return CO_E_ALREADYINITIALIZED;

    dirtyflag = false;
    initNewCalled = true;
    return S_OK;
}

/*
    Set the properties of the Qt widget to the values provided in the \a bag.
*/
HRESULT WINAPI QAxServerBase::Load(IPropertyBag *bag, IErrorLog * /*log*/)
{
    if (!bag)
	return E_POINTER;

    if (InitNew() != S_OK)
	return E_UNEXPECTED;

    bool error = false;
    const QMetaObject *mo = qt.object->metaObject();
    for (int prop = 0; prop < mo->propertyCount(); ++prop) {
	if (!isPropertyExposed(prop))
	    continue;
	QMetaProperty property = mo->property(prop);
	const char* pname = property.name();
	BSTR bstr = QStringToBSTR(QLatin1String(pname));
	VARIANT var;
	var.vt = VT_EMPTY;
	HRESULT res = bag->Read(bstr, &var, 0);
	if (property.isWritable() && var.vt != VT_EMPTY) {
	    if (res != S_OK || !qt.object->setProperty(pname, VARIANTToQVariant(var, property.typeName(), property.type())))
		error = true;
	}
	SysFreeString(bstr);
    }

    updateGeometry();

    return /*error ? E_FAIL :*/ S_OK;
}

/*
    Save the properties of the Qt widget into the \a bag.
*/
HRESULT WINAPI QAxServerBase::Save(IPropertyBag *bag, BOOL clearDirty, BOOL /*saveAll*/)
{
    if (!bag)
	return E_POINTER;

    if (clearDirty)
	dirtyflag = false;
    bool error = false;
    const QMetaObject *mo = qt.object->metaObject();
    for (int prop = 0; prop < mo->propertyCount(); ++prop) {
	if (!isPropertyExposed(prop))
	    continue;
	QMetaProperty property = mo->property(prop);
        if (QByteArray(property.typeName()).endsWith('*'))
            continue;

	BSTR bstr = QStringToBSTR(QLatin1String(property.name()));
	QVariant qvar = qt.object->property(property.name());
	if (!qvar.isValid())
	    error = true;
	VARIANT var;
	QVariantToVARIANT(qvar, var);
	bag->Write(bstr, &var);
	SysFreeString(bstr);
    }
    return /*error ? E_FAIL :*/ S_OK;
}

//**** IPersistFile
/*
*/
HRESULT WINAPI QAxServerBase::SaveCompleted(LPCOLESTR fileName)
{
    if (qt.object->metaObject()->indexOfClassInfo("MIME") == -1)
        return E_NOTIMPL;

    currentFileName = QString::fromWCharArray(fileName);
    return S_OK;
}

HRESULT WINAPI QAxServerBase::GetCurFile(LPOLESTR *currentFile)
{
    if (qt.object->metaObject()->indexOfClassInfo("MIME") == -1)
        return E_NOTIMPL;

    if (currentFileName.isEmpty()) {
        *currentFile = 0;
        return S_FALSE;
    }
    IMalloc *malloc = 0;
    CoGetMalloc(1, &malloc);
    if (!malloc)
        return E_OUTOFMEMORY;

    *currentFile = static_cast<wchar_t *>(malloc->Alloc(currentFileName.length() * 2));
    malloc->Release();
    memcpy(*currentFile, currentFileName.unicode(), currentFileName.length() * 2);

    return S_OK;
}

HRESULT WINAPI QAxServerBase::Load(LPCOLESTR fileName, DWORD mode)
{
    const QMetaObject *mo = qt.object->metaObject();
    int mimeIndex = mo->indexOfClassInfo("MIME");
    if (mimeIndex == -1)
        return E_NOTIMPL;

    QAxBindable *axb = (QAxBindable*)qt.object->qt_metacast("QAxBindable");
    if (!axb) {
        qWarning() << class_name << ": No QAxBindable implementation for mime-type handling";
        return E_NOTIMPL;
    }

    QString loadFileName = QString::fromWCharArray(fileName);
    QString fileExtension = loadFileName.mid(loadFileName.lastIndexOf(QLatin1Char('.')) + 1);
    QFile file(loadFileName);

    QString mimeType = QLatin1String(mo->classInfo(mimeIndex).value());
    QStringList mimeTypes = mimeType.split(QLatin1Char(';'));
    for (int m = 0; m < mimeTypes.count(); ++m) {
        QString mime = mimeTypes.at(m);
        if (mime.count(QLatin1Char(':')) != 2) {
            qWarning() << class_name << ": Invalid syntax in Q_CLASSINFO for MIME";
            continue;
        }

        mimeType = mime.left(mimeType.indexOf(QLatin1Char(':'))); // first type
        if (mimeType.isEmpty()) {
            qWarning() << class_name << ": Invalid syntax in Q_CLASSINFO for MIME";
            continue;
        }
        QString mimeExtension = mime.mid(mimeType.length() + 1);
        mimeExtension = mimeExtension.left(mimeExtension.indexOf(QLatin1Char(':')));
        if (mimeExtension != fileExtension)
            continue;

        if (axb->readData(&file, mimeType)) {
            currentFileName = loadFileName;
            return S_OK;
        }
    }

    return E_FAIL;
}

HRESULT WINAPI QAxServerBase::Save(LPCOLESTR fileName, BOOL fRemember)
{
    const QMetaObject *mo = qt.object->metaObject();
    int mimeIndex = mo->indexOfClassInfo("MIME");
    if (mimeIndex == -1)
        return E_NOTIMPL;

    QAxBindable *axb = (QAxBindable*)qt.object->qt_metacast("QAxBindable");
    if (!axb) {
        qWarning() << class_name << ": No QAxBindable implementation for mime-type handling";
        return E_NOTIMPL;
    }

    QString saveFileName = QString::fromWCharArray(fileName);
    QString fileExtension = saveFileName.mid(saveFileName.lastIndexOf(QLatin1Char('.')) + 1);
    QFile file(saveFileName);

    QString mimeType = QLatin1String(mo->classInfo(mimeIndex).value());
    QStringList mimeTypes = mimeType.split(QLatin1Char(';'));
    for (int m = 0; m < mimeTypes.count(); ++m) {
        QString mime = mimeTypes.at(m);
        if (mime.count(QLatin1Char(':')) != 2) {
            qWarning() << class_name << ": Invalid syntax in Q_CLASSINFO for MIME";
            continue;
        }
        mimeType = mime.left(mimeType.indexOf(QLatin1Char(':'))); // first type
        if (mimeType.isEmpty()) {
            qWarning() << class_name << ": Invalid syntax in Q_CLASSINFO for MIME";
            continue;
        }
        QString mimeExtension = mime.mid(mimeType.length() + 1);
        mimeExtension = mimeExtension.left(mimeExtension.indexOf(QLatin1Char(':')));
        if (mimeExtension != fileExtension)
            continue;
        if (axb->writeData(&file)) {
            if (fRemember)
                currentFileName = saveFileName;
            return S_OK;
        }
    }
    return E_FAIL;
}

//**** IViewObject
/*
    Draws the widget into the provided device context.
*/
HRESULT WINAPI QAxServerBase::Draw(DWORD dwAspect, LONG lindex, void *pvAspect, DVTARGETDEVICE *ptd,
		HDC hicTargetDev, HDC hdcDraw, LPCRECTL lprcBounds, LPCRECTL /*lprcWBounds*/,
		BOOL(__stdcall* /*pfnContinue*/)(ULONG_PTR), ULONG_PTR /*dwContinue*/)
{
    if (!lprcBounds)
	return E_INVALIDARG;

    internalCreate();
    if (!isWidget || !qt.widget)
	return OLE_E_BLANK;

    switch (dwAspect) {
    case DVASPECT_CONTENT:
    case DVASPECT_OPAQUE:
    case DVASPECT_TRANSPARENT:
	break;
    default:
	return DV_E_DVASPECT;
    }
    if (!ptd)
	hicTargetDev = 0;

    bool bDeleteDC = false;
    if (!hicTargetDev) {
	hicTargetDev = ::CreateDC(L"DISPLAY", NULL, NULL, NULL);
	bDeleteDC = (hicTargetDev != hdcDraw);
    }

    RECTL rc = *lprcBounds;
    bool bMetaFile = GetDeviceCaps(hdcDraw, TECHNOLOGY) == DT_METAFILE;
    if (!bMetaFile)
        ::LPtoDP(hicTargetDev, (LPPOINT)&rc, 2);

    QPixmap pm = QPixmap::grabWidget(qt.widget);
    HBITMAP hbm = pm.toWinHBITMAP();
    HDC hdc = CreateCompatibleDC(0);
    SelectObject(hdc, hbm);
    ::StretchBlt(hdcDraw, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, hdc, 0, 0,pm.width(), pm.height(), SRCCOPY);
    DeleteDC(hdc);
    DeleteObject(hbm);

    if (bDeleteDC)
	DeleteDC(hicTargetDev);

    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::GetColorSet(DWORD dwDrawAspect, LONG lindex, void *pvAspect, DVTARGETDEVICE *ptd,
		HDC hicTargetDev, LOGPALETTE **ppColorSet)
{
    return E_NOTIMPL;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::Freeze(DWORD dwAspect, LONG lindex, void *pvAspect, DWORD *pdwFreeze)
{
    return E_NOTIMPL;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::Unfreeze(DWORD dwFreeze)
{
    return E_NOTIMPL;
}

/*
    Stores the provided advise sink.
*/
HRESULT WINAPI QAxServerBase::SetAdvise(DWORD /*aspects*/, DWORD /*advf*/, IAdviseSink *pAdvSink)
{
    if (m_spAdviseSink) m_spAdviseSink->Release();

    m_spAdviseSink = pAdvSink;
    if (m_spAdviseSink) m_spAdviseSink->AddRef();
    return S_OK;
}

/*
    Returns the advise sink.
*/
HRESULT WINAPI QAxServerBase::GetAdvise(DWORD* /*aspects*/, DWORD* /*advf*/, IAdviseSink **ppAdvSink)
{
    if (!ppAdvSink)
	return E_POINTER;

    *ppAdvSink = m_spAdviseSink;
    if (*ppAdvSink)
	(*ppAdvSink)->AddRef();
    return S_OK;
}

//**** IViewObject2
/*
    Returns the current size ONLY if the widget has already been sized.
*/
HRESULT WINAPI QAxServerBase::GetExtent(DWORD dwAspect, LONG /*lindex*/, DVTARGETDEVICE* /*ptd*/, LPSIZEL lpsizel)
{
    if (!isWidget || !qt.widget || !qt.widget->testAttribute(Qt::WA_Resized))
        return OLE_E_BLANK;

    return GetExtent(dwAspect, lpsizel);
}

//**** IOleControl
/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::GetControlInfo(LPCONTROLINFO)
{
    return E_NOTIMPL;
}

/*
    Turns event firing on and off.
*/
HRESULT WINAPI QAxServerBase::FreezeEvents(BOOL bFreeze)
{
    // member of CComControl
    if (bFreeze)
	freezeEvents++;
    else
	freezeEvents--;

    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::OnMnemonic(LPMSG)
{
    return E_NOTIMPL;
}

/*
    Update the ambient properties of the Qt widget.
*/
HRESULT WINAPI QAxServerBase::OnAmbientPropertyChange(DISPID dispID)
{
    if (!m_spClientSite || !theObject)
	return S_OK;

    IDispatch *disp = 0;
    m_spClientSite->QueryInterface(IID_IDispatch, (void**)&disp);
    if (!disp)
	return S_OK;

    VARIANT var;
    VariantInit(&var);
    DISPPARAMS params = { 0, 0, 0, 0 };
    disp->Invoke(dispID, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &params, &var, 0, 0);
    disp->Release();
    disp = 0;

    switch(dispID) {
    case DISPID_AMBIENT_APPEARANCE:
	break;
    case DISPID_AMBIENT_AUTOCLIP:
	break;
    case DISPID_AMBIENT_BACKCOLOR:
    case DISPID_AMBIENT_FORECOLOR:
	if (isWidget) {
	    long rgb;
	    if (var.vt == VT_UI4)
		rgb = var.ulVal;
	    else if (var.vt == VT_I4)
		rgb = var.lVal;
	    else
		break;
	    QPalette pal = qt.widget->palette();
	    pal.setColor(dispID == DISPID_AMBIENT_BACKCOLOR ? QPalette::Window : QPalette::WindowText,
		OLEColorToQColor(rgb));
	    qt.widget->setPalette(pal);
	}
	break;
    case DISPID_AMBIENT_DISPLAYASDEFAULT:
	break;
    case DISPID_AMBIENT_DISPLAYNAME:
	if (var.vt != VT_BSTR || !isWidget)
	    break;
	qt.widget->setWindowTitle(QString::fromWCharArray(var.bstrVal));
	break;
    case DISPID_AMBIENT_FONT:
	if (var.vt != VT_DISPATCH || !isWidget)
	    break;
	{
            QVariant qvar = VARIANTToQVariant(var, "QFont", QVariant::Font);
            QFont qfont = qvariant_cast<QFont>(qvar);
            qt.widget->setFont(qfont);
	}
	break;
    case DISPID_AMBIENT_LOCALEID:
	break;
    case DISPID_AMBIENT_MESSAGEREFLECT:
	if (var.vt != VT_BOOL)
	    break;
	if (var.boolVal)
	    qt.widget->installEventFilter(this);
	else
	    qt.widget->removeEventFilter(this);
	break;
    case DISPID_AMBIENT_PALETTE:
	break;
    case DISPID_AMBIENT_SCALEUNITS:
	break;
    case DISPID_AMBIENT_SHOWGRABHANDLES:
	break;
    case DISPID_AMBIENT_SHOWHATCHING:
	break;
    case DISPID_AMBIENT_SUPPORTSMNEMONICS:
	break;
    case DISPID_AMBIENT_TEXTALIGN:
	break;
    case DISPID_AMBIENT_UIDEAD:
	if (var.vt != VT_BOOL || !isWidget)
	    break;
	qt.widget->setEnabled(!var.boolVal);
	break;
    case DISPID_AMBIENT_USERMODE:
	if (var.vt != VT_BOOL)
	    break;
	inDesignMode = !var.boolVal;
	break;
    case DISPID_AMBIENT_RIGHTTOLEFT:
	if (var.vt != VT_BOOL)
	    break;
	qApp->setLayoutDirection(var.boolVal?Qt::RightToLeft:Qt::LeftToRight);
	break;
    }

    return S_OK;
}

//**** IOleWindow
/*
    Returns the HWND of the control.
*/
HRESULT WINAPI QAxServerBase::GetWindow(HWND *pHwnd)
{
    if (!pHwnd)
	return E_POINTER;
    *pHwnd = m_hWnd;
    return S_OK;
}

/*
    Enters What's This mode.
*/
HRESULT WINAPI QAxServerBase::ContextSensitiveHelp(BOOL fEnterMode)
{
    if (fEnterMode)
	QWhatsThis::enterWhatsThisMode();
    else
	QWhatsThis::leaveWhatsThisMode();
    return S_OK;
}

//**** IOleInPlaceObject
/*
    Deactivates the control in place.
*/
HRESULT WINAPI QAxServerBase::InPlaceDeactivate()
{
    if (!isInPlaceActive)
	return S_OK;
    UIDeactivate();

    isInPlaceActive = false;

    // if we have a window, tell it to go away.
    if (m_hWnd) {
	if (::IsWindow(m_hWnd))
	    ::DestroyWindow(m_hWnd);
	m_hWnd = 0;
    }

    if (m_spInPlaceSite)
	m_spInPlaceSite->OnInPlaceDeactivate();

    return S_OK;
}

/*
    Deactivates the control's user interface.
*/
HRESULT WINAPI QAxServerBase::UIDeactivate()
{
    // if we're not UIActive, not much to do.
    if (!isUIActive || !m_spInPlaceSite)
	return S_OK;

    isUIActive = false;

    // notify frame windows, if appropriate, that we're no longer ui-active.
    HWND hwndParent;
    if (m_spInPlaceSite->GetWindow(&hwndParent) == S_OK) {
	if (m_spInPlaceFrame) m_spInPlaceFrame->Release();
	m_spInPlaceFrame = 0;
	IOleInPlaceUIWindow *spInPlaceUIWindow = 0;
        RECT rcPos, rcClip;
        OLEINPLACEFRAMEINFO frameInfo;
        frameInfo.cb = sizeof(OLEINPLACEFRAMEINFO);

	m_spInPlaceSite->GetWindowContext(&m_spInPlaceFrame, &spInPlaceUIWindow, &rcPos, &rcClip, &frameInfo);
	if (spInPlaceUIWindow) {
	    spInPlaceUIWindow->SetActiveObject(0, 0);
	    spInPlaceUIWindow->Release();
	}
	if (m_spInPlaceFrame) {
	    removeMenu();
            if (menuBar) {
                menuBar->removeEventFilter(this);
                menuBar = 0;
            }
            if (statusBar) {
                statusBar->removeEventFilter(this);
		const int index = statusBar->metaObject()->indexOfSignal("messageChanged(QString)");
		QMetaObject::disconnect(statusBar, index, this, -1);
	        statusBar = 0;
            }
	    m_spInPlaceFrame->SetActiveObject(0, 0);
	    m_spInPlaceFrame->Release();
	    m_spInPlaceFrame = 0;
	}
    }
    // we don't need to explicitly release the focus here since somebody
    // else grabbing the focus is usually why we are getting called at all
    m_spInPlaceSite->OnUIDeactivate(false);

    return S_OK;
}

/*
    Positions the control, and applies requested clipping.
*/
HRESULT WINAPI QAxServerBase::SetObjectRects(LPCRECT prcPos, LPCRECT prcClip)
{
    if (prcPos == 0 || prcClip == 0)
	return E_POINTER;

    if (m_hWnd) {
	// the container wants us to clip, so figure out if we really need to
	RECT rcIXect;
	BOOL b = IntersectRect(&rcIXect, prcPos, prcClip);
	HRGN tempRgn = 0;
	if (b && !EqualRect(&rcIXect, prcPos)) {
	    OffsetRect(&rcIXect, -(prcPos->left), -(prcPos->top));
	    tempRgn = CreateRectRgnIndirect(&rcIXect);
	}

	::SetWindowRgn(m_hWnd, tempRgn, true);
	::SetWindowPos(m_hWnd, 0, prcPos->left, prcPos->top,
            prcPos->right - prcPos->left, prcPos->bottom - prcPos->top,
	    SWP_NOZORDER | SWP_NOACTIVATE);
    }

    //Save the new extent.
    m_currentExtent.rwidth() = qBound(qt.widget->minimumWidth(), int(prcPos->right - prcPos->left), qt.widget->maximumWidth());
    m_currentExtent.rheight() = qBound(qt.widget->minimumHeight(), int(prcPos->bottom - prcPos->top), qt.widget->maximumHeight());

    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::ReactivateAndUndo()
{
    return E_NOTIMPL;
}

//**** IOleInPlaceActiveObject

Q_GUI_EXPORT int qt_translateKeyCode(int);

HRESULT WINAPI QAxServerBase::TranslateAcceleratorW(MSG *pMsg)
{
    if (pMsg->message != WM_KEYDOWN || !isWidget)
        return S_FALSE;

    DWORD dwKeyMod = 0;
    if (::GetKeyState(VK_SHIFT) < 0)
        dwKeyMod |= 1;	// KEYMOD_SHIFT
    if (::GetKeyState(VK_CONTROL) < 0)
        dwKeyMod |= 2;	// KEYMOD_CONTROL
    if (::GetKeyState(VK_MENU) < 0)
        dwKeyMod |= 4;	// KEYMOD_ALT

    switch (LOWORD(pMsg->wParam)) {
    case VK_TAB:
        if (isUIActive) {
            bool shift = ::GetKeyState(VK_SHIFT) < 0;
            bool giveUp = true;
            QWidget *curFocus = qt.widget->focusWidget();
            if (curFocus) {
                if (shift) {
                    if (!curFocus->isWindow()) {
                        QWidget *nextFocus = curFocus->nextInFocusChain();
                        QWidget *prevFocus = 0;
                        QWidget *topLevel = 0;
                        while (nextFocus != curFocus) {
                            if (nextFocus->focusPolicy() & Qt::TabFocus) {
                                prevFocus = nextFocus;
                                topLevel = 0;
                            } else if (nextFocus->isWindow()) {
                                topLevel = nextFocus;
                            }
                            nextFocus = nextFocus->nextInFocusChain();
                        }

                        if (!topLevel) {
                            giveUp = false;
                            ((HackWidget*)curFocus)->focusNextPrevChild(false);
                            curFocus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
                        }
                    }
                } else {
                    QWidget *nextFocus = curFocus;
                    while (1) {
                        nextFocus = nextFocus->nextInFocusChain();
                        if (nextFocus->isWindow())
                            break;
                        if (nextFocus->focusPolicy() & Qt::TabFocus) {
                            giveUp = false;
                            ((HackWidget*)curFocus)->focusNextPrevChild(true);
                            curFocus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
                            break;
                        }
                    }
                }
            }
            if (giveUp) {
                HWND hwnd = ::GetParent(m_hWnd);
                ::SetFocus(hwnd);
            } else {
                return S_OK;
            }

        }
        break;

    case VK_LEFT:
    case VK_RIGHT:
    case VK_UP:
    case VK_DOWN:
        if (isUIActive)
            return S_FALSE;
        break;

    default:
        if (isUIActive && qt.widget->focusWidget()) {
            int state = Qt::NoButton;
            if (dwKeyMod & 1)
                state |= Qt::ShiftModifier;
            if (dwKeyMod & 2)
                state |= Qt::ControlModifier;
            if (dwKeyMod & 4)
                state |= Qt::AltModifier;

            int key = pMsg->wParam;
            if (!(key >= 'A' && key <= 'Z') && !(key >= '0' && key <= '9'))
                key = qt_translateKeyCode(pMsg->wParam);

            QKeyEvent override(QEvent::ShortcutOverride, key, (Qt::KeyboardModifiers)state);
            override.ignore();
            QApplication::sendEvent(qt.widget->focusWidget(), &override);
            if (override.isAccepted())
                return S_FALSE;
        }
        break;
    }

    if (!m_spClientSite)
        return S_FALSE;

    IOleControlSite *controlSite = 0;
    m_spClientSite->QueryInterface(IID_IOleControlSite, (void**)&controlSite);
    if (!controlSite)
        return S_FALSE;
    bool resetUserData = false;
    // set server type in the user-data of the window.
#ifdef GWLP_USERDATA
    LONG_PTR serverType = QAX_INPROC_SERVER;
#else
    LONG serverType = QAX_INPROC_SERVER;
#endif
    if (qAxOutProcServer)
        serverType = QAX_OUTPROC_SERVER;
#ifdef GWLP_USERDATA
    LONG_PTR oldData = SetWindowLongPtr(pMsg->hwnd, GWLP_USERDATA, serverType);
#else
    LONG oldData = SetWindowLong(pMsg->hwnd, GWL_USERDATA, serverType);
#endif
    HRESULT hres = controlSite->TranslateAcceleratorW(pMsg, dwKeyMod);
    controlSite->Release();
    // reset the user-data for the window.
#ifdef GWLP_USERDATA
    SetWindowLongPtr(pMsg->hwnd, GWLP_USERDATA, oldData);
#else
    SetWindowLong(pMsg->hwnd, GWL_USERDATA, oldData);
#endif
    return hres;
}

HRESULT WINAPI QAxServerBase::TranslateAcceleratorA(MSG *pMsg)
{
    return TranslateAcceleratorW(pMsg);
}

HRESULT WINAPI QAxServerBase::OnFrameWindowActivate(BOOL fActivate)
{
    if (fActivate) {
	if (wasUIActive)
	    ::SetFocus(m_hWnd);
    } else {
	wasUIActive = isUIActive;
    }
    return S_OK;
}

HRESULT WINAPI QAxServerBase::OnDocWindowActivate(BOOL fActivate)
{
    return S_OK;
}

HRESULT WINAPI QAxServerBase::ResizeBorder(LPCRECT prcBorder, IOleInPlaceUIWindow *pUIWindow, BOOL fFrameWindow)
{
    return S_OK;
}

HRESULT WINAPI QAxServerBase::EnableModeless(BOOL fEnable)
{
    if (!isWidget)
	return S_OK;

    EnableWindow(qt.widget->winId(), fEnable);
    return S_OK;
}

//**** IOleObject

static inline LPOLESTR QStringToOLESTR(const QString &qstring)
{
    LPOLESTR olestr = (wchar_t*)CoTaskMemAlloc(qstring.length()*2+2);
    memcpy(olestr, (ushort*)qstring.unicode(), qstring.length()*2);
    olestr[qstring.length()] = 0;
    return olestr;
}

/*
    \reimp

    See documentation of IOleObject::GetUserType.
*/
HRESULT WINAPI QAxServerBase::GetUserType(DWORD dwFormOfType, LPOLESTR *pszUserType)
{
    if (!pszUserType)
	return E_POINTER;

    switch (dwFormOfType) {
    case USERCLASSTYPE_FULL:
	*pszUserType = QStringToOLESTR(class_name);
	break;
    case USERCLASSTYPE_SHORT:
	if (!qt.widget || !isWidget || qt.widget->windowTitle().isEmpty())
	    *pszUserType = QStringToOLESTR(class_name);
	else
	    *pszUserType = QStringToOLESTR(qt.widget->windowTitle());
	break;
    case USERCLASSTYPE_APPNAME:
	*pszUserType = QStringToOLESTR(qApp->objectName());
	break;
    }

    return S_OK;
}

/*
    Returns the status flags registered for this control.
*/
HRESULT WINAPI QAxServerBase::GetMiscStatus(DWORD dwAspect, DWORD *pdwStatus)
{
    return OleRegGetMiscStatus(qAxFactory()->classID(class_name), dwAspect, pdwStatus);
}

/*
    Stores the provided advise sink.
*/
HRESULT WINAPI QAxServerBase::Advise(IAdviseSink* pAdvSink, DWORD* pdwConnection)
{
    *pdwConnection = adviseSinks.count() + 1;
    STATDATA data = { {0, 0, DVASPECT_CONTENT, -1, TYMED_NULL} , 0, pAdvSink, *pdwConnection };
    adviseSinks.append(data);
    pAdvSink->AddRef();
    return S_OK;
}

/*
    Closes the control.
*/
HRESULT WINAPI QAxServerBase::Close(DWORD dwSaveOption)
{
    if (dwSaveOption != OLECLOSE_NOSAVE && m_spClientSite)
	m_spClientSite->SaveObject();
    if (isInPlaceActive) {
	HRESULT hr = InPlaceDeactivate();
	if (FAILED(hr))
	    return hr;
    }
    if (m_hWnd) {
	if (IsWindow(m_hWnd))
	    DestroyWindow(m_hWnd);
	m_hWnd = 0;
	if (m_spClientSite)
	    m_spClientSite->OnShowWindow(false);
    }

    if (m_spInPlaceSite) m_spInPlaceSite->Release();
    m_spInPlaceSite = 0;

    if (m_spAdviseSink)
	m_spAdviseSink->OnClose();
    for (int i = 0; i < adviseSinks.count(); ++i) {
        adviseSinks.at(i).pAdvSink->OnClose();
    }

    return S_OK;
}

bool qax_disable_inplaceframe = true;

/*
    Executes the steps to activate the control.
*/
HRESULT QAxServerBase::internalActivate()
{
    if (!m_spClientSite)
	return S_OK;
    if (!m_spInPlaceSite)
        m_spClientSite->QueryInterface(IID_IOleInPlaceSite, (void**)&m_spInPlaceSite);
    if (!m_spInPlaceSite)
	return E_FAIL;

    HRESULT hr = E_FAIL;
    if (!isInPlaceActive) {
	BOOL bNoRedraw = false;
	hr = m_spInPlaceSite->CanInPlaceActivate();
	if (FAILED(hr))
	    return hr;
	if (hr != S_OK)
	    return E_FAIL;
	m_spInPlaceSite->OnInPlaceActivate();
    }

    isInPlaceActive = true;
    OnAmbientPropertyChange(DISPID_AMBIENT_USERMODE);

    if (isWidget) {
        IOleInPlaceUIWindow *spInPlaceUIWindow = 0;
        HWND hwndParent;
        if (m_spInPlaceSite->GetWindow(&hwndParent) == S_OK) {
            // get location in the parent window, as well as some information about the parent
            if (m_spInPlaceFrame) m_spInPlaceFrame->Release();
            m_spInPlaceFrame = 0;
            RECT rcPos, rcClip;
            OLEINPLACEFRAMEINFO frameInfo;
            frameInfo.cb = sizeof(OLEINPLACEFRAMEINFO);
            m_spInPlaceSite->GetWindowContext(&m_spInPlaceFrame, &spInPlaceUIWindow, &rcPos, &rcClip, &frameInfo);
            if (m_hWnd) {
                ::ShowWindow(m_hWnd, SW_SHOW);
                if (!::IsChild(m_hWnd, ::GetFocus()) && qt.widget->focusPolicy() != Qt::NoFocus)
                    ::SetFocus(m_hWnd);
            } else {
                create(hwndParent, rcPos);
            }
        }

	// Gone active by now, take care of UIACTIVATE
	canTakeFocus = qt.widget->focusPolicy() != Qt::NoFocus && !inDesignMode;
	if (!canTakeFocus && !inDesignMode) {
	    QList<QWidget*> widgets = qt.widget->findChildren<QWidget*>();
	    for (int w = 0; w < widgets.count(); ++w) {
		QWidget *widget = widgets[w];
		canTakeFocus = widget->focusPolicy() != Qt::NoFocus;
                if (canTakeFocus)
                    break;
	    }
	}
	if (!isUIActive && canTakeFocus) {
	    isUIActive = true;
	    hr = m_spInPlaceSite->OnUIActivate();
	    if (FAILED(hr)) {
		if (m_spInPlaceFrame) m_spInPlaceFrame->Release();
		m_spInPlaceFrame = 0;
		if (spInPlaceUIWindow) spInPlaceUIWindow->Release();
		return hr;
	    }

	    if (isInPlaceActive) {
		if (!::IsChild(m_hWnd, ::GetFocus()))
		    ::SetFocus(m_hWnd);
	    }

	    if (m_spInPlaceFrame) {
		hr = m_spInPlaceFrame->SetActiveObject(this, QStringToBSTR(class_name));
		if (!FAILED(hr)) {
		    menuBar = (qt.widget && !qax_disable_inplaceframe) ? qt.widget->findChild<QMenuBar*>() : 0;
		    if (menuBar && !menuBar->isVisible()) {
			createMenu(menuBar);
			menuBar->hide();
			menuBar->installEventFilter(this);
		    }
		    statusBar = qt.widget ? qt.widget->findChild<QStatusBar*>() : 0;
		    if (statusBar && !statusBar->isVisible()) {
			const int index = statusBar->metaObject()->indexOfSignal("messageChanged(QString)");
			QMetaObject::connect(statusBar, index, this, -1);
			statusBar->hide();
			statusBar->installEventFilter(this);
		    }
		}
	    }
	    if (spInPlaceUIWindow) {
		spInPlaceUIWindow->SetActiveObject(this, QStringToBSTR(class_name));
		spInPlaceUIWindow->SetBorderSpace(0);
	    }
	}
        if (spInPlaceUIWindow) spInPlaceUIWindow->Release();
	ShowWindow(m_hWnd, SW_NORMAL);
    }

    m_spClientSite->ShowObject();

    return S_OK;
}

/*
    Executes the "verb" \a iVerb.
*/
HRESULT WINAPI QAxServerBase::DoVerb(LONG iVerb, LPMSG /*lpmsg*/, IOleClientSite* /*pActiveSite*/, LONG /*lindex*/,
			       HWND /*hwndParent*/, LPCRECT /*prcPosRect*/)
{
    HRESULT hr = E_NOTIMPL;
    switch (iVerb)
    {
    case OLEIVERB_SHOW:
	hr = internalActivate();
	if (SUCCEEDED(hr))
	    hr = S_OK;
	break;

    case OLEIVERB_PRIMARY:
    case OLEIVERB_INPLACEACTIVATE:
	hr = internalActivate();
	if (SUCCEEDED(hr)) {
	    hr = S_OK;
	    update();
	}
	break;

    case OLEIVERB_UIACTIVATE:
	if (!isUIActive) {
	    hr = internalActivate();
	    if (SUCCEEDED(hr))
		hr = S_OK;
	}
	break;

    case OLEIVERB_HIDE:
	UIDeactivate();
	if (m_hWnd)
	    ::ShowWindow(m_hWnd, SW_HIDE);
	hr = S_OK;
	return hr;

    default:
	break;
    }
    return hr;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::EnumAdvise(IEnumSTATDATA** /*ppenumAdvise*/)
{
    return E_NOTIMPL;
}

/*
    Returns an enumerator for the verbs registered for this class.
*/
HRESULT WINAPI QAxServerBase::EnumVerbs(IEnumOLEVERB** ppEnumOleVerb)
{
    if (!ppEnumOleVerb)
	return E_POINTER;
    return OleRegEnumVerbs(qAxFactory()->classID(class_name), ppEnumOleVerb);
}

/*
    Returns the current client site..
*/
HRESULT WINAPI QAxServerBase::GetClientSite(IOleClientSite** ppClientSite)
{
    if (!ppClientSite)
	return E_POINTER;
    *ppClientSite = m_spClientSite;
    if (*ppClientSite)
	(*ppClientSite)->AddRef();
    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::GetClipboardData(DWORD, IDataObject**)
{
    return E_NOTIMPL;
}

/*
    Returns the current extent.
*/
HRESULT WINAPI QAxServerBase::GetExtent(DWORD dwDrawAspect, SIZEL* psizel)
{
    if (dwDrawAspect != DVASPECT_CONTENT || !isWidget || !qt.widget)
	return E_FAIL;
    if (!psizel)
	return E_POINTER;

    psizel->cx = MAP_PIX_TO_LOGHIM(m_currentExtent.width(), qt.widget->logicalDpiX());
    psizel->cy = MAP_PIX_TO_LOGHIM(m_currentExtent.height(), qt.widget->logicalDpiY());
    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::GetMoniker(DWORD, DWORD, IMoniker** )
{
    return E_NOTIMPL;
}

/*
    Returns the CLSID of this class.
*/
HRESULT WINAPI QAxServerBase::GetUserClassID(CLSID* pClsid)
{
    if (!pClsid)
	return E_POINTER;
    *pClsid = qAxFactory()->classID(class_name);
    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::InitFromData(IDataObject*, BOOL, DWORD)
{
    return E_NOTIMPL;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::IsUpToDate()
{
    return S_OK;
}

/*
    Stores the client site.
*/
HRESULT WINAPI QAxServerBase::SetClientSite(IOleClientSite* pClientSite)
{
    // release all client site interfaces
    if (m_spClientSite) m_spClientSite->Release();
    if (m_spInPlaceSite) m_spInPlaceSite->Release();
    m_spInPlaceSite = 0;
    if (m_spInPlaceFrame) m_spInPlaceFrame->Release();
    m_spInPlaceFrame = 0;

    m_spClientSite = pClientSite;
    if (m_spClientSite) {
        m_spClientSite->AddRef();
	m_spClientSite->QueryInterface(IID_IOleInPlaceSite, (void **)&m_spInPlaceSite);
    }

    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::SetColorScheme(LOGPALETTE*)
{
    return E_NOTIMPL;
}


#ifdef QT_DLL // avoid conflict with symbol in static lib
bool qt_sendSpontaneousEvent(QObject *o, QEvent *e)
{
    return QCoreApplication::sendSpontaneousEvent(o, e);
}
#endif

/*
    Tries to set the size of the control.
*/
HRESULT WINAPI QAxServerBase::SetExtent(DWORD dwDrawAspect, SIZEL* psizel)
{
    if (dwDrawAspect != DVASPECT_CONTENT)
	return DV_E_DVASPECT;
    if (!psizel)
	return E_POINTER;

    if (!isWidget || !qt.widget) // nothing to do
	return S_OK;

    QSize proposedSize(MAP_LOGHIM_TO_PIX(psizel->cx, qt.widget->logicalDpiX()),
        MAP_LOGHIM_TO_PIX(psizel->cy, qt.widget->logicalDpiY()));

    // can the widget be resized at all?
    if (qt.widget->minimumSize() == qt.widget->maximumSize() && qt.widget->minimumSize() != proposedSize)
        return E_FAIL;
    //Save the extent, bound to the widget restrictions.
    m_currentExtent.rwidth() = qBound(qt.widget->minimumWidth(), proposedSize.width(), qt.widget->maximumWidth());
    m_currentExtent.rheight() = qBound(qt.widget->minimumHeight(), proposedSize.height(), qt.widget->maximumHeight());

    resize(proposedSize);
    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::SetHostNames(LPCOLESTR szContainerApp, LPCOLESTR szContainerObj)
{
    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::SetMoniker(DWORD, IMoniker*)
{
    return E_NOTIMPL;
}

/*
    Disconnects an advise sink.
*/
HRESULT WINAPI QAxServerBase::Unadvise(DWORD dwConnection)
{
    for (int i = 0; i < adviseSinks.count(); ++i) {
        STATDATA entry = adviseSinks.at(i);
        if (entry.dwConnection == dwConnection) {
            entry.pAdvSink->Release();
            adviseSinks.removeAt(i);
            return S_OK;
        }
    }
    return OLE_E_NOCONNECTION;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::Update()
{
    return S_OK;
}

//**** IDataObject
/*
    Calls IViewObject::Draw after setting up the parameters.
*/
HRESULT WINAPI QAxServerBase::GetData(FORMATETC *pformatetcIn, STGMEDIUM *pmedium)
{
    if (!pmedium)
	return E_POINTER;
    if ((pformatetcIn->tymed & TYMED_MFPICT) == 0)
	return DATA_E_FORMATETC;

    internalCreate();
    if (!isWidget || !qt.widget)
	return E_UNEXPECTED;

    // Container wants to draw, but the size is not defined yet - ask container
    if (m_spInPlaceSite && !qt.widget->testAttribute(Qt::WA_Resized)) {
	IOleInPlaceUIWindow *spInPlaceUIWindow = 0;
        RECT rcPos, rcClip;
        OLEINPLACEFRAMEINFO frameInfo;
        frameInfo.cb = sizeof(OLEINPLACEFRAMEINFO);

	HRESULT hres = m_spInPlaceSite->GetWindowContext(&m_spInPlaceFrame, &spInPlaceUIWindow, &rcPos, &rcClip, &frameInfo);
        if (hres == S_OK) {
            QSize size(rcPos.right - rcPos.left, rcPos.bottom - rcPos.top);
            resize(size);
        } else {
            qt.widget->adjustSize();
        }
        if (spInPlaceUIWindow) spInPlaceUIWindow->Release(); // no need for it
    }

    int width = qt.widget->width();
    int height = qt.widget->height();
    RECTL rectl = {0, 0, width, height};

    HDC hdc = CreateMetaFile(0);
    SaveDC(hdc);
    SetWindowOrgEx(hdc, 0, 0, 0);
    SetWindowExtEx(hdc, rectl.right, rectl.bottom, 0);

    Draw(pformatetcIn->dwAspect, pformatetcIn->lindex, 0, pformatetcIn->ptd, 0, hdc, &rectl, &rectl, 0, 0);

    RestoreDC(hdc, -1);
    HMETAFILE hMF = CloseMetaFile(hdc);
    if (!hMF)
	return E_UNEXPECTED;

    HGLOBAL hMem = GlobalAlloc(GMEM_SHARE | GMEM_MOVEABLE, sizeof(METAFILEPICT));
    if (!hMem) {
	DeleteMetaFile(hMF);
	return ResultFromScode(STG_E_MEDIUMFULL);
    }

    LPMETAFILEPICT pMF = (LPMETAFILEPICT)GlobalLock(hMem);
    pMF->hMF = hMF;
    pMF->mm = MM_ANISOTROPIC;
    pMF->xExt = MAP_PIX_TO_LOGHIM(width, qt.widget->logicalDpiX());
    pMF->yExt = MAP_PIX_TO_LOGHIM(height, qt.widget->logicalDpiY());
    GlobalUnlock(hMem);

    memset(pmedium, 0, sizeof(STGMEDIUM));
    pmedium->tymed = TYMED_MFPICT;
    pmedium->hGlobal = hMem;
    pmedium->pUnkForRelease = 0;

    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::DAdvise(FORMATETC *pformatetc, DWORD advf,
				      IAdviseSink *pAdvSink, DWORD *pdwConnection)
{
    if (pformatetc->dwAspect != DVASPECT_CONTENT)
        return E_FAIL;

    *pdwConnection = adviseSinks.count() + 1;
    STATDATA data = {
        {pformatetc->cfFormat,pformatetc->ptd,pformatetc->dwAspect,pformatetc->lindex,pformatetc->tymed},
        advf, pAdvSink, *pdwConnection
    };
    adviseSinks.append(data);
    pAdvSink->AddRef();
    return S_OK;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::DUnadvise(DWORD dwConnection)
{
    return Unadvise(dwConnection);
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::EnumDAdvise(IEnumSTATDATA ** /*ppenumAdvise*/)
{
    return E_NOTIMPL;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::GetDataHere(FORMATETC* /* pformatetc */, STGMEDIUM* /* pmedium */)
{
    return E_NOTIMPL;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::QueryGetData(FORMATETC* /* pformatetc */)
{
    return E_NOTIMPL;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::GetCanonicalFormatEtc(FORMATETC* /* pformatectIn */,FORMATETC* /* pformatetcOut */)
{
    return E_NOTIMPL;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::SetData(FORMATETC* /* pformatetc */, STGMEDIUM* /* pmedium */, BOOL /* fRelease */)
{
    return E_NOTIMPL;
}

/*
    Not implemented.
*/
HRESULT WINAPI QAxServerBase::EnumFormatEtc(DWORD /* dwDirection */, IEnumFORMATETC** /* ppenumFormatEtc */)
{
    return E_NOTIMPL;
}



static int mapModifiers(int state)
{
    int ole = 0;
    if (state & Qt::ShiftModifier)
	ole |= 1;
    if (state & Qt::ControlModifier)
	ole |= 2;
    if (state & Qt::AltModifier)
	ole |= 4;

    return ole;
}

/*
    \reimp
*/
bool QAxServerBase::eventFilter(QObject *o, QEvent *e)
{
    if (!theObject)
	return QObject::eventFilter(o, e);

    if ((e->type() == QEvent::Show || e->type() == QEvent::Hide) && (o == statusBar || o == menuBar)) {
	if (o == menuBar) {
	    if (e->type() == QEvent::Hide) {
		createMenu(menuBar);
	    } else if (e->type() == QEvent::Show) {
		removeMenu();
	    }
	} else if (statusBar) {
	    statusBar->setSizeGripEnabled(false);
	}
	updateGeometry();
	if (m_spInPlaceSite && qt.widget->sizeHint().isValid()) {
            RECT rect = {0, 0, qt.widget->sizeHint().width(), qt.widget->sizeHint().height()};
	    m_spInPlaceSite->OnPosRectChange(&rect);
	}
    }
    switch (e->type()) {
    case QEvent::ChildAdded:
	static_cast<QChildEvent*>(e)->child()->installEventFilter(this);
	break;
    case QEvent::ChildRemoved:
	static_cast<QChildEvent*>(e)->child()->removeEventFilter(this);
	break;
    case QEvent::KeyPress:
	if (o == qt.object && hasStockEvents) {
	    QKeyEvent *ke = (QKeyEvent*)e;
	    int key = ke->key();
	    int state = ke->modifiers();
	    void *argv[] = {
		0,
		&key,
		&state
	    };
	    qt_metacall(QMetaObject::InvokeMetaMethod, DISPID_KEYDOWN, argv);
	    if (!ke->text().isEmpty())
		qt_metacall(QMetaObject::InvokeMetaMethod, DISPID_KEYPRESS, argv);
	}
	break;
    case QEvent::KeyRelease:
	if (o == qt.object && hasStockEvents) {
	    QKeyEvent *ke = (QKeyEvent*)e;
	    int key = ke->key();
	    int state = ke->modifiers();
	    void *argv[] = {
		0,
		&key,
		&state
	    };
	    qt_metacall(QMetaObject::InvokeMetaMethod, DISPID_KEYUP, argv);
	}
	break;
    case QEvent::MouseMove:
	if (o == qt.object && hasStockEvents) {
	    QMouseEvent *me = (QMouseEvent*)e;
            int button = me->buttons() & Qt::MouseButtonMask;
	    int state = mapModifiers(me->modifiers());
	    int x = me->x();
	    int y = me->y();
	    void *argv[] = {
		0,
		&button,
		&state,
		&x,
		&y
	    };
	    qt_metacall(QMetaObject::InvokeMetaMethod, DISPID_MOUSEMOVE, argv);
	}
	break;
    case QEvent::MouseButtonRelease:
	if (o == qt.object && hasStockEvents) {
	    QMouseEvent *me = (QMouseEvent*)e;
	    int button = me->button();
	    int state = mapModifiers(me->modifiers());
	    int x = me->x();
	    int y = me->y();
	    void *argv[] = {
		0,
		&button,
		&state,
		&x,
		&y
	    };
	    qt_metacall(QMetaObject::InvokeMetaMethod, DISPID_MOUSEUP, argv);
	    qt_metacall(QMetaObject::InvokeMetaMethod, DISPID_CLICK, 0);
	}
	break;
    case QEvent::MouseButtonDblClick:
	if (o == qt.object && hasStockEvents) {
	    qt_metacall(QMetaObject::InvokeMetaMethod, DISPID_DBLCLICK, 0);
	}
	break;
    case QEvent::MouseButtonPress:
        if (m_spInPlaceSite && !isUIActive) {
            internalActivate();
        }
	if (o == qt.widget && hasStockEvents) {
	    QMouseEvent *me = (QMouseEvent*)e;
	    int button = me->button();
	    int state = mapModifiers(me->modifiers());
	    int x = me->x();
	    int y = me->y();
	    void *argv[] = {
		0,
		&button,
		&state,
		&x,
		&y
	    };
	    qt_metacall(QMetaObject::InvokeMetaMethod, DISPID_MOUSEDOWN, argv);
	}
	break;
    case QEvent::Show:
	if (m_hWnd && o == qt.widget)
	    ShowWindow(m_hWnd, SW_SHOW);
	updateMask();
	break;
    case QEvent::Hide:
	if (m_hWnd && o == qt.widget)
	    ShowWindow(m_hWnd, SW_HIDE);
	break;

    case QEvent::EnabledChange:
        if (m_hWnd && o == qt.widget)
            EnableWindow(m_hWnd, qt.widget->isEnabled());
        // Fall Through
    case QEvent::FontChange:
    case QEvent::ActivationChange:
    case QEvent::StyleChange:
    case QEvent::IconTextChange:
    case QEvent::ModifiedChange:
    case QEvent::Resize:
	updateMask();
	break;
    case QEvent::WindowBlocked: {
        if (!m_spInPlaceFrame)
            break;
        m_spInPlaceFrame->EnableModeless(FALSE);
        MSG msg;
        // Visual Basic 6.0 posts the message WM_USER+3078 from the EnableModeless().
        // While handling this message, VB will disable all current top-levels. After 
        // this we have to re-enable the Qt modal widget to receive input events. 
        if (PeekMessage(&msg, 0, WM_USER+3078, WM_USER+3078, PM_REMOVE)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            QWidget *modalWidget = QApplication::activeModalWidget();
            if (modalWidget && modalWidget->isVisible() && modalWidget->isEnabled() 
                && !IsWindowEnabled(modalWidget->effectiveWinId()))
                EnableWindow(modalWidget->effectiveWinId(), TRUE);
        }
        break;
        }
    case QEvent::WindowUnblocked:
        if (!m_spInPlaceFrame)
            break;
        m_spInPlaceFrame->EnableModeless(TRUE);
        break;
    default:
	break;
    }
    return QObject::eventFilter(o, e);
}

QT_END_NAMESPACE
#endif // QT_NO_WIN_ACTIVEQT