summaryrefslogtreecommitdiff
path: root/extensions/source/ole/oleobjw.cxx
blob: 2a2b7eb256f102e33f03fade4982a550dd720645 (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "ole2uno.hxx"
#include "rtl/ustrbuf.hxx"


#include "osl/diagnose.h"
#include "osl/doublecheckedlocking.h"
#include "osl/thread.h"

#include <memory>
#include <com/sun/star/script/FailReason.hpp>
#include <com/sun/star/beans/XMaterialHolder.hpp>
#include <com/sun/star/script/XTypeConverter.hpp>
#include <com/sun/star/script/FinishEngineEvent.hpp>
#include <com/sun/star/script/InterruptReason.hpp>
#include <com/sun/star/script/XEngineListener.hpp>
#include <com/sun/star/script/XDebugging.hpp>
#include <com/sun/star/script/XInvocation.hpp>
#include <com/sun/star/script/ContextInformation.hpp>
#include <com/sun/star/script/FinishReason.hpp>
#include <com/sun/star/script/XEngine.hpp>
#include <com/sun/star/script/InterruptEngineEvent.hpp>
#include <com/sun/star/script/XLibraryAccess.hpp>
#include <com/sun/star/bridge/ModelDependent.hpp>

#include "com/sun/star/bridge/oleautomation/NamedArgument.hpp"
#include "com/sun/star/bridge/oleautomation/PropertyPutArgument.hpp"

#include <typelib/typedescription.hxx>
#include <rtl/uuid.h>
#include <rtl/ustring.hxx>

#include "jscriptclasses.hxx"

#include "oleobjw.hxx"
#include "unoobjw.hxx"
#include <stdio.h>
using namespace std;
using namespace osl;
using namespace cppu;
using namespace com::sun::star::script;
using namespace com::sun::star::lang;
using namespace com::sun::star::bridge;
using namespace com::sun::star::bridge::oleautomation;
using namespace com::sun::star::bridge::ModelDependent;
using namespace ::com::sun::star;


#define JSCRIPT_ID_PROPERTY L"_environment"
#define JSCRIPT_ID          L"jscript"
namespace ole_adapter
{


// key: XInterface pointer created by Invocation Adapter Factory
// value: XInterface pointer to the wrapper class.
// Entries to the map are made within
// Any createOleObjectWrapper(IUnknown* pUnknown, const Type& aType);
// Entries are being deleted if the wrapper class's destructor has been
// called.
// Before UNO object is wrapped to COM object this map is checked
// to see if the UNO object is already a wrapper.
std::unordered_map<sal_uIntPtr, sal_uIntPtr> AdapterToWrapperMap;
// key: XInterface of the wrapper object.
// value: XInterface of the Interface created by the Invocation Adapter Factory.
// A COM wrapper is responsible for removing the corresponding entry
// in AdapterToWrappperMap if it is being destroyed. Because the wrapper does not
// know about its adapted interface it uses WrapperToAdapterMap to get the
// adapted interface which is then used to locate the entry in AdapterToWrapperMap.
std::unordered_map<sal_uIntPtr,sal_uIntPtr> WrapperToAdapterMap;

std::unordered_map<sal_uIntPtr, WeakReference<XInterface> > ComPtrToWrapperMap;
/*****************************************************************************

    class implementation IUnknownWrapper_Impl

*****************************************************************************/

IUnknownWrapper_Impl::IUnknownWrapper_Impl( Reference<XMultiServiceFactory>& xFactory,
                                           sal_uInt8 unoWrapperClass, sal_uInt8 comWrapperClass):
    UnoConversionUtilities<IUnknownWrapper_Impl>( xFactory, unoWrapperClass, comWrapperClass),
    m_pxIdlClass( NULL), m_eJScript( JScriptUndefined),
    m_bComTlbIndexInit(false),  m_bHasDfltMethod(false), m_bHasDfltProperty(false)
{
}


IUnknownWrapper_Impl::~IUnknownWrapper_Impl()
{
    o2u_attachCurrentThread();
    MutexGuard guard(getBridgeMutex());
    XInterface * xIntRoot = (OWeakObject *)this;
#if OSL_DEBUG_LEVEL > 0
    acquire(); // make sure we don't delete us twice because of Reference
    OSL_ASSERT( Reference<XInterface>( static_cast<XWeak*>(this), UNO_QUERY).get() == xIntRoot );
#endif

    // remove entries in global maps
    typedef std::unordered_map<sal_uIntPtr, sal_uIntPtr>::iterator _IT;
    _IT it= WrapperToAdapterMap.find( (sal_uIntPtr) xIntRoot);
    if( it != WrapperToAdapterMap.end())
    {
        sal_uIntPtr adapter= it->second;

        AdapterToWrapperMap.erase( adapter);
        WrapperToAdapterMap.erase( it);
    }

     IT_Com it_c= ComPtrToWrapperMap.find( (sal_uIntPtr) m_spUnknown.p);
    if(it_c != ComPtrToWrapperMap.end())
        ComPtrToWrapperMap.erase(it_c);
}

Any IUnknownWrapper_Impl::queryInterface(const Type& t)
    throw (RuntimeException)
{
    if (t == cppu::UnoType<XDefaultMethod>::get() && !m_bHasDfltMethod )
        return Any();
    if (t == cppu::UnoType<XDefaultProperty>::get() && !m_bHasDfltProperty )
        return Any();
    if ( ( t == cppu::UnoType<XInvocation>::get() || t == cppu::UnoType<XAutomationInvocation>::get() ) && !m_spDispatch)
        return Any();
    // XDirectInvocation seems to be an oracle replacement for XAutomationInvocation, however it is flawed especially wrt. assumptions about whether to invoke a
    // Put or Get property, the implementation code has no business guessing that, it's up to the caller to decide that. Worse XDirectInvocation duplicates lots of code.
    // XAutomationInvocation provides separate calls for put& get
    // properties. Note: Currently the basic runtime doesn't call put properties directly, it should... after all the basic runtime should know whether it is calling a put or get property.
    // For the moment for ease of merging we will let the XDirectInvoke and XAuthomationInvocation interfaces stay side by side (and for the moment at least I would prefer the basic
    // runtime to call XAutomationInvocation instead of XDirectInvoke
    return WeakImplHelper<XBridgeSupplier2,
        XInitialization, XAutomationObject, XDefaultProperty, XDefaultMethod, XDirectInvocation, XAutomationInvocation >::queryInterface(t);
}

Reference<XIntrospectionAccess> SAL_CALL IUnknownWrapper_Impl::getIntrospection()
    throw (RuntimeException )
{
    Reference<XIntrospectionAccess> ret;

    return ret;
}

Any SAL_CALL IUnknownWrapper_Impl::invokeGetProperty( const OUString& aPropertyName, const Sequence< Any >& aParams, Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam ) throw (css::lang::IllegalArgumentException, css::script::CannotConvertException, css::reflection::InvocationTargetException, css::uno::RuntimeException)
{
    Any aResult;
    try
    {
        o2u_attachCurrentThread();
        ITypeInfo * pInfo = getTypeInfo();
        FuncDesc aDescGet(pInfo);
        FuncDesc aDescPut(pInfo);
        VarDesc aVarDesc(pInfo);
        getPropDesc(aPropertyName, & aDescGet, & aDescPut, & aVarDesc);
        if ( !aDescGet )
        {
            OUString msg("[automation bridge]Property \"" + aPropertyName +
                "\" is not supported");
            throw UnknownPropertyException(msg);
        }
        aResult = invokeWithDispIdComTlb( aDescGet, aPropertyName, aParams, aOutParamIndex, aOutParam );
    }
    catch ( const Exception& e )
    {
       throw RuntimeException("[automation bridge] unexpected exception in "
               "IUnknownWrapper_Impl::invokeGetProperty ! Message : \n" +
                e.Message);
    }
    return aResult;
}

Any SAL_CALL IUnknownWrapper_Impl::invokePutProperty( const OUString& aPropertyName, const Sequence< Any >& aParams, Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam ) throw (css::lang::IllegalArgumentException, css::script::CannotConvertException, css::reflection::InvocationTargetException, css::uno::RuntimeException)
{
    Any aResult;
    try
    {
        o2u_attachCurrentThread();
        ITypeInfo * pInfo = getTypeInfo();
        FuncDesc aDescGet(pInfo);
        FuncDesc aDescPut(pInfo);
        VarDesc aVarDesc(pInfo);
        getPropDesc(aPropertyName, & aDescGet, & aDescPut, & aVarDesc);
        if ( !aDescPut )
        {
            OUString msg("[automation bridge]Property \"" + aPropertyName +
                "\" is not supported");
            throw UnknownPropertyException(msg);
        }
        aResult = invokeWithDispIdComTlb( aDescPut, aPropertyName, aParams, aOutParamIndex, aOutParam );
    }
    catch ( const Exception& e )
    {
       throw RuntimeException("[automation bridge] unexpected exception in "
               "IUnknownWrapper_Impl::invokePutProperty ! Message : \n" +
                e.Message);
    }
    return aResult;
}


Any SAL_CALL IUnknownWrapper_Impl::invoke( const OUString& aFunctionName,
             const Sequence< Any >& aParams, Sequence< sal_Int16 >& aOutParamIndex,
             Sequence< Any >& aOutParam )
    throw(IllegalArgumentException, CannotConvertException, InvocationTargetException,
          RuntimeException)
{
    if ( ! m_spDispatch )
    {
        throw RuntimeException(
            "[automation bridge] The object does not have an IDispatch interface");
    }

    Any ret;

    try
    {
        o2u_attachCurrentThread();

        TypeDescription methodDesc;
        getMethodInfo(aFunctionName, methodDesc);
        if( methodDesc.is())
        {
            ret = invokeWithDispIdUnoTlb(aFunctionName,
                                         aParams,
                                         aOutParamIndex,
                                         aOutParam);
        }
        else
        {
            ret= invokeWithDispIdComTlb( aFunctionName,
                                         aParams,
                                         aOutParamIndex,
                                         aOutParam);
        }
    }
    catch (const IllegalArgumentException &)
    {
        throw;
    }
    catch (const CannotConvertException &)
    {
        throw;
    }
    catch (const BridgeRuntimeError & e)
    {
         throw RuntimeException(e.message);
    }
    catch (const Exception & e)
    {
        throw RuntimeException("[automation bridge] unexpected exception in "
                                     "IUnknownWrapper_Impl::invoke ! Message : \n" +
                               e.Message);

    }
    catch(...)
    {
        throw RuntimeException("[automation bridge] unexpected exception in "
                  "IUnknownWrapper_Impl::Invoke !");
    }
    return ret;
}

void SAL_CALL IUnknownWrapper_Impl::setValue( const OUString& aPropertyName,
                 const Any& aValue )
    throw(UnknownPropertyException, CannotConvertException, InvocationTargetException,
          RuntimeException)
{
    if ( ! m_spDispatch )
    {
        throw RuntimeException(
            "[automation bridge] The object does not have an IDispatch interface");
    }
    try
    {
        o2u_attachCurrentThread();

        ITypeInfo * pInfo = getTypeInfo();
        FuncDesc aDescGet(pInfo);
        FuncDesc aDescPut(pInfo);
        VarDesc aVarDesc(pInfo);
        getPropDesc(aPropertyName, & aDescGet, & aDescPut, & aVarDesc);
        //check if there is such a property at all or if it is read only
        if ( ! aDescPut && ! aDescGet && ! aVarDesc)
        {
            OUString msg("[automation bridge]Property \"" + aPropertyName +
                         "\" is not supported");
            throw UnknownPropertyException(msg);
        }

        if ( (! aDescPut && aDescGet)
             || (aVarDesc && aVarDesc->wVarFlags == VARFLAG_FREADONLY) )
        {
            //read-only
            OUString msg("[automation bridge] Property " + aPropertyName +
                         " is read-only");
            OString sMsg = OUStringToOString(msg, osl_getThreadTextEncoding());
            OSL_FAIL(sMsg.getStr());
            // ignore silently
            return;
        }

        HRESULT hr= S_OK;
        DISPPARAMS dispparams;
        CComVariant varArg;
        CComVariant varRefArg;
        CComVariant varResult;
        ExcepInfo excepinfo;
        unsigned int uArgErr;

        // converting UNO value to OLE variant
        DISPID dispidPut= DISPID_PROPERTYPUT;
        dispparams.rgdispidNamedArgs = &dispidPut;
        dispparams.cArgs = 1;
        dispparams.cNamedArgs = 1;
        dispparams.rgvarg = & varArg;

        OSL_ASSERT(aDescPut || aVarDesc);

        VARTYPE vt = 0;
        DISPID dispid = 0;
        INVOKEKIND invkind = INVOKE_PROPERTYPUT;
        //determine the expected type, dispid, invoke kind (DISPATCH_PROPERTYPUT,
        //DISPATCH_PROPERTYPUTREF)
        if (aDescPut)
        {
            vt = getElementTypeDesc(& aDescPut->lprgelemdescParam[0].tdesc);
            dispid = aDescPut->memid;
            invkind = aDescPut->invkind;
        }
        else
        {
            vt = getElementTypeDesc( & aVarDesc->elemdescVar.tdesc);
            dispid = aVarDesc->memid;
            if (vt == VT_UNKNOWN || vt == VT_DISPATCH ||
                (vt & VT_ARRAY) || (vt & VT_BYREF))
            {
                invkind = INVOKE_PROPERTYPUTREF;
            }
        }

        // convert the uno argument
        if (vt & VT_BYREF)
        {
            anyToVariant( & varRefArg, aValue, ::sal::static_int_cast< VARTYPE, int >( vt ^ VT_BYREF ) );
            varArg.vt = vt;
            if( (vt & VT_TYPEMASK) == VT_VARIANT)
                varArg.byref = & varRefArg;
            else if ((vt & VT_TYPEMASK) == VT_DECIMAL)
                varArg.byref = & varRefArg.decVal;
            else
                varArg.byref = & varRefArg.byref;
        }
        else
        {
            anyToVariant(& varArg, aValue, vt);
        }
        // call to IDispatch
        hr = m_spDispatch->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT, ::sal::static_int_cast< WORD, INVOKEKIND >( invkind ),
                                 &dispparams, & varResult, & excepinfo, &uArgErr);

        // lookup error code
        switch (hr)
        {
        case S_OK:
            break;
        case DISP_E_BADPARAMCOUNT:
            throw RuntimeException();
            break;
        case DISP_E_BADVARTYPE:
            throw RuntimeException();
            break;
        case DISP_E_EXCEPTION:
            throw InvocationTargetException();
            break;
        case DISP_E_MEMBERNOTFOUND:
            throw UnknownPropertyException();
            break;
        case DISP_E_NONAMEDARGS:
            throw RuntimeException();
            break;
        case DISP_E_OVERFLOW:
            throw CannotConvertException("call to OLE object failed", static_cast<XInterface*>(
                                             static_cast<XWeak*>(this)), TypeClass_UNKNOWN, FailReason::OUT_OF_RANGE, uArgErr);
            break;
        case DISP_E_PARAMNOTFOUND:
            throw IllegalArgumentException("call to OLE object failed", static_cast<XInterface*>(
                                            static_cast<XWeak*>(this)), ::sal::static_int_cast< sal_Int16, unsigned int >( uArgErr )) ;
            break;
        case DISP_E_TYPEMISMATCH:
            throw CannotConvertException("call to OLE object failed", static_cast<XInterface*>(
                                             static_cast<XWeak*>(this)), TypeClass_UNKNOWN, FailReason::UNKNOWN, ::sal::static_int_cast< sal_Int16, unsigned int >( uArgErr ));
            break;
        case DISP_E_UNKNOWNINTERFACE:
            throw RuntimeException();
            break;
        case DISP_E_UNKNOWNLCID:
            throw RuntimeException();
            break;
        case DISP_E_PARAMNOTOPTIONAL:
            throw CannotConvertException("call to OLE object failed",static_cast<XInterface*>(
                                             static_cast<XWeak*>(this)) , TypeClass_UNKNOWN, FailReason::NO_DEFAULT_AVAILABLE, uArgErr);
            break;
        default:
            throw  RuntimeException();
            break;
        }
    }
    catch (const CannotConvertException &)
    {
        throw;
    }
    catch (const UnknownPropertyException &)
    {
        throw;
    }
    catch (const BridgeRuntimeError& e)
    {
        throw RuntimeException(e.message);
    }
    catch (const Exception & e)
    {
        throw RuntimeException("[automation bridge] unexpected exception in "
                               "IUnknownWrapper_Impl::setValue ! Message : \n" +
                               e.Message);

    }
    catch (...)
    {
        throw RuntimeException(
            "[automation bridge] unexpected exception in "
            "IUnknownWrapper_Impl::setValue !");
    }
}

Any SAL_CALL IUnknownWrapper_Impl::getValue( const OUString& aPropertyName )
        throw(UnknownPropertyException, RuntimeException)
{
    if ( ! m_spDispatch )
    {
        throw RuntimeException(
            "[automation bridge] The object does not have an IDispatch interface");
    }
    Any ret;
    try
    {
        o2u_attachCurrentThread();
        ITypeInfo * pInfo = getTypeInfo();
        // I was going to implement an XServiceInfo interface to allow the type
        // of the automation object to be exposed.. but it seems
        // from looking at comments in the code that it is possible for
        // this object to actually wrap an UNO object ( I guess if automation is
        // used from MSO to create Openoffice objects ) Therefore, those objects
        // will more than likely already have their own XServiceInfo interface.
        // Instead here I chose a name that should be illegal both in COM and
        // UNO ( from an IDL point of view ) therefore I think this is a safe
        // hack
        if ( aPropertyName == "$GetTypeName" )
        {
            if ( pInfo && m_sTypeName.getLength() == 0 )
            {
                 m_sTypeName = "IDispatch";
                CComBSTR sName;

                if ( SUCCEEDED( pInfo->GetDocumentation( -1, &sName, NULL, NULL, NULL  ) ) )
                {
                    OUString sTmp( reinterpret_cast<const sal_Unicode*>(LPCOLESTR(sName)));
                    if ( sTmp.startsWith("_") )
                       sTmp = sTmp.copy(1);
                    // do we own the memory for pTypeLib, msdn doco is vague
                    // I'll assume we do
                    CComPtr< ITypeLib > pTypeLib;
                    unsigned int index;
                    if ( SUCCEEDED(  pInfo->GetContainingTypeLib(  &pTypeLib.p, &index )) )
                    {
                        if ( SUCCEEDED( pTypeLib->GetDocumentation( -1, &sName, NULL, NULL, NULL  ) ) )
                        {
                            OUString sLibName( reinterpret_cast<const sal_Unicode*>(LPCOLESTR(sName)));
                            m_sTypeName = sLibName.concat( OUString(".") ).concat( sTmp );

                        }
                    }
                }

            }
            ret <<= m_sTypeName;
            return ret;
        }
        FuncDesc aDescGet(pInfo);
        FuncDesc aDescPut(pInfo);
        VarDesc aVarDesc(pInfo);
        getPropDesc(aPropertyName, & aDescGet, & aDescPut, & aVarDesc);
        if ( ! aDescGet && ! aDescPut && ! aVarDesc)
        {
            //property not found
            OUString msg("[automation bridge]Property \"" + aPropertyName +
                         "\" is not supported");
            throw UnknownPropertyException(msg);
        }
        // write-only should not be possible
        OSL_ASSERT(  aDescGet  || ! aDescPut);

        HRESULT hr;
        DISPPARAMS dispparams = {0, 0, 0, 0};
        CComVariant varResult;
        ExcepInfo excepinfo;
        unsigned int uArgErr;
        DISPID dispid;
        if (aDescGet)
            dispid = aDescGet->memid;
        else if (aVarDesc)
            dispid = aVarDesc->memid;
        else
            dispid = aDescPut->memid;

        hr = m_spDispatch->Invoke(dispid,
                                 IID_NULL,
                                 LOCALE_USER_DEFAULT,
                                 DISPATCH_PROPERTYGET,
                                 &dispparams,
                                 &varResult,
                                 &excepinfo,
                                 &uArgErr);

        // converting return value and out parameter back to UNO
        if (hr == S_OK)
        {
            // If the com object implements uno interfaces then we have
            // to convert the attribute into the expected type.
            TypeDescription attrInfo;
            getAttributeInfo(aPropertyName, attrInfo);
            if( attrInfo.is() )
                variantToAny( &varResult, ret, Type( attrInfo.get()->pWeakRef));
            else
                variantToAny(&varResult, ret);
        }

        // lookup error code
        switch (hr)
        {
        case S_OK:
            break;
        case DISP_E_BADPARAMCOUNT:
        case DISP_E_BADVARTYPE:
        case DISP_E_EXCEPTION:
            throw RuntimeException(OUString(reinterpret_cast<const sal_Unicode*>(excepinfo.bstrDescription)));
            break;
        case DISP_E_MEMBERNOTFOUND:
            throw UnknownPropertyException(OUString(reinterpret_cast<const sal_Unicode*>(excepinfo.bstrDescription)));
            break;
        default:
            throw RuntimeException(OUString(reinterpret_cast<const sal_Unicode*>(excepinfo.bstrDescription)));
            break;
        }
    }
    catch ( const UnknownPropertyException& )
    {
        throw;
    }
    catch (const BridgeRuntimeError& e)
    {
        throw RuntimeException(e.message);
    }
    catch (const Exception & e)
    {
        throw RuntimeException("[automation bridge] unexpected exception in "
                               "IUnknownWrapper_Impl::getValue ! Message : \n" +
                               e.Message);
    }
    catch (...)
    {
        throw RuntimeException(
            "[automation bridge] unexpected exception in "
            "IUnknownWrapper_Impl::getValue !");
    }
    return ret;
}

sal_Bool SAL_CALL IUnknownWrapper_Impl::hasMethod( const OUString& aName )
        throw(RuntimeException)
{
    if ( ! m_spDispatch )
    {
        throw RuntimeException(
            "[automation bridge] The object does not have an IDispatch interface");
    }
    sal_Bool ret = sal_False;

    try
    {
        o2u_attachCurrentThread();
        ITypeInfo* pInfo = getTypeInfo();
        FuncDesc aDesc(pInfo);
        getFuncDesc(aName, & aDesc);
        // Automation properties can have arguments. Those are treated as methods and
        //are called through XInvocation::invoke.
        if ( ! aDesc)
        {
            FuncDesc aDescGet(pInfo);
            FuncDesc aDescPut(pInfo);
            VarDesc aVarDesc(pInfo);
            getPropDesc( aName, & aDescGet, & aDescPut, & aVarDesc);
            if ((aDescGet && aDescGet->cParams > 0)
                || (aDescPut && aDescPut->cParams > 0))
                ret = sal_True;
        }
        else
            ret = sal_True;
    }
    catch (const BridgeRuntimeError& e)
    {
        throw RuntimeException(e.message);
    }
    catch (const Exception & e)
    {
        throw RuntimeException("[automation bridge] unexpected exception in "
                               "IUnknownWrapper_Impl::hasMethod ! Message : \n" +
                               e.Message);
    }
    catch (...)
    {
        throw RuntimeException("[automation bridge] unexpected exception in "
            "IUnknownWrapper_Impl::hasMethod !");
    }
    return ret;
}

sal_Bool SAL_CALL IUnknownWrapper_Impl::hasProperty( const OUString& aName )
        throw(RuntimeException)
{
    if ( ! m_spDispatch )
    {
        throw RuntimeException("[automation bridge] The object does not have an "
            "IDispatch interface");
    }
    sal_Bool ret = sal_False;
    try
    {
        o2u_attachCurrentThread();

        ITypeInfo * pInfo = getTypeInfo();
        FuncDesc aDescGet(pInfo);
        FuncDesc aDescPut(pInfo);
        VarDesc aVarDesc(pInfo);
        getPropDesc(aName, & aDescGet, & aDescPut, & aVarDesc);

    // we should probably just check the func kind
        // basic has been modified to handle properties ( 'get' ) props at
    // least with parameters
    // additionally you can call invoke(Get|Set)Property on the bridge
        // you can determine if a property has parameter is hasMethod
    // returns true for the name
        if (aVarDesc
            || aDescPut
            || aDescGet )
        {
            ret = sal_True;
        }
    }
    catch (const BridgeRuntimeError& e)
    {
        throw RuntimeException(e.message);
    }
    catch (const Exception & e)
    {
        throw RuntimeException("[automation bridge] unexpected exception in "
                               "IUnknownWrapper_Impl::hasProperty ! Message : \n" +
                               e.Message);

    }
    catch (...)
    {
        throw RuntimeException("[automation bridge] unexpected exception in "
            "IUnknownWrapper_Impl::hasProperty !");
    }
    return ret;
}

Any SAL_CALL IUnknownWrapper_Impl::createBridge( const Any& modelDepObject,
                const Sequence< sal_Int8 >& /*aProcessId*/, sal_Int16 sourceModelType,
                 sal_Int16 destModelType )
    throw( IllegalArgumentException, RuntimeException)
{
    Any ret;
    o2u_attachCurrentThread();

    if (
        (sourceModelType == UNO) &&
        (destModelType == OLE) &&
        (modelDepObject.getValueTypeClass() == TypeClass_INTERFACE)
       )
    {
        Reference<XInterface> xInt( *(XInterface**) modelDepObject.getValue());
        Reference<XInterface> xSelf( (OWeakObject*)this);

        if (xInt == xSelf)
        {
            VARIANT* pVariant = (VARIANT*) CoTaskMemAlloc(sizeof(VARIANT));

            VariantInit(pVariant);
            if (m_bOriginalDispatch == sal_True)
            {
                pVariant->vt = VT_DISPATCH;
                pVariant->pdispVal = m_spDispatch;
                pVariant->pdispVal->AddRef();
            }
            else
            {
                pVariant->vt = VT_UNKNOWN;
                pVariant->punkVal = m_spUnknown;
                pVariant->punkVal->AddRef();
            }

            ret.setValue(static_cast<void*>(&pVariant), cppu::UnoType<sal_uIntPtr>::get());
        }
    }

    return ret;
}
/** @internal
    @exception IllegalArgumentException
    @exception CannotConvertException
    @exception InvocationTargetException
    @RuntimeException
*/
Any  IUnknownWrapper_Impl::invokeWithDispIdUnoTlb(const OUString& sFunctionName,
                                                  const Sequence< Any >& Params,
                                                  Sequence< sal_Int16 >& OutParamIndex,
                                                  Sequence< Any >& OutParam)
{
    Any ret;
    HRESULT hr= S_OK;

    sal_Int32 parameterCount= Params.getLength();
    sal_Int32 outParameterCount= 0;
    typelib_InterfaceMethodTypeDescription* pMethod= NULL;
    TypeDescription methodDesc;
    getMethodInfo(sFunctionName, methodDesc);

    // We need to know whether the IDispatch is from a JScript object.
    // Then out and in/out parameters have to be treated differently than
    // with common COM objects.
    sal_Bool bJScriptObject= isJScriptObject();
    std::unique_ptr<CComVariant[]> sarParams;
    std::unique_ptr<CComVariant[]> sarParamsRef;
    CComVariant *pVarParams= NULL;
    CComVariant *pVarParamsRef= NULL;
    sal_Bool bConvRet= sal_True;

    if( methodDesc.is())
    {
        pMethod = (typelib_InterfaceMethodTypeDescription* )methodDesc.get();
        parameterCount = pMethod->nParams;
        // Create the Array for the array being passed in DISPPARAMS
        // the array also contains the outparameter (but not the values)
        if( pMethod->nParams > 0)
        {
            sarParams.reset(new CComVariant[ parameterCount]);
            pVarParams = sarParams.get();
        }

        // Create the Array for the out an in/out parameter. These values
        // are referenced by the VT_BYREF VARIANTs in DISPPARAMS.
        // We need to find out the number of out and in/out parameter.
        for( sal_Int32 i=0; i < parameterCount; i++)
        {
            if( pMethod->pParams[i].bOut)
                outParameterCount++;
        }

        if( !bJScriptObject)
        {
            sarParamsRef.reset(new CComVariant[outParameterCount]);
            pVarParamsRef = sarParamsRef.get();
            // build up the parameters for IDispatch::Invoke
            sal_Int32 outParamIndex=0;
            int i = 0;
            try
            {
                for( i= 0; i < parameterCount; i++)
                {
                    // In parameter
                    if( pMethod->pParams[i].bIn == sal_True && ! pMethod->pParams[i].bOut)
                    {
                        anyToVariant( &pVarParams[parameterCount - i -1], Params.getConstArray()[i]);
                    }
                    // Out parameter + in/out parameter
                    else if( pMethod->pParams[i].bOut == sal_True)
                    {
                        CComVariant var;
                        if(pMethod->pParams[i].bIn)
                        {
                            anyToVariant( & var,Params[i]);
                            pVarParamsRef[outParamIndex] = var;
                        }

                        switch( pMethod->pParams[i].pTypeRef->eTypeClass)
                        {
                        case TypeClass_INTERFACE:
                        case TypeClass_STRUCT:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt= VT_DISPATCH;
                                pVarParamsRef[ outParamIndex].pdispVal= 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_DISPATCH | VT_BYREF;
                            pVarParams[parameterCount - i -1].ppdispVal= &pVarParamsRef[outParamIndex].pdispVal;
                            break;
                        case TypeClass_ENUM:
                        case TypeClass_LONG:
                        case TypeClass_UNSIGNED_LONG:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_I4;
                                pVarParamsRef[ outParamIndex].lVal = 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_I4 | VT_BYREF;
                            pVarParams[parameterCount - i -1].plVal= &pVarParamsRef[outParamIndex].lVal;
                            break;
                        case TypeClass_SEQUENCE:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_ARRAY| VT_VARIANT;
                                pVarParamsRef[ outParamIndex].parray= NULL;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_ARRAY| VT_BYREF | VT_VARIANT;
                            pVarParams[parameterCount - i -1].pparray= &pVarParamsRef[outParamIndex].parray;
                            break;
                        case TypeClass_ANY:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_EMPTY;
                                pVarParamsRef[ outParamIndex].lVal = 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_VARIANT | VT_BYREF;
                            pVarParams[parameterCount - i -1].pvarVal = &pVarParamsRef[outParamIndex];
                            break;
                        case TypeClass_BOOLEAN:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_BOOL;
                                pVarParamsRef[ outParamIndex].boolVal = 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_BOOL| VT_BYREF;
                            pVarParams[parameterCount - i -1].pboolVal =
                                & pVarParamsRef[outParamIndex].boolVal;
                            break;

                        case TypeClass_STRING:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_BSTR;
                                pVarParamsRef[ outParamIndex].bstrVal= 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_BSTR| VT_BYREF;
                            pVarParams[parameterCount - i -1].pbstrVal=
                                & pVarParamsRef[outParamIndex].bstrVal;
                            break;

                        case TypeClass_FLOAT:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_R4;
                                pVarParamsRef[ outParamIndex].fltVal= 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_R4| VT_BYREF;
                            pVarParams[parameterCount - i -1].pfltVal =
                                & pVarParamsRef[outParamIndex].fltVal;
                            break;
                        case TypeClass_DOUBLE:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_R8;
                                pVarParamsRef[ outParamIndex].dblVal= 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_R8| VT_BYREF;
                            pVarParams[parameterCount - i -1].pdblVal=
                                & pVarParamsRef[outParamIndex].dblVal;
                            break;
                        case TypeClass_BYTE:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_UI1;
                                pVarParamsRef[ outParamIndex].bVal= 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_UI1| VT_BYREF;
                            pVarParams[parameterCount - i -1].pbVal=
                                & pVarParamsRef[outParamIndex].bVal;
                            break;
                        case TypeClass_CHAR:
                        case TypeClass_SHORT:
                        case TypeClass_UNSIGNED_SHORT:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_I2;
                                pVarParamsRef[ outParamIndex].iVal = 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_I2| VT_BYREF;
                            pVarParams[parameterCount - i -1].piVal=
                                & pVarParamsRef[outParamIndex].iVal;
                            break;

                        default:
                            if( ! pMethod->pParams[i].bIn)
                            {
                                pVarParamsRef[ outParamIndex].vt = VT_EMPTY;
                                pVarParamsRef[ outParamIndex].lVal = 0;
                            }
                            pVarParams[parameterCount - i -1].vt = VT_VARIANT | VT_BYREF;
                            pVarParams[parameterCount - i -1].pvarVal =
                                & pVarParamsRef[outParamIndex];
                        }
                        outParamIndex++;
                    } // end else if
                } // end for
            }
            catch (IllegalArgumentException & e)
            {
                e.ArgumentPosition = ::sal::static_int_cast< sal_Int16, int >( i );
                throw;
            }
            catch (CannotConvertException & e)
            {
                e.ArgumentIndex = i;
                throw;
            }
        }
        else // it is an JScriptObject
        {
            int i = 0;
            try
            {
                for( ; i< parameterCount; i++)
                {
                    // In parameter
                    if( pMethod->pParams[i].bIn == sal_True && ! pMethod->pParams[i].bOut)
                    {
                        anyToVariant( &pVarParams[parameterCount - i -1], Params.getConstArray()[i]);
                    }
                    // Out parameter + in/out parameter
                    else if( pMethod->pParams[i].bOut == sal_True)
                    {
                        CComObject<JScriptOutParam>* pParamObject;
                        if( SUCCEEDED( CComObject<JScriptOutParam>::CreateInstance( &pParamObject)))
                        {
                            CComPtr<IUnknown> pUnk(pParamObject->GetUnknown());
#ifdef __MINGW32__
                            CComQIPtr<IDispatch, &__uuidof(IDispatch)> pDisp( pUnk);
#else
                            CComQIPtr<IDispatch> pDisp( pUnk);
#endif

                            pVarParams[ parameterCount - i -1].vt= VT_DISPATCH;
                            pVarParams[ parameterCount - i -1].pdispVal= pDisp;
                            pVarParams[ parameterCount - i -1].pdispVal->AddRef();
                            // if the param is in/out then put the parameter on index 0
                            if( pMethod->pParams[i].bIn == sal_True ) // in / out
                            {
                                CComVariant varParam;
                                anyToVariant( &varParam, Params.getConstArray()[i]);
                                CComDispatchDriver dispDriver( pDisp);
                                if(FAILED( dispDriver.PutPropertyByName( L"0", &varParam)))
                                    throw BridgeRuntimeError(
                                              "[automation bridge]IUnknownWrapper_Impl::"
                                              "invokeWithDispIdUnoTlb\n"
                                              "Could not set property \"0\" for the in/out "
                                              "param!");

                            }
                        }
                        else
                        {
                            throw BridgeRuntimeError(
                                      "[automation bridge]IUnknownWrapper_Impl::"
                                      "invokeWithDispIdUnoTlb\n"
                                      "Could not create out parameter at index: " +
                                OUString::number((sal_Int32) i));
                        }

                    }
                }
            }
            catch (IllegalArgumentException & e)
            {
                e.ArgumentPosition = ::sal::static_int_cast< sal_Int16, int >( i );
                throw;
            }
            catch (CannotConvertException & e)
            {
                e.ArgumentIndex = i;
                throw;
            }
        }
    }
    // No type description Available, that is we have to deal with a COM component,
    // that does not implements UNO interfaces ( IDispatch based)
    else
    {
        //We should not run into this block, because invokeWithDispIdComTlb should
        //have been called instead.
        OSL_ASSERT(0);
    }


    CComVariant     varResult;
    ExcepInfo       excepinfo;
    unsigned int    uArgErr;
    DISPPARAMS dispparams= { pVarParams, NULL, static_cast<UINT>(parameterCount), 0};

    // Get the DISPID
    FuncDesc aDesc(getTypeInfo());
    getFuncDesc(sFunctionName, & aDesc);
    // invoking OLE method
    hr = m_spDispatch->Invoke(aDesc->memid,
                             IID_NULL,
                             LOCALE_USER_DEFAULT,
                             DISPATCH_METHOD,
                             &dispparams,
                             &varResult,
                             &excepinfo,
                             &uArgErr);

    // converting return value and out parameter back to UNO
    if (hr == S_OK)
    {
        if( outParameterCount && pMethod)
        {
            OutParamIndex.realloc( outParameterCount);
            OutParam.realloc( outParameterCount);
            sal_Int32 outIndex=0;
            int i = 0;
            try
            {
                for( ; i < parameterCount; i++)
                {
                    if( pMethod->pParams[i].bOut )
                    {
                        OutParamIndex[outIndex]= (sal_Int16) i;
                        Any outAny;
                        if( !bJScriptObject)
                        {
                            variantToAny( &pVarParamsRef[outIndex], outAny,
                                        Type(pMethod->pParams[i].pTypeRef), sal_False);
                            OutParam[outIndex++]= outAny;
                        }
                        else //JScriptObject
                        {
                            if( pVarParams[i].vt == VT_DISPATCH)
                            {
                                CComDispatchDriver pDisp( pVarParams[i].pdispVal);
                                if( pDisp)
                                {
                                    CComVariant varOut;
                                    if( SUCCEEDED( pDisp.GetPropertyByName( L"0", &varOut)))
                                    {
                                        variantToAny( &varOut, outAny,
                                                    Type(pMethod->pParams[parameterCount - 1 - i].pTypeRef), sal_False);
                                        OutParam[outParameterCount - 1 - outIndex++]= outAny;
                                    }
                                    else
                                        bConvRet= sal_False;
                                }
                                else
                                    bConvRet= sal_False;
                            }
                            else
                                bConvRet= sal_False;
                        }
                    }
                    if( !bConvRet) break;
                }
            }
            catch(IllegalArgumentException & e)
            {
                e.ArgumentPosition = ::sal::static_int_cast< sal_Int16, int >( i );
                throw;
            }
            catch(CannotConvertException & e)
            {
                e.ArgumentIndex = i;
                throw;
            }
        }
        // return value, no type information available
        if ( bConvRet)
        {
            try
            {
                if( pMethod )
                    variantToAny(&varResult, ret, Type( pMethod->pReturnTypeRef), sal_False);
                else
                    variantToAny(&varResult, ret, sal_False);
            }
            catch (IllegalArgumentException & e)
            {
                e.Message =
                    "[automation bridge]IUnknownWrapper_Impl::invokeWithDispIdUnoTlb\n"
                    "Could not convert return value! \n Message: \n" + e.Message;
                throw;
            }
            catch (CannotConvertException & e)
            {
                e.Message =
                    "[automation bridge]IUnknownWrapper_Impl::invokeWithDispIdUnoTlb\n"
                    "Could not convert return value! \n Message: \n" + e.Message;
                throw;
            }
        }
    }

    if( !bConvRet) // conversion of return or out parameter failed
        throw CannotConvertException("Call to COM object failed. Conversion of return or out value failed",
                                      Reference<XInterface>( static_cast<XWeak*>(this), UNO_QUERY   ), TypeClass_UNKNOWN,
                                      FailReason::UNKNOWN, 0);// lookup error code
    // conversion of return or out parameter failed
    switch (hr)
    {
    case S_OK:
        break;
    case DISP_E_BADPARAMCOUNT:
        throw IllegalArgumentException();
        break;
    case DISP_E_BADVARTYPE:
        throw RuntimeException();
        break;
    case DISP_E_EXCEPTION:
        throw InvocationTargetException();
        break;
    case DISP_E_MEMBERNOTFOUND:
        throw IllegalArgumentException();
        break;
    case DISP_E_NONAMEDARGS:
        throw IllegalArgumentException();
        break;
    case DISP_E_OVERFLOW:
        throw CannotConvertException("call to OLE object failed", static_cast<XInterface*>(
                                         static_cast<XWeak*>(this)), TypeClass_UNKNOWN, FailReason::OUT_OF_RANGE, uArgErr);
        break;
    case DISP_E_PARAMNOTFOUND:
        throw IllegalArgumentException("call to OLE object failed", static_cast<XInterface*>(
                                           static_cast<XWeak*>(this)), ::sal::static_int_cast< sal_Int16, unsigned int >( uArgErr ));
        break;
    case DISP_E_TYPEMISMATCH:
        throw CannotConvertException("call to OLE object failed",static_cast<XInterface*>(
                                         static_cast<XWeak*>(this)) , TypeClass_UNKNOWN, FailReason::UNKNOWN, uArgErr);
        break;
    case DISP_E_UNKNOWNINTERFACE:
        throw RuntimeException() ;
        break;
    case DISP_E_UNKNOWNLCID:
        throw RuntimeException() ;
        break;
    case DISP_E_PARAMNOTOPTIONAL:
        throw CannotConvertException("call to OLE object failed", static_cast<XInterface*>(
                                         static_cast<XWeak*>(this)), TypeClass_UNKNOWN, FailReason::NO_DEFAULT_AVAILABLE, uArgErr);
                break;
    default:
        throw RuntimeException();
        break;
    }

    return ret;
}


// XInitialization
void SAL_CALL IUnknownWrapper_Impl::initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException)
{
    // 1.parameter is IUnknown
    // 2.parameter is a boolean which indicates if the COM pointer was a IUnknown or IDispatch
    // 3.parameter is a Sequence<Type>
    o2u_attachCurrentThread();
    OSL_ASSERT(aArguments.getLength() == 3);

    m_spUnknown= *(IUnknown**) aArguments[0].getValue();
#ifdef __MINGW32__
    m_spUnknown->QueryInterface(IID_IDispatch, reinterpret_cast<LPVOID*>( & m_spDispatch.p));
#else
    m_spUnknown.QueryInterface( & m_spDispatch.p);
#endif

    aArguments[1] >>= m_bOriginalDispatch;
    aArguments[2] >>= m_seqTypes;

    ITypeInfo* pType = NULL;
    try
    {
        // a COM object implementation that has no TypeInfo is still a legal COM object;
        // such objects can at least be transported through UNO using the bridge
        // so we should allow to create wrappers for them as well
        pType = getTypeInfo();
    }
    catch( const BridgeRuntimeError& )
    {}
    catch( const Exception& )
    {}

    if ( pType )
    {
        try
        {
            // Get Default member
            CComBSTR defaultMemberName;
            if ( SUCCEEDED( pType->GetDocumentation(0, &defaultMemberName, 0, 0, 0 ) ) )
            {
                OUString usName(reinterpret_cast<const sal_Unicode*>(LPCOLESTR(defaultMemberName)));
                FuncDesc aDescGet(pType);
                FuncDesc aDescPut(pType);
                VarDesc aVarDesc(pType);
                // see if this is a property first ( more likely to be a property then a method )
                getPropDesc( usName, & aDescGet, & aDescPut, & aVarDesc);

                if ( !aDescGet && !aDescPut )
                {
                    getFuncDesc( usName, &aDescGet );
                    if ( !aDescGet )
                        throw BridgeRuntimeError( "[automation bridge]IUnknownWrapper_Impl::initialize() Failed to get Function or Property desc. for " + usName );
                }
                // now for some funny heuristics to make basic understand what to do
                // a single aDescGet ( that doesn't take any params ) would be
                // a read only ( defaultmember ) property e.g. this object
                // should implement XDefaultProperty
                // a single aDescGet ( that *does* ) take params is basically a
                // default method e.g. implement XDefaultMethod

                // a DescPut ( I guess we only really support a default param with '1' param ) as a setValue ( but I guess we can leave it through, the object will fail if we don't get it right anyway )
                if ( aDescPut || ( aDescGet && aDescGet->cParams == 0 ) )
                    m_bHasDfltProperty = true;
                if ( aDescGet->cParams > 0 )
                    m_bHasDfltMethod = true;
                if ( m_bHasDfltProperty || m_bHasDfltMethod )
                    m_sDefaultMember = usName;
            }
        }
        catch ( const BridgeRuntimeError & e )
        {
            throw RuntimeException( e.message );
        }
        catch( const Exception& e )
        {
            throw RuntimeException(
                    "[automation bridge] unexpected exception in IUnknownWrapper_Impl::initialiase() error message: \n" + e.Message );
        }
    }
}


// XDirectInvocation
uno::Any SAL_CALL IUnknownWrapper_Impl::directInvoke( const OUString& aName, const uno::Sequence< uno::Any >& aParams )
    throw (lang::IllegalArgumentException, script::CannotConvertException, reflection::InvocationTargetException, uno::RuntimeException)
{
    Any aResult;

    if ( !m_spDispatch )
    {
        throw RuntimeException(
            "[automation bridge] The object does not have an IDispatch interface");
    }

    o2u_attachCurrentThread();
    DISPID dispid;
    if ( !getDispid( aName, &dispid ) )
        throw IllegalArgumentException(
            "[automation bridge] The object does not have a function or property "
            + aName, Reference<XInterface>(), 0);

    CComVariant     varResult;
    ExcepInfo       excepinfo;
    unsigned int    uArgErr = 0;
    INVOKEKIND pInvkinds[2];
    pInvkinds[0] = INVOKE_FUNC;
    pInvkinds[1] = aParams.getLength() ? INVOKE_PROPERTYPUT : INVOKE_PROPERTYGET;
    HRESULT hInvRes = E_FAIL;

    // try Invoke first, if it does not work, try put/get property
    for ( sal_Int32 nStep = 0; FAILED( hInvRes ) && nStep < 2; nStep++ )
    {
        DISPPARAMS      dispparams = {NULL, NULL, 0, 0};

        std::unique_ptr<DISPID[]> arDispidNamedArgs;
        std::unique_ptr<CComVariant[]> ptrArgs;
        std::unique_ptr<CComVariant[]> ptrRefArgs; // referenced arguments
        CComVariant * arArgs = NULL;
        CComVariant * arRefArgs = NULL;

        dispparams.cArgs = aParams.getLength();

        // Determine the number of named arguments
        for ( sal_Int32 nInd = 0; nInd < aParams.getLength(); nInd++ )
            if ( aParams[nInd].getValueType() == cppu::UnoType<NamedArgument>::get() )
                dispparams.cNamedArgs ++;

        // fill the named arguments
        if ( dispparams.cNamedArgs > 0
          && !( dispparams.cNamedArgs == 1 && pInvkinds[nStep] == INVOKE_PROPERTYPUT ) )
        {
            int nSizeAr = dispparams.cNamedArgs + 1;
            if ( pInvkinds[nStep] == INVOKE_PROPERTYPUT )
                nSizeAr = dispparams.cNamedArgs;

            std::unique_ptr<OLECHAR*[]> saNames(new OLECHAR*[nSizeAr]);
            OLECHAR ** pNames = saNames.get();
            pNames[0] = const_cast<OLECHAR*>(reinterpret_cast<LPCOLESTR>(aName.getStr()));

            int cNamedArg = 0;
            for ( size_t nInd = 0; nInd < dispparams.cArgs; nInd++ )
            {
                if ( aParams[nInd].getValueType() == cppu::UnoType<NamedArgument>::get())
                {
                    const NamedArgument& arg = *(NamedArgument const*)aParams[nInd].getValue();

                    //We put the parameter names in reverse order into the array,
                    //so we can use the DISPID array for DISPPARAMS::rgdispidNamedArgs
                    //The first name in the array is the method name
                    pNames[nSizeAr - 1 - cNamedArg++] = const_cast<OLECHAR*>(reinterpret_cast<LPCOLESTR>(arg.Name.getStr()));
                }
            }

            arDispidNamedArgs.reset( new DISPID[nSizeAr] );
            HRESULT hr = getTypeInfo()->GetIDsOfNames( pNames, nSizeAr, arDispidNamedArgs.get() );
            if ( hr == E_NOTIMPL )
                hr = m_spDispatch->GetIDsOfNames(IID_NULL, pNames, nSizeAr, LOCALE_USER_DEFAULT, arDispidNamedArgs.get() );

            if ( SUCCEEDED( hr ) )
            {
                if ( pInvkinds[nStep] == DISPATCH_PROPERTYPUT )
                {
                    DISPID*  arIDs = arDispidNamedArgs.get();
                    arIDs[0] = DISPID_PROPERTYPUT;
                    dispparams.rgdispidNamedArgs = arIDs;
                }
                else
                {
                    DISPID*  arIDs = arDispidNamedArgs.get();
                    dispparams.rgdispidNamedArgs = & arIDs[1];
                }
            }
            else if (hr == DISP_E_UNKNOWNNAME)
            {
                 throw IllegalArgumentException(
                     "[automation bridge]One of the named arguments is wrong!",
                     Reference<XInterface>(), 0);
            }
            else
            {
                throw InvocationTargetException(
                    "[automation bridge] ITypeInfo::GetIDsOfNames returned error "
                    + OUString::number((sal_Int32) hr, 16), Reference<XInterface>(), Any());
            }
        }

        //Convert arguments
        ptrArgs.reset(new CComVariant[dispparams.cArgs]);
        ptrRefArgs.reset(new CComVariant[dispparams.cArgs]);
        arArgs = ptrArgs.get();
        arRefArgs = ptrRefArgs.get();

        sal_Int32 nInd = 0;
        try
        {
            sal_Int32 revIndex = 0;
            for ( nInd = 0; nInd < sal_Int32(dispparams.cArgs); nInd++)
            {
                revIndex = dispparams.cArgs - nInd - 1;
                arRefArgs[revIndex].byref = 0;
                Any  anyArg;
                if ( nInd < aParams.getLength() )
                    anyArg = aParams.getConstArray()[nInd];

                // Property Put arguments
                if ( anyArg.getValueType() == cppu::UnoType<PropertyPutArgument>::get() )
                {
                    PropertyPutArgument arg;
                    anyArg >>= arg;
                    anyArg <<= arg.Value;
                }
                // named argument
                if (anyArg.getValueType() == cppu::UnoType<NamedArgument>::get())
                {
                    NamedArgument aNamedArgument;
                    anyArg >>= aNamedArgument;
                    anyArg <<= aNamedArgument.Value;
                }

                if ( nInd < aParams.getLength() && anyArg.getValueTypeClass() != TypeClass_VOID )
                {
                    anyToVariant( &arArgs[revIndex], anyArg, VT_VARIANT );
                }
                else
                {
                    arArgs[revIndex].vt = VT_ERROR;
                    arArgs[revIndex].scode = DISP_E_PARAMNOTFOUND;
                }
            }
        }
        catch (IllegalArgumentException & e)
        {
            e.ArgumentPosition = ::sal::static_int_cast< sal_Int16, sal_Int32 >( nInd );
            throw;
        }
        catch (CannotConvertException & e)
        {
            e.ArgumentIndex = nInd;
            throw;
        }

        dispparams.rgvarg = arArgs;
        // invoking OLE method
        DWORD localeId = LOCALE_USER_DEFAULT;
        hInvRes = m_spDispatch->Invoke( dispid,
                                        IID_NULL,
                                        localeId,
                                        ::sal::static_int_cast< WORD, INVOKEKIND >( pInvkinds[nStep] ),
                                        &dispparams,
                                        &varResult,
                                        &excepinfo,
                                        &uArgErr);
    }

    // converting return value and out parameter back to UNO
    if ( SUCCEEDED( hInvRes ) )
        variantToAny( &varResult, aResult, sal_False );
    else
    {
        // map error codes to exceptions
        OUString message;
        switch ( hInvRes )
        {
            case S_OK:
                break;
            case DISP_E_BADPARAMCOUNT:
                throw IllegalArgumentException("[automation bridge] Wrong "
                      "number of arguments. Object returned DISP_E_BADPARAMCOUNT.",
                      0, 0);
                break;
            case DISP_E_BADVARTYPE:
                throw RuntimeException("[automation bridge] One or more "
                      "arguments have the wrong type. Object returned "
                      "DISP_E_BADVARTYPE.", 0);
                break;
            case DISP_E_EXCEPTION:
                    message = "[automation bridge]: ";
                    message += OUString(reinterpret_cast<const sal_Unicode*>(excepinfo.bstrDescription),
                        ::SysStringLen(excepinfo.bstrDescription));
                    throw InvocationTargetException(message, Reference<XInterface>(), Any());
                    break;
            case DISP_E_MEMBERNOTFOUND:
                message = "[automation bridge]: A function with the name \""
                    + aName + "\" is not supported. Object returned "
                    "DISP_E_MEMBERNOTFOUND.";
                throw IllegalArgumentException(message, 0, 0);
                break;
            case DISP_E_NONAMEDARGS:
                throw IllegalArgumentException("[automation bridge] Object "
                      "returned DISP_E_NONAMEDARGS",0, ::sal::static_int_cast< sal_Int16, unsigned int >( uArgErr ));
                break;
            case DISP_E_OVERFLOW:
                throw CannotConvertException("[automation bridge] Call failed.",
                                             static_cast<XInterface*>(
                    static_cast<XWeak*>(this)), TypeClass_UNKNOWN, FailReason::OUT_OF_RANGE, uArgErr);
                break;
            case DISP_E_PARAMNOTFOUND:
                throw IllegalArgumentException("[automation bridge]Call failed."
                                               "Object returned DISP_E_PARAMNOTFOUND.",
                                               0, ::sal::static_int_cast< sal_Int16, unsigned int >( uArgErr ));
                break;
            case DISP_E_TYPEMISMATCH:
                throw CannotConvertException("[automation bridge] Call  failed. "
                                             "Object returned DISP_E_TYPEMISMATCH",
                    static_cast<XInterface*>(
                    static_cast<XWeak*>(this)) , TypeClass_UNKNOWN, FailReason::UNKNOWN, uArgErr);
                break;
            case DISP_E_UNKNOWNINTERFACE:
                throw RuntimeException("[automation bridge] Call failed. "
                                           "Object returned DISP_E_UNKNOWNINTERFACE.",0);
                break;
            case DISP_E_UNKNOWNLCID:
                throw RuntimeException("[automation bridge] Call failed. "
                                           "Object returned DISP_E_UNKNOWNLCID.",0);
                break;
            case DISP_E_PARAMNOTOPTIONAL:
                throw CannotConvertException("[automation bridge] Call failed."
                      "Object returned DISP_E_PARAMNOTOPTIONAL",
                            static_cast<XInterface*>(static_cast<XWeak*>(this)),
                                  TypeClass_UNKNOWN, FailReason::NO_DEFAULT_AVAILABLE, uArgErr);
                break;
            default:
                throw RuntimeException();
                break;
        }
    }

    return aResult;
}

sal_Bool SAL_CALL IUnknownWrapper_Impl::hasMember( const OUString& aName )
    throw (uno::RuntimeException)
{
    if ( ! m_spDispatch )
    {
        throw RuntimeException(
            "[automation bridge] The object does not have an IDispatch interface");
    }

    o2u_attachCurrentThread();
    DISPID dispid;
    return getDispid( aName, &dispid );
}


// UnoConversionUtilities --------------------------------------------------------------------------------
Reference< XInterface > IUnknownWrapper_Impl::createUnoWrapperInstance()
{
    if( m_nUnoWrapperClass == INTERFACE_OLE_WRAPPER_IMPL)
    {
        Reference<XWeak> xWeak= static_cast<XWeak*>( new InterfaceOleWrapper_Impl(
                                m_smgr, m_nUnoWrapperClass, m_nComWrapperClass));
        return Reference<XInterface>( xWeak, UNO_QUERY);
    }
    else if( m_nUnoWrapperClass == UNO_OBJECT_WRAPPER_REMOTE_OPT)
    {
        Reference<XWeak> xWeak= static_cast<XWeak*>( new UnoObjectWrapperRemoteOpt(
                                m_smgr, m_nUnoWrapperClass, m_nComWrapperClass));
        return Reference<XInterface>( xWeak, UNO_QUERY);
    }
    else
        return Reference<XInterface>();
}
Reference<XInterface> IUnknownWrapper_Impl::createComWrapperInstance()
{
    Reference<XWeak> xWeak= static_cast<XWeak*>( new IUnknownWrapper_Impl(
                            m_smgr, m_nUnoWrapperClass, m_nComWrapperClass));
    return Reference<XInterface>( xWeak, UNO_QUERY);
}


void IUnknownWrapper_Impl::getMethodInfo(const OUString& sName, TypeDescription& methodInfo)
{
    TypeDescription desc= getInterfaceMemberDescOfCurrentCall(sName);
    if( desc.is())
    {
        typelib_TypeDescription* pMember= desc.get();
        if( pMember->eTypeClass == typelib_TypeClass_INTERFACE_METHOD )
            methodInfo= pMember;
    }
}

void IUnknownWrapper_Impl::getAttributeInfo(const OUString& sName, TypeDescription& attributeInfo)
{
    TypeDescription desc= getInterfaceMemberDescOfCurrentCall(sName);
    if( desc.is())
    {
        typelib_TypeDescription* pMember= desc.get();
        if( pMember->eTypeClass == typelib_TypeClass_INTERFACE_ATTRIBUTE )
        {
            attributeInfo= ((typelib_InterfaceAttributeTypeDescription*)pMember)->pAttributeTypeRef;
        }
    }
}
TypeDescription IUnknownWrapper_Impl::getInterfaceMemberDescOfCurrentCall(const OUString& sName)
{
    TypeDescription ret;

    for( sal_Int32 i=0; i < m_seqTypes.getLength(); i++)
    {
        TypeDescription _curDesc( m_seqTypes[i]);
        _curDesc.makeComplete();
        typelib_InterfaceTypeDescription * pInterface= (typelib_InterfaceTypeDescription*) _curDesc.get();
        if( pInterface)
        {
            typelib_InterfaceMemberTypeDescription* pMember= NULL;
            //find the member description of the current call
            for( int j=0; j < pInterface->nAllMembers; j++)
            {
                typelib_TypeDescriptionReference* pTypeRefMember = pInterface->ppAllMembers[j];
                typelib_TypeDescription* pDescMember= NULL;
                TYPELIB_DANGER_GET( &pDescMember, pTypeRefMember);

                typelib_InterfaceMemberTypeDescription* pInterfaceMember=
                    (typelib_InterfaceMemberTypeDescription*) pDescMember;
                if( OUString( pInterfaceMember->pMemberName) == sName)
                {
                    pMember= pInterfaceMember;
                    break;
                }
                TYPELIB_DANGER_RELEASE( pDescMember);
            }

            if( pMember)
            {
                ret= (typelib_TypeDescription*)pMember;
                TYPELIB_DANGER_RELEASE( (typelib_TypeDescription*)pMember);
            }
        }
        if( ret.is())
            break;
    }
    return ret;
}

sal_Bool IUnknownWrapper_Impl::isJScriptObject()
{
    if(  m_eJScript == JScriptUndefined)
    {
        CComDispatchDriver disp( m_spDispatch);
        if( disp)
        {
            CComVariant result;
            if( SUCCEEDED(  disp.GetPropertyByName( JSCRIPT_ID_PROPERTY, &result)))
            {
                if(result.vt == VT_BSTR)
                {
                    CComBSTR name( result.bstrVal);
                    name.ToLower();
                    if( name == CComBSTR(JSCRIPT_ID))
                        m_eJScript= IsJScript;
                }
            }
        }
        if( m_eJScript == JScriptUndefined)
            m_eJScript= NoJScript;
    }

    return m_eJScript == NoJScript ? sal_False : sal_True;
}


/** @internal
    The function ultimately calls IDispatch::Invoke on the wrapped COM object.
    The COM object does not implement UNO Interfaces ( via IDispatch). This
    is the case when the OleObjectFactory service has been used to create a
    component.
    @exception IllegalArgumentException
    @exception CannotConvertException
    @InvocationTargetException
    @RuntimeException
    @BridgeRuntimeError
*/
Any  IUnknownWrapper_Impl::invokeWithDispIdComTlb(const OUString& sFuncName,
                                                  const Sequence< Any >& Params,
                                                  Sequence< sal_Int16 >& OutParamIndex,
                                                  Sequence< Any >& OutParam)
{
    // Get type info for the call. It can be a method call or property put or
    // property get operation.
    FuncDesc aFuncDesc(getTypeInfo());
    getFuncDescForInvoke(sFuncName, Params, & aFuncDesc);
    return invokeWithDispIdComTlb( aFuncDesc, sFuncName, Params, OutParamIndex, OutParam );
}

Any  IUnknownWrapper_Impl::invokeWithDispIdComTlb(FuncDesc& aFuncDesc,
                                                  const OUString& sFuncName,
                                                  const Sequence< Any >& Params,
                                                  Sequence< sal_Int16 >& OutParamIndex,
                                                  Sequence< Any >& OutParam)
{
    Any ret;
    HRESULT result;

    DISPPARAMS      dispparams = {NULL, NULL, 0, 0};
    CComVariant     varResult;
    ExcepInfo       excepinfo;
    unsigned int    uArgErr;
    sal_Int32       i = 0;
    sal_Int32 nUnoArgs = Params.getLength();
    DISPID idPropertyPut = DISPID_PROPERTYPUT;
    std::unique_ptr<DISPID[]> arDispidNamedArgs;
    std::unique_ptr<CComVariant[]> ptrArgs;
    std::unique_ptr<CComVariant[]> ptrRefArgs; // referenced arguments
    CComVariant * arArgs = NULL;
    CComVariant * arRefArgs = NULL;
    sal_Int32 revIndex = 0;

    //Set the array of DISPIDs for named args if it is a property put operation.
    //If there are other named arguments another array is set later on.
    if (aFuncDesc->invkind == INVOKE_PROPERTYPUT
        || aFuncDesc->invkind == INVOKE_PROPERTYPUTREF)
        dispparams.rgdispidNamedArgs = & idPropertyPut;

    //Determine the number of named arguments
    for (int iParam = 0; iParam < nUnoArgs; iParam ++)
    {
        const Any & curArg = Params[iParam];
        if (curArg.getValueType() == cppu::UnoType<NamedArgument>::get())
            dispparams.cNamedArgs ++;
    }
    //In a property put operation a property value is a named argument (DISPID_PROPERTYPUT).
    //Therefore the number of named arguments is increased by one.
    //Although named, the argument is not named in an actual language, such as Basic,
    //therefore it is never a com.sun.star.bridge.oleautomation.NamedArgument
    if (aFuncDesc->invkind == DISPATCH_PROPERTYPUT
        || aFuncDesc->invkind == DISPATCH_PROPERTYPUTREF)
        dispparams.cNamedArgs ++;

    //Determine the number of all arguments and named arguments
    if (aFuncDesc->cParamsOpt == -1)
    {
        //Attribute vararg is set on this method. "Unlimited" number of args
        //supported. There can be no optional or defaultvalue on any of the arguments.
        dispparams.cArgs = nUnoArgs;
    }
    else
    {
        //If there are named arguments, then the dispparams.cArgs
        //is the number of supplied args, otherwise it is the expected number.
        if (dispparams.cNamedArgs)
            dispparams.cArgs = nUnoArgs;
        else
            dispparams.cArgs = aFuncDesc->cParams;
    }

    //check if there are not to many arguments supplied
    if (::sal::static_int_cast< sal_uInt32, int >( nUnoArgs ) > dispparams.cArgs)
    {
        OUStringBuffer buf(256);
        buf.appendAscii("[automation bridge] There are too many arguments for this method");
        throw IllegalArgumentException( buf.makeStringAndClear(),
            Reference<XInterface>(), (sal_Int16) dispparams.cArgs);
    }

    //Set up the array of DISPIDs (DISPPARAMS::rgdispidNamedArgs)
    //for the named arguments.
    //If there is only one named arg and if it is because of a property put
    //operation, then we need not set up the DISPID array.
    if (dispparams.cNamedArgs > 0 &&
        ! (dispparams.cNamedArgs == 1 &&
           (aFuncDesc->invkind == INVOKE_PROPERTYPUT ||
            aFuncDesc->invkind == INVOKE_PROPERTYPUTREF)))
    {
        //set up an array containing the member and parameter names
        //which is then used in ITypeInfo::GetIDsOfNames
        //First determine the size of the array of names which is passed to
        //ITypeInfo::GetIDsOfNames. It must hold the method names + the named
        //args.
        int nSizeAr = dispparams.cNamedArgs + 1;
        if (aFuncDesc->invkind == INVOKE_PROPERTYPUT
            || aFuncDesc->invkind == INVOKE_PROPERTYPUTREF)
        {
            nSizeAr = dispparams.cNamedArgs; //counts the DISID_PROPERTYPUT
        }

        std::unique_ptr<OLECHAR*[]> saNames(new OLECHAR*[nSizeAr]);
        OLECHAR ** arNames = saNames.get();
        arNames[0] = const_cast<OLECHAR*>(reinterpret_cast<LPCOLESTR>(sFuncName.getStr()));

        int cNamedArg = 0;
        for (size_t iParams = 0; iParams < dispparams.cArgs; iParams ++)
        {
            const Any &  curArg = Params[iParams];
            if (curArg.getValueType() == cppu::UnoType<NamedArgument>::get())
            {
                const NamedArgument& arg = *(NamedArgument const*) curArg.getValue();
                //We put the parameter names in reverse order into the array,
                //so we can use the DISPID array for DISPPARAMS::rgdispidNamedArgs
                //The first name in the array is the method name
                arNames[nSizeAr - 1 - cNamedArg++] = const_cast<OLECHAR*>(reinterpret_cast<LPCOLESTR>(arg.Name.getStr()));
            }
        }

        //Prepare the array of DISPIDs for ITypeInfo::GetIDsOfNames
        //it must be big enough to contain the DISPIDs of the member + parameters
        arDispidNamedArgs.reset(new DISPID[nSizeAr]);
        HRESULT hr = getTypeInfo()->GetIDsOfNames(arNames, nSizeAr,
                                                  arDispidNamedArgs.get());
        if ( hr == E_NOTIMPL )
            hr = m_spDispatch->GetIDsOfNames(IID_NULL, arNames, nSizeAr, LOCALE_USER_DEFAULT, arDispidNamedArgs.get() );

        if (hr == S_OK)
        {
            // In a "property put" operation, the property value is a named param with the
            //special DISPID DISPID_PROPERTYPUT
            if (aFuncDesc->invkind == DISPATCH_PROPERTYPUT
                || aFuncDesc->invkind == DISPATCH_PROPERTYPUTREF)
            {
                //Element at index 0 in the DISPID array must be DISPID_PROPERTYPUT
                //The first item in the array arDispidNamedArgs is the DISPID for
                //the method. We replace it with DISPID_PROPERTYPUT.
                DISPID*  arIDs = arDispidNamedArgs.get();
                arIDs[0] = DISPID_PROPERTYPUT;
                dispparams.rgdispidNamedArgs = arIDs;
            }
            else
            {
                //The first item in the array arDispidNamedArgs is the DISPID for
                //the method. It must be removed
                DISPID*  arIDs = arDispidNamedArgs.get();
                dispparams.rgdispidNamedArgs = & arIDs[1];
            }
        }
        else if (hr == DISP_E_UNKNOWNNAME)
        {
             throw IllegalArgumentException(
                 "[automation bridge]One of the named arguments is wrong!",
                 Reference<XInterface>(), 0);
        }
        else
        {
            throw InvocationTargetException(
                "[automation bridge] ITypeInfo::GetIDsOfNames returned error "
                + OUString::number((sal_Int32) hr, 16), Reference<XInterface>(), Any());
        }
    }

    //Convert arguments
    ptrArgs.reset(new CComVariant[dispparams.cArgs]);
    ptrRefArgs.reset(new CComVariant[dispparams.cArgs]);
    arArgs = ptrArgs.get();
    arRefArgs = ptrRefArgs.get();
    try
    {
        for (i = 0; i < (sal_Int32) dispparams.cArgs; i++)
        {
            revIndex= dispparams.cArgs - i -1;
            arRefArgs[revIndex].byref=0;
            Any  anyArg;
            if ( i < nUnoArgs)
                anyArg= Params.getConstArray()[i];

            unsigned short paramFlags = PARAMFLAG_FOPT | PARAMFLAG_FIN;
            VARTYPE varType = VT_VARIANT;
            if (aFuncDesc->cParamsOpt != -1 || aFuncDesc->cParams != (i + 1))
            {
                paramFlags = aFuncDesc->lprgelemdescParam[i].paramdesc.wParamFlags;
                varType = getElementTypeDesc(&aFuncDesc->lprgelemdescParam[i].tdesc);
            }

            // Make sure that there is a UNO parameter for every
            // expected parameter. If there is no UNO parameter where the
            // called function expects one, then it must be optional. Otherwise
            // it's a UNO programming error.
            if (i  >= nUnoArgs && !(paramFlags & PARAMFLAG_FOPT))
            {
                OUStringBuffer buf(256);
                buf.appendAscii("ole automation bridge: The called function expects an argument at"
                                "position: "); //a different number of arguments")),
                buf.append(OUString::number((sal_Int32) i));
                buf.appendAscii(" (index starting at 0).");
                throw IllegalArgumentException( buf.makeStringAndClear(),
                                                Reference<XInterface>(), (sal_Int16) i);
            }

            // Property Put arguments
            if (anyArg.getValueType() == cppu::UnoType<PropertyPutArgument>::get())
            {
                PropertyPutArgument arg;
                anyArg >>= arg;
                anyArg <<= arg.Value;
            }
            // named argument
            if (anyArg.getValueType() == cppu::UnoType<NamedArgument>::get())
            {
                NamedArgument aNamedArgument;
                anyArg >>= aNamedArgument;
                anyArg <<= aNamedArgument.Value;
            }
            // out param
            if (paramFlags & PARAMFLAG_FOUT &&
                ! (paramFlags & PARAMFLAG_FIN)  )
            {
                VARTYPE type = ::sal::static_int_cast< VARTYPE, int >( varType ^ VT_BYREF );
                if (i < nUnoArgs)
                {
                    arRefArgs[revIndex].vt= type;
                }
                else
                {
                    //optional arg
                    arRefArgs[revIndex].vt = VT_ERROR;
                    arRefArgs[revIndex].scode = DISP_E_PARAMNOTFOUND;
                }
                if( type == VT_VARIANT )
                {
                    arArgs[revIndex].vt= VT_VARIANT | VT_BYREF;
                    arArgs[revIndex].byref= &arRefArgs[revIndex];
                }
                else
                {
                    arArgs[revIndex].vt= varType;
                    if (type == VT_DECIMAL)
                        arArgs[revIndex].byref= & arRefArgs[revIndex].decVal;
                    else
                        arArgs[revIndex].byref= & arRefArgs[revIndex].byref;
                }
            }
            // in/out  + in byref params
            else if (varType & VT_BYREF)
            {
                VARTYPE type = ::sal::static_int_cast< VARTYPE, int >( varType ^ VT_BYREF );
                CComVariant var;

                if (i < nUnoArgs && anyArg.getValueTypeClass() != TypeClass_VOID)
                {
                    anyToVariant( & arRefArgs[revIndex], anyArg, type);
                }
                else if (paramFlags & PARAMFLAG_FHASDEFAULT)
                {
                    //optional arg with default
                    VariantCopy( & arRefArgs[revIndex],
                                & aFuncDesc->lprgelemdescParam[i].paramdesc.
                                pparamdescex->varDefaultValue);
                }
                else
                {
                    //optional arg
                    //e.g: call func(x) in basic : func() ' no arg supplied
                    OSL_ASSERT(paramFlags & PARAMFLAG_FOPT);
                    arRefArgs[revIndex].vt = VT_ERROR;
                    arRefArgs[revIndex].scode = DISP_E_PARAMNOTFOUND;
                }

                // Set the converted arguments in the array which will be
                // DISPPARAMS::rgvarg
                // byref arg VT_XXX |VT_BYREF
                arArgs[revIndex].vt = varType;
                if (revIndex == 0 && aFuncDesc->invkind == INVOKE_PROPERTYPUT)
                {
                    arArgs[revIndex] = arRefArgs[revIndex];
                }
                else if (type == VT_DECIMAL)
                {
                    arArgs[revIndex].byref= & arRefArgs[revIndex].decVal;
                }
                else if (type == VT_VARIANT)
                {
                    if ( ! (paramFlags & PARAMFLAG_FOUT))
                        arArgs[revIndex] = arRefArgs[revIndex];
                    else
                        arArgs[revIndex].byref = & arRefArgs[revIndex];
                }
                else
                {
                    arArgs[revIndex].byref = & arRefArgs[revIndex].byref;
                    arArgs[revIndex].vt = ::sal::static_int_cast< VARTYPE, int >( arRefArgs[revIndex].vt | VT_BYREF );
                }

            }
            // in parameter no VT_BYREF except for array, interfaces
            else
            {   // void any stands for optional param
                if (i < nUnoArgs && anyArg.getValueTypeClass() != TypeClass_VOID)
                {
                    anyToVariant( & arArgs[revIndex], anyArg, varType);
                }
                //optional arg but no void any supplied
                //Basic:  obj.func() ' first parameter left out because it is optional
                else if (paramFlags & PARAMFLAG_FHASDEFAULT)
                {
                    //optional arg with default either as direct arg : VT_XXX or
                    VariantCopy( & arArgs[revIndex],
                        & aFuncDesc->lprgelemdescParam[i].paramdesc.
                            pparamdescex->varDefaultValue);
                }
                else if (paramFlags & PARAMFLAG_FOPT)
                {
                    arArgs[revIndex].vt = VT_ERROR;
                    arArgs[revIndex].scode = DISP_E_PARAMNOTFOUND;
                }
                else
                {
                    arArgs[revIndex].vt = VT_EMPTY;
                    arArgs[revIndex].lVal = 0;
                }
            }
        }
    }
    catch (IllegalArgumentException & e)
    {
        e.ArgumentPosition = ::sal::static_int_cast< sal_Int16, sal_Int32 >( i );
        throw;
    }
    catch (CannotConvertException & e)
    {
        e.ArgumentIndex = i;
        throw;
    }
    dispparams.rgvarg= arArgs;
    // invoking OLE method
    DWORD localeId = LOCALE_USER_DEFAULT;
    result = m_spDispatch->Invoke(aFuncDesc->memid,
                                 IID_NULL,
                                 localeId,
                                 ::sal::static_int_cast< WORD, INVOKEKIND >( aFuncDesc->invkind ),
                                 &dispparams,
                                 &varResult,
                                 &excepinfo,
                                 &uArgErr);

    // converting return value and out parameter back to UNO
    if (result == S_OK)
    {

        // allocate space for the out param Sequence and indices Sequence
        int outParamsCount= 0; // includes in/out parameter
        for (int j = 0; j < aFuncDesc->cParams; j++)
        {
            if (aFuncDesc->lprgelemdescParam[j].paramdesc.wParamFlags &
                PARAMFLAG_FOUT)
                outParamsCount++;
        }

        OutParamIndex.realloc(outParamsCount);
        OutParam.realloc(outParamsCount);
        // Convert out params
        if (outParamsCount)
        {
            int outParamIndex=0;
            for (int paramIndex = 0; paramIndex < nUnoArgs; paramIndex ++)
            {
                //Determine the index within the method signature
                int realParamIndex = paramIndex;
                int revParamIndex = dispparams.cArgs - paramIndex - 1;
                if (Params[paramIndex].getValueType()
                    == cppu::UnoType<NamedArgument>::get())
                {
                    //dispparams.rgdispidNamedArgs contains the mapping from index
                    //of named args list to index of parameter list
                    realParamIndex = dispparams.rgdispidNamedArgs[revParamIndex];
                }

                // no named arg, always come before named args
                if (! (aFuncDesc->lprgelemdescParam[realParamIndex].paramdesc.wParamFlags
                       & PARAMFLAG_FOUT))
                    continue;
                Any outAny;
                // variantToAny is called with the "reduce range" parameter set to sal_False.
                // That causes VT_I4 values not to be converted down to a "lower" type. That
                // feature exist for JScript only because it only uses VT_I4 for integer types.
                try
                {
                    variantToAny( & arRefArgs[revParamIndex], outAny, sal_False );
                }
                catch (IllegalArgumentException & e)
                {
                    e.ArgumentPosition = (sal_Int16)paramIndex;
                    throw;
                }
                catch (CannotConvertException & e)
                {
                    e.ArgumentIndex = paramIndex;
                    throw;
                }
                OutParam[outParamIndex] = outAny;
                OutParamIndex[outParamIndex] = ::sal::static_int_cast< sal_Int16, int >( paramIndex );
                outParamIndex++;
            }
            OutParam.realloc(outParamIndex);
            OutParamIndex.realloc(outParamIndex);
        }
        // Return value
        variantToAny(&varResult, ret, sal_False);
    }

    // map error codes to exceptions
    OUString message;
    switch (result)
    {
        case S_OK:
            break;
        case DISP_E_BADPARAMCOUNT:
            throw IllegalArgumentException("[automation bridge] Wrong "
                  "number of arguments. Object returned DISP_E_BADPARAMCOUNT.",
                  0, 0);
            break;
        case DISP_E_BADVARTYPE:
            throw RuntimeException("[automation bridge] One or more "
                  "arguments have the wrong type. Object returned "
                  "DISP_E_BADVARTYPE.", 0);
            break;
        case DISP_E_EXCEPTION:
                message = "[automation bridge]: ";
                message += OUString(reinterpret_cast<const sal_Unicode*>(excepinfo.bstrDescription),
                                    ::SysStringLen(excepinfo.bstrDescription));

                throw InvocationTargetException(message, Reference<XInterface>(), Any());
            break;
        case DISP_E_MEMBERNOTFOUND:
            message = "[automation bridge]: A function with the name \""
                + sFuncName + "\" is not supported. Object returned "
                "DISP_E_MEMBERNOTFOUND.";
            throw IllegalArgumentException(message, 0, 0);
            break;
        case DISP_E_NONAMEDARGS:
            throw IllegalArgumentException("[automation bridge] Object "
                  "returned DISP_E_NONAMEDARGS",0, ::sal::static_int_cast< sal_Int16, unsigned int >( uArgErr ));
            break;
        case DISP_E_OVERFLOW:
            throw CannotConvertException("[automation bridge] Call failed.",
                                         static_cast<XInterface*>(
                static_cast<XWeak*>(this)), TypeClass_UNKNOWN, FailReason::OUT_OF_RANGE, uArgErr);
            break;
        case DISP_E_PARAMNOTFOUND:
            throw IllegalArgumentException("[automation bridge]Call failed."
                                           "Object returned DISP_E_PARAMNOTFOUND.",
                                           0, ::sal::static_int_cast< sal_Int16, unsigned int >( uArgErr ));
            break;
        case DISP_E_TYPEMISMATCH:
            throw CannotConvertException("[automation bridge] Call  failed. "
                                         "Object returned DISP_E_TYPEMISMATCH",
                static_cast<XInterface*>(
                static_cast<XWeak*>(this)) , TypeClass_UNKNOWN, FailReason::UNKNOWN, uArgErr);
            break;
        case DISP_E_UNKNOWNINTERFACE:
            throw RuntimeException("[automation bridge] Call failed. "
                                       "Object returned DISP_E_UNKNOWNINTERFACE.",0);
            break;
        case DISP_E_UNKNOWNLCID:
            throw RuntimeException("[automation bridge] Call failed. "
                                       "Object returned DISP_E_UNKNOWNLCID.",0);
            break;
        case DISP_E_PARAMNOTOPTIONAL:
            throw CannotConvertException("[automation bridge] Call failed."
                  "Object returned DISP_E_PARAMNOTOPTIONAL",
                        static_cast<XInterface*>(static_cast<XWeak*>(this)),
                              TypeClass_UNKNOWN, FailReason::NO_DEFAULT_AVAILABLE, uArgErr);
            break;
        default:
            throw RuntimeException();
            break;
    }

    return ret;
}

void IUnknownWrapper_Impl::getFuncDescForInvoke(const OUString & sFuncName,
                                                const Sequence<Any> & seqArgs,
                                                FUNCDESC** pFuncDesc)
{
    int nUnoArgs = seqArgs.getLength();
    const Any * arArgs = seqArgs.getConstArray();
    ITypeInfo* pInfo = getTypeInfo();

    //If the last of the positional arguments is a PropertyPutArgument
    //then obtain the type info for the property put operation.

    //The property value is always the last argument, in a positional argument list
    //or in a list of named arguments. A PropertyPutArgument is actually a named argument
    //hence it must not be put in an extra NamedArgument structure
    if (nUnoArgs > 0 &&
        arArgs[nUnoArgs - 1].getValueType() == cppu::UnoType<PropertyPutArgument>::get())
    {
        // DISPATCH_PROPERTYPUT
        FuncDesc aDescGet(pInfo);
        FuncDesc aDescPut(pInfo);
        VarDesc aVarDesc(pInfo);
        getPropDesc(sFuncName, & aDescGet, & aDescPut, & aVarDesc);
        if ( ! aDescPut)
        {
            throw IllegalArgumentException(
                "[automation bridge] The object does not have a writeable property: "
                + sFuncName, Reference<XInterface>(), 0);
        }
        *pFuncDesc = aDescPut.Detach();
    }
    else
    {   // DISPATCH_METHOD
        FuncDesc aFuncDesc(pInfo);
        getFuncDesc(sFuncName, & aFuncDesc);
        if ( ! aFuncDesc)
        {
            // Fallback: DISPATCH_PROPERTYGET can mostly be called as
            // DISPATCH_METHOD
            ITypeInfo * pTypeInfo = getTypeInfo();
            FuncDesc aDescPut(pTypeInfo);
            VarDesc aVarDesc(pTypeInfo);
            getPropDesc(sFuncName, & aFuncDesc, & aDescPut, & aVarDesc);
            if ( ! aFuncDesc )
            {
                throw IllegalArgumentException(
                    "[automation bridge] The object does not have a function"
                    "or readable property \""
                    + sFuncName, Reference<XInterface>(), 0);
            }
        }
        *pFuncDesc = aFuncDesc.Detach();
    }
}
bool IUnknownWrapper_Impl::getDispid(const OUString& sFuncName, DISPID * id)
{
    OSL_ASSERT(m_spDispatch);
    LPOLESTR lpsz = const_cast<LPOLESTR> (reinterpret_cast<LPCOLESTR>(sFuncName.getStr()));
    HRESULT hr = m_spDispatch->GetIDsOfNames(IID_NULL, &lpsz, 1, LOCALE_USER_DEFAULT, id);
    return hr == S_OK;
}
void IUnknownWrapper_Impl::getFuncDesc(const OUString & sFuncName, FUNCDESC ** pFuncDesc)

{
    OSL_ASSERT( * pFuncDesc == 0);
    buildComTlbIndex();
    typedef TLBFuncIndexMap::const_iterator cit;
    //We assume there is only one entry with the function name. A property
    //would have two entries.
    cit itIndex= m_mapComFunc.find(sFuncName);
    if (itIndex == m_mapComFunc.end())
    {
        //try case insensive with IDispatch::GetIDsOfNames
        DISPID id;
        if (getDispid(sFuncName, &id))
        {
            CComBSTR memberName;
            unsigned int pcNames=0;
            // get the case sensitive name
            if( SUCCEEDED(getTypeInfo()->GetNames( id, & memberName, 1, &pcNames)))
            {
                //get the associated index and add an entry to the map
                //with the name sFuncName which differs in the casing of the letters to
                //the actual name as obtained from ITypeInfo
                OUString sRealName(reinterpret_cast<const sal_Unicode*>(LPCOLESTR(memberName)));
                cit itOrg  = m_mapComFunc.find(sRealName);
                OSL_ASSERT(itOrg != m_mapComFunc.end());
                // maybe this is a property, if so we need
                // to store either both id's ( put/get ) or
                // just the get. Storing both is more consistent
                pair<cit, cit> pItems = m_mapComFunc.equal_range( sRealName );
                for ( ;pItems.first != pItems.second; ++pItems.first )
                    m_mapComFunc.insert( TLBFuncIndexMap::value_type ( make_pair(sFuncName, pItems.first->second ) ));
                itIndex =
                    m_mapComFunc.find( sFuncName );
            }
        }
    }

#if OSL_DEBUG_LEVEL >= 1
    // There must only be one entry if sFuncName represents a function or two
    // if it is a property
    pair<cit, cit> p = m_mapComFunc.equal_range(sFuncName.toAsciiLowerCase());
    int numEntries = 0;
    for ( ;p.first != p.second; p.first ++, numEntries ++);
    OSL_ASSERT( ! (numEntries > 3) );
#endif
    if( itIndex != m_mapComFunc.end())
    {
        ITypeInfo* pType= getTypeInfo();
        FUNCDESC * pDesc = NULL;
        if (SUCCEEDED(pType->GetFuncDesc(itIndex->second, & pDesc)))
        {
            if (pDesc->invkind == INVOKE_FUNC)
            {
                (*pFuncDesc) = pDesc;
            }
            else
            {
                pType->ReleaseFuncDesc(pDesc);
            }
        }
        else
        {
            throw BridgeRuntimeError("[automation bridge] Could not get "
                                     "FUNCDESC for " + sFuncName);
        }
    }
   //else no entry found for sFuncName, pFuncDesc will not be filled in
}

void IUnknownWrapper_Impl::getPropDesc(const OUString & sFuncName, FUNCDESC ** pFuncDescGet,
                                       FUNCDESC** pFuncDescPut, VARDESC** pVarDesc)
{
    OSL_ASSERT( * pFuncDescGet == 0 && * pFuncDescPut == 0);
    buildComTlbIndex();
    typedef TLBFuncIndexMap::const_iterator cit;
    pair<cit, cit> p = m_mapComFunc.equal_range(sFuncName);
    if (p.first == m_mapComFunc.end())
    {
        //try case insensive with IDispatch::GetIDsOfNames
        DISPID id;
        if (getDispid(sFuncName, &id))
        {
            CComBSTR memberName;
            unsigned int pcNames=0;
            // get the case sensitive name
            if( SUCCEEDED(getTypeInfo()->GetNames( id, & memberName, 1, &pcNames)))
            {
                //As opposed to getFuncDesc, we do not add the value because we would
                // need to find the get and set description for the property. This would
                //mean to iterate over all FUNCDESCs again.
                p = m_mapComFunc.equal_range(OUString(reinterpret_cast<const sal_Unicode*>(LPCOLESTR(memberName))));
            }
        }
    }

    for ( int i = 0 ;p.first != p.second; p.first ++, i ++)
    {
        // There are a maximum of two entries, property put and property get
        OSL_ASSERT( ! (i > 2) );
        ITypeInfo* pType= getTypeInfo();
        FUNCDESC * pFuncDesc = NULL;
        if (SUCCEEDED( pType->GetFuncDesc(p.first->second, & pFuncDesc)))
        {
            if (pFuncDesc->invkind == INVOKE_PROPERTYGET)
            {
                (*pFuncDescGet) = pFuncDesc;
            }
            else if (pFuncDesc->invkind == INVOKE_PROPERTYPUT ||
                     pFuncDesc->invkind == INVOKE_PROPERTYPUTREF)
            {
                //a property can have 3 entries, put, put ref, get
                // If INVOKE_PROPERTYPUTREF or INVOKE_PROPERTYPUT is used
                //depends on what is found first.
                if ( * pFuncDescPut)
                {
                    //we already have found one
                    pType->ReleaseFuncDesc(pFuncDesc);
                }
                else
                {
                    (*pFuncDescPut) = pFuncDesc;
                }
            }
            else
            {
                pType->ReleaseFuncDesc(pFuncDesc);
            }
        }
        //ITypeInfo::GetFuncDesc may even provide a funcdesc for a VARDESC
        // with invkind = INVOKE_FUNC. Since this function should only return
        //a value for a real property (XInvokation::hasMethod, ..::hasProperty
        //we need to make sure that sFuncName represents a real property.
        VARDESC * pVD = NULL;
        if (SUCCEEDED(pType->GetVarDesc(p.first->second, & pVD)))
            (*pVarDesc) = pVD;
    }
   //else no entry for sFuncName, pFuncDesc will not be filled in
}

VARTYPE IUnknownWrapper_Impl::getUserDefinedElementType( ITypeInfo* pTypeInfo, const DWORD nHrefType )
{
    VARTYPE _type( VT_NULL );
    if ( pTypeInfo )
    {
        CComPtr<ITypeInfo> spRefInfo;
        pTypeInfo->GetRefTypeInfo( nHrefType, &spRefInfo.p );
        if ( spRefInfo )
        {
            TypeAttr attr( spRefInfo );
            spRefInfo->GetTypeAttr( &attr );
            if ( attr->typekind == TKIND_ENUM )
            {
                // We use the type of the first enum value.
                if ( attr->cVars == 0 )
                {
                    throw BridgeRuntimeError("[automation bridge] Could not obtain type description");
                }
                VarDesc var( spRefInfo );
                spRefInfo->GetVarDesc( 0, &var );
                _type = var->lpvarValue->vt;
            }
            else if ( attr->typekind == TKIND_INTERFACE )
            {
                _type = VT_UNKNOWN;
            }
            else if ( attr->typekind == TKIND_DISPATCH )
            {
                _type = VT_DISPATCH;
            }
            else if ( attr->typekind == TKIND_ALIAS )
            {
                // TKIND_ALIAS is a type that is an alias for another type. So get that alias type.
                _type = getUserDefinedElementType( pTypeInfo, attr->tdescAlias.hreftype );
            }
            else
            {
                throw BridgeRuntimeError( "[automation bridge] Unhandled user defined type." );
            }
        }
    }
    return _type;
}

VARTYPE IUnknownWrapper_Impl::getElementTypeDesc(const TYPEDESC *desc)
{
    VARTYPE _type( VT_NULL );

    if (desc->vt == VT_PTR)
    {
        _type = getElementTypeDesc(desc->lptdesc);
        _type |= VT_BYREF;
    }
    else if (desc->vt == VT_SAFEARRAY)
    {
        _type = getElementTypeDesc(desc->lptdesc);
        _type |= VT_ARRAY;
    }
    else if (desc->vt == VT_USERDEFINED)
    {
        ITypeInfo* thisInfo = getTypeInfo(); //kept by this instance
        _type = getUserDefinedElementType( thisInfo, desc->hreftype );
    }
    else
    {
        _type = desc->vt;
    }
    return _type;
}

void IUnknownWrapper_Impl::buildComTlbIndex()
{
    if ( ! m_bComTlbIndexInit)
    {
        MutexGuard guard(getBridgeMutex());
        {
            if ( ! m_bComTlbIndexInit)
            {
                OUString sError;
                ITypeInfo* pType= getTypeInfo();
                TypeAttr typeAttr(pType);
                if( SUCCEEDED( pType->GetTypeAttr( &typeAttr)))
                {
                    for( long i= 0; i < typeAttr->cFuncs; i++)
                    {
                        FuncDesc funcDesc(pType);
                        if( SUCCEEDED( pType->GetFuncDesc( i, &funcDesc)))
                        {
                            CComBSTR memberName;
                            unsigned int pcNames=0;
                            if( SUCCEEDED(pType->GetNames( funcDesc->memid, & memberName, 1, &pcNames)))
                            {
                                OUString usName(reinterpret_cast<const sal_Unicode*>(LPCOLESTR(memberName)));
                                m_mapComFunc.insert( TLBFuncIndexMap::value_type( usName, i));
                            }
                            else
                            {
                                sError = "[automation bridge] IUnknownWrapper_Impl::buildComTlbIndex, "
                                         "ITypeInfo::GetNames failed.";
                            }
                        }
                        else
                            sError = "[automation bridge] IUnknownWrapper_Impl::buildComTlbIndex, "
                                     "ITypeInfo::GetFuncDesc failed.";
                    }

                    //If we create an Object in JScript and a property then it
                    //has VARDESC instead of FUNCDESC
                    for (long i = 0; i < typeAttr->cVars; i++)
                    {
                        VarDesc varDesc(pType);
                        if (SUCCEEDED(pType->GetVarDesc(i, & varDesc)))
                        {
                            CComBSTR memberName;
                            unsigned int pcNames = 0;
                            if (SUCCEEDED(pType->GetNames(varDesc->memid, & memberName, 1, &pcNames)))
                            {
                                if (varDesc->varkind == VAR_DISPATCH)
                                {
                                    OUString usName(reinterpret_cast<const sal_Unicode*>(LPCOLESTR(memberName)));
                                    m_mapComFunc.insert(TLBFuncIndexMap::value_type(
                                                        usName, i));
                                }
                            }
                            else
                            {
                                sError = "[automation bridge] IUnknownWrapper_Impl::buildComTlbIndex, "
                                         "ITypeInfo::GetNames failed.";
                            }
                        }
                        else
                            sError = "[automation bridge] IUnknownWrapper_Impl::buildComTlbIndex, "
                                     "ITypeInfo::GetVarDesc failed.";

                    }
                }
                else
                    sError = "[automation bridge] IUnknownWrapper_Impl::buildComTlbIndex, "
                             "ITypeInfo::GetTypeAttr failed.";

                if (sError.getLength())
                {
                    throw BridgeRuntimeError(sError);
                }

                m_bComTlbIndexInit = true;
            }
        }
    }
}

ITypeInfo* IUnknownWrapper_Impl::getTypeInfo()
{
    if( !m_spDispatch)
    {
        throw BridgeRuntimeError("The object has no IDispatch interface!");
    }

    if( !m_spTypeInfo )
    {
        MutexGuard guard(getBridgeMutex());
        if( ! m_spTypeInfo)
        {
            CComPtr< ITypeInfo > spType;
            if( SUCCEEDED( m_spDispatch->GetTypeInfo( 0, LOCALE_USER_DEFAULT, &spType.p)))

            {
                OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();

                //If this is a dual interface then TYPEATTR::typekind is usually TKIND_INTERFACE
                //We need to get the type description for TKIND_DISPATCH
                TypeAttr typeAttr(spType.p);
                if( SUCCEEDED(spType->GetTypeAttr( &typeAttr)))
                {
                    if (typeAttr->typekind == TKIND_INTERFACE &&
                            typeAttr->wTypeFlags & TYPEFLAG_FDUAL)
                    {
                        HREFTYPE refDispatch;
                        if (SUCCEEDED(spType->GetRefTypeOfImplType(::sal::static_int_cast< UINT, int >( -1 ), &refDispatch)))
                        {
                            CComPtr<ITypeInfo> spTypeDisp;
                            if (SUCCEEDED(spType->GetRefTypeInfo(refDispatch, & spTypeDisp)))
                                m_spTypeInfo= spTypeDisp;
                        }
                        else
                        {
                            throw BridgeRuntimeError(
                                "[automation bridge] Could not obtain type information "
                                "for dispatch interface." );
                        }
                    }
                    else if (typeAttr->typekind == TKIND_DISPATCH)
                    {
                        m_spTypeInfo= spType;
                    }
                    else
                    {
                        throw BridgeRuntimeError(
                            "[automation bridge] Automation object does not "
                            "provide type information.");
                    }
                }
            }
            else
            {
                throw BridgeRuntimeError("[automation bridge]The dispatch object does not "
                                         "support ITypeInfo!");
            }
        }
    }
    return m_spTypeInfo;
}

} // end namespace

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */