bump product version to 4.1.6.2
[LibreOffice.git] / extensions / source / ole / unoconversionutilities.hxx
bloba77fbf6b777eb6a756b9d96874fdb9f3467395c1
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
19 #ifndef _UNO_CONVERSION_UTILITIES
20 #define _UNO_CONVERSION_UTILITIES
22 #include "boost/scoped_array.hpp"
23 #include "com/sun/star/script/XInvocationAdapterFactory.hpp"
24 #include "com/sun/star/script/XInvocationAdapterFactory2.hpp"
25 #include "com/sun/star/script/XTypeConverter.hpp"
26 #include "com/sun/star/script/FailReason.hpp"
27 #include "com/sun/star/bridge/oleautomation/Date.hpp"
28 #include "com/sun/star/bridge/oleautomation/Currency.hpp"
29 #include "com/sun/star/bridge/oleautomation/SCode.hpp"
30 #include "com/sun/star/bridge/oleautomation/Decimal.hpp"
31 #include "typelib/typedescription.hxx"
32 #include "ole2uno.hxx"
34 #include "unotypewrapper.hxx"
35 #include <boost/unordered_map.hpp>
37 // for some reason DECIMAL_NEG (wtypes.h) which contains BYTE is not resolved.
38 typedef unsigned char BYTE;
39 // classes for wrapping uno objects
40 #define INTERFACE_OLE_WRAPPER_IMPL 1
41 #define UNO_OBJECT_WRAPPER_REMOTE_OPT 2
43 #define INVOCATION_SERVICE reinterpret_cast<const sal_Unicode*>(L"com.sun.star.script.Invocation")
46 // classes for wrapping ole objects
47 #define IUNKNOWN_WRAPPER_IMPL 1
49 #define INTERFACE_ADAPTER_FACTORY reinterpret_cast<const sal_Unicode*>(L"com.sun.star.script.InvocationAdapterFactory")
50 // COM or JScript objects implementing UNO interfaces have to implement this property
51 #define SUPPORTED_INTERFACES_PROP L"_implementedInterfaces"
52 // Second property without leading underscore for use in VB
53 #define SUPPORTED_INTERFACES_PROP2 L"Bridge_ImplementedInterfaces"
55 using namespace com::sun::star::script;
56 using namespace com::sun::star::beans;
57 using namespace com::sun::star::uno;
58 #ifdef __MINGW32__
59 using namespace com::sun::star::bridge;
60 using namespace com::sun::star::bridge::ModelDependent;
61 #endif
62 using namespace com::sun::star::bridge::oleautomation;
63 using namespace boost;
64 namespace ole_adapter
66 extern boost::unordered_map<sal_uInt32, sal_uInt32> AdapterToWrapperMap;
67 extern boost::unordered_map<sal_uInt32, sal_uInt32> WrapperToAdapterMap;
68 typedef boost::unordered_map<sal_uInt32, sal_uInt32>::iterator IT_Wrap;
69 typedef boost::unordered_map<sal_uInt32, sal_uInt32>::iterator CIT_Wrap;
70 //Maps IUnknown pointers to a weak reference of the respective wrapper class (e.g.
71 // IUnknownWrapperImpl. It is the responsibility of the wrapper to remove the entry when
72 // it is being destroyed.
73 // Used to ensure that an Automation object is always mapped to the same UNO objects.
74 extern boost::unordered_map<sal_uInt32, WeakReference<XInterface> > ComPtrToWrapperMap;
75 typedef boost::unordered_map<sal_uInt32, WeakReference<XInterface> >::iterator IT_Com;
76 typedef boost::unordered_map<sal_uInt32, WeakReference<XInterface> >::const_iterator CIT_Com;
78 // Maps XInterface pointers to a weak reference of its wrapper class (i.e.
79 // InterfaceOleWrapper_Impl). It is the responsibility of the wrapper to remove the entry when
80 // it is being destroyed. It is used to ensure the identity of objects. That is, an UNO interface
81 // is mapped to IDispatch which is kept alive in the COM environment. If the same
82 // UNO interface is mapped again to COM then the IDispach of the first mapped instance
83 // must be returned.
84 extern boost::unordered_map<sal_uInt32, WeakReference<XInterface> > UnoObjToWrapperMap;
85 typedef boost::unordered_map<sal_uInt32, WeakReference<XInterface> >::iterator IT_Uno;
86 typedef boost::unordered_map<sal_uInt32, WeakReference<XInterface> >::const_iterator CIT_Uno;
87 #ifdef __MINGW32__
88 inline void reduceRange( Any& any);
89 #endif
94 // createUnoObjectWrapper gets a wrapper instance by calling createUnoWrapperInstance
95 // and initializes it via XInitialization. The wrapper object is required to implement
96 // XBridgeSupplier so that it can convert itself to IDispatch.
97 // class T: Deriving class ( must implement XInterface )
98 /** All methods are allowed to throw at least a BridgeRuntimeError.
100 template< class >
101 class UnoConversionUtilities
103 public:
104 UnoConversionUtilities( const Reference<XMultiServiceFactory> & smgr):
105 m_nUnoWrapperClass( INTERFACE_OLE_WRAPPER_IMPL),
106 m_nComWrapperClass( IUNKNOWN_WRAPPER_IMPL),
107 m_smgr( smgr)
110 UnoConversionUtilities( const Reference<XMultiServiceFactory> & xFactory, sal_uInt8 unoWrapperClass, sal_uInt8 comWrapperClass )
111 : m_smgr( xFactory), m_nComWrapperClass( comWrapperClass), m_nUnoWrapperClass( unoWrapperClass)
114 virtual ~UnoConversionUtilities() {}
115 /** converts only into oleautomation types, that is there is no VT_I1, VT_UI2, VT_UI4
116 a sal_Unicode character is converted into a BSTR.
117 @exception com.sun.star.lang.IllegalArgumentException
118 If the any was inappropriate for conversion.
119 @exception com.sun.star.script.CannotConvertException
120 The any contains a type class for which no conversion is provided.
122 void anyToVariant(VARIANT* pVariant, const Any& rAny);
123 void anyToVariant(VARIANT* pVariant, const Any& rAny, VARTYPE type);
125 /** @exception com.sun.star.lang.IllegalArgumentException
126 If rSeq does not contain a sequence then the exception is thrown.
128 SAFEARRAY* createUnoSequenceWrapper(const Any& rSeq);
129 /** @exception com.sun.star.lang.IllegalArgumentException
130 If rSeq does not contain a sequence or elemtype has no proper value
131 then the exception is thrown.
133 SAFEARRAY* createUnoSequenceWrapper(const Any& rSeq, VARTYPE elemtype);
135 @exception com.sun.star.lang.IllegalArgumentException
136 If rObj does not contain a struct or interface
138 void createUnoObjectWrapper(const Any & rObj, VARIANT * pVar);
139 /** @exception CannotConvertException
140 Thrown if the VARIANT contains a type that cannot be coerced in the expected Any.
141 ArgumentIndex is 0.
142 @IllegalArgumentException
143 Thrown if the VARIANT is inappropriate for conversion. ArgumentPosition is -1,
145 void variantToAny(const VARIANT* pVariant, Any& rAny, sal_Bool bReduceValueRange = sal_True);
146 /** This method converts variants arguments in calls from COM -> UNO. Only then
147 the expected UNO type is known.
148 @exception CannotConvertException
149 Thrown if the VARIANT contains a type that cannot be coerced in the expected Any.
150 ArgumentIndex is 0.
151 @IllegalArgumentException
152 Thrown if the VARIANT is inappropriate for conversion. ArgumentPosition is -1,
154 void variantToAny( const VARIANTARG* pArg, Any& rAny, const Type& ptype, sal_Bool bReduceValueRange = sal_True);
157 @exception IllegalArgumentException
158 -if pVar does not contain VT_UNKNOWN or VT_DISPATCH or
159 pVar is used for a particular UNO type which is not supported by pVar
161 Any createOleObjectWrapper(VARIANT* pVar, const Type& aType= Type());
164 Return true means var contained a ValueObject, and it was successfully converted.
165 The result is in any. It an error occurred a BridgeRuntimeError will be thrown.
167 bool convertValueObject( const VARIANTARG *var, Any& any);
168 void dispatchExObject2Sequence( const VARIANTARG* pvar, Any& anySeq, const Type& type);
170 Sequence<Any> createOleArrayWrapperOfDim(SAFEARRAY* pArray, unsigned int dimCount, unsigned int actDim, long* index,
171 VARTYPE type, const Type& unotype);
172 Sequence<Any> createOleArrayWrapper(SAFEARRAY* pArray, VARTYPE type, const Type& unotype= Type());
175 VARTYPE mapTypeClassToVartype( TypeClass type);
176 Reference< XSingleServiceFactory > getInvocationFactory(const Any& anyObject);
179 virtual Reference< XInterface > createUnoWrapperInstance()=0;
180 virtual Reference< XInterface > createComWrapperInstance()=0;
182 static sal_Bool isJScriptArray(const VARIANT* pvar);
184 Sequence<Type> getImplementedInterfaces(IUnknown* pUnk);
186 protected:
187 Reference<XInterface> createAdapter(const Sequence<Type>& types, const Reference<XInterface>& receiver);
189 // helper function for Sequence conversion
190 void getElementCountAndTypeOfSequence( const Any& rSeq, sal_Int32 dim, Sequence< sal_Int32 >& seqElementCounts, TypeDescription& typeDesc);
191 // helper function for Sequence conversion
192 sal_Bool incrementMultidimensionalIndex(sal_Int32 dimensions, const sal_Int32 * parDimensionLength,
193 sal_Int32 * parMultidimensionalIndex);
194 // helper function for Sequence conversion
195 size_t getOleElementSize( VARTYPE type);
197 Type getElementTypeOfSequence( const Type& seqType);
199 //Provides a typeconverter
200 Reference<XTypeConverter> getTypeConverter();
202 // This member determines what class is used to convert a UNO object
203 // or struct to a COM object. It is passed along to the o2u_anyToVariant
204 // function in the createBridge function implementation
205 sal_uInt8 m_nUnoWrapperClass;
206 sal_uInt8 m_nComWrapperClass;
208 // The servicemanager is either a local smgr or remote when the service
209 // com.sun.star.bridge.OleBridgeSupplierVar1 is used. This service can be
210 // created by createInstanceWithArguments where one can supply a service
211 // manager that is to be used.
212 // Local service manager as supplied by the loader when the creator function
213 // of the service is being called.
214 Reference<XMultiServiceFactory> m_smgr;
215 // An explicitly supplied service manager when the service
216 // com.sun.star.bridge.OleBridgeSupplierVar1 is used. That can be a remote
217 // manager.
218 Reference<XMultiServiceFactory> m_smgrRemote;
219 Reference<XSingleServiceFactory> m_xInvocationFactoryLocal;
220 Reference<XSingleServiceFactory> m_xInvocationFactoryRemote;
222 private:
223 // Holds the type converter which is used for sequence conversion etc.
224 // Use the getTypeConverter function to obtain the interface.
225 Reference<XTypeConverter> m_typeConverter;
230 // ask the object for XBridgeSupplier2 and on success bridges
231 // the uno object to IUnknown or IDispatch.
232 // return true the UNO object supports
233 template < class T >
234 bool convertSelfToCom( T& unoInterface, VARIANT * pVar)
236 bool ret = false;
237 Reference< XInterface > xInt( unoInterface, UNO_QUERY);
238 if( xInt.is())
240 Reference< XBridgeSupplier2 > xSupplier( xInt, UNO_QUERY);
241 if( xSupplier.is())
243 sal_Int8 arId[16];
244 rtl_getGlobalProcessId( (sal_uInt8*)arId);
245 Sequence<sal_Int8> seqId( arId, 16);
246 Any anySource;
247 anySource <<= xInt;
248 Any anyDisp= xSupplier->createBridge( anySource, seqId, UNO, OLE);
249 if( anyDisp.getValueTypeClass() == TypeClass_UNSIGNED_LONG)
251 VARIANT* pvariant= *(VARIANT**)anyDisp.getValue();
252 HRESULT hr;
253 if (FAILED(hr = VariantCopy(pVar, pvariant)))
254 throw BridgeRuntimeError(
255 "[automation bridge] convertSelfToCom\n"
256 "VariantCopy failed! Error: " +
257 OUString::valueOf(hr));
258 VariantClear( pvariant);
259 CoTaskMemFree( pvariant);
260 ret = true;
264 return ret;
269 // Gets the invocation factory depending on the Type in the Any.
270 // The factory can be created by a local or remote multi service factory.
271 // In case there is a remote multi service factory available there are
272 // some services or types for which the local factory is used. The exceptions
273 // are: all structs.
274 // Param anyObject - contains the object ( interface, struct) for what we need an invocation object.
276 template<class T>
277 Reference< XSingleServiceFactory > UnoConversionUtilities<T>::getInvocationFactory(const Any& anyObject)
279 Reference< XSingleServiceFactory > retVal;
280 MutexGuard guard( getBridgeMutex());
281 if( anyObject.getValueTypeClass() != TypeClass_STRUCT &&
282 m_smgrRemote.is() )
284 if( ! m_xInvocationFactoryRemote.is() )
285 m_xInvocationFactoryRemote= Reference<XSingleServiceFactory>(
286 m_smgrRemote->createInstance( INVOCATION_SERVICE), UNO_QUERY);
287 retVal= m_xInvocationFactoryRemote;
289 else
291 if( ! m_xInvocationFactoryLocal.is() )
292 m_xInvocationFactoryLocal= Reference<XSingleServiceFactory>(
293 m_smgr->createInstance(INVOCATION_SERVICE ), UNO_QUERY);
294 retVal= m_xInvocationFactoryLocal;
296 return retVal;
299 template<class T>
300 void UnoConversionUtilities<T>::variantToAny( const VARIANTARG* pArg, Any& rAny, const Type& ptype, sal_Bool bReduceValueRange /* = sal_True */)
304 HRESULT hr;
305 bool bFail = false;
306 bool bCannotConvert = false;
307 CComVariant var;
309 // There is no need to support indirect values, since they're not supported by UNO
310 if( FAILED(hr= VariantCopyInd( &var, const_cast<VARIANTARG*>(pArg)))) // remove VT_BYREF
311 throw BridgeRuntimeError(
312 "[automation bridge] UnoConversionUtilities<T>::variantToAny \n"
313 "VariantCopyInd failed for reason : " + OUString::valueOf(hr));
314 bool bHandled = convertValueObject( & var, rAny);
315 if( bHandled)
316 OSL_ENSURE( rAny.getValueType() == ptype, "type in Value Object must match the type parameter");
318 if( ! bHandled)
320 // convert into a variant type that is the equivalent to the type
321 // the sequence expects. Thus variantToAny produces the correct type
322 // E.g. An Array object contains VT_I4 and the sequence expects shorts
323 // than the vartype must be changed. The reason is, you can't specify the
324 // type in JavaScript and the script engine determines the type beeing used.
325 switch( ptype.getTypeClass())
327 case TypeClass_CHAR: // could be: new Array( 12, 'w', "w")
328 if( var.vt == VT_BSTR)
330 if(SUCCEEDED( hr= VariantChangeType( &var, &var, 0, VT_BSTR)))
331 rAny.setValue( (void*)V_BSTR( &var), ptype);
332 else if (hr == DISP_E_TYPEMISMATCH)
333 bCannotConvert = true;
334 else
335 bFail = true;
337 else
339 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_I2)))
340 rAny.setValue((void*) & var.iVal, ptype);
341 else if (hr == DISP_E_TYPEMISMATCH)
342 bCannotConvert = true;
343 else
344 bFail = true;
346 break;
347 case TypeClass_INTERFACE: // could also be an IUnknown
348 case TypeClass_STRUCT:
350 rAny = createOleObjectWrapper( & var, ptype);
351 break;
353 case TypeClass_ENUM:
354 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_I4)))
355 rAny.setValue((void*) & var.lVal, ptype);
356 else if (hr == DISP_E_TYPEMISMATCH)
357 bCannotConvert = true;
358 else
359 bFail = true;
360 break;
361 case TypeClass_SEQUENCE:
362 // There are different ways of receiving a sequence:
363 // 1: JScript, VARTYPE: VT_DISPATCH
364 // 2. VBScript simple arraysVT_VARIANT|VT_BYREF the referenced VARIANT contains
365 // a VT_ARRAY| <type>
366 // 3. VBSrcript multi dimensional arrays: VT_ARRAY|VT_BYREF
367 if( pArg->vt == VT_DISPATCH)
369 dispatchExObject2Sequence( pArg, rAny, ptype);
371 else
373 if ((var.vt & VT_ARRAY) != 0)
375 VARTYPE oleType = ::sal::static_int_cast< VARTYPE, int >( var.vt ^ VT_ARRAY );
376 Sequence<Any> unoSeq = createOleArrayWrapper( var.parray, oleType, ptype);
377 Reference<XTypeConverter> conv = getTypeConverter();
378 if (conv.is())
382 Any anySeq = makeAny(unoSeq);
383 Any convAny = conv->convertTo(anySeq, ptype);
384 rAny = convAny;
386 catch (const IllegalArgumentException& e)
388 throw BridgeRuntimeError(
389 "[automation bridge]com.sun.star.lang.IllegalArgumentException "
390 "in UnoConversionUtilities<T>::variantToAny! Message: " +
391 e.Message);
393 catch (const CannotConvertException& e)
395 throw BridgeRuntimeError(
396 "[automation bridge]com.sun.star.script.CannotConvertException "
397 "in UnoConversionUtilities<T>::variantToAny! Message: " +
398 e.Message);
403 break;
404 case TypeClass_VOID:
405 rAny.setValue(NULL,Type());
406 break;
407 case TypeClass_ANY: // Any
408 // There could be a JScript Array that needs special handling
409 // If an Any is expected and this Any must contain a Sequence
410 // then we cannot figure out what element type is required.
411 // Therefore we convert to Sequence< Any >
412 if( pArg->vt == VT_DISPATCH && isJScriptArray( pArg))
414 dispatchExObject2Sequence( pArg, rAny,
415 getCppuType((Sequence<Any>*) 0));
417 else if (pArg->vt == VT_DECIMAL)
419 //Decimal maps to hyper in calls from COM -> UNO
420 // It does not matter if we create a sal_uInt64 or sal_Int64,
421 // because the UNO object is called through invocation which
422 //will do a type conversion if necessary
423 if (var.decVal.sign == 0)
425 // positive value
426 variantToAny( & var, rAny, getCppuType( (sal_uInt64*) 0),
427 bReduceValueRange);
429 else
431 //negative value
432 variantToAny( & var, rAny, getCppuType( (sal_Int64*) 0),
433 bReduceValueRange);
436 else
438 variantToAny( & var, rAny);
440 break;
441 case TypeClass_BOOLEAN: // VARIANT could be VARIANT_BOOL or other
442 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_BOOL)))
443 variantToAny( & var, rAny);
444 else if (hr == DISP_E_TYPEMISMATCH)
445 bCannotConvert = true;
446 else
447 bFail = true;
448 break;
449 case TypeClass_STRING: // UString
450 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_BSTR)))
451 variantToAny( & var, rAny);
452 else if (hr == DISP_E_TYPEMISMATCH)
453 bCannotConvert = true;
454 else
455 bFail = true;
456 break;
457 case TypeClass_FLOAT: // float
458 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_R4)))
459 variantToAny( & var, rAny);
460 else if (hr == DISP_E_TYPEMISMATCH)
461 bCannotConvert = true;
462 else
463 bFail = true;
464 break;
465 case TypeClass_DOUBLE: // double
466 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_R8)))
467 variantToAny(& var, rAny);
468 else if (hr == DISP_E_TYPEMISMATCH)
469 bCannotConvert = true;
470 else
471 bFail = true;
472 break;
473 case TypeClass_BYTE: // BYTE
474 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_I1)))
475 variantToAny( & var, rAny);
476 else if (hr == DISP_E_TYPEMISMATCH)
477 bCannotConvert = true;
478 else
479 bFail = true;
480 break;
481 case TypeClass_SHORT: // INT16
482 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_I2)))
483 variantToAny( & var, rAny);
484 else if (hr == DISP_E_TYPEMISMATCH)
485 bCannotConvert = true;
486 else
487 bFail = true;
488 break;
489 case TypeClass_LONG:
490 if(SUCCEEDED(hr = VariantChangeType(& var, &var, 0, VT_I4)))
491 variantToAny( & var, rAny, bReduceValueRange);
492 else if (hr == DISP_E_TYPEMISMATCH)
493 bCannotConvert = true;
494 else
495 bFail = true;
496 break;
497 case TypeClass_HYPER:
498 if(SUCCEEDED(hr = VariantChangeType(& var, &var, 0, VT_DECIMAL)))
500 if (var.decVal.Lo64 > SAL_CONST_UINT64(0x8000000000000000)
501 || var.decVal.Hi32 > 0
502 || var.decVal.scale > 0)
504 bFail = true;
505 break;
507 sal_Int64 value = var.decVal.Lo64;
508 if (var.decVal.sign == DECIMAL_NEG)
509 value |= SAL_CONST_UINT64(0x8000000000000000);
510 rAny <<= value;
512 else if (hr == DISP_E_TYPEMISMATCH)
513 bCannotConvert = true;
514 else
515 bFail = true;
516 break;
517 case TypeClass_UNSIGNED_SHORT: // UINT16
518 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_UI2)))
519 variantToAny( & var, rAny);
520 else if (hr == DISP_E_TYPEMISMATCH)
521 bCannotConvert = true;
522 else
523 bFail = true;
524 break;
525 case TypeClass_UNSIGNED_LONG:
526 if(SUCCEEDED(hr = VariantChangeType( & var, &var, 0, VT_UI4)))
527 variantToAny( & var, rAny, bReduceValueRange);
528 else if (hr == DISP_E_TYPEMISMATCH)
529 bCannotConvert = true;
530 else
531 bFail = true;
532 break;
533 case TypeClass_UNSIGNED_HYPER:
534 if(SUCCEEDED(hr = VariantChangeType(& var, &var, 0, VT_DECIMAL)))
536 if (var.decVal.Hi32 > 0 || var.decVal.scale > 0)
538 bFail = true;
539 break;
541 rAny <<= var.decVal.Lo64;
543 else if (hr == DISP_E_TYPEMISMATCH)
544 bCannotConvert = true;
545 else
546 bFail = true;
547 break;
548 case TypeClass_TYPE:
549 if(SUCCEEDED(hr = VariantChangeType(& var, &var, 0, VT_UNKNOWN)))
550 variantToAny( & var, rAny);
551 else if (hr == DISP_E_TYPEMISMATCH)
552 bCannotConvert = true;
553 else
554 bFail = true;
555 break;
556 default:
557 bCannotConvert = true;
558 break;
561 if (bCannotConvert)
562 throw CannotConvertException(
563 "[automation bridge]UnoConversionUtilities<T>::variantToAny \n"
564 "Cannot convert the value of vartype :\"" +
565 OUString::valueOf((sal_Int32) var.vt) +
566 "\" to the expected UNO type of type class: " +
567 OUString::valueOf((sal_Int32) ptype.getTypeClass()),
568 0, TypeClass_UNKNOWN, FailReason::TYPE_NOT_SUPPORTED,0);
570 if (bFail)
571 throw IllegalArgumentException(
572 "[automation bridge]UnoConversionUtilities<T>:variantToAny\n"
573 "The provided VARIANT of type\" " + OUString::valueOf((sal_Int32) var.vt) +
574 "\" is unappropriate for conversion!", Reference<XInterface>(), -1);
576 catch (const CannotConvertException &)
578 throw;
580 catch (const IllegalArgumentException &)
582 throw;
584 catch (const BridgeRuntimeError &)
586 throw;
588 catch (const Exception & e)
590 throw BridgeRuntimeError("[automation bridge] unexpected exception in "
591 "UnoConversionUtilities<T>::variantToAny ! Message : \n" +
592 e.Message);
594 catch(...)
596 throw BridgeRuntimeError(
597 "[automation bridge] unexpected exception in "
598 "UnoConversionUtilities<T>::variantToAny !");
602 // The function only converts Sequences to SAFEARRAYS with elements of the type
603 // specified by the parameter type. Everything else is forwarded to
604 // anyToVariant(VARIANT* pVariant, const Any& rAny)
605 // Param type must not be VT_BYREF
606 template<class T>
607 void UnoConversionUtilities<T>::anyToVariant(VARIANT* pVariant, const Any& rAny, VARTYPE type)
611 HRESULT hr= S_OK;
613 OSL_ASSERT( (type & VT_BYREF) == 0);
614 if (type & VT_ARRAY)
616 type ^= VT_ARRAY;
617 SAFEARRAY* ar= createUnoSequenceWrapper( rAny, type);
618 if( ar)
620 VariantClear( pVariant);
621 pVariant->vt= ::sal::static_int_cast< VARTYPE, int >( VT_ARRAY | type );
622 pVariant->byref= ar;
625 else if(type == VT_VARIANT)
627 anyToVariant(pVariant, rAny);
629 else
631 CComVariant var;
632 anyToVariant( &var, rAny);
633 if(FAILED(hr = VariantChangeType(&var, &var, 0, type)))
635 if (hr == DISP_E_TYPEMISMATCH)
636 throw CannotConvertException(
637 "[automation bridge]UnoConversionUtilities<T>::anyToVariant \n"
638 "Cannot convert the value of type :\"" +
639 rAny.getValueTypeName() +
640 "\" to the expected Automation type of VARTYPE: " +
641 OUString::valueOf((sal_Int32)type),
642 0, TypeClass_UNKNOWN, FailReason::TYPE_NOT_SUPPORTED,0);
644 throw BridgeRuntimeError(
645 "[automation bridge]UnoConversionUtilities<T>::anyToVariant \n"
646 "Conversion of any with " +
647 rAny.getValueType().getTypeName() +
648 " to VARIANT with type: " + OUString::valueOf((sal_Int32) type) +
649 " failed! Error code: " + OUString::valueOf(hr));
652 if(FAILED(hr = VariantCopy(pVariant, &var)))
654 throw BridgeRuntimeError(
655 "[automation bridge]UnoConversionUtilities<T>::anyToVariant \n"
656 "VariantCopy failed for reason: " + OUString::valueOf(hr));
660 catch (const IllegalArgumentException &)
662 throw;
664 catch (const CannotConvertException &)
666 throw;
668 catch (const BridgeRuntimeError&)
670 throw;
672 catch(const Exception & e)
674 throw BridgeRuntimeError(
675 "[automation bridge]UnoConversionUtilities<T>::anyToVariant \n"
676 "Unexpected exception occurred. Message: " + e.Message);
678 catch(...)
680 throw BridgeRuntimeError(
681 "[automation bridge]UnoConversionUtilities<T>::anyToVariant \n"
682 "Unexpected exception occurred.");
686 template<class T>
687 void UnoConversionUtilities<T>::anyToVariant(VARIANT* pVariant, const Any& rAny)
689 bool bIllegal = false;
692 switch (rAny.getValueTypeClass())
694 case TypeClass_INTERFACE:
696 Reference<XInterface> xInt;
697 if (rAny >>= xInt)
699 createUnoObjectWrapper(rAny, pVariant);
701 else
703 bIllegal = true;
705 break;
707 case TypeClass_STRUCT:
709 if (rAny.getValueType() == getCppuType((Date*)0))
711 Date d;
712 if (rAny >>= d)
714 pVariant->vt = VT_DATE;
715 pVariant->date = d.Value;
717 else
719 bIllegal = true;
722 else if(rAny.getValueType() == getCppuType((Decimal*)0))
724 Decimal d;
725 if (rAny >>= d)
727 pVariant->vt = VT_DECIMAL;
728 pVariant->decVal.scale = d.Scale;
729 pVariant->decVal.sign = d.Sign;
730 pVariant->decVal.Lo32 = d.LowValue;
731 pVariant->decVal.Mid32 = d.MiddleValue;
732 pVariant->decVal.Hi32 = d.HighValue;
734 else
736 bIllegal = true;
739 else if (rAny.getValueType() == getCppuType((Currency*)0))
741 Currency c;
742 if (rAny >>= c)
744 pVariant->vt = VT_CY;
745 pVariant->cyVal.int64 = c.Value;
747 else
749 bIllegal = true;
752 else if(rAny.getValueType() == getCppuType((SCode*)0))
754 SCode s;
755 if (rAny >>= s)
757 pVariant->vt = VT_ERROR;
758 pVariant->scode = s.Value;
760 else
762 bIllegal = true;
765 else
767 createUnoObjectWrapper(rAny, pVariant);
769 break;
771 case TypeClass_SEQUENCE: // sequence ??? SafeArray descriptor
773 SAFEARRAY* pArray = createUnoSequenceWrapper(rAny);
774 if (pArray)
776 V_VT(pVariant) = VT_ARRAY | VT_VARIANT;
777 V_ARRAY(pVariant) = pArray;
779 else
781 bIllegal = true;
783 break;
785 case TypeClass_VOID:
787 HRESULT hr = S_OK;
788 if (FAILED(hr = VariantClear(pVariant)))
790 throw BridgeRuntimeError(
791 "[automation bridge]UnoConversionUtilities<T>::anyToVariant\n"
792 "VariantClear failed with error:" + OUString::valueOf(hr));
794 break;
796 case TypeClass_BOOLEAN:
798 sal_Bool value;
799 if (rAny >>= value)
801 pVariant->vt = VT_BOOL;
802 pVariant->boolVal = value == sal_True? VARIANT_TRUE: VARIANT_FALSE;
804 else
806 bIllegal = true;
808 break;
810 case TypeClass_CHAR:
812 // Because VT_UI2 does not conform to oleautomation we convert into VT_I2 instead
813 sal_uInt16 value = *(sal_Unicode*) rAny.getValue();
814 pVariant->vt = VT_I2;
815 pVariant->iVal = value;
816 break;
818 case TypeClass_STRING:
820 OUString value;
821 if (rAny >>= value)
823 pVariant->vt = VT_BSTR;
824 pVariant->bstrVal = SysAllocString(reinterpret_cast<LPCOLESTR>(value.getStr()));
826 else
828 bIllegal = true;
830 break;
832 case TypeClass_FLOAT:
834 float value;
835 if (rAny >>= value)
837 pVariant->vt = VT_R4;
838 pVariant->fltVal = value;
840 else
842 bIllegal = true;
844 break;
846 case TypeClass_DOUBLE:
848 double value;
849 if (rAny >>= value)
851 pVariant->vt = VT_R8;
852 pVariant->dblVal = value;
854 else
856 bIllegal = true;
858 break;
860 case TypeClass_BYTE:
862 // ole automation does not know a signed char but only unsigned char
863 sal_Int8 value;
864 if (rAny >>= value)
866 pVariant->vt = VT_UI1;
867 pVariant->bVal = value;
869 else
871 bIllegal = true;
873 break;
875 case TypeClass_SHORT: // INT16
876 case TypeClass_UNSIGNED_SHORT: // UINT16
878 sal_Int16 value;
879 if (rAny >>= value)
881 pVariant->vt = VT_I2;
882 pVariant->iVal = value;
884 else
886 bIllegal = true;
888 break;
890 case TypeClass_ENUM:
892 sal_Int32 value = *(sal_Int32*) rAny.getValue();
893 pVariant->vt = VT_I4;
894 pVariant->lVal= value;
895 break;
897 case TypeClass_LONG:
898 case TypeClass_UNSIGNED_LONG:
900 sal_Int32 value;
901 if (rAny >>= value)
903 pVariant->vt = VT_I4;
904 pVariant->lVal= value;
906 else
908 bIllegal = true;
910 break;
912 case TypeClass_HYPER:
915 pVariant->vt = VT_DECIMAL;
916 pVariant->decVal.scale = 0;
917 pVariant->decVal.sign = 0;
918 pVariant->decVal.Hi32 = 0;
920 sal_Int64 value;
921 rAny >>= value;
923 if (value & SAL_CONST_UINT64(0x8000000000000000))
924 pVariant->decVal.sign = DECIMAL_NEG;
926 pVariant->decVal.Lo64 = value;
927 break;
929 case TypeClass_UNSIGNED_HYPER:
931 pVariant->vt = VT_DECIMAL;
932 pVariant->decVal.scale = 0;
933 pVariant->decVal.sign = 0;
934 pVariant->decVal.Hi32 = 0;
936 sal_uInt64 value;
937 rAny >>= value;
938 pVariant->decVal.Lo64 = value;
939 break;
941 case TypeClass_TYPE:
943 Type type;
944 rAny >>= type;
945 CComVariant var;
946 if (createUnoTypeWrapper(type.getTypeName(), & var) == false)
947 throw BridgeRuntimeError(
948 "[automation bridge] UnoConversionUtilities<T>::anyToVariant \n"
949 "Error during conversion of UNO type to Automation object!");
951 if (FAILED(VariantCopy(pVariant, &var)))
952 throw BridgeRuntimeError(
953 "[automation bridge] UnoConversionUtilities<T>::anyToVariant \n"
954 "Unexpected error!");
955 break;
957 default:
958 //TypeClass_SERVICE:
959 //TypeClass_EXCEPTION:
960 //When a InvocationTargetException is thrown when calling XInvocation::invoke
961 //on a UNO object, then the target exception is directly used to create a
962 //EXEPINFO structure
963 //TypeClass_TYPEDEF
964 //TypeClass_ANY:
965 //TypeClass_UNKNOWN:
966 //TypeClass_UNSIGNED_OCTET:
967 // TypeClass_UNION:
968 // TypeClass_ARRAY:
969 // TypeClass_UNSIGNED_INT:
970 // TypeClass_UNSIGNED_BYTE:
971 // TypeClass_MODULE:
972 throw CannotConvertException(
973 "[automation bridge]UnoConversionUtilities<T>::anyToVariant\n"
974 "There is no conversion for this UNO type to a Automation type."
975 "The destination type class is the type class of the UNO "
976 "argument which was to be converted.",
977 Reference<XInterface>(), rAny.getValueTypeClass(),
978 FailReason::TYPE_NOT_SUPPORTED, 0);
980 break;
982 if (bIllegal)
984 throw IllegalArgumentException(
985 "[automation bridge]UnoConversionUtilities<T>::anyToVariant\n"
986 "The provided any of type\" " + rAny.getValueType().getTypeName() +
987 "\" is unappropriate for conversion!", Reference<XInterface>(), -1);
991 catch (const CannotConvertException &)
993 throw;
995 catch (const IllegalArgumentException &)
997 throw;
999 catch(const BridgeRuntimeError&)
1001 throw;
1003 catch(const Exception & e)
1005 throw BridgeRuntimeError(
1006 "[automation bridge]UnoConversionUtilities<T>::anyToVariant \n"
1007 "Unexpected exception occurred. Message: " + e.Message);
1009 catch(...)
1011 throw BridgeRuntimeError(
1012 "[automation bridge]UnoConversionUtilities<T>::anyToVariant \n"
1013 "Unexpected exception occurred. " );
1017 // Creates an SAFEARRAY of the specified element and if necessary
1018 // creates a SAFEARRAY with multiple dimensions.
1019 // Used by sal_Bool anyToVariant(VARIANT* pVariant, const Any& rAny, VARTYPE type);
1020 template<class T>
1021 SAFEARRAY* UnoConversionUtilities<T>::createUnoSequenceWrapper(const Any& rSeq, VARTYPE elemtype)
1023 if (rSeq.getValueTypeClass() != TypeClass_SEQUENCE)
1024 throw IllegalArgumentException(
1025 "[automation bridge]UnoConversionUtilities<T>::createUnoSequenceWrapper \n"
1026 "The any does not contain a sequence!", 0, 0);
1027 if (elemtype == VT_NULL || elemtype == VT_EMPTY)
1028 throw IllegalArgumentException(
1029 "[automation bridge]UnoConversionUtilities<T>::createUnoSequenceWrapper \n"
1030 "No element type supplied!",0, -1);
1031 SAFEARRAY* pArray= NULL;
1032 // Get the dimensions. This is done by examining the type name string
1033 // The count of brackets determines the dimensions.
1034 OUString sTypeName= rSeq.getValueType().getTypeName();
1035 sal_Int32 dims=0;
1036 for(sal_Int32 lastIndex=0;(lastIndex= sTypeName.indexOf( L'[', lastIndex)) != -1; lastIndex++,dims++);
1038 //get the maximum number of elements per dimensions and the typedescription of the elements
1039 Sequence<sal_Int32> seqElementCounts( dims);
1040 TypeDescription elementTypeDesc;
1041 getElementCountAndTypeOfSequence( rSeq, 1, seqElementCounts, elementTypeDesc );
1043 if( elementTypeDesc.is() )
1045 // set up the SAFEARRAY
1046 scoped_array<SAFEARRAYBOUND> sarSafeArrayBound(new SAFEARRAYBOUND[dims]);
1047 SAFEARRAYBOUND* prgsabound= sarSafeArrayBound.get();
1048 for( sal_Int32 i=0; i < dims; i++)
1050 //prgsabound[0] is the right most dimension
1051 prgsabound[dims - i - 1].lLbound = 0;
1052 prgsabound[dims - i - 1].cElements = seqElementCounts[i];
1055 typelib_TypeDescription* rawTypeDesc= elementTypeDesc.get();
1056 sal_Int32 elementSize= rawTypeDesc->nSize;
1057 size_t oleElementSize= getOleElementSize( elemtype);
1058 // SafeArrayCreate clears the memory for the data itself.
1059 pArray = SafeArrayCreate(elemtype, dims, prgsabound);
1061 // convert the Sequence's elements and populate the SAFEARRAY
1062 if( pArray)
1064 // Iterate over every Sequence that contains the actual elements
1065 void* pSAData;
1066 if( SUCCEEDED( SafeArrayAccessData( pArray, &pSAData)))
1068 const sal_Int32* parElementCount= seqElementCounts.getConstArray();
1069 uno_Sequence * pMultiSeq= *(uno_Sequence* const*) rSeq.getValue();
1070 sal_Int32 dimsSeq= dims - 1;
1072 // arDimSeqIndizes contains the current index of a block of data.
1073 // E.g. Sequence<Sequence<sal_Int32>> , the index would refer to Sequence<sal_Int32>
1074 // In this case arDimSeqIndices would have the size 1. That is the elements are not counted
1075 // but the Sequences that contain those elements.
1076 // The indices ar 0 based
1077 scoped_array<sal_Int32> sarDimsSeqIndices;
1078 sal_Int32* arDimsSeqIndices= NULL;
1079 if( dimsSeq > 0)
1081 sarDimsSeqIndices.reset(new sal_Int32[dimsSeq]);
1082 arDimsSeqIndices = sarDimsSeqIndices.get();
1083 memset( arDimsSeqIndices, 0, sizeof( sal_Int32 ) * dimsSeq);
1086 char* psaCurrentData= (char*)pSAData;
1090 // Get the Sequence at the current index , see arDimsSeqIndices
1091 uno_Sequence * pCurrentSeq= pMultiSeq;
1092 sal_Int32 curDim=1; // 1 based
1093 sal_Bool skipSeq= sal_False;
1094 while( curDim <= dimsSeq )
1096 // get the Sequence at the index if valid
1097 if( pCurrentSeq->nElements > arDimsSeqIndices[ curDim - 1] ) // don't point to Nirvana
1099 // size of Sequence is 4
1100 sal_Int32 offset= arDimsSeqIndices[ curDim - 1] * 4;
1101 pCurrentSeq= *(uno_Sequence**) &pCurrentSeq->elements[ offset];
1102 curDim++;
1104 else
1106 // There is no Sequence at this index, so skip this index
1107 skipSeq= sal_True;
1108 break;
1112 if( skipSeq)
1113 continue;
1115 // Calculate the current position within the datablock of the SAFEARRAY
1116 // for the next Sequence.
1117 sal_Int32 memOffset= 0;
1118 sal_Int32 dimWeight= parElementCount[ dims - 1]; // size of the rightmost dimension
1119 for(sal_Int16 idims=0; idims < dimsSeq; idims++ )
1121 memOffset+= arDimsSeqIndices[dimsSeq - 1 - idims] * dimWeight;
1122 // now determine the weight of the dimension to the left of the current.
1123 if( dims - 2 - idims >=0)
1124 dimWeight*= parElementCount[dims - 2 - idims];
1126 psaCurrentData= (char*)pSAData + memOffset * oleElementSize;
1127 // convert the Sequence and put the elements into the Safearray
1128 for( sal_Int32 i= 0; i < pCurrentSeq->nElements; i++)
1130 Any unoElement( pCurrentSeq->elements + i * elementSize, rawTypeDesc );
1131 // The any is being converted into an VARIANT which value is then copied
1132 // to the SAFEARRAY's data block. When copying one has to follow the rules for
1133 // copying certain types, as are VT_DISPATCH, VT_UNKNOWN, VT_VARIANT, VT_BSTR.
1134 // To increase performance, we just do a memcpy of VARIANT::byref. This is possible
1135 // because anyToVariant has already followed the copying rules. To make this
1136 // work there must not be a VariantClear.
1137 // One Exception is VARIANT because I don't know how VariantCopy works.
1139 VARIANT var;
1140 VariantInit( &var);
1141 anyToVariant( &var, unoElement);
1142 if( elemtype == VT_VARIANT )
1144 VariantCopy( ( VARIANT*)psaCurrentData, &var);
1145 VariantClear( &var);
1147 else
1148 memcpy( psaCurrentData, &var.byref, oleElementSize);
1150 psaCurrentData+= oleElementSize;
1153 while( incrementMultidimensionalIndex( dimsSeq, parElementCount, arDimsSeqIndices));
1155 SafeArrayUnaccessData( pArray);
1159 return pArray;
1162 // Increments a multi dimensional index.
1163 // Returns true as long as the index has been successfully incremented, false otherwise.
1164 // False is also returned if an overflow of the most significant dimension occurs. E.g.
1165 // assume an array with the dimensions (2,2), then the lowest index is (0,0) and the highest
1166 // index is (1,1). If the function is being called with the index (1,1) then the overflow would
1167 // occur, with the result (0,0) and a sal_False as return value.
1168 // Param dimensions - number of dimensions
1169 // Param parDimensionsLength - The array contains the size of each dimension, that is the
1170 // size of the array equals the parameter dimensions.
1171 // The rightmost dimensions is the least significant one
1172 // ( parDimensionsLengths[ dimensions -1 ] ).
1173 // Param parMultiDimensionalIndex - The array contains the index. Each dimension index is
1174 // 0 based.
1175 template<class T>
1176 sal_Bool UnoConversionUtilities<T>::incrementMultidimensionalIndex(sal_Int32 dimensions,
1177 const sal_Int32 * parDimensionLengths,
1178 sal_Int32 * parMultidimensionalIndex)
1180 if( dimensions < 1)
1181 return sal_False;
1183 sal_Bool ret= sal_True;
1184 sal_Bool carry= sal_True; // to get into the while loop
1186 sal_Int32 currentDimension= dimensions; //most significant is 1
1187 while( carry)
1189 parMultidimensionalIndex[ currentDimension - 1]++;
1190 // if carryover, set index to 0 and handle carry on a level above
1191 if( parMultidimensionalIndex[ currentDimension - 1] > (parDimensionLengths[ currentDimension - 1] - 1))
1192 parMultidimensionalIndex[ currentDimension - 1]= 0;
1193 else
1194 carry= sal_False;
1196 currentDimension --;
1197 // if dimensions drops below 1 and carry is set than then all indices are 0 again
1198 // this is signalled by returning sal_False
1199 if( currentDimension < 1 && carry)
1201 carry= sal_False;
1202 ret= sal_False;
1205 return ret;
1208 // Determines the size of a certain OLE type. The function takes
1209 // only those types into account which are oleautomation types and
1210 // can have a value ( unless VT_NULL, VT_EMPTY, VT_ARRAY, VT_BYREF).
1211 // Currently used in createUnoSequenceWrapper to calculate addresses
1212 // for data within a SAFEARRAY.
1213 template<class T>
1214 size_t UnoConversionUtilities<T>::getOleElementSize( VARTYPE type)
1216 size_t size;
1217 switch( type)
1219 case VT_BOOL: size= sizeof( VARIANT_BOOL);break;
1220 case VT_UI1: size= sizeof( unsigned char);break;
1221 case VT_R8: size= sizeof( double);break;
1222 case VT_R4: size= sizeof( float);break;
1223 case VT_I2: size= sizeof( short);break;
1224 case VT_I4: size= sizeof( long);break;
1225 case VT_BSTR: size= sizeof( BSTR); break;
1226 case VT_ERROR: size= sizeof( SCODE); break;
1227 case VT_DISPATCH:
1228 case VT_UNKNOWN: size= sizeof( IUnknown*); break;
1229 case VT_VARIANT: size= sizeof( VARIANT);break;
1230 default: size= 0;
1232 return size;
1235 //If a Sequence is being converted into a SAFEARRAY then we possibly have
1236 // to create a SAFEARRAY with multiple dimensions. This is the case when a
1237 // Sequence contains Sequences ( Sequence< Sequence < XXX > > ). The leftmost
1238 // Sequence in the declaration is assumed to represent dimension 1. Because
1239 // all Sequence elements of a Sequence can have different length, we have to
1240 // determine the maximum length which is then the length of the respective
1241 // dimension.
1242 // getElementCountAndTypeOfSequence determines the length of each dimension and calls itself recursively
1243 // in the process.
1244 // param rSeq - an Any that has to contain a Sequence
1245 // param dim - the dimension for which the number of elements is being determined,
1246 // must be one.
1247 // param seqElementCounts - countains the maximum number of elements for each
1248 // dimension. Index 0 contains the number of dimension one.
1249 // After return the Sequence contains the maximum number of
1250 // elements for each dimension.
1251 // The length of the Sequence must equal the number of dimensions.
1252 // param typeClass - TypeClass of the element type that is no Sequence, e.g.
1253 // Sequence< Sequence <Sequence <sal_Int32> > > - type is sal_Int32)
1254 template<class T>
1255 void UnoConversionUtilities<T>::getElementCountAndTypeOfSequence( const Any& rSeq, sal_Int32 dim,
1256 Sequence< sal_Int32 >& seqElementCounts, TypeDescription& typeDesc)
1258 sal_Int32 dimCount= (*(uno_Sequence* const *) rSeq.getValue())->nElements;
1259 if( dimCount > seqElementCounts[ dim-1])
1260 seqElementCounts[ dim-1]= dimCount;
1262 // we need the element type to construct the any that is
1263 // passed into getElementCountAndTypeOfSequence again
1264 typelib_TypeDescription* pSeqDesc= NULL;
1265 rSeq.getValueTypeDescription( &pSeqDesc);
1266 typelib_TypeDescriptionReference* pElementDescRef= ((typelib_IndirectTypeDescription*)pSeqDesc)->pType;
1268 // if the elements are Sequences than do recursion
1269 if( dim < seqElementCounts.getLength() )
1271 uno_Sequence* pSeq = *(uno_Sequence* const*) rSeq.getValue();
1272 uno_Sequence** arSequences= (uno_Sequence**)pSeq->elements;
1273 for( sal_Int32 i=0; i < dimCount; i++)
1275 uno_Sequence* arElement= arSequences[ i];
1276 getElementCountAndTypeOfSequence( Any( &arElement, pElementDescRef), dim + 1 , seqElementCounts, typeDesc);
1279 else
1281 // determine the element type ( e.g. Sequence< Sequence <Sequence <sal_Int32> > > - type is sal_Int32)
1282 typeDesc= pElementDescRef;
1284 typelib_typedescription_release( pSeqDesc);
1288 template<class T>
1289 SAFEARRAY* UnoConversionUtilities<T>::createUnoSequenceWrapper(const Any& rSeq)
1291 SAFEARRAY* pArray = NULL;
1292 sal_uInt32 n = 0;
1294 if( rSeq.getValueTypeClass() != TypeClass_SEQUENCE )
1295 throw IllegalArgumentException(
1296 "[automation bridge]UnoConversionUtilities<T>::createUnoSequenceWrapper\n"
1297 "The UNO argument is not a sequence", 0, -1);
1299 uno_Sequence * punoSeq= *(uno_Sequence**) rSeq.getValue();
1301 typelib_TypeDescriptionReference* pSeqTypeRef= rSeq.getValueTypeRef();
1302 typelib_TypeDescription* pSeqType= NULL;
1303 TYPELIB_DANGER_GET( &pSeqType, pSeqTypeRef);
1304 typelib_IndirectTypeDescription * pSeqIndDec= (typelib_IndirectTypeDescription*) pSeqType;
1307 typelib_TypeDescriptionReference * pSeqElementTypeRef= pSeqIndDec->pType;
1308 TYPELIB_DANGER_RELEASE( pSeqType);
1310 typelib_TypeDescription* pSeqElementDesc= NULL;
1311 TYPELIB_DANGER_GET( &pSeqElementDesc, pSeqElementTypeRef);
1312 sal_Int32 nElementSize= pSeqElementDesc->nSize;
1313 n= punoSeq->nElements;
1315 SAFEARRAYBOUND rgsabound[1];
1316 rgsabound[0].lLbound = 0;
1317 rgsabound[0].cElements = n;
1318 VARIANT oleElement;
1319 long safeI[1];
1321 pArray = SafeArrayCreate(VT_VARIANT, 1, rgsabound);
1323 Any unoElement;
1324 sal_uInt8 * pSeqData= (sal_uInt8*) punoSeq->elements;
1326 for (sal_uInt32 i = 0; i < n; i++)
1328 unoElement.setValue( pSeqData + i * nElementSize, pSeqElementDesc);
1329 VariantInit(&oleElement);
1331 anyToVariant(&oleElement, unoElement);
1333 safeI[0] = i;
1334 SafeArrayPutElement(pArray, safeI, &oleElement);
1336 VariantClear(&oleElement);
1338 TYPELIB_DANGER_RELEASE( pSeqElementDesc);
1340 return pArray;
1343 /* The argument rObj can contain
1344 - UNO struct
1345 - UNO interface
1346 - UNO interface created by this bridge (adapter factory)
1347 - UNO interface created by this bridge ( COM Wrapper)
1349 pVar must be initialized.
1351 template<class T>
1352 void UnoConversionUtilities<T>::createUnoObjectWrapper(const Any & rObj, VARIANT * pVar)
1354 MutexGuard guard(getBridgeMutex());
1356 Reference<XInterface> xInt;
1358 TypeClass tc = rObj.getValueTypeClass();
1359 if (tc != TypeClass_INTERFACE && tc != TypeClass_STRUCT)
1360 throw IllegalArgumentException(
1361 "[automation bridge]UnoConversionUtilities<T>::createUnoObjectWrapper \n"
1362 "Cannot create an Automation interface for a UNO type which is not "
1363 "a struct or interface!", 0, -1);
1365 if (rObj.getValueTypeClass() == TypeClass_INTERFACE)
1367 if (! (rObj >>= xInt))
1368 throw IllegalArgumentException(
1369 "[automation bridge] UnoConversionUtilities<T>::createUnoObjectWrapper\n "
1370 "Could not create wrapper object for UNO object!", 0, -1);
1371 //If XInterface is NULL, which is a valid value, then simply return NULL.
1372 if ( ! xInt.is())
1374 pVar->vt = VT_UNKNOWN;
1375 pVar->punkVal = NULL;
1376 return;
1378 //make sure we have the main XInterface which is used with a map
1379 xInt = Reference<XInterface>(xInt, UNO_QUERY);
1380 //If there is already a wrapper for the UNO object then use it
1382 Reference<XInterface> xIntWrapper;
1383 // Does a UNO wrapper exist already ?
1384 IT_Uno it_uno = UnoObjToWrapperMap.find( (sal_uInt32) xInt.get());
1385 if(it_uno != UnoObjToWrapperMap.end())
1387 xIntWrapper = it_uno->second;
1388 if (xIntWrapper.is())
1390 convertSelfToCom(xIntWrapper, pVar);
1391 return;
1394 // Is the object a COM wrapper ( either XInvocation, or Adapter object)
1395 // or does it suppy an IDispatch by its own ?
1396 else
1398 Reference<XInterface> xIntComWrapper = xInt;
1399 typedef boost::unordered_map<sal_uInt32,sal_uInt32>::iterator _IT;
1400 // Adapter? then get the COM wrapper to which the adapter delegates its calls
1401 _IT it= AdapterToWrapperMap.find( (sal_uInt32) xInt.get());
1402 if( it != AdapterToWrapperMap.end() )
1403 xIntComWrapper= reinterpret_cast<XInterface*>(it->second);
1405 if (convertSelfToCom(xIntComWrapper, pVar))
1406 return;
1409 // If we have no UNO wrapper nor the IDispatch yet then we have to create
1410 // a wrapper. For that we need an XInvocation from the UNO object.
1412 // get an XInvocation or create one using the invocation service
1413 Reference<XInvocation> xInv(xInt, UNO_QUERY);
1414 if ( ! xInv.is())
1416 Reference<XSingleServiceFactory> xInvFactory= getInvocationFactory(rObj);
1417 if (xInvFactory.is())
1419 Sequence<Any> params(1);
1420 params.getArray()[0] = rObj;
1421 Reference<XInterface> xInt = xInvFactory->createInstanceWithArguments(params);
1422 xInv= Reference<XInvocation>(xInt, UNO_QUERY);
1426 if (xInv.is())
1428 Reference<XInterface> xNewWrapper = createUnoWrapperInstance();
1429 Reference<XInitialization> xInitWrapper(xNewWrapper, UNO_QUERY);
1430 if (xInitWrapper.is())
1432 VARTYPE vartype= getVarType( rObj);
1434 if (xInt.is())
1436 Any params[3];
1437 params[0] <<= xInv;
1438 params[1] <<= xInt;
1439 params[2] <<= vartype;
1440 xInitWrapper->initialize( Sequence<Any>(params, 3));
1442 else
1444 Any params[2];
1445 params[0] <<= xInv;
1446 params[1] <<= vartype;
1447 xInitWrapper->initialize( Sequence<Any>(params, 2));
1450 // put the newly created object into a map. If the same object will
1451 // be mapped again and there is already a wrapper then the old wrapper
1452 // will be used.
1453 if(xInt.is()) // only interfaces
1454 UnoObjToWrapperMap[(sal_uInt32) xInt.get()]= xNewWrapper;
1455 convertSelfToCom(xNewWrapper, pVar);
1456 return;
1461 template<class T>
1462 void UnoConversionUtilities<T>::variantToAny( const VARIANT* pVariant, Any& rAny,
1463 sal_Bool bReduceValueRange /* = sal_True */)
1465 HRESULT hr = S_OK;
1468 CComVariant var;
1470 // There is no need to support indirect values, since they're not supported by UNO
1471 if( FAILED(hr= VariantCopyInd( &var, const_cast<VARIANTARG*>(pVariant)))) // remove VT_BYREF
1472 throw BridgeRuntimeError(
1473 "[automation bridge] UnoConversionUtilities<T>::variantToAny \n"
1474 "VariantCopyInd failed for reason : " + OUString::valueOf(hr));
1476 if ( ! convertValueObject( & var, rAny))
1478 if ((var.vt & VT_ARRAY) > 0)
1480 VARTYPE oleTypeFlags = ::sal::static_int_cast< VARTYPE, int >( var.vt ^ VT_ARRAY );
1482 Sequence<Any> unoSeq = createOleArrayWrapper(var.parray, oleTypeFlags);
1483 rAny.setValue( &unoSeq, getCppuType( &unoSeq));
1485 else
1487 switch (var.vt)
1489 case VT_EMPTY:
1490 rAny.setValue(NULL, Type());
1491 break;
1492 case VT_NULL:
1493 rAny.setValue(NULL, Type());
1494 break;
1495 case VT_I2:
1496 rAny.setValue( & var.iVal, getCppuType( (sal_Int16*)0));
1497 break;
1498 case VT_I4:
1499 rAny.setValue( & var.lVal, getCppuType( (sal_Int32*)0));
1500 // necessary for use in JavaScript ( see "reduceRange")
1501 if( bReduceValueRange)
1502 reduceRange(rAny);
1503 break;
1504 case VT_R4:
1505 rAny.setValue( & var.fltVal, getCppuType( (float*)0));
1506 break;
1507 case VT_R8:
1508 rAny.setValue(& var.dblVal, getCppuType( (double*)0));
1509 break;
1510 case VT_CY:
1512 Currency cy(var.cyVal.int64);
1513 rAny <<= cy;
1514 break;
1516 case VT_DATE:
1518 Date d(var.date);
1519 rAny <<= d;
1520 break;
1522 case VT_BSTR:
1524 OUString b(reinterpret_cast<const sal_Unicode*>(var.bstrVal));
1525 rAny.setValue( &b, getCppuType( &b));
1526 break;
1528 case VT_UNKNOWN:
1529 case VT_DISPATCH:
1531 //check if it is a UNO type
1532 #ifdef __MINGW32__
1533 CComQIPtr<IUnoTypeWrapper, &__uuidof(IUnoTypeWrapper)> spType((IUnknown*) var.byref);
1534 #else
1535 CComQIPtr<IUnoTypeWrapper> spType((IUnknown*) var.byref);
1536 #endif
1537 if (spType)
1539 CComBSTR sName;
1540 if (FAILED(spType->get_Name(&sName)))
1541 throw BridgeRuntimeError(
1542 "[automation bridge]UnoConversionUtilities<T>::variantToAny \n"
1543 "Failed to get the type name from a UnoTypeWrapper!");
1544 Type type;
1545 if (getType(sName, type) == false)
1547 throw CannotConvertException(
1548 "[automation bridge]UnoConversionUtilities<T>::variantToAny \n"
1549 "A UNO type with the name: " + OUString(reinterpret_cast<const sal_Unicode*>(LPCOLESTR(sName))) +
1550 "does not exist!",
1551 0, TypeClass_UNKNOWN, FailReason::TYPE_NOT_SUPPORTED,0);
1553 rAny <<= type;
1555 else
1557 rAny = createOleObjectWrapper( & var);
1559 break;
1561 case VT_ERROR:
1563 SCode scode(var.scode);
1564 rAny <<= scode;
1565 break;
1567 case VT_BOOL:
1569 sal_Bool b= var.boolVal == VARIANT_TRUE;
1570 rAny.setValue( &b, getCppuType( &b));
1571 break;
1573 case VT_I1:
1574 rAny.setValue( & var.cVal, getCppuType((sal_Int8*)0));
1575 break;
1576 case VT_UI1: // there is no unsigned char in UNO
1577 rAny.setValue( & var.bVal, getCppuType( (sal_Int8*)0));
1578 break;
1579 case VT_UI2:
1580 rAny.setValue( & var.uiVal, getCppuType( (sal_uInt16*)0));
1581 break;
1582 case VT_UI4:
1583 rAny.setValue( & var.ulVal, getCppuType( (sal_uInt32*)0));
1584 break;
1585 case VT_INT:
1586 rAny.setValue( & var.intVal, getCppuType( (sal_Int32*)0));
1587 break;
1588 case VT_UINT:
1589 rAny.setValue( & var.uintVal, getCppuType( (sal_uInt32*)0));
1590 break;
1591 case VT_VOID:
1592 rAny.setValue( NULL, Type());
1593 break;
1594 case VT_DECIMAL:
1596 Decimal dec;
1597 dec.Scale = var.decVal.scale;
1598 dec.Sign = var.decVal.sign;
1599 dec.LowValue = var.decVal.Lo32;
1600 dec.MiddleValue = var.decVal.Mid32;
1601 dec.HighValue = var.decVal.Hi32;
1602 rAny <<= dec;
1603 break;
1606 default:
1607 break;
1612 catch (const IllegalArgumentException &)
1614 throw;
1616 catch (const CannotConvertException &)
1618 throw;
1620 catch (const BridgeRuntimeError &)
1622 throw;
1624 catch (const Exception & e)
1626 throw BridgeRuntimeError("[automation bridge] unexpected exception in "
1627 "UnoConversionUtilities<T>::variantToAny ! Message : \n" +
1628 e.Message);
1630 catch(...)
1632 throw BridgeRuntimeError(
1633 "[automation bridge] unexpected exception in "
1634 "UnoConversionUtilities<T>::variantToAny !");
1638 // The function converts an IUnknown* into an UNO interface or struct. The
1639 // IUnknown pointer can constitute different kind of objects:
1640 // 1. a wrapper of an UNO struct (the wrapper was created by this bridge)
1641 // 2. a wrapper of an UNO interface (created by this bridge)
1642 // 3. a dispatch object that implements UNO interfaces
1643 // 4. a dispatch object.
1645 // If the parameter "aType" has a value then the COM object ( pUnknown) is supposed to
1646 // implement the interface described by "aType". Moreover it ( pUnknown) can implement
1647 // several other
1648 // UNO interfaces in which case it has to support the SUPPORTED_INTERFACES_PROP (see
1649 // #define) property. That property contains all names of interfaces.
1650 // "pUnknown" is wrapped by a COM wrapper object that implements XInvocation, e.g.
1651 // IUnknownWrapper_Impl. Additionally an object of type "aType" is created by help
1652 // of the INTERFACE_ADAPTER_FACTORY (see #define) service. The implementation of
1653 // "aType" calls on the COM wrapper's XInvocation::invoke. If the COM object supports
1654 // more then one UNO interfaces, as can be determined by the property
1655 // SUPPORTED_INTERFACES_PROP, then the INTERFACE_ADAPTER_FACTORY creates an object that
1656 // implements all these interfaces.
1657 // This is only done if "pUnknown" is not already a UNO wrapper,
1658 // that is it is actually NOT an UNO object that was converted to a COM object. If it is an
1659 // UNO wrapper than the original UNO object is being extracted, queried for "aType" (if
1660 // it is no struct) and returned.
1661 template<class T>
1662 #ifdef __MINGW32__
1663 Any UnoConversionUtilities<T>::createOleObjectWrapper(VARIANT* pVar, const Type& aType)
1664 #else
1665 Any UnoConversionUtilities<T>::createOleObjectWrapper(VARIANT* pVar, const Type& aType= Type())
1666 #endif
1668 //To allow passing "Nothing" in VS 2008 we need to accept VT_EMPTY
1669 if (pVar->vt != VT_UNKNOWN && pVar->vt != VT_DISPATCH && pVar->vt != VT_EMPTY)
1670 throw IllegalArgumentException(
1671 "[automation bridge]UnoConversionUtilities<T>::createOleObjectWrapper \n"
1672 "The VARIANT does not contain an object type! ", 0, -1);
1674 MutexGuard guard( getBridgeMutex());
1676 CComPtr<IUnknown> spUnknown;
1677 CComPtr<IDispatch> spDispatch;
1679 if (pVar->vt == VT_UNKNOWN)
1681 spUnknown = pVar->punkVal;
1682 if (spUnknown)
1683 #ifdef __MINGW32__
1684 spUnknown->QueryInterface( IID_IDispatch, reinterpret_cast<LPVOID*>( & spDispatch.p));
1685 #else
1686 spUnknown.QueryInterface( & spDispatch.p);
1687 #endif
1689 else if (pVar->vt == VT_DISPATCH && pVar->pdispVal != NULL)
1691 CComPtr<IDispatch> spDispatch(pVar->pdispVal);
1692 if (spDispatch)
1693 #ifdef __MINGW32__
1694 spDispatch->QueryInterface( IID_IUnknown, reinterpret_cast<LPVOID*>( & spUnknown.p));
1695 #else
1696 spDispatch.QueryInterface( & spUnknown.p);
1697 #endif
1700 static Type VOID_TYPE= Type();
1701 Any ret;
1702 //If no Type is provided and pVar contains IUnknown then we return a XInterface.
1703 //If pVar contains an IDispatch then we return a XInvocation.
1704 Type desiredType = aType;
1706 if (aType == VOID_TYPE)
1708 switch (pVar->vt)
1710 case VT_EMPTY:
1711 case VT_UNKNOWN:
1712 desiredType = getCppuType((Reference<XInterface>*) 0);
1713 break;
1714 case VT_DISPATCH:
1715 desiredType = getCppuType((Reference<XInvocation>*) 0);
1716 break;
1717 default:
1718 desiredType = aType;
1722 // COM pointer are NULL, no wrapper required
1723 if (spUnknown == NULL)
1725 Reference<XInterface> xInt;
1726 if( aType.getTypeClass() == TypeClass_INTERFACE)
1727 ret.setValue( &xInt, aType);
1728 else if( aType.getTypeClass() == TypeClass_STRUCT)
1729 ret.setValue( NULL, aType);
1730 else
1731 ret <<= xInt;
1732 return ret;
1736 // Check if "spUnknown" is a UNO wrapper, that is an UNO object that has been
1737 // passed to COM. Then it supports IUnoObjectWrapper
1738 // and we extract the original UNO object.
1739 #ifdef __MINGW32__
1740 CComQIPtr<IUnoObjectWrapper, &__uuidof(IUnoObjectWrapper)> spUno( spUnknown);
1741 #else
1742 CComQIPtr<IUnoObjectWrapper> spUno( spUnknown);
1743 #endif
1744 if( spUno)
1745 { // it is a wrapper
1746 Reference<XInterface> xInt;
1747 if( SUCCEEDED( spUno->getOriginalUnoObject( &xInt)))
1749 ret <<= xInt;
1751 else
1753 Any any;
1754 if( SUCCEEDED( spUno->getOriginalUnoStruct(&any)))
1755 ret= any;
1757 return ret;
1760 // "spUnknown" is a real COM object.
1761 // Before we create a new wrapper object we check if there is an existing wrapper
1762 // There can be two kinds of wrappers, those who wrap dispatch - UNO objects, and those who
1763 // wrap ordinary dispatch objects. The dispatch-UNO objects usually are adapted to represent
1764 // particular UNO interfaces.
1765 Reference<XInterface> xIntWrapper;
1766 CIT_Com cit_currWrapper= ComPtrToWrapperMap.find( reinterpret_cast<sal_uInt32>(spUnknown.p));
1767 if(cit_currWrapper != ComPtrToWrapperMap.end())
1768 xIntWrapper = cit_currWrapper->second;
1769 if (xIntWrapper.is())
1771 //Try to find an adapter for the wrapper
1772 //find the proper Adapter. The pointer in the WrapperToAdapterMap are valid as long as
1773 //we get a pointer to the wrapper from ComPtrToWrapperMap, because the Adapter hold references
1774 //to the wrapper.
1775 CIT_Wrap it = WrapperToAdapterMap.find((sal_uInt32) xIntWrapper.get());
1776 if (it == WrapperToAdapterMap.end())
1778 // No adapter available.
1779 //The COM component could be a UNO object. Then we need to provide
1780 // a proxy that implements all interfaces
1781 Sequence<Type> seqTypes= getImplementedInterfaces(spUnknown);
1782 Reference<XInterface> xIntAdapter;
1783 if (seqTypes.getLength() > 0)
1785 //It is a COM UNO object
1786 xIntAdapter = createAdapter(seqTypes, xIntWrapper);
1788 else
1790 // Some ordinary COM object
1791 xIntAdapter = xIntWrapper;
1793 // return the wrapper directly, return XInterface or XInvocation
1794 ret = xIntWrapper->queryInterface(desiredType);
1795 if ( ! ret.hasValue())
1796 throw IllegalArgumentException(
1797 "[automation bridge]UnoConversionUtilities<T>::createOleObjectWrapper \n"
1798 "The COM object is not suitable for the UNO type: " +
1799 desiredType.getTypeName(), 0, -1);
1801 else
1803 //There is an adapter available
1804 Reference<XInterface> xIntAdapter((XInterface*) it->second);
1805 ret = xIntAdapter->queryInterface( desiredType);
1806 if ( ! ret.hasValue())
1807 throw IllegalArgumentException(
1808 "[automation bridge]UnoConversionUtilities<T>::createOleObjectWrapper \n"
1809 "The COM object is not suitable for the UNO type: " +
1810 desiredType.getTypeName(), 0, -1);
1813 return ret;
1815 // No existing wrapper. Therefore create a new proxy.
1816 // If the object implements UNO interfaces then get the types.
1817 Sequence<Type> seqTypes = getImplementedInterfaces(spUnknown);
1818 if (seqTypes.getLength() == 0 &&
1819 aType != VOID_TYPE && aType != getCppuType((Reference<XInvocation>*)0))
1821 seqTypes = Sequence<Type>( & aType, 1);
1824 //There is no existing wrapper, therefore we create one for the real COM object
1825 Reference<XInterface> xIntNewProxy= createComWrapperInstance();
1826 if ( ! xIntNewProxy.is())
1827 throw BridgeRuntimeError(
1828 "[automation bridge]UnoConversionUtilities<T>::createOleObjectWrapper \n"
1829 "Could not create proxy object for COM object!");
1831 // initialize the COM wrapper
1832 Reference<XInitialization> xInit( xIntNewProxy, UNO_QUERY);
1833 OSL_ASSERT( xInit.is());
1835 Any params[3];
1836 #ifdef __MINGW32__
1837 params[0] <<= reinterpret_cast<sal_uInt32>( spUnknown.p );
1838 #else
1839 params[0] <<= (sal_uInt32) spUnknown.p;
1840 #endif
1841 sal_Bool bDisp = pVar->vt == VT_DISPATCH ? sal_True : sal_False;
1842 params[1].setValue( & bDisp, getBooleanCppuType());
1843 params[2] <<= seqTypes;
1845 xInit->initialize( Sequence<Any>( params, 3));
1846 #ifdef __MINGW32__
1847 ComPtrToWrapperMap[reinterpret_cast<sal_uInt32>( spUnknown.p )]= xIntNewProxy;
1848 #else
1849 ComPtrToWrapperMap[reinterpret_cast<sal_uInt32>(spUnknown.p)]= xIntNewProxy;
1850 #endif
1852 // we have a wrapper object
1853 //The wrapper implements already XInvocation and XInterface. If
1854 //param aType is void then the object is supposed to have XInvocation.
1855 if (aType == getCppuType((Reference<XInvocation>*)0) ||
1856 (aType == VOID_TYPE && seqTypes.getLength() == 0 ))
1858 ret = xIntNewProxy->queryInterface(desiredType);
1860 else
1862 Reference<XInterface> xIntAdapter =
1863 createAdapter(seqTypes, xIntNewProxy);
1864 ret = xIntAdapter->queryInterface(desiredType);
1866 return ret;
1868 template<class T>
1869 Reference<XInterface> UnoConversionUtilities<T>::createAdapter(const Sequence<Type>& seqTypes,
1870 const Reference<XInterface>& receiver)
1872 Reference< XInterface> xIntAdapterFac;
1873 xIntAdapterFac= m_smgr->createInstance(INTERFACE_ADAPTER_FACTORY);
1874 // We create an adapter object that does not only implement the required type but also
1875 // all types that the COM object pretends to implement. An COM object must therefore
1876 // support the property "_implementedInterfaces".
1877 Reference<XInterface> xIntAdapted;
1878 Reference<XInvocation> xInv(receiver, UNO_QUERY);
1879 Reference<XInvocationAdapterFactory2> xAdapterFac( xIntAdapterFac, UNO_QUERY);
1880 if( xAdapterFac.is())
1881 xIntAdapted= xAdapterFac->createAdapter( xInv, seqTypes);
1883 if( xIntAdapted.is())
1885 // Put the pointer to the wrapper object and the interface pointer of the adapted interface
1886 // in a global map. Thus we can determine in a call to createUnoObjectWrapper whether the UNO
1887 // object is a wrapped COM object. In that case we extract the original COM object rather than
1888 // creating a wrapper around the UNO object.
1889 typedef boost::unordered_map<sal_uInt32,sal_uInt32>::value_type VALUE;
1890 AdapterToWrapperMap.insert( VALUE( (sal_uInt32) xIntAdapted.get(), (sal_uInt32) receiver.get()));
1891 WrapperToAdapterMap.insert( VALUE( (sal_uInt32) receiver.get(), (sal_uInt32) xIntAdapted.get()));
1893 else
1895 throw BridgeRuntimeError(
1896 "[automation bridge]UnoConversionUtilities<T>::createOleObjectWrapper \n"
1897 "Could not create a proxy for COM object! Creation of adapter failed.");
1899 return xIntAdapted;
1901 // "convertValueObject" converts a JScriptValue object contained in "var" into
1902 // an any. The type contained in the any is stipulated by a "type value" thas
1903 // was set within the JScript script on the value object ( see JScriptValue).
1904 template<class T>
1905 bool UnoConversionUtilities<T>::convertValueObject( const VARIANTARG *var, Any& any)
1907 bool ret = false;
1910 bool bFail = false;
1911 HRESULT hr= S_OK;
1912 CComVariant varDisp;
1914 if(SUCCEEDED(hr = varDisp.ChangeType( VT_DISPATCH, var)))
1916 CComPtr <IJScriptValueObject> spValue;
1917 VARIANT_BOOL varBool;
1918 CComBSTR bstrType;
1919 CComVariant varValue;
1920 CComPtr<IDispatch> spDisp( varDisp.pdispVal);
1921 if(spDisp)
1923 if(SUCCEEDED( spDisp->QueryInterface( __uuidof( IJScriptValueObject),
1924 reinterpret_cast<void**> (&spValue))))
1926 ret = true; // is is a ValueObject
1927 //If it is an out - param then it does not need to be converted. In/out and
1928 // in params does so.
1929 if (SUCCEEDED(hr= spValue->IsOutParam( &varBool)))
1931 // if varBool == true then no conversion needed because out param
1932 if (varBool == VARIANT_FALSE)
1934 if(SUCCEEDED(hr = spValue->GetValue( & bstrType, & varValue)))
1936 Type type;
1937 if (getType(bstrType, type))
1938 variantToAny( & varValue, any, type);
1939 else
1940 bFail = true;
1942 else
1943 bFail = true;
1946 else
1947 bFail = true;
1951 else if( hr != DISP_E_TYPEMISMATCH && hr != E_NOINTERFACE)
1952 bFail = true;
1954 if (bFail)
1955 throw BridgeRuntimeError(
1956 "[automation bridge] Conversion of ValueObject failed ");
1958 catch (const BridgeRuntimeError &)
1960 throw;
1962 catch (const Exception & e)
1964 throw BridgeRuntimeError("[automation bridge] unexpected exception in "
1965 "UnoConversionUtilities<T>::convertValueObject ! Message : \n" +
1966 e.Message);
1968 catch(...)
1970 throw BridgeRuntimeError(
1971 "[automation bridge] unexpected exception in "
1972 "UnoConversionUtilities<T>::convertValueObject !");
1974 return ret;
1977 template<class T>
1978 void UnoConversionUtilities<T>::dispatchExObject2Sequence( const VARIANTARG* pvar, Any& anySeq, const Type& type)
1982 bool bFail = false;
1983 if( pvar->vt != VT_DISPATCH)
1984 throw BridgeRuntimeError("[automation bridge] UnoConversionUtilities<T>::dispatchExObject2Sequence \n"
1985 "Conversion of dispatch object to Sequence failed!");
1986 IDispatchEx* pdispEx;
1987 HRESULT hr;
1988 if( FAILED( hr= pvar->pdispVal->QueryInterface( IID_IDispatchEx,
1989 reinterpret_cast<void**>( &pdispEx))))
1990 throw BridgeRuntimeError("[automation bridge] UnoConversionUtilities<T>::dispatchExObject2Sequence \n"
1991 "Conversion of dispatch object to Sequence failed!");
1993 DISPID dispid;
1994 OUString sindex;
1995 DISPPARAMS param= {0,0,0,0};
1996 CComVariant result;
1998 OLECHAR* sLength= L"length";
2000 // Get the length of the array. Can also be obtained throu GetNextDispID. The
2001 // method only returns DISPIDs of the array data. Their names are like "0", "1" etc.
2002 if( FAILED( hr= pdispEx->GetIDsOfNames(IID_NULL, &sLength , 1, LOCALE_USER_DEFAULT, &dispid)))
2003 throw BridgeRuntimeError("[automation bridge] UnoConversionUtilities<T>::dispatchExObject2Sequence \n"
2004 "Conversion of dispatch object to Sequence failed!");
2005 if( FAILED( hr= pdispEx->InvokeEx(dispid, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET,
2006 &param, &result, NULL, NULL)))
2007 throw BridgeRuntimeError("[automation bridge] UnoConversionUtilities<T>::dispatchExObject2Sequence \n"
2008 "Conversion of dispatch object to Sequence failed!");
2009 if( FAILED( VariantChangeType( &result, &result, 0, VT_I4)))
2010 throw BridgeRuntimeError("[automation bridge] UnoConversionUtilities<T>::dispatchExObject2Sequence \n"
2011 "Conversion of dispatch object to Sequence failed!");
2012 long length= result.lVal;
2014 result.Clear();
2016 // get a few basic facts about the sequence, and reallocate:
2017 // create the Sequences
2018 // get the size of the elements
2019 typelib_TypeDescription *pDesc= NULL;
2020 type.getDescription( &pDesc);
2022 typelib_IndirectTypeDescription *pSeqDesc= reinterpret_cast<typelib_IndirectTypeDescription*>(pDesc);
2023 typelib_TypeDescriptionReference *pSeqElemDescRef= pSeqDesc->pType; // type of the Sequence' elements
2024 Type elemType( pSeqElemDescRef);
2025 _typelib_TypeDescription* pSeqElemDesc=NULL;
2026 TYPELIB_DANGER_GET( &pSeqElemDesc, pSeqElemDescRef)
2027 sal_uInt32 nelementSize= pSeqElemDesc->nSize;
2028 TYPELIB_DANGER_RELEASE( pSeqElemDesc)
2030 uno_Sequence *p_uno_Seq;
2031 uno_sequence_construct( &p_uno_Seq, pDesc, NULL, length, cpp_acquire);
2033 typelib_TypeClass typeElement= pSeqDesc->pType->eTypeClass;
2034 char *pArray= p_uno_Seq->elements;
2036 // Get All properties in the object, convert their values to the expected type and
2037 // put them into the passed in sequence
2038 for( sal_Int32 i= 0; i< length; i++)
2040 OUString ousIndex=OUString::valueOf( i);
2041 OLECHAR* sindex = (OLECHAR*)ousIndex.getStr();
2043 if( FAILED( hr= pdispEx->GetIDsOfNames(IID_NULL, &sindex , 1, LOCALE_USER_DEFAULT, &dispid)))
2045 throw BridgeRuntimeError("[automation bridge] UnoConversionUtilities<T>::dispatchExObject2Sequence \n"
2046 "Conversion of dispatch object to Sequence failed!");
2048 if( FAILED( hr= pdispEx->InvokeEx(dispid, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET,
2049 &param, &result, NULL, NULL)))
2051 throw BridgeRuntimeError("[automation bridge] UnoConversionUtilities<T>::dispatchExObject2Sequence \n"
2052 "Conversion of dispatch object to Sequence failed!");
2055 // If the result is VT_DISPATCH than the Sequence's element type could be Sequence
2056 // Look that up in the CoreReflection to make clear.
2057 // That requires a recursiv conversion
2058 Any any;
2059 // Destination address within the out-Sequence "anySeq" where to copy the next converted element
2060 void* pDest= (void*)(pArray + (i * nelementSize));
2062 if( result.vt & VT_DISPATCH && typeElement == typelib_TypeClass_SEQUENCE)
2064 variantToAny( &result, any, elemType, sal_False);
2065 // copy the converted VARIANT, that is a Sequence to the Sequence
2066 uno_Sequence * p_unoSeq= *(uno_Sequence**)any.getValue();
2067 // just copy the pointer of the uno_Sequence
2068 // nelementSize should be 4 !!!!
2069 memcpy( pDest, &p_unoSeq, nelementSize);
2070 osl_atomic_increment( &p_unoSeq->nRefCount);
2072 else // Element type is no Sequence -> do one conversion
2074 variantToAny( &result, any, elemType, sal_False);
2075 if( typeElement == typelib_TypeClass_ANY)
2077 // copy the converted VARIANT to the Sequence
2078 uno_type_assignData( pDest, pSeqElemDescRef , &any, pSeqElemDescRef,cpp_queryInterface,
2079 cpp_acquire, cpp_release);
2081 else
2083 // type after conversion must be the element type of the sequence
2084 OSL_ENSURE( (any.getValueTypeClass() == typeElement), "wrong conversion");
2085 uno_type_assignData( pDest, pSeqElemDescRef,const_cast<void*>( any.getValue()), any.getValueTypeRef(),
2086 cpp_queryInterface, cpp_acquire, cpp_release);
2089 } // else
2090 result.Clear();
2091 anySeq.setValue( &p_uno_Seq, pDesc);
2092 uno_destructData( &p_uno_Seq, pDesc, cpp_release);
2093 typelib_typedescription_release( pDesc);
2095 if (bFail)
2096 throw BridgeRuntimeError(
2097 "[automation bridge] Conversion of ValueObject failed ");
2099 catch (const BridgeRuntimeError &)
2101 throw;
2103 catch (const Exception & e)
2105 throw BridgeRuntimeError("[automation bridge] unexpected exception in "
2106 "UnoConversionUtilities<T>::convertValueObject ! Message : \n" +
2107 e.Message);
2109 catch(...)
2111 throw BridgeRuntimeError(
2112 "[automation bridge] unexpected exception in "
2113 "UnoConversionUtilities<T>::convertValueObject !");
2117 /* The argument unotype is the type that is expected by the currently called UNO function.
2118 For example: []long, [][]long. If the function calls itself recursively then the element type
2119 is passed on. For example a two dimensional SAFEARRAY of type VT_I4 is to be converted. Then
2120 unotype has to be either void or [][]long. When the function calls itself recursivly then
2121 it passes the element type which is []long.
2123 template<class T>
2124 Sequence<Any> UnoConversionUtilities<T>::createOleArrayWrapperOfDim(SAFEARRAY* pArray,
2125 unsigned int dimCount, unsigned int actDim, long* index, VARTYPE type, const Type& unotype)
2127 HRESULT hr= S_OK;
2128 long lBound;
2129 long uBound;
2130 long nCountElements;
2132 SafeArrayGetLBound(pArray, actDim, &lBound);
2133 SafeArrayGetUBound(pArray, actDim, &uBound);
2134 nCountElements= uBound - lBound +1;
2136 Sequence<Any> anySeq(nCountElements);
2137 Any* pUnoArray = anySeq.getArray();
2139 for (index[actDim - 1] = lBound; index[actDim - 1] <= uBound; index[actDim - 1]++)
2141 if (actDim > 1 )
2143 Sequence<Any> element = createOleArrayWrapperOfDim(pArray, dimCount,
2144 actDim - 1, index, type, getElementTypeOfSequence(unotype));
2146 pUnoArray[index[actDim - 1] - lBound].setValue(&element, getCppuType(&element));
2148 else
2150 VARIANT variant;
2152 VariantInit(&variant);
2154 V_VT(&variant) = type;
2156 switch (type)
2158 case VT_I2:
2159 SafeArrayGetElement(pArray, index, &V_I2(&variant));
2160 break;
2161 case VT_I4:
2162 SafeArrayGetElement(pArray, index, &V_I4(&variant));
2163 break;
2164 case VT_R4:
2165 SafeArrayGetElement(pArray, index, &V_R4(&variant));
2166 break;
2167 case VT_R8:
2168 SafeArrayGetElement(pArray, index, &V_R8(&variant));
2169 break;
2170 case VT_CY:
2171 SafeArrayGetElement(pArray, index, &V_CY(&variant));
2172 break;
2173 case VT_DATE:
2174 SafeArrayGetElement(pArray, index, &V_DATE(&variant));
2175 break;
2176 case VT_BSTR:
2177 hr= SafeArrayGetElement(pArray, index, &V_BSTR(&variant));
2178 break;
2179 case VT_DISPATCH:
2180 SafeArrayGetElement(pArray, index, &V_DISPATCH(&variant));
2181 break;
2182 case VT_ERROR:
2183 SafeArrayGetElement(pArray, index, &V_ERROR(&variant));
2184 break;
2185 case VT_BOOL:
2186 SafeArrayGetElement(pArray, index, &V_BOOL(&variant));
2187 break;
2188 case VT_VARIANT:
2189 SafeArrayGetElement(pArray, index, &variant);
2190 break;
2191 case VT_UNKNOWN:
2192 SafeArrayGetElement(pArray, index, &V_UNKNOWN(&variant));
2193 break;
2194 case VT_I1:
2195 SafeArrayGetElement(pArray, index, &V_I1(&variant));
2196 break;
2197 case VT_UI1:
2198 SafeArrayGetElement(pArray, index, &V_UI1(&variant));
2199 break;
2200 case VT_UI2:
2201 SafeArrayGetElement(pArray, index, &V_UI2(&variant));
2202 break;
2203 case VT_UI4:
2204 SafeArrayGetElement(pArray, index, &V_UI4(&variant));
2205 break;
2206 default:
2207 break;
2210 if( unotype.getTypeClass() == TypeClass_VOID)
2211 // the function was called without specifying the destination type
2212 variantToAny(&variant, pUnoArray[index[actDim - 1] - lBound], sal_False);
2213 else
2214 variantToAny(&variant, pUnoArray[index[actDim - 1] - lBound],
2215 getElementTypeOfSequence(unotype), sal_False);
2217 VariantClear(&variant);
2220 return anySeq;
2223 template<class T>
2224 Type UnoConversionUtilities<T>::getElementTypeOfSequence( const Type& seqType)
2226 Type retValue;
2227 if( seqType.getTypeClass() != TypeClass_VOID)
2229 OSL_ASSERT( seqType.getTypeClass() == TypeClass_SEQUENCE);
2230 typelib_IndirectTypeDescription* pDescSeq= NULL;
2231 seqType.getDescription((typelib_TypeDescription** ) & pDescSeq);
2232 retValue = Type(pDescSeq->pType);
2233 typelib_typedescription_release( (typelib_TypeDescription*) pDescSeq);
2235 return retValue;
2237 template<class T>
2238 Sequence<Any> UnoConversionUtilities<T>::createOleArrayWrapper(SAFEARRAY* pArray, VARTYPE type, const Type& unoType)
2240 sal_uInt32 dim = SafeArrayGetDim(pArray);
2242 Sequence<Any> ret;
2244 if (dim > 0)
2246 scoped_array<long> sarIndex(new long[dim]);
2247 long * index = sarIndex.get();
2249 for (unsigned int i = 0; i < dim; i++)
2251 index[i] = 0;
2254 ret = createOleArrayWrapperOfDim(pArray, dim, dim, index, type, unoType);
2257 return ret;
2260 // If an VARIANT has the type VT_DISPATCH it can either be an JScript Array
2261 // or some other object. This function finds out if it is such an array or
2262 // not. Currently there's no way to make sure it's an array
2263 // so we assume that when the object has a property "0" then it is an Array.
2264 // An JScript has property like "0", "1", "2" etc. which represent the
2265 // value at the corresponding index of the array
2266 template<class T>
2267 sal_Bool UnoConversionUtilities<T>::isJScriptArray(const VARIANT* rvar)
2269 OSL_ENSURE( rvar->vt == VT_DISPATCH, "param is not a VT_DISPATCH");
2270 HRESULT hr;
2271 OLECHAR* sindex= L"0";
2272 DISPID id;
2273 if ( rvar->vt == VT_DISPATCH && rvar->pdispVal )
2275 hr= rvar->pdispVal->GetIDsOfNames( IID_NULL, &sindex, 1,
2276 LOCALE_USER_DEFAULT, &id);
2278 if( SUCCEEDED ( hr) )
2279 return sal_True;
2282 return sal_False;
2285 template<class T>
2286 VARTYPE UnoConversionUtilities<T>::mapTypeClassToVartype( TypeClass type)
2288 VARTYPE ret;
2289 switch( type)
2291 case TypeClass_INTERFACE: ret= VT_DISPATCH;
2292 break;
2293 case TypeClass_STRUCT: ret= VT_DISPATCH;
2294 break;
2295 case TypeClass_ENUM: ret= VT_I4;
2296 break;
2297 case TypeClass_SEQUENCE: ret= VT_ARRAY;
2298 break;
2299 case TypeClass_ANY: ret= VT_VARIANT;
2300 break;
2301 case TypeClass_BOOLEAN: ret= VT_BOOL;
2302 break;
2303 case TypeClass_CHAR: ret= VT_I2;
2304 break;
2305 case TypeClass_STRING: ret= VT_BSTR;
2306 break;
2307 case TypeClass_FLOAT: ret= VT_R4;
2308 break;
2309 case TypeClass_DOUBLE: ret= VT_R8;
2310 break;
2311 case TypeClass_BYTE: ret= VT_UI1;
2312 break;
2313 case TypeClass_SHORT: ret= VT_I2;
2314 break;
2315 case TypeClass_LONG: ret= VT_I4;
2316 break;
2317 case TypeClass_UNSIGNED_SHORT: ret= VT_UI2;
2318 break;
2319 case TypeClass_UNSIGNED_LONG: ret= VT_UI4;
2320 break;
2321 default:
2322 ret= VT_EMPTY;
2324 return ret;
2327 template<class T>
2328 Sequence<Type> UnoConversionUtilities<T>::getImplementedInterfaces(IUnknown* pUnk)
2330 Sequence<Type> seqTypes;
2331 CComDispatchDriver disp( pUnk);
2332 if( disp)
2334 CComVariant var;
2335 HRESULT hr= S_OK;
2336 // There are two different property names possible.
2337 if( FAILED( hr= disp.GetPropertyByName( SUPPORTED_INTERFACES_PROP, &var)))
2339 hr= disp.GetPropertyByName( SUPPORTED_INTERFACES_PROP2, &var);
2341 if (SUCCEEDED( hr))
2343 // we exspect an array( SafeArray or IDispatch) of Strings.
2344 Any anyNames;
2345 variantToAny( &var, anyNames, getCppuType( (Sequence<Any>*) 0));
2346 Sequence<Any> seqAny;
2347 if( anyNames >>= seqAny)
2349 seqTypes.realloc( seqAny.getLength());
2350 for( sal_Int32 i=0; i < seqAny.getLength(); i++)
2352 OUString typeName;
2353 seqAny[i] >>= typeName;
2354 seqTypes[i]= Type( TypeClass_INTERFACE, typeName);
2359 return seqTypes;
2361 template<class T>
2362 Reference<XTypeConverter> UnoConversionUtilities<T>::getTypeConverter()
2364 if ( ! m_typeConverter.is())
2366 MutexGuard guard(getBridgeMutex());
2367 if ( ! m_typeConverter.is())
2369 Reference<XInterface> xIntConverter =
2370 m_smgr->createInstance("com.sun.star.script.Converter");
2371 if (xIntConverter.is())
2372 m_typeConverter = Reference<XTypeConverter>(xIntConverter, UNO_QUERY);
2375 return m_typeConverter;
2378 // This function tries to the change the type of a value (contained in the Any)
2379 // to the smallest possible that can hold the value. This is actually done only
2380 // for types of VT_I4 (see o2u_variantToAny). The reason is the following:
2381 // JavaScript passes integer values always as VT_I4. If there is a parameter or
2382 // property of type any then the bridge converts the any's content according
2383 // to "o2u_variantToAny". Because the VARTYPE is VT_I4 the value would be converted
2384 // to TypeClass_LONG. Say the method XPropertySet::setPropertyValue( string name, any value)
2385 // would be called on an object and the property actually is of TypeClass_SHORT.
2386 // After conversion of the VARIANT parameter the Any would contain type
2387 // TypeClass_LONG. Because the corereflection does not cast from long to short
2388 // the "setPropertValue" would fail as the value has not the right type.
2390 // The corereflection does convert small integer types to bigger types.
2391 // Therefore we can reduce the type if possible and avoid the above mentioned
2392 // problem.
2394 // The function is not used when elements are to be converted for Sequences.
2396 #ifndef _REDUCE_RANGE
2397 #define _REDUCE_RANGE
2398 inline void reduceRange( Any& any)
2400 OSL_ASSERT( any.getValueTypeClass() == TypeClass_LONG);
2402 sal_Int32 value= *(sal_Int32*)any.getValue();
2403 if( value <= 0x7f && value >= -0x80)
2404 {// -128 bis 127
2405 sal_Int8 charVal= static_cast<sal_Int8>( value);
2406 any.setValue( &charVal, getCppuType( (sal_Int8*)0));
2408 else if( value <= 0x7fff && value >= -0x8000)
2409 {// -32768 bis 32767
2410 sal_Int16 shortVal= static_cast<sal_Int16>( value);
2411 any.setValue( &shortVal, getCppuType( (sal_Int16*)0));
2414 #endif
2418 } // end namespace
2419 #endif
2421 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */