From 940b4d1848e8c70ab7642901a68594e8016caffc Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sat, 27 Apr 2024 18:51:28 +0200 Subject: Adding upstream version 1:7.0.4. Signed-off-by: Daniel Baumann --- cppuhelper/source/access_control.cxx | 131 ++ cppuhelper/source/bootstrap.cxx | 242 +++ cppuhelper/source/compat.cxx | 172 ++ cppuhelper/source/component.cxx | 223 ++ cppuhelper/source/component_context.cxx | 596 +++++ cppuhelper/source/defaultbootstrap.cxx | 107 + cppuhelper/source/exc_thrower.cxx | 312 +++ cppuhelper/source/factory.cxx | 967 +++++++++ cppuhelper/source/findsofficepath.c | 219 ++ cppuhelper/source/gcc3.map | 443 ++++ cppuhelper/source/implbase.cxx | 285 +++ cppuhelper/source/implbase_ex.cxx | 413 ++++ cppuhelper/source/implementationentry.cxx | 94 + cppuhelper/source/interfacecontainer.cxx | 595 +++++ .../source/loadsharedlibcomponentfactory.hxx | 44 + cppuhelper/source/macro_expander.cxx | 182 ++ cppuhelper/source/macro_expander.hxx | 59 + cppuhelper/source/paths.cxx | 135 ++ cppuhelper/source/paths.hxx | 40 + cppuhelper/source/propertysetmixin.cxx | 1140 ++++++++++ cppuhelper/source/propshlp.cxx | 1184 ++++++++++ cppuhelper/source/servicemanager.cxx | 1988 +++++++++++++++++ cppuhelper/source/servicemanager.hxx | 351 +++ cppuhelper/source/shlib.cxx | 423 ++++ cppuhelper/source/supportsservice.cxx | 30 + cppuhelper/source/tdmgr.cxx | 660 ++++++ cppuhelper/source/typemanager.cxx | 2279 ++++++++++++++++++++ cppuhelper/source/typemanager.hxx | 128 ++ cppuhelper/source/typeprovider.cxx | 305 +++ cppuhelper/source/unourl.cxx | 266 +++ cppuhelper/source/weak.cxx | 530 +++++ 31 files changed, 14543 insertions(+) create mode 100644 cppuhelper/source/access_control.cxx create mode 100644 cppuhelper/source/bootstrap.cxx create mode 100644 cppuhelper/source/compat.cxx create mode 100644 cppuhelper/source/component.cxx create mode 100644 cppuhelper/source/component_context.cxx create mode 100644 cppuhelper/source/defaultbootstrap.cxx create mode 100644 cppuhelper/source/exc_thrower.cxx create mode 100644 cppuhelper/source/factory.cxx create mode 100644 cppuhelper/source/findsofficepath.c create mode 100644 cppuhelper/source/gcc3.map create mode 100644 cppuhelper/source/implbase.cxx create mode 100644 cppuhelper/source/implbase_ex.cxx create mode 100644 cppuhelper/source/implementationentry.cxx create mode 100644 cppuhelper/source/interfacecontainer.cxx create mode 100644 cppuhelper/source/loadsharedlibcomponentfactory.hxx create mode 100644 cppuhelper/source/macro_expander.cxx create mode 100644 cppuhelper/source/macro_expander.hxx create mode 100644 cppuhelper/source/paths.cxx create mode 100644 cppuhelper/source/paths.hxx create mode 100644 cppuhelper/source/propertysetmixin.cxx create mode 100644 cppuhelper/source/propshlp.cxx create mode 100644 cppuhelper/source/servicemanager.cxx create mode 100644 cppuhelper/source/servicemanager.hxx create mode 100644 cppuhelper/source/shlib.cxx create mode 100644 cppuhelper/source/supportsservice.cxx create mode 100644 cppuhelper/source/tdmgr.cxx create mode 100644 cppuhelper/source/typemanager.cxx create mode 100644 cppuhelper/source/typemanager.hxx create mode 100644 cppuhelper/source/typeprovider.cxx create mode 100644 cppuhelper/source/unourl.cxx create mode 100644 cppuhelper/source/weak.cxx (limited to 'cppuhelper/source') diff --git a/cppuhelper/source/access_control.cxx b/cppuhelper/source/access_control.cxx new file mode 100644 index 000000000..0e18ef786 --- /dev/null +++ b/cppuhelper/source/access_control.cxx @@ -0,0 +1,131 @@ +/* -*- 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 + +#include +#include +#include +#include +#include + +using namespace ::osl; +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; + +namespace +{ + OUString str_ac_singleton() + { + return "/singletons/com.sun.star.security.theAccessController"; + } +} + +namespace cppu +{ + +AccessControl::AccessControl( Reference< XComponentContext > const & xContext ) +{ + if (! (xContext->getValueByName( str_ac_singleton() ) >>= m_xController)) + { + throw SecurityException( "no access controller!" ); + } +} + +AccessControl::AccessControl( + Reference< security::XAccessController > const & xController ) + : m_xController( xController ) +{ + if (! m_xController.is()) + { + throw SecurityException( "no access controller!" ); + } +} + +AccessControl::AccessControl( AccessControl const & ac ) + : m_xController( ac.m_xController ) +{ + if (! m_xController.is()) + { + throw SecurityException( "no access controller!" ); + } +} + +namespace { + +#ifdef _WIN32 +#pragma pack(push, 8) +#endif + // binary comp. to all Permission structs + struct permission + { + rtl_uString * m_str1; + rtl_uString * m_str2; + }; +#ifdef _WIN32 +#pragma pack(pop) +#endif + +void checkPermission( + Reference< security::XAccessController > const & xController, + Type const & type, rtl_uString * str1, rtl_uString * str2 ) +{ + permission perm; + perm.m_str1 = str1; + perm.m_str2 = str2; + + uno_Any a; + a.pType = type.getTypeLibType(); + a.pData = &perm; + + xController->checkPermission( * static_cast< Any * >( &a ) ); +} + +} + +void AccessControl::checkRuntimePermission( + OUString const & name ) +{ + checkPermission( + m_xController, + cppu::UnoType::get(), name.pData, nullptr ); +} + +void AccessControl::checkFilePermission( + OUString const & url, + OUString const & actions ) +{ + checkPermission( + m_xController, + cppu::UnoType::get(), url.pData, actions.pData ); +} + +void AccessControl::checkSocketPermission( + OUString const & host, + OUString const & actions ) +{ + checkPermission( + m_xController, + cppu::UnoType::get(), host.pData, actions.pData ); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/bootstrap.cxx b/cppuhelper/source/bootstrap.cxx new file mode 100644 index 000000000..34ae38823 --- /dev/null +++ b/cppuhelper/source/bootstrap.cxx @@ -0,0 +1,242 @@ +/* -*- 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 + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "macro_expander.hxx" + +namespace com :: sun :: star :: uno { class XComponentContext; } + +using namespace ::osl; +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; + +using rtl::Bootstrap; + +namespace cppu +{ + +BootstrapException::BootstrapException() +{ +} + +BootstrapException::BootstrapException( const OUString & rMessage ) + :m_aMessage( rMessage ) +{ +} + +BootstrapException::BootstrapException( const BootstrapException & e ) +{ + m_aMessage = e.m_aMessage; +} + +BootstrapException::~BootstrapException() +{ +} + +BootstrapException & BootstrapException::operator=( const BootstrapException & e ) +{ + m_aMessage = e.m_aMessage; + return *this; +} + +const OUString & BootstrapException::getMessage() const +{ + return m_aMessage; +} + +Reference< XComponentContext > SAL_CALL bootstrap() +{ + Reference< XComponentContext > xRemoteContext; + + try + { + auto* p1 = cppuhelper_detail_findSofficePath(); + if (p1 == nullptr) { + throw BootstrapException( + "no soffice installation found!"); + } + OUString p2; +#if defined(_WIN32) + p2 = o3tl::toU(p1); + free(p1); +#else + bool bOk = rtl_convertStringToUString( + &p2.pData, p1, std::strlen(p1), osl_getThreadTextEncoding(), + (RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR | + RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR | + RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR)); + free(p1); + if (!bOk) + { + throw BootstrapException( + "bad characters in soffice installation path!"); + } +#endif + OUString path; + if (osl::FileBase::getFileURLFromSystemPath(p2, path) != + osl::FileBase::E_None) + { + throw BootstrapException( + "cannot convert soffice installation path to URL!"); + } + if (!path.isEmpty() && !path.endsWith("/")) { + path += "/"; + } + + OUString uri; + if (!Bootstrap::get("URE_BOOTSTRAP", uri)) { + Bootstrap::set( + "URE_BOOTSTRAP", + Bootstrap::encode( + path + +#if defined MACOSX + "../Resources/" +#endif + SAL_CONFIGFILE("fundamental"))); + } + + // create default local component context + Reference< XComponentContext > xLocalContext( + defaultBootstrap_InitialComponentContext() ); + if ( !xLocalContext.is() ) + throw BootstrapException( "no local component context!" ); + + // create a random pipe name + rtlRandomPool hPool = rtl_random_createPool(); + if ( hPool == nullptr ) + throw BootstrapException( "cannot create random pool!" ); + sal_uInt8 bytes[ 16 ]; + if ( rtl_random_getBytes( hPool, bytes, SAL_N_ELEMENTS( bytes ) ) + != rtl_Random_E_None ) + throw BootstrapException( "random pool error!" ); + rtl_random_destroyPool( hPool ); + OUStringBuffer buf("uno"); + for (unsigned char byte : bytes) + buf.append( static_cast< sal_Int32 >( byte ) ); + OUString sPipeName( buf.makeStringAndClear() ); + + // arguments + OUString args [] = { + OUString("--nologo"), + OUString("--nodefault"), + OUString("--norestore"), + OUString("--nolockcheck"), + OUString("--accept=pipe,name=" + sPipeName + ";urp;") + }; + rtl_uString * ar_args [] = { + args[ 0 ].pData, + args[ 1 ].pData, + args[ 2 ].pData, + args[ 3 ].pData, + args[ 4 ].pData + }; + ::osl::Security sec; + + // start office process + oslProcess hProcess = nullptr; + oslProcessError rc = osl_executeProcess( + OUString(path + "soffice").pData, ar_args, SAL_N_ELEMENTS( ar_args ), + osl_Process_DETACHED, + sec.getHandle(), + nullptr, // => current working dir + nullptr, 0, // => no env vars + &hProcess ); + switch ( rc ) + { + case osl_Process_E_None: + osl_freeProcessHandle( hProcess ); + break; + case osl_Process_E_NotFound: + throw BootstrapException( "image not found!" ); + case osl_Process_E_TimedOut: + throw BootstrapException( "timeout occurred!" ); + case osl_Process_E_NoPermission: + throw BootstrapException( "permission denied!" ); + case osl_Process_E_Unknown: + throw BootstrapException( "unknown error!" ); + case osl_Process_E_InvalidError: + default: + throw BootstrapException( "unmapped error!" ); + } + + // create a URL resolver + Reference< bridge::XUnoUrlResolver > xUrlResolver( + bridge::UnoUrlResolver::create( xLocalContext ) ); + + // connection string + OUString sConnectString( "uno:pipe,name=" + sPipeName + ";urp;StarOffice.ComponentContext" ); + + // wait until office is started + for ( ; ; ) + { + try + { + // try to connect to office + xRemoteContext.set( + xUrlResolver->resolve( sConnectString ), UNO_QUERY_THROW ); + break; + } + catch ( connection::NoConnectException & ) + { + // wait 500 ms, then try to connect again + ::osl::Thread::wait( std::chrono::milliseconds(500) ); + } + } + } + catch ( Exception & e ) + { + throw BootstrapException( + "unexpected UNO exception caught: " + e.Message ); + } + + return xRemoteContext; +} + +OUString bootstrap_expandUri(OUString const & uri) { + OUString rest; + return uri.startsWith("vnd.sun.star.expand:", &rest) + ? cppuhelper::detail::expandMacros( + rtl::Uri::decode( + rest, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8)) + : uri; +} + +} // namespace cppu + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/compat.cxx b/cppuhelper/source/compat.cxx new file mode 100644 index 000000000..f6572ea47 --- /dev/null +++ b/cppuhelper/source/compat.cxx @@ -0,0 +1,172 @@ +/* -*- 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 + +#include + +#include +#include +#include +#include + +namespace com::sun::star { + namespace lang { + class XMultiComponentFactory; + class XMultiServiceFactory; + class XTypeProvider; + } + namespace reflection { class XIdlClass; } + namespace registry { + class XRegistryKey; + class XSimpleRegistry; + } + namespace uno { + class XComponentContext; + class XInterface; + } +} + +// Stubs for removed functionality, to be killed when we bump cppuhelper SONAME + +namespace cppu { + +SAL_DLLPUBLIC_EXPORT +css::uno::Reference< css::lang::XMultiComponentFactory > bootstrapInitialSF( + OUString const &) +{ + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::uno::XComponentContext > SAL_CALL +bootstrap_InitialComponentContext( + css::uno::Reference< css::registry::XSimpleRegistry > const &, + OUString const &) +{ + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::registry::XSimpleRegistry > +SAL_CALL createNestedRegistry(OUString const &) { + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::lang::XMultiServiceFactory > +SAL_CALL createRegistryServiceFactory( + OUString const &, OUString const &, sal_Bool, + OUString const &) +{ + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +SAL_DLLPUBLIC_EXPORT css::uno::Reference< css::registry::XSimpleRegistry > +SAL_CALL createSimpleRegistry(OUString const &) { + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +SAL_DLLPUBLIC_EXPORT css::reflection::XIdlClass * SAL_CALL +createStandardClassWithSequence( + css::uno::Reference< css::lang::XMultiServiceFactory > const &, + OUString const &, + css::uno::Reference< css::reflection::XIdlClass > const &, + css::uno::Sequence< OUString > const &) +{ + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +SAL_DLLPUBLIC_EXPORT css::uno::Reference SAL_CALL +invokeStaticComponentFactory( + oslGenericFunction, OUString const &, + css::uno::Reference const &, + css::uno::Reference const &, + OUString const &) +{ + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +SAL_DLLPUBLIC_EXPORT css::uno::Reference SAL_CALL +loadSharedLibComponentFactory( + OUString const &, OUString const &, OUString const &, + css::uno::Reference const &, + css::uno::Reference const &, + OUString const &) +{ + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +struct SAL_DLLPUBLIC_EXPORT ClassData { + css::uno::Sequence SAL_CALL getImplementationId(); + + css::uno::Sequence SAL_CALL getTypes(); + + void SAL_CALL initTypeProvider(); + + css::uno::Any SAL_CALL query( + css::uno::Type const &, css::lang::XTypeProvider *); + + void SAL_CALL writeTypeOffset(css::uno::Type const &, sal_Int32); +}; + +css::uno::Sequence ClassData::getImplementationId() { + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +css::uno::Sequence ClassData::getTypes() { + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +void ClassData::initTypeProvider() { + std::abort(); +} + +css::uno::Any ClassData::query( + css::uno::Type const &, css::lang::XTypeProvider *) +{ + for (;;) { std::abort(); } // avoid "must return a value" warnings +} + +void ClassData::writeTypeOffset(css::uno::Type const &, sal_Int32) { + std::abort(); +} + +SAL_WNOUNREACHABLE_CODE_PUSH +struct SAL_DLLPUBLIC_EXPORT ClassDataBase { + ClassDataBase(); + + explicit ClassDataBase(sal_Int32); + + ~ClassDataBase(); +}; + +ClassDataBase::ClassDataBase() { + std::abort(); +} + +ClassDataBase::ClassDataBase(sal_Int32) { + std::abort(); +} + +ClassDataBase::~ClassDataBase() { + std::abort(); +} +SAL_WNOUNREACHABLE_CODE_POP + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/component.cxx b/cppuhelper/source/component.cxx new file mode 100644 index 000000000..c88713287 --- /dev/null +++ b/cppuhelper/source/component.cxx @@ -0,0 +1,223 @@ +/* -*- 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 +#include +#include +#include +#include +#include +#include + +using namespace osl; +using namespace com::sun::star; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; + +namespace cppu +{ + + +// class OComponentHelper + + +OComponentHelper::OComponentHelper( Mutex & rMutex ) + : rBHelper( rMutex ) +{ +} +OComponentHelper::~OComponentHelper() +{ +} + +Any OComponentHelper::queryInterface( Type const & rType ) +{ + return OWeakAggObject::queryInterface( rType ); +} +Any OComponentHelper::queryAggregation( Type const & rType ) +{ + if (rType == cppu::UnoType::get()) + { + void * p = static_cast< lang::XComponent * >( this ); + return Any( &p, rType ); + } + if (rType == cppu::UnoType::get()) + { + void * p = static_cast< lang::XTypeProvider * >( this ); + return Any( &p, rType ); + } + return OWeakAggObject::queryAggregation( rType ); +} +void OComponentHelper::acquire() throw () +{ + OWeakAggObject::acquire(); +} + +void OComponentHelper::release() throw() +{ + Reference x( xDelegator ); + if (! x.is()) + { + if (osl_atomic_decrement( &m_refCount ) == 0) + { + if (! rBHelper.bDisposed) + { + // *before* again incrementing our ref count, ensure that our weak connection point + // will not create references to us anymore (via XAdapter::queryAdapted) + disposeWeakConnectionPoint(); + + Reference xHoldAlive( *this ); + // First dispose + try + { + dispose(); + } + catch (css::uno::RuntimeException & exc) + { + // release should not throw exceptions + SAL_WARN( "cppuhelper", exc ); + } + + // only the alive ref holds the object + OSL_ASSERT( m_refCount == 1 ); + // destroy the object if xHoldAlive decrement the refcount to 0 + return; + } + } + // restore the reference count + osl_atomic_increment( &m_refCount ); + } + OWeakAggObject::release(); +} + +Sequence< Type > OComponentHelper::getTypes() +{ + static OTypeCollection s_aTypes( + cppu::UnoType::get(), + cppu::UnoType::get(), + cppu::UnoType::get(), + cppu::UnoType::get() ); + + return s_aTypes.getTypes(); +} + +// XComponent +void OComponentHelper::disposing() +{ +} + +// XComponent +void OComponentHelper::dispose() +{ + // An frequently programming error is to release the last + // reference to this object in the disposing message. + // Make it robust, hold a self Reference. + Reference xSelf( this ); + + // Guard dispose against multiple threading + // Remark: It is an error to call dispose more than once + bool bDoDispose = false; + { + MutexGuard aGuard( rBHelper.rMutex ); + if( !rBHelper.bDisposed && !rBHelper.bInDispose ) + { + // only one call go into this section + rBHelper.bInDispose = true; + bDoDispose = true; + } + } + + // Do not hold the mutex because we are broadcasting + if( bDoDispose ) + { + // Create an event with this as sender + try + { + try + { + Reference xSource( + Reference::query( static_cast(this) ) ); + EventObject aEvt; + aEvt.Source = xSource; + // inform all listeners to release this object + // The listener container are automatically cleared + rBHelper.aLC.disposeAndClear( aEvt ); + // notify subclasses to do their dispose + disposing(); + } + catch (...) + { + MutexGuard aGuard( rBHelper.rMutex ); + // bDispose and bInDisposing must be set in this order: + rBHelper.bDisposed = true; + rBHelper.bInDispose = false; + throw; + } + MutexGuard aGuard( rBHelper.rMutex ); + // bDispose and bInDisposing must be set in this order: + rBHelper.bDisposed = true; + rBHelper.bInDispose = false; + } + catch (RuntimeException &) + { + throw; + } + catch (Exception & exc) + { + css::uno::Any anyEx = cppu::getCaughtException(); + throw lang::WrappedTargetRuntimeException( + "unexpected UNO exception caught: " + exc.Message, + nullptr, anyEx ); + } + } + else + { + // in a multithreaded environment, it can't be avoided + // that dispose is called twice. + // However this condition is traced, because it MAY indicate an error. + SAL_WARN("cppuhelper", "OComponentHelper::dispose() - dispose called twice" ); + } +} + +// XComponent +void OComponentHelper::addEventListener( + const Reference & rxListener ) +{ + ClearableMutexGuard aGuard( rBHelper.rMutex ); + if (rBHelper.bDisposed || rBHelper.bInDispose) + { + aGuard.clear(); + Reference< XInterface > x( static_cast(this), UNO_QUERY ); + rxListener->disposing( EventObject( x ) ); + } + else + { + rBHelper.addListener( cppu::UnoType::get(), rxListener ); + } +} + +// XComponent +void OComponentHelper::removeEventListener( + const Reference & rxListener ) +{ + rBHelper.removeListener( cppu::UnoType::get(), rxListener ); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/component_context.cxx b/cppuhelper/source/component_context.cxx new file mode 100644 index 000000000..739be2800 --- /dev/null +++ b/cppuhelper/source/component_context.cxx @@ -0,0 +1,596 @@ +/* -*- 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 + +#include +#include + +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#define SMGR_SINGLETON "/singletons/com.sun.star.lang.theServiceManager" +#define TDMGR_SINGLETON "/singletons/com.sun.star.reflection.theTypeDescriptionManager" +#define AC_SINGLETON "/singletons/com.sun.star.security.theAccessController" + +using namespace ::osl; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star; + +namespace cppu +{ + +static void try_dispose( Reference< XInterface > const & xInstance ) +{ + Reference< lang::XComponent > xComp( xInstance, UNO_QUERY ); + if (xComp.is()) + { + xComp->dispose(); + } +} + +static void try_dispose( Reference< lang::XComponent > const & xComp ) +{ + if (xComp.is()) + { + xComp->dispose(); + } +} + +namespace { + +class DisposingForwarder + : public WeakImplHelper< lang::XEventListener > +{ + Reference< lang::XComponent > m_xTarget; + + explicit DisposingForwarder( Reference< lang::XComponent > const & xTarget ) + : m_xTarget( xTarget ) + { + OSL_ASSERT( m_xTarget.is() ); + } +public: + // listens at source for disposing, then disposes target + static inline void listen( + Reference< lang::XComponent > const & xSource, + Reference< lang::XComponent > const & xTarget ); + + virtual void SAL_CALL disposing( lang::EventObject const & rSource ) override; +}; + +} + +inline void DisposingForwarder::listen( + Reference< lang::XComponent > const & xSource, + Reference< lang::XComponent > const & xTarget ) +{ + if (xSource.is()) + { + xSource->addEventListener( new DisposingForwarder( xTarget ) ); + } +} + +void DisposingForwarder::disposing( lang::EventObject const & ) +{ + m_xTarget->dispose(); + m_xTarget.clear(); +} + +namespace { + +struct MutexHolder +{ +protected: + Mutex m_mutex; +}; + + +class ComponentContext + : private MutexHolder + , public WeakComponentImplHelper< XComponentContext, + container::XNameContainer > +{ +protected: + Reference< XComponentContext > m_xDelegate; + + struct ContextEntry + { + Any value; + bool lateInit; + + ContextEntry( Any const & value_, bool lateInit_ ) + : value( value_ ) + , lateInit( lateInit_ ) + {} + }; + typedef std::unordered_map< OUString, ContextEntry > t_map; + t_map m_map; + + Reference< lang::XMultiComponentFactory > m_xSMgr; + +protected: + Any lookupMap( OUString const & rName ); + + virtual void SAL_CALL disposing() override; +public: + ComponentContext( + ContextEntry_Init const * pEntries, sal_Int32 nEntries, + Reference< XComponentContext > const & xDelegate ); + + // XComponentContext + virtual Any SAL_CALL getValueByName( OUString const & rName ) override; + virtual Reference SAL_CALL getServiceManager() override; + + // XNameContainer + virtual void SAL_CALL insertByName( + OUString const & name, Any const & element ) override; + virtual void SAL_CALL removeByName( OUString const & name ) override; + // XNameReplace + virtual void SAL_CALL replaceByName( + OUString const & name, Any const & element ) override; + // XNameAccess + virtual Any SAL_CALL getByName( OUString const & name ) override; + virtual Sequence SAL_CALL getElementNames() override; + virtual sal_Bool SAL_CALL hasByName( OUString const & name ) override; + // XElementAccess + virtual Type SAL_CALL getElementType() override; + virtual sal_Bool SAL_CALL hasElements() override; +}; + +} + +// XNameContainer + +void ComponentContext::insertByName( + OUString const & name, Any const & element ) +{ + ContextEntry entry( + element, + /* lateInit_: */ + name.startsWith( "/singletons/" ) && + !element.hasValue() ); + MutexGuard guard( m_mutex ); + std::pair insertion( m_map.emplace( + name, entry ) ); + if (! insertion.second) + throw container::ElementExistException( + "element already exists: " + name, + static_cast(this) ); +} + + +void ComponentContext::removeByName( OUString const & name ) +{ + MutexGuard guard( m_mutex ); + t_map::iterator iFind( m_map.find( name ) ); + if (iFind == m_map.end()) + throw container::NoSuchElementException( + "no such element: " + name, + static_cast(this) ); + + m_map.erase(iFind); +} + +// XNameReplace + +void ComponentContext::replaceByName( + OUString const & name, Any const & element ) +{ + MutexGuard guard( m_mutex ); + t_map::iterator iFind( m_map.find( name ) ); + if (iFind == m_map.end()) + throw container::NoSuchElementException( + "no such element: " + name, + static_cast(this) ); + if (name.startsWith( "/singletons/" ) && + !element.hasValue()) + { + iFind->second.value.clear(); + iFind->second.lateInit = true; + } + else + { + iFind->second.value = element; + iFind->second.lateInit = false; + } +} + +// XNameAccess + +Any ComponentContext::getByName( OUString const & name ) +{ + return getValueByName( name ); +} + + +Sequence ComponentContext::getElementNames() +{ + MutexGuard guard( m_mutex ); + return comphelper::mapKeysToSequence(m_map); +} + + +sal_Bool ComponentContext::hasByName( OUString const & name ) +{ + MutexGuard guard( m_mutex ); + return m_map.find( name ) != m_map.end(); +} + +// XElementAccess + +Type ComponentContext::getElementType() +{ + return cppu::UnoType::get(); +} + + +sal_Bool ComponentContext::hasElements() +{ + MutexGuard guard( m_mutex ); + return ! m_map.empty(); +} + + +Any ComponentContext::lookupMap( OUString const & rName ) +{ + ResettableMutexGuard guard( m_mutex ); + t_map::iterator iFind( m_map.find( rName ) ); + if (iFind == m_map.end()) + return Any(); + + ContextEntry& rFindEntry = iFind->second; + if (! rFindEntry.lateInit) + return rFindEntry.value; + + // late init singleton entry + Reference< XInterface > xInstance; + guard.clear(); + + try + { + Any usesService( getValueByName( rName + "/service" ) ); + Any args_( getValueByName( rName + "/arguments" ) ); + Sequence args; + if (args_.hasValue() && !(args_ >>= args)) + { + args.realloc( 1 ); + args[ 0 ] = args_; + } + + Reference< lang::XSingleComponentFactory > xFac; + if (usesService >>= xFac) // try via factory + { + xInstance = args.hasElements() + ? xFac->createInstanceWithArgumentsAndContext( args, this ) + : xFac->createInstanceWithContext( this ); + } + else + { + Reference< lang::XSingleServiceFactory > xFac2; + if (usesService >>= xFac2) + { + // try via old XSingleServiceFactory + xInstance = args.hasElements() + ? xFac2->createInstanceWithArguments( args ) + : xFac2->createInstance(); + } + else if (m_xSMgr.is()) // optionally service name + { + OUString serviceName; + if ((usesService >>= serviceName) && + !serviceName.isEmpty()) + { + xInstance = args.hasElements() + ? m_xSMgr->createInstanceWithArgumentsAndContext( + serviceName, args, this ) + : m_xSMgr->createInstanceWithContext( + serviceName, this ); + } + } + } + } + catch (const RuntimeException &) + { + throw; + } + catch (const Exception & exc) + { + SAL_WARN( + "cppuhelper", + "exception occurred raising singleton \"" << rName << "\": " + << exc); + } + + SAL_WARN_IF(!xInstance.is(), + "cppuhelper", "no service object raising singleton " << rName); + + Any ret; + guard.reset(); + iFind = m_map.find( rName ); + if (iFind != m_map.end()) + { + ContextEntry & rEntry = iFind->second; + if (rEntry.lateInit) + { + rEntry.value <<= xInstance; + rEntry.lateInit = false; + return rEntry.value; + } + ret = rEntry.value; + } + guard.clear(); + if (ret != xInstance) { + try_dispose( xInstance ); + } + return ret; +} + + +Any ComponentContext::getValueByName( OUString const & rName ) +{ + // to determine the root context: + if ( rName == "_root" ) + { + if (m_xDelegate.is()) + return m_xDelegate->getValueByName( rName ); + return Any( Reference(this) ); + } + + Any ret( lookupMap( rName ) ); + if (!ret.hasValue() && m_xDelegate.is()) + { + return m_xDelegate->getValueByName( rName ); + } + return ret; +} + +Reference< lang::XMultiComponentFactory > ComponentContext::getServiceManager() +{ + if ( !m_xSMgr.is() ) + { + throw DeploymentException( + "null component context service manager", + static_cast(this) ); + } + return m_xSMgr; +} + +void ComponentContext::disposing() +{ + Reference< lang::XComponent > xTDMgr, xAC; // to be disposed separately + + // dispose all context objects + for ( auto& [rName, rEntry] : m_map ) + { + // service manager disposed separately + if (!m_xSMgr.is() || + !rName.startsWith( SMGR_SINGLETON )) + { + if (rEntry.lateInit) + { + // late init + MutexGuard guard( m_mutex ); + if (rEntry.lateInit) + { + rEntry.value.clear(); // release factory + rEntry.lateInit = false; + continue; + } + } + + Reference< lang::XComponent > xComp; + rEntry.value >>= xComp; + if (xComp.is()) + { + if ( rName == TDMGR_SINGLETON ) + { + xTDMgr = xComp; + } + else if ( rName == AC_SINGLETON ) + { + xAC = xComp; + } + else // dispose immediately + { + xComp->dispose(); + } + } + } + } + + // dispose service manager + try_dispose( m_xSMgr ); + m_xSMgr.clear(); + // dispose ac + try_dispose( xAC ); + // dispose tdmgr; revokes callback from cppu runtime + try_dispose( xTDMgr ); + + m_map.clear(); + + // Hack to terminate any JNI bridge's AsynchronousFinalizer thread (as JNI + // proxies get finalized with arbitrary delay, so the bridge typically does + // not dispose itself early enough before the process exits): + uno_Environment ** envs; + sal_Int32 envCount; + uno_getRegisteredEnvironments( + &envs, &envCount, &rtl_allocateMemory, OUString("java").pData); + assert(envCount >= 0); + assert(envCount == 0 || envs != nullptr); + if (envs) { + for (sal_Int32 i = 0; i != envCount; ++i) { + assert(envs[i] != nullptr); + assert(envs[i]->dispose != nullptr); + (*envs[i]->dispose)(envs[i]); + } + std::free(envs); + } +} + +ComponentContext::ComponentContext( + ContextEntry_Init const * pEntries, sal_Int32 nEntries, + Reference< XComponentContext > const & xDelegate ) + : WeakComponentImplHelper( m_mutex ), + m_xDelegate( xDelegate ) +{ + for ( sal_Int32 nPos = 0; nPos < nEntries; ++nPos ) + { + ContextEntry_Init const & rEntry = pEntries[ nPos ]; + + if ( rEntry.name == SMGR_SINGLETON ) + { + rEntry.value >>= m_xSMgr; + } + + if (rEntry.bLateInitService) + { + // singleton entry + m_map.emplace( rEntry.name, ContextEntry( Any(), true ) ); + // service + m_map.emplace( rEntry.name + "/service", ContextEntry( rEntry.value, false ) ); + // initial-arguments are provided as optional context entry + } + else + { + // only value, no late init factory nor string + m_map.emplace( rEntry.name, ContextEntry( rEntry.value, false ) ); + } + } + + if (!(!m_xSMgr.is() && m_xDelegate.is())) + return; + + // wrap delegate's smgr XPropertySet into new smgr + Reference< lang::XMultiComponentFactory > xMgr( m_xDelegate->getServiceManager() ); + if (!xMgr.is()) + return; + + osl_atomic_increment( &m_refCount ); + try + { + // create new smgr based on delegate's one + m_xSMgr.set( + xMgr->createInstanceWithContext( + "com.sun.star.comp.stoc.OServiceManagerWrapper", xDelegate ), + UNO_QUERY ); + // patch DefaultContext property of new one + Reference< beans::XPropertySet > xProps( m_xSMgr, UNO_QUERY ); + OSL_ASSERT( xProps.is() ); + if (xProps.is()) + { + Reference< XComponentContext > xThis( this ); + xProps->setPropertyValue( "DefaultContext", Any( xThis ) ); + } + } + catch (...) + { + osl_atomic_decrement( &m_refCount ); + throw; + } + osl_atomic_decrement( &m_refCount ); + OSL_ASSERT( m_xSMgr.is() ); +} + + +extern "C" { static void s_createComponentContext_v(va_list * pParam) +{ + ContextEntry_Init const * pEntries = va_arg(*pParam, ContextEntry_Init const *); + sal_Int32 nEntries = va_arg(*pParam, sal_Int32); + XComponentContext * pDelegatee = va_arg(*pParam, XComponentContext *); + void ** ppContext = va_arg(*pParam, void **); + uno::Mapping * pTarget2curr = va_arg(*pParam, uno::Mapping *); + + Reference xDelegate(pDelegatee, SAL_NO_ACQUIRE); + Reference xContext; + + if (nEntries > 0) + { + try + { + ComponentContext * p = new ComponentContext( pEntries, nEntries, xDelegate ); + xContext.set(p); + // listen delegate for disposing, to dispose this (wrapping) context first. + DisposingForwarder::listen( Reference< lang::XComponent >::query( xDelegate ), p ); + } + catch (Exception & exc) + { + SAL_WARN( "cppuhelper", exc ); + xContext.clear(); + } + } + else + { + xContext = xDelegate; + } + + *ppContext = pTarget2curr->mapInterface(xContext.get(), cppu::UnoType::get()); +}} + +Reference< XComponentContext > SAL_CALL createComponentContext( + ContextEntry_Init const * pEntries, sal_Int32 nEntries, + Reference< XComponentContext > const & xDelegate ) +{ + uno::Environment curr_env(Environment::getCurrent()); + uno::Environment source_env(CPPU_CURRENT_LANGUAGE_BINDING_NAME); + + uno::Mapping curr2source(curr_env, source_env); + uno::Mapping source2curr(source_env, curr_env); + + std::unique_ptr mapped_entries(new ContextEntry_Init[nEntries]); + for (sal_Int32 nPos = 0; nPos < nEntries; ++ nPos) + { + mapped_entries[nPos].bLateInitService = pEntries[nPos].bLateInitService; + mapped_entries[nPos].name = pEntries[nPos].name; + + uno_type_any_constructAndConvert(&mapped_entries[nPos].value, + const_cast(pEntries[nPos].value.getValue()), + pEntries[nPos].value.getValueTypeRef(), + curr2source.get()); + } + + void * mapped_delegate = curr2source.mapInterface(xDelegate.get(), cppu::UnoType::get()); + XComponentContext * pXComponentContext = nullptr; + source_env.invoke(s_createComponentContext_v, mapped_entries.get(), nEntries, mapped_delegate, &pXComponentContext, &source2curr); + mapped_entries.reset(); + + return Reference(pXComponentContext, SAL_NO_ACQUIRE); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/defaultbootstrap.cxx b/cppuhelper/source/defaultbootstrap.cxx new file mode 100644 index 000000000..4796c92e9 --- /dev/null +++ b/cppuhelper/source/defaultbootstrap.cxx @@ -0,0 +1,107 @@ +/* -*- 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/. + */ + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "macro_expander.hxx" +#include "paths.hxx" +#include "servicemanager.hxx" +#include "typemanager.hxx" + +namespace com :: sun :: star :: uno { class XComponentContext; } + +namespace { + +OUString getBootstrapVariable( + rtl::Bootstrap const & bootstrap, OUString const & name) +{ + OUString v; + if (!bootstrap.getFrom(name, v)) { + throw css::uno::DeploymentException( + "Cannot obtain " + name + " from uno ini"); + } + return v; +} + +} + +css::uno::Reference< css::uno::XComponentContext > +cppu::defaultBootstrap_InitialComponentContext(OUString const & iniUri) +{ + rtl::Bootstrap bs(iniUri); + if (bs.getHandle() == nullptr) { + throw css::uno::DeploymentException( + "Cannot open uno ini " + iniUri); + } + rtl::Reference smgr( + new cppuhelper::ServiceManager); + smgr->init(getBootstrapVariable(bs, "UNO_SERVICES")); + rtl::Reference tmgr(new cppuhelper::TypeManager); + tmgr->init(getBootstrapVariable(bs, "UNO_TYPES")); + std::vector< cppu::ContextEntry_Init > context_values; + context_values.push_back( + cppu::ContextEntry_Init( + "/singletons/com.sun.star.lang.theServiceManager", + css::uno::Any( + css::uno::Reference< css::uno::XInterface >( + static_cast< cppu::OWeakObject * >(smgr.get()))), + false)); + context_values.push_back( + cppu::ContextEntry_Init( + "/singletons/com.sun.star.reflection.theTypeDescriptionManager", + css::uno::Any( + css::uno::Reference< css::uno::XInterface >( + static_cast< cppu::OWeakObject * >(tmgr.get()))), + false)); + context_values.push_back( //TODO: from services.rdb? + cppu::ContextEntry_Init( + "/singletons/com.sun.star.util.theMacroExpander", + css::uno::Any( + cppuhelper::detail::create_bootstrap_macro_expander_factory()), + true)); + smgr->addSingletonContextEntries(&context_values); + context_values.push_back( + cppu::ContextEntry_Init( + "/services/com.sun.star.security.AccessController/mode", + css::uno::Any(OUString("off")), false)); + context_values.push_back( + cppu::ContextEntry_Init( + "/singletons/com.sun.star.security.theAccessController", + css::uno::Any( + OUString("com.sun.star.security.AccessController")), + true)); + assert(!context_values.empty()); + css::uno::Reference< css::uno::XComponentContext > context( + createComponentContext(context_values.data(), context_values.size())); + smgr->setContext(context); + cppu::installTypeDescriptionManager(tmgr.get()); + return context; +} + +css::uno::Reference< css::uno::XComponentContext > +cppu::defaultBootstrap_InitialComponentContext() +{ + return defaultBootstrap_InitialComponentContext(getUnoIniUri()); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/exc_thrower.cxx b/cppuhelper/source/exc_thrower.cxx new file mode 100644 index 000000000..7c40d12db --- /dev/null +++ b/cppuhelper/source/exc_thrower.cxx @@ -0,0 +1,312 @@ +/* -*- 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using namespace ::osl; +using namespace ::cppu; +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; + +namespace +{ + +using cppuhelper::detail::XExceptionThrower; + + +struct ExceptionThrower : public uno_Interface, XExceptionThrower +{ + ExceptionThrower(); + + virtual ~ExceptionThrower() {} + + static Type const & getCppuType() + { + return cppu::UnoType::get(); + } + + // XInterface + virtual Any SAL_CALL queryInterface( Type const & type ) override; + virtual void SAL_CALL acquire() throw () override; + virtual void SAL_CALL release() throw () override; + + // XExceptionThrower + virtual void SAL_CALL throwException( Any const & exc ) override; + virtual void SAL_CALL rethrowException() override; +}; + +extern "C" +{ + + +void ExceptionThrower_acquire_release_nop( + SAL_UNUSED_PARAMETER uno_Interface * ) +{} + + +void ExceptionThrower_dispatch( + uno_Interface * pUnoI, typelib_TypeDescription const * pMemberType, + void * pReturn, void * pArgs [], uno_Any ** ppException ) +{ + OSL_ASSERT( pMemberType->eTypeClass == typelib_TypeClass_INTERFACE_METHOD ); + + switch (reinterpret_cast< typelib_InterfaceMemberTypeDescription * >( + const_cast< typelib_TypeDescription * >( pMemberType ) )-> + nPosition) + { + case 0: // queryInterface() + { + Type const & rType_demanded = + *static_cast< Type const * >( pArgs[ 0 ] ); + if (rType_demanded.equals( cppu::UnoType::get() ) || + rType_demanded.equals( ExceptionThrower::getCppuType() )) + { + typelib_TypeDescription * pTD = nullptr; + TYPELIB_DANGER_GET( &pTD, rType_demanded.getTypeLibType() ); + uno_any_construct( + static_cast< uno_Any * >( pReturn ), &pUnoI, pTD, nullptr ); + TYPELIB_DANGER_RELEASE( pTD ); + } + else + { + uno_any_construct( + static_cast< uno_Any * >( pReturn ), nullptr, nullptr, nullptr ); + } + *ppException = nullptr; + break; + } + case 1: // acquire() + case 2: // release() + *ppException = nullptr; + break; + case 3: // throwException() + { + uno_Any * pAny = static_cast< uno_Any * >( pArgs[ 0 ] ); + OSL_ASSERT( pAny->pType->eTypeClass == typelib_TypeClass_EXCEPTION ); + uno_type_any_construct( *ppException, pAny->pData, pAny->pType, nullptr ); + break; + } + default: + { + OSL_ASSERT( false ); + RuntimeException exc( "not implemented!" ); + uno_type_any_construct( + *ppException, &exc, cppu::UnoType::get().getTypeLibType(), nullptr ); + break; + } + } +} + +} // extern "C" + + +Any ExceptionThrower::queryInterface( Type const & type ) +{ + if (type.equals( cppu::UnoType::get() ) || + type.equals( ExceptionThrower::getCppuType() )) + { + XExceptionThrower * that = this; + return Any( &that, type ); + } + return Any(); +} + + +void ExceptionThrower::acquire() throw () +{ +} + +void ExceptionThrower::release() throw () +{ +} + + +void ExceptionThrower::throwException( Any const & exc ) +{ + OSL_FAIL( "unexpected!" ); + cppu::throwException( exc ); +} + + +void ExceptionThrower::rethrowException() +{ + throw; +} + + +ExceptionThrower::ExceptionThrower() +{ + uno_Interface::acquire = ExceptionThrower_acquire_release_nop; + uno_Interface::release = ExceptionThrower_acquire_release_nop; + uno_Interface::pDispatcher = ExceptionThrower_dispatch; +} + +class theExceptionThrower : public rtl::Static {}; + +#if defined(IOS) || (defined(__aarch64__) && defined(ANDROID)) +// In the native iOS / Android app, where we don't have any Java, Python, +// BASIC, or other scripting, the only thing that would use the C++/UNO bridge +// functionality that invokes codeSnippet() was cppu::throwException(). +// +// codeSnippet() is part of what corresponds to the code that uses +// run-time-generated machine code on other platforms. We can't generate code +// at run-time on iOS, that has been known forever. +// +// Instead of digging in and trying to understand what is wrong, another +// solution was chosen. It turns out that the number of types of exception +// objects thrown by cppu::throwException() is fairly small. During startup of +// the LibreOffice code, and loading of an .odt document, only one kind of +// exception is thrown this way... (The lovely +// css::ucb:InteractiveAugmentedIOException.) +// +// So we can simply have code that checks what the type of object being thrown +// is, and explicitly throws such an object then with a normal C++ throw +// statement. Seems to work. +template void tryThrow(css::uno::Any const& aException) +{ + E aSpecificException; + if (aException >>= aSpecificException) + throw aSpecificException; +} + +void lo_mobile_throwException(css::uno::Any const& aException) +{ + assert(aException.getValueTypeClass() == css::uno::TypeClass_EXCEPTION); + + tryThrow(aException); + tryThrow(aException); + tryThrow(aException); + + SAL_WARN("cppuhelper", "lo_mobile_throwException: Unhandled exception type: " << aException.getValueTypeName()); + + assert(false); +} +#endif // defined(IOS) || (defined(__aarch64__) && defined(ANDROID)) + +} // anonymous namespace + + +namespace cppu +{ + + +void SAL_CALL throwException( Any const & exc ) +{ + if (exc.getValueTypeClass() != TypeClass_EXCEPTION) + { + throw RuntimeException( + "no UNO exception given " + "(must be derived from com::sun::star::uno::Exception)!" ); + } + +#if defined(IOS) || (defined(__aarch64__) && defined(ANDROID)) + lo_mobile_throwException(exc); +#else + Mapping uno2cpp(Environment(UNO_LB_UNO), Environment::getCurrent()); + if (! uno2cpp.is()) + { + throw RuntimeException( + "cannot get binary UNO to C++ mapping!" ); + } + + Reference< XExceptionThrower > xThrower; + uno2cpp.mapInterface( + reinterpret_cast< void ** >( &xThrower ), + static_cast< uno_Interface * >( &theExceptionThrower::get() ), + ExceptionThrower::getCppuType() ); + OSL_ASSERT( xThrower.is() ); + xThrower->throwException( exc ); +#endif +} + + +Any SAL_CALL getCaughtException() +{ +#if defined(__aarch64__) && defined(ANDROID) + // FIXME This stuff works on 32bit ARM, let's use the shortcut only for + // the 64bit ARM. + return Any(); +#else + Mapping cpp2uno(Environment::getCurrent(), Environment(UNO_LB_UNO)); + if (! cpp2uno.is()) + { + throw RuntimeException( + "cannot get C++ to binary UNO mapping!" ); + } + Mapping uno2cpp(Environment(UNO_LB_UNO), Environment::getCurrent()); + if (! uno2cpp.is()) + { + throw RuntimeException( + "cannot get binary UNO to C++ mapping!" ); + } + + typelib_TypeDescription * pTD = nullptr; + TYPELIB_DANGER_GET( + &pTD, ExceptionThrower::getCppuType().getTypeLibType() ); + + UnoInterfaceReference unoI; + cpp2uno.mapInterface( + reinterpret_cast< void ** >( &unoI.m_pUnoI ), + static_cast< XExceptionThrower * >( &theExceptionThrower::get() ), pTD ); + OSL_ASSERT( unoI.is() ); + + typelib_TypeDescription * pMemberTD = nullptr; + TYPELIB_DANGER_GET( + &pMemberTD, + reinterpret_cast< typelib_InterfaceTypeDescription * >( pTD )-> + ppMembers[ 1 ] /* rethrowException() */ ); + + uno_Any exc_mem; + uno_Any * exc = &exc_mem; + unoI.dispatch( pMemberTD, nullptr, nullptr, &exc ); + + TYPELIB_DANGER_RELEASE( pMemberTD ); + TYPELIB_DANGER_RELEASE( pTD ); + + if (exc == nullptr) + { + throw RuntimeException( "rethrowing C++ exception failed!" ); + } + + Any ret; + uno_any_destruct( &ret, reinterpret_cast< uno_ReleaseFunc >(cpp_release) ); + uno_type_any_constructAndConvert( + &ret, exc->pData, exc->pType, uno2cpp.get() ); + uno_any_destruct( exc, nullptr ); + return ret; +#endif +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/factory.cxx b/cppuhelper/source/factory.cxx new file mode 100644 index 000000000..8a951033c --- /dev/null +++ b/cppuhelper/source/factory.cxx @@ -0,0 +1,967 @@ +/* -*- 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + + +using namespace osl; +using namespace com::sun::star; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::loader; +using namespace com::sun::star::registry; + +namespace cppu +{ + +namespace { + +class OSingleFactoryHelper + : public XServiceInfo + , public XSingleServiceFactory + , public lang::XSingleComponentFactory + , public XUnloadingPreference +{ +public: + OSingleFactoryHelper( + const Reference & rServiceManager, + const OUString & rImplementationName_, + ComponentInstantiation pCreateFunction_, + ComponentFactoryFunc fptr, + const Sequence< OUString > * pServiceNames_ ) + : xSMgr( rServiceManager ) + , pCreateFunction( pCreateFunction_ ) + , m_fptr( fptr ) + , aImplementationName( rImplementationName_ ) + { + if( pServiceNames_ ) + aServiceNames = *pServiceNames_; + } + + virtual ~OSingleFactoryHelper(); + + // XInterface + Any SAL_CALL queryInterface( const Type & rType ) override; + + // XSingleServiceFactory + Reference SAL_CALL createInstance() override; + virtual Reference SAL_CALL createInstanceWithArguments(const Sequence& Arguments) override; + // XSingleComponentFactory + virtual Reference< XInterface > SAL_CALL createInstanceWithContext( + Reference< XComponentContext > const & xContext ) override; + virtual Reference< XInterface > SAL_CALL createInstanceWithArgumentsAndContext( + Sequence< Any > const & rArguments, + Reference< XComponentContext > const & xContext ) override; + + // XServiceInfo + OUString SAL_CALL getImplementationName() override; + sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; + Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + +protected: + /** + * Create an instance specified by the factory. The one instance logic is implemented + * in the createInstance and createInstanceWithArguments methods. + * @return the newly created instance. Do not return a previous (one instance) instance. + * @throw css::uno::Exception + * @throw css::uno::RuntimeException + */ + virtual Reference createInstanceEveryTime( + Reference< XComponentContext > const & xContext ); + + Reference xSMgr; + ComponentInstantiation pCreateFunction; + ComponentFactoryFunc m_fptr; + Sequence< OUString > aServiceNames; + OUString aImplementationName; +}; + +} + +OSingleFactoryHelper::~OSingleFactoryHelper() +{ +} + + +Any OSingleFactoryHelper::queryInterface( const Type & rType ) +{ + return ::cppu::queryInterface( + rType, + static_cast< XSingleComponentFactory * >( this ), + static_cast< XSingleServiceFactory * >( this ), + static_cast< XServiceInfo * >( this ) , + static_cast< XUnloadingPreference * >( this )); +} + +// OSingleFactoryHelper +Reference OSingleFactoryHelper::createInstanceEveryTime( + Reference< XComponentContext > const & xContext ) +{ + if (m_fptr) + { + return (*m_fptr)( xContext ); + } + if( pCreateFunction ) + { + if (xContext.is()) + { + Reference< lang::XMultiServiceFactory > xContextMgr( + xContext->getServiceManager(), UNO_QUERY ); + if (xContextMgr.is()) + return (*pCreateFunction)( xContextMgr ); + } + return (*pCreateFunction)( xSMgr ); + } + return Reference< XInterface >(); +} + +// XSingleServiceFactory +Reference OSingleFactoryHelper::createInstance() +{ + return createInstanceWithContext( Reference< XComponentContext >() ); +} + +// XSingleServiceFactory +Reference OSingleFactoryHelper::createInstanceWithArguments( + const Sequence& Arguments ) +{ + return createInstanceWithArgumentsAndContext( + Arguments, Reference< XComponentContext >() ); +} + +// XSingleComponentFactory + +Reference< XInterface > OSingleFactoryHelper::createInstanceWithContext( + Reference< XComponentContext > const & xContext ) +{ + return createInstanceEveryTime( xContext ); +} + +Reference< XInterface > OSingleFactoryHelper::createInstanceWithArgumentsAndContext( + Sequence< Any > const & rArguments, + Reference< XComponentContext > const & xContext ) +{ + Reference< XInterface > xRet( createInstanceWithContext( xContext ) ); + + Reference< lang::XInitialization > xInit( xRet, UNO_QUERY ); + // always call initialize, even if there are no arguments. #i63511# + if (xInit.is()) + { + xInit->initialize( rArguments ); + } + else + { + if ( rArguments.hasElements() ) + { + // dispose the here created UNO object before throwing out exception + // to avoid risk of memory leaks #i113722# + Reference xComp( xRet, UNO_QUERY ); + if (xComp.is()) + xComp->dispose(); + + throw lang::IllegalArgumentException( + "cannot pass arguments to component => no XInitialization implemented!", + Reference< XInterface >(), 0 ); + } + } + + return xRet; +} + +// XServiceInfo +OUString OSingleFactoryHelper::getImplementationName() +{ + return aImplementationName; +} + +// XServiceInfo +sal_Bool OSingleFactoryHelper::supportsService( + const OUString& ServiceName ) +{ + return cppu::supportsService(this, ServiceName); +} + +// XServiceInfo +Sequence< OUString > OSingleFactoryHelper::getSupportedServiceNames() +{ + return aServiceNames; +} + +namespace { + +struct OFactoryComponentHelper_Mutex +{ + Mutex aMutex; +}; + +class OFactoryComponentHelper + : public OFactoryComponentHelper_Mutex + , public OComponentHelper + , public OSingleFactoryHelper +{ +public: + OFactoryComponentHelper( + const Reference & rServiceManager, + const OUString & rImplementationName_, + ComponentInstantiation pCreateFunction_, + ComponentFactoryFunc fptr, + const Sequence< OUString > * pServiceNames_, + bool bOneInstance_ ) + : OComponentHelper( aMutex ) + , OSingleFactoryHelper( rServiceManager, rImplementationName_, pCreateFunction_, fptr, pServiceNames_ ) + , bOneInstance( bOneInstance_ ) + { + } + + // XInterface + Any SAL_CALL queryInterface( const Type & rType ) override; + void SAL_CALL acquire() throw() override + { OComponentHelper::acquire(); } + void SAL_CALL release() throw() override + { OComponentHelper::release(); } + + // XSingleServiceFactory + Reference SAL_CALL createInstance() override; + Reference SAL_CALL createInstanceWithArguments( const Sequence& Arguments ) override; + // XSingleComponentFactory + virtual Reference< XInterface > SAL_CALL createInstanceWithContext( + Reference< XComponentContext > const & xContext ) override; + virtual Reference< XInterface > SAL_CALL createInstanceWithArgumentsAndContext( + Sequence< Any > const & rArguments, + Reference< XComponentContext > const & xContext ) override; + + // XTypeProvider + virtual Sequence< Type > SAL_CALL getTypes() override; + virtual Sequence< sal_Int8 > SAL_CALL getImplementationId() override; + + // XAggregation + Any SAL_CALL queryAggregation( const Type & rType ) override; + + // XUnloadingPreference + virtual sal_Bool SAL_CALL releaseOnNotification() override; + + // OComponentHelper + void SAL_CALL dispose() override; + +private: + Reference xTheInstance; + bool bOneInstance; +protected: + // needed for implementing XUnloadingPreference in inheriting classes + bool isOneInstance() const {return bOneInstance;} + bool isInstance() const {return xTheInstance.is();} +}; + +} + +Any SAL_CALL OFactoryComponentHelper::queryInterface( const Type & rType ) +{ + if( rType == cppu::UnoType::get() ) + { + return Any( + Reference< XUnloadingPreference >( + static_cast< XUnloadingPreference * >(this) ) ); + } + return OComponentHelper::queryInterface( rType ); +} + +// XAggregation +Any OFactoryComponentHelper::queryAggregation( const Type & rType ) +{ + Any aRet( OComponentHelper::queryAggregation( rType ) ); + return (aRet.hasValue() ? aRet : OSingleFactoryHelper::queryInterface( rType )); +} + +// XTypeProvider +Sequence< Type > OFactoryComponentHelper::getTypes() +{ + Type ar[ 4 ]; + ar[ 0 ] = cppu::UnoType::get(); + ar[ 1 ] = cppu::UnoType::get(); + ar[ 2 ] = cppu::UnoType::get(); + + if (m_fptr) + ar[ 3 ] = cppu::UnoType::get(); + + return Sequence< Type >( ar, m_fptr ? 4 : 3 ); +} + +Sequence< sal_Int8 > OFactoryComponentHelper::getImplementationId() +{ + return css::uno::Sequence(); +} + +// XSingleServiceFactory +Reference OFactoryComponentHelper::createInstance() +{ + if( bOneInstance ) + { + if( !xTheInstance.is() ) + { + MutexGuard aGuard( aMutex ); + if( !xTheInstance.is() ) + xTheInstance = OSingleFactoryHelper::createInstance(); + } + return xTheInstance; + } + return OSingleFactoryHelper::createInstance(); +} + +Reference OFactoryComponentHelper::createInstanceWithArguments( + const Sequence& Arguments ) +{ + if( bOneInstance ) + { + if( !xTheInstance.is() ) + { + MutexGuard aGuard( aMutex ); +// OSL_ENSURE( !xTheInstance.is(), "### arguments will be ignored!" ); + if( !xTheInstance.is() ) + xTheInstance = OSingleFactoryHelper::createInstanceWithArguments( Arguments ); + } + return xTheInstance; + } + return OSingleFactoryHelper::createInstanceWithArguments( Arguments ); +} + +// XSingleComponentFactory + +Reference< XInterface > OFactoryComponentHelper::createInstanceWithContext( + Reference< XComponentContext > const & xContext ) +{ + if( bOneInstance ) + { + if( !xTheInstance.is() ) + { + MutexGuard aGuard( aMutex ); +// OSL_ENSURE( !xTheInstance.is(), "### context will be ignored!" ); + if( !xTheInstance.is() ) + xTheInstance = OSingleFactoryHelper::createInstanceWithContext( xContext ); + } + return xTheInstance; + } + return OSingleFactoryHelper::createInstanceWithContext( xContext ); +} + +Reference< XInterface > OFactoryComponentHelper::createInstanceWithArgumentsAndContext( + Sequence< Any > const & rArguments, + Reference< XComponentContext > const & xContext ) +{ + if( bOneInstance ) + { + if( !xTheInstance.is() ) + { + MutexGuard aGuard( aMutex ); +// OSL_ENSURE( !xTheInstance.is(), "### context and arguments will be ignored!" ); + if( !xTheInstance.is() ) + xTheInstance = OSingleFactoryHelper::createInstanceWithArgumentsAndContext( rArguments, xContext ); + } + return xTheInstance; + } + return OSingleFactoryHelper::createInstanceWithArgumentsAndContext( rArguments, xContext ); +} + + +// OComponentHelper +void OFactoryComponentHelper::dispose() +{ + OComponentHelper::dispose(); + + Reference x; + { + // do not delete in the guard section + MutexGuard aGuard( aMutex ); + x = xTheInstance; + xTheInstance.clear(); + } + // if it is a component call dispose at the component + Reference xComp( x, UNO_QUERY ); + if( xComp.is() ) + xComp->dispose(); +} + +// XUnloadingPreference +// This class is used for single factories, component factories and +// one-instance factories. Depending on the usage this function has +// to return different values. +// one-instance factory: sal_False +// single factory: sal_True +// component factory: sal_True +sal_Bool SAL_CALL OFactoryComponentHelper::releaseOnNotification() +{ + if( bOneInstance) + return false; + return true; +} + +namespace { + +class ORegistryFactoryHelper : public OFactoryComponentHelper, + public OPropertySetHelper + +{ +public: + ORegistryFactoryHelper( + const Reference & rServiceManager, + const OUString & rImplementationName_, + const Reference & xImplementationKey_, + bool bOneInstance_ ) + : OFactoryComponentHelper( + rServiceManager, rImplementationName_, nullptr, nullptr, nullptr, bOneInstance_ ), + OPropertySetHelper( OComponentHelper::rBHelper ), + xImplementationKey( xImplementationKey_ ) + {} + + // XInterface + virtual Any SAL_CALL queryInterface( Type const & type ) override; + virtual void SAL_CALL acquire() throw () override; + virtual void SAL_CALL release() throw () override; + // XTypeProvider + virtual Sequence< Type > SAL_CALL getTypes() override; + // XPropertySet + virtual Reference< beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() override; + + // OPropertySetHelper + virtual IPropertyArrayHelper & SAL_CALL getInfoHelper() override; + virtual sal_Bool SAL_CALL convertFastPropertyValue( + Any & rConvertedValue, Any & rOldValue, + sal_Int32 nHandle, Any const & rValue ) override; + virtual void SAL_CALL setFastPropertyValue_NoBroadcast( + sal_Int32 nHandle, Any const & rValue ) override; + using OPropertySetHelper::getFastPropertyValue; + virtual void SAL_CALL getFastPropertyValue( + Any & rValue, sal_Int32 nHandle ) const override; + + // OSingleFactoryHelper + Reference createInstanceEveryTime( + Reference< XComponentContext > const & xContext ) override; + + // XSingleServiceFactory + Reference SAL_CALL createInstanceWithArguments(const Sequence& Arguments) override; + // XSingleComponentFactory + Reference< XInterface > SAL_CALL createInstanceWithArgumentsAndContext( + Sequence< Any > const & rArguments, + Reference< XComponentContext > const & xContext ) override; + + // XServiceInfo + Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + // XUnloadingPreference + sal_Bool SAL_CALL releaseOnNotification() override; + + +private: + /// @throws css::uno::Exception + /// @throws css::uno::RuntimeException + Reference< XInterface > createModuleFactory(); + + /** The registry key of the implementation section */ + Reference xImplementationKey; + /** The factory created with the loader. */ + Reference xModuleFactory; + Reference xModuleFactoryDepr; + Reference< beans::XPropertySetInfo > m_xInfo; + std::unique_ptr< IPropertyArrayHelper > m_property_array_helper; +protected: + using OPropertySetHelper::getTypes; +}; + +} + +// XInterface + +Any SAL_CALL ORegistryFactoryHelper::queryInterface( + Type const & type ) +{ + Any ret( OFactoryComponentHelper::queryInterface( type ) ); + if (ret.hasValue()) + return ret; + return OPropertySetHelper::queryInterface( type ); +} + + +void ORegistryFactoryHelper::acquire() throw () +{ + OFactoryComponentHelper::acquire(); +} + + +void ORegistryFactoryHelper::release() throw () +{ + OFactoryComponentHelper::release(); +} + +// XTypeProvider + +Sequence< Type > ORegistryFactoryHelper::getTypes() +{ + Sequence< Type > types( OFactoryComponentHelper::getTypes() ); + sal_Int32 pos = types.getLength(); + types.realloc( pos + 3 ); + Type * p = types.getArray(); + p[ pos++ ] = cppu::UnoType::get(); + p[ pos++ ] = cppu::UnoType::get(); + p[ pos++ ] = cppu::UnoType::get(); + return types; +} + +// XPropertySet + +Reference< beans::XPropertySetInfo > +ORegistryFactoryHelper::getPropertySetInfo() +{ + ::osl::MutexGuard guard( aMutex ); + if (! m_xInfo.is()) + m_xInfo = createPropertySetInfo( getInfoHelper() ); + return m_xInfo; +} + +// OPropertySetHelper + +IPropertyArrayHelper & ORegistryFactoryHelper::getInfoHelper() +{ + ::osl::MutexGuard guard( aMutex ); + if (m_property_array_helper == nullptr) + { + beans::Property prop( + "ImplementationKey" /* name */, + 0 /* handle */, + cppu::UnoType::get(), + beans::PropertyAttribute::READONLY | + beans::PropertyAttribute::OPTIONAL ); + m_property_array_helper.reset( + new ::cppu::OPropertyArrayHelper( &prop, 1 ) ); + } + return *m_property_array_helper; +} + + +sal_Bool ORegistryFactoryHelper::convertFastPropertyValue( + Any &, Any &, sal_Int32, Any const & ) +{ + OSL_FAIL( "unexpected!" ); + return false; +} + + +void ORegistryFactoryHelper::setFastPropertyValue_NoBroadcast( + sal_Int32, Any const & ) +{ + throw beans::PropertyVetoException( + "unexpected: only readonly properties!", + static_cast< OWeakObject * >(this) ); +} + + +void ORegistryFactoryHelper::getFastPropertyValue( + Any & rValue, sal_Int32 nHandle ) const +{ + if (nHandle == 0) + { + rValue <<= xImplementationKey; + } + else + { + rValue.clear(); + throw beans::UnknownPropertyException( + "unknown property!", static_cast< OWeakObject * >( + const_cast< ORegistryFactoryHelper * >(this) ) ); + } +} + +Reference ORegistryFactoryHelper::createInstanceEveryTime( + Reference< XComponentContext > const & xContext ) +{ + if( !xModuleFactory.is() && !xModuleFactoryDepr.is() ) + { + Reference< XInterface > x( createModuleFactory() ); + if (x.is()) + { + MutexGuard aGuard( aMutex ); + if( !xModuleFactory.is() && !xModuleFactoryDepr.is() ) + { + xModuleFactory.set( x, UNO_QUERY ); + xModuleFactoryDepr.set( x, UNO_QUERY ); + } + } + } + if( xModuleFactory.is() ) + { + return xModuleFactory->createInstanceWithContext( xContext ); + } + if( xModuleFactoryDepr.is() ) + { + return xModuleFactoryDepr->createInstance(); + } + + return Reference(); +} + +Reference SAL_CALL ORegistryFactoryHelper::createInstanceWithArguments( + const Sequence& Arguments ) +{ + if( !xModuleFactory.is() && !xModuleFactoryDepr.is() ) + { + Reference< XInterface > x( createModuleFactory() ); + if (x.is()) + { + MutexGuard aGuard( aMutex ); + if( !xModuleFactory.is() && !xModuleFactoryDepr.is() ) + { + xModuleFactory.set( x, UNO_QUERY ); + xModuleFactoryDepr.set( x, UNO_QUERY ); + } + } + } + if( xModuleFactoryDepr.is() ) + { + return xModuleFactoryDepr->createInstanceWithArguments( Arguments ); + } + if( xModuleFactory.is() ) + { + SAL_INFO("cppuhelper", "no context ORegistryFactoryHelper::createInstanceWithArgumentsAndContext()!"); + return xModuleFactory->createInstanceWithArgumentsAndContext( Arguments, Reference< XComponentContext >() ); + } + + return Reference(); +} + +Reference< XInterface > ORegistryFactoryHelper::createInstanceWithArgumentsAndContext( + Sequence< Any > const & rArguments, + Reference< XComponentContext > const & xContext ) +{ + if( !xModuleFactory.is() && !xModuleFactoryDepr.is() ) + { + Reference< XInterface > x( createModuleFactory() ); + if (x.is()) + { + MutexGuard aGuard( aMutex ); + if( !xModuleFactory.is() && !xModuleFactoryDepr.is() ) + { + xModuleFactory.set( x, UNO_QUERY ); + xModuleFactoryDepr.set( x, UNO_QUERY ); + } + } + } + if( xModuleFactory.is() ) + { + return xModuleFactory->createInstanceWithArgumentsAndContext( rArguments, xContext ); + } + if( xModuleFactoryDepr.is() ) + { + SAL_INFO_IF(xContext.is(), "cppuhelper", "ignoring context calling ORegistryFactoryHelper::createInstaceWithArgumentsAndContext()!"); + return xModuleFactoryDepr->createInstanceWithArguments( rArguments ); + } + + return Reference(); +} + + +// OSingleFactoryHelper +Reference< XInterface > ORegistryFactoryHelper::createModuleFactory() +{ + OUString aActivatorUrl; + OUString aActivatorName; + OUString aLocation; + + Reference xActivatorKey = xImplementationKey->openKey( + "/UNO/ACTIVATOR" ); + if( xActivatorKey.is() && xActivatorKey->getValueType() == RegistryValueType_ASCII ) + { + aActivatorUrl = xActivatorKey->getAsciiValue(); + + aActivatorName = aActivatorUrl.getToken(0, ':'); + + Reference xLocationKey = xImplementationKey->openKey( + "/UNO/LOCATION" ); + if( xLocationKey.is() && xLocationKey->getValueType() == RegistryValueType_ASCII ) + aLocation = xLocationKey->getAsciiValue(); + } + else + { + // old style"url" + // the location of the program code of the implementation + Reference xLocationKey = xImplementationKey->openKey( + "/UNO/URL" ); + // is the key of the right type ? + if( xLocationKey.is() && xLocationKey->getValueType() == RegistryValueType_ASCII ) + { + // one implementation found -> try to activate + aLocation = xLocationKey->getAsciiValue(); + + // search protocol delimiter + sal_Int32 nPos = aLocation.indexOf("://"); + if( nPos != -1 ) + { + aActivatorName = aLocation.copy( 0, nPos ); + if( aActivatorName == "java" ) + aActivatorName = "com.sun.star.loader.Java"; + else if( aActivatorName == "module" ) + aActivatorName = "com.sun.star.loader.SharedLibrary"; + aLocation = aLocation.copy( nPos + 3 ); + } + } + } + + Reference< XInterface > xFactory; + if( !aActivatorName.isEmpty() ) + { + Reference x = xSMgr->createInstance( aActivatorName ); + Reference xLoader( x, UNO_QUERY ); + if (xLoader.is()) + { + xFactory = xLoader->activate( aImplementationName, aActivatorUrl, aLocation, xImplementationKey ); + } + } + return xFactory; +} + +// XServiceInfo +Sequence< OUString > ORegistryFactoryHelper::getSupportedServiceNames() +{ + MutexGuard aGuard( aMutex ); + if( !aServiceNames.hasElements() ) + { + // not yet loaded + try + { + Reference xKey = xImplementationKey->openKey( "UNO/SERVICES" ); + + if (xKey.is()) + { + // length of prefix. +1 for the '/' at the end + sal_Int32 nPrefixLen = xKey->getKeyName().getLength() + 1; + + // Full qualified names like "IMPLEMENTATIONS/TEST/UNO/SERVICES/com.sun.star..." + Sequence seqKeys = xKey->getKeyNames(); + for( OUString & key : seqKeys ) + key = key.copy(nPrefixLen); + + aServiceNames = seqKeys; + } + } + catch (InvalidRegistryException &) + { + } + } + return aServiceNames; +} + +sal_Bool SAL_CALL ORegistryFactoryHelper::releaseOnNotification() +{ + bool retVal= true; + if( isOneInstance() && isInstance()) + { + retVal= false; + } + else if( ! isOneInstance()) + { + // try to delegate + if( xModuleFactory.is()) + { + Reference xunloading( xModuleFactory, UNO_QUERY); + if( xunloading.is()) + retVal= xunloading->releaseOnNotification(); + } + else if( xModuleFactoryDepr.is()) + { + Reference xunloading( xModuleFactoryDepr, UNO_QUERY); + if( xunloading.is()) + retVal= xunloading->releaseOnNotification(); + } + } + return retVal; +} + +namespace { + +class OFactoryProxyHelper : public WeakImplHelper< XServiceInfo, XSingleServiceFactory, + XUnloadingPreference > +{ + Reference xFactory; + +public: + + explicit OFactoryProxyHelper( const Reference & rFactory ) + : xFactory( rFactory ) + {} + + // XSingleServiceFactory + Reference SAL_CALL createInstance() override; + Reference SAL_CALL createInstanceWithArguments(const Sequence& Arguments) override; + + // XServiceInfo + OUString SAL_CALL getImplementationName() override; + sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; + Sequence< OUString > SAL_CALL getSupportedServiceNames() override; + //XUnloadingPreference + sal_Bool SAL_CALL releaseOnNotification() override; + +}; + +} + +// XSingleServiceFactory +Reference OFactoryProxyHelper::createInstance() +{ + return xFactory->createInstance(); +} + +// XSingleServiceFactory +Reference OFactoryProxyHelper::createInstanceWithArguments +( + const Sequence& Arguments +) +{ + return xFactory->createInstanceWithArguments( Arguments ); +} + +// XServiceInfo +OUString OFactoryProxyHelper::getImplementationName() +{ + Reference xInfo( xFactory, UNO_QUERY ); + if( xInfo.is() ) + return xInfo->getImplementationName(); + return OUString(); +} + +// XServiceInfo +sal_Bool OFactoryProxyHelper::supportsService(const OUString& ServiceName) +{ + return cppu::supportsService(this, ServiceName); +} + +// XServiceInfo +Sequence< OUString > OFactoryProxyHelper::getSupportedServiceNames() +{ + Reference xInfo( xFactory, UNO_QUERY ); + if( xInfo.is() ) + return xInfo->getSupportedServiceNames(); + return Sequence< OUString >(); +} + +sal_Bool SAL_CALL OFactoryProxyHelper::releaseOnNotification() +{ + + Reference pref( xFactory, UNO_QUERY); + if( pref.is()) + return pref->releaseOnNotification(); + return true; +} + +// global function +Reference SAL_CALL createSingleFactory( + const Reference & rServiceManager, + const OUString & rImplementationName, + ComponentInstantiation pCreateFunction, + const Sequence< OUString > & rServiceNames, + rtl_ModuleCount * ) +{ + return new OFactoryComponentHelper( + rServiceManager, rImplementationName, pCreateFunction, nullptr, &rServiceNames, false ); +} + +// global function +Reference SAL_CALL createFactoryProxy( + SAL_UNUSED_PARAMETER const Reference &, + const Reference & rFactory ) +{ + return new OFactoryProxyHelper( rFactory ); +} + +// global function +Reference SAL_CALL createOneInstanceFactory( + const Reference & rServiceManager, + const OUString & rImplementationName, + ComponentInstantiation pCreateFunction, + const Sequence< OUString > & rServiceNames, + rtl_ModuleCount * ) +{ + return new OFactoryComponentHelper( + rServiceManager, rImplementationName, pCreateFunction, nullptr, &rServiceNames, true ); +} + +// global function +Reference SAL_CALL createSingleRegistryFactory( + const Reference & rServiceManager, + const OUString & rImplementationName, + const Reference & rImplementationKey ) +{ + return new ORegistryFactoryHelper( + rServiceManager, rImplementationName, rImplementationKey, false ); +} + +// global function +Reference SAL_CALL createOneInstanceRegistryFactory( + const Reference & rServiceManager, + const OUString & rImplementationName, + const Reference & rImplementationKey ) +{ + return new ORegistryFactoryHelper( + rServiceManager, rImplementationName, rImplementationKey, true ); +} + + +Reference< lang::XSingleComponentFactory > SAL_CALL createSingleComponentFactory( + ComponentFactoryFunc fptr, + OUString const & rImplementationName, + Sequence< OUString > const & rServiceNames, + rtl_ModuleCount *) +{ + return new OFactoryComponentHelper( + Reference< XMultiServiceFactory >(), rImplementationName, nullptr, fptr, &rServiceNames, false ); +} + +Reference< lang::XSingleComponentFactory > SAL_CALL createOneInstanceComponentFactory( + ComponentFactoryFunc fptr, + OUString const & rImplementationName, + Sequence< OUString > const & rServiceNames, + rtl_ModuleCount *) +{ + return new OFactoryComponentHelper( + Reference< XMultiServiceFactory >(), rImplementationName, nullptr, fptr, &rServiceNames, true ); +} + +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/findsofficepath.c b/cppuhelper/source/findsofficepath.c new file mode 100644 index 000000000..75d370981 --- /dev/null +++ b/cppuhelper/source/findsofficepath.c @@ -0,0 +1,219 @@ +/* -*- 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 + +#include +#include + +#include + +#if defined(_WIN32) + +#define WIN32_LEAN_AND_MEAN +#include + +/* + * Gets the installation path from the Windows Registry for the specified + * registry key. + * + * @param hroot open handle to predefined root registry key + * @param subKeyName name of the subkey to open + * + * @return the installation path or NULL, if no installation was found or + * if an error occurred + */ +static wchar_t* getPathFromRegistryKey( HKEY hroot, const wchar_t* subKeyName ) +{ + HKEY hkey; + DWORD type; + wchar_t* data = NULL; + DWORD size; + + /* open the specified registry key */ + if ( RegOpenKeyExW( hroot, subKeyName, 0, KEY_READ, &hkey ) != ERROR_SUCCESS ) + { + return NULL; + } + + /* find the type and size of the default value */ + if ( RegQueryValueExW( hkey, NULL, NULL, &type, NULL, &size) != ERROR_SUCCESS ) + { + RegCloseKey( hkey ); + return NULL; + } + + /* get memory to hold the default value */ + data = (wchar_t*) malloc( size + sizeof(wchar_t) ); + + /* read the default value */ + if ( RegQueryValueExW( hkey, NULL, NULL, &type, (LPBYTE) data, &size ) != ERROR_SUCCESS ) + { + RegCloseKey( hkey ); + free( data ); + return NULL; + } + + // According to https://msdn.microsoft.com/en-us/ms724911, If the data has the REG_SZ, + // REG_MULTI_SZ or REG_EXPAND_SZ type, the string may not have been stored with the + // proper terminating null characters + data[size / sizeof(wchar_t)] = 0; + + /* release registry key handle */ + RegCloseKey( hkey ); + + return data; +} + +/* + * Gets the installation path from the Windows Registry. + * + * @return the installation path or NULL, if no installation was found or + * if an error occurred + */ +static wchar_t* platformSpecific() +{ + const wchar_t* UNOPATHVARNAME = L"UNO_PATH"; + + /* get the installation path from the UNO_PATH environment variable */ + wchar_t* env = _wgetenv(UNOPATHVARNAME); + + if (env && env[0]) + { + return wcsdup(env); + } + + const wchar_t* SUBKEYNAME = L"Software\\LibreOffice\\UNO\\InstallPath"; + + /* read the key's default value from HKEY_CURRENT_USER */ + wchar_t* path = getPathFromRegistryKey( HKEY_CURRENT_USER, SUBKEYNAME ); + + if ( path == NULL ) + { + /* read the key's default value from HKEY_LOCAL_MACHINE */ + path = getPathFromRegistryKey( HKEY_LOCAL_MACHINE, SUBKEYNAME ); + } + + return path; +} + +#else + +#include + +/* + * Gets the installation path from the PATH environment variable. + * + *

An installation is found, if the executable 'soffice' or a symbolic link + * is in one of the directories listed in the PATH environment variable.

+ * + * @return the installation path or NULL, if no installation was found or + * if an error occurred + */ +static char* platformSpecific(void) +{ + const char* UNOPATHVARNAME = "UNO_PATH"; + + /* get the installation path from the UNO_PATH environment variable */ + char* env = getenv(UNOPATHVARNAME); + + const int SEPARATOR = '/'; + const char* PATHSEPARATOR = ":"; + const char* PATHVARNAME = "PATH"; + const char* APPENDIX = "/libreoffice"; + + char* path = NULL; + char* str = NULL; + char* dir = NULL; + char* sep = NULL; + + char buffer[PATH_MAX]; + int pos; + + if (env && env[0]) + { + return strdup(env); + } + + /* get the value of the PATH environment variable */ + env = getenv( PATHVARNAME ); + if (env == NULL) + return NULL; + + str = strdup( env ); + if (str == NULL) + return NULL; + + /* get the tokens separated by ':' */ + dir = strtok( str, PATHSEPARATOR ); + + while ( dir ) + { + /* construct soffice file path */ + char* resolved = NULL; + char* file = (char*) malloc( strlen( dir ) + strlen( APPENDIX ) + 1 ); + if (file == NULL) + { + free(str); + return NULL; + } + + strcpy( file, dir ); + strcat( file, APPENDIX ); + + /* resolve symbolic link */ + resolved = realpath( file, buffer ); + if ( resolved != NULL ) + { + /* get path to program directory */ + sep = strrchr( resolved, SEPARATOR ); + + if ( sep != NULL ) + { + pos = sep - resolved; + path = (char*) malloc( pos + 1 ); + strncpy( path, resolved, pos ); + path[ pos ] = '\0'; + free( file ); + break; + } + } + + dir = strtok( NULL, PATHSEPARATOR ); + free( file ); + } + + free( str ); + + return path; +} + +#endif + +#if defined(_WIN32) +wchar_t* +#else +char* +#endif +cppuhelper_detail_findSofficePath() +{ + return platformSpecific(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/gcc3.map b/cppuhelper/source/gcc3.map new file mode 100644 index 000000000..d5af50655 --- /dev/null +++ b/cppuhelper/source/gcc3.map @@ -0,0 +1,443 @@ +# +# 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 . +# +UDK_3_0_0 { + global: + _ZTI*; _ZTS*; # weak RTTI symbols for C++ exceptions + +_ZN3com3sun4star3uno19WeakReferenceHelperC1ERKNS2_9ReferenceINS2_10XInterfaceEEE; +_ZN3com3sun4star3uno19WeakReferenceHelperC1ERKS3_; +_ZN3com3sun4star3uno19WeakReferenceHelperC2ERKNS2_9ReferenceINS2_10XInterfaceEEE; +_ZN3com3sun4star3uno19WeakReferenceHelperC2ERKS3_; +_ZN3com3sun4star3uno19WeakReferenceHelperaSERKS3_; +_ZN3com3sun4star3uno19WeakReferenceHelperD1Ev; +_ZN3com3sun4star3uno19WeakReferenceHelperD2Ev; +_ZN4cppu11OWeakObject12queryAdapterEv; +_ZN4cppu11OWeakObject14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZN4cppu11OWeakObject7acquireEv; +_ZN4cppu11OWeakObject7releaseEv; +_ZN4cppu11OWeakObjectD0Ev; +_ZN4cppu11OWeakObjectD1Ev; +_ZN4cppu11OWeakObjectD2Ev; +_ZN4cppu13ClassDataBaseC1E?; +_ZN4cppu13ClassDataBaseC1Ev; +_ZN4cppu13ClassDataBaseC2E?; +_ZN4cppu13ClassDataBaseC2Ev; +_ZN4cppu13ClassDataBaseD1Ev; +_ZN4cppu13ClassDataBaseD2Ev; +_ZN4cppu14OWeakAggObject12setDelegatorERKN3com3sun4star3uno9ReferenceINS4_10XInterfaceEEE; +_ZN4cppu14OWeakAggObject14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZN4cppu14OWeakAggObject16queryAggregationERKN3com3sun4star3uno4TypeE; +_ZN4cppu14OWeakAggObject7acquireEv; +_ZN4cppu14OWeakAggObject7releaseEv; +_ZN4cppu14OWeakAggObjectD0Ev; +_ZN4cppu14OWeakAggObjectD1Ev; +_ZN4cppu14OWeakAggObjectD2Ev; +_ZN4cppu14throwExceptionERKN3com3sun4star3uno3AnyE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeERKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC1ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeERKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu15OTypeCollectionC2ERKN3com3sun4star3uno4TypeES7_S7_S7_S7_S7_S7_S7_S7_S7_S7_S7_RKNS4_8SequenceIS5_EE; +_ZN4cppu16ImplHelper_queryERKN3com3sun4star3uno4TypeEPNS_10class_dataEPv; +_ZN4cppu16OComponentHelper14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZN4cppu16OComponentHelper16addEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZN4cppu16OComponentHelper16queryAggregationERKN3com3sun4star3uno4TypeE; +_ZN4cppu16OComponentHelper19removeEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZN4cppu16OComponentHelper7acquireEv; +_ZN4cppu16OComponentHelper7disposeEv; +_ZN4cppu16OComponentHelper7releaseEv; +_ZN4cppu16OComponentHelper8getTypesEv; +_ZN4cppu16OComponentHelper9disposingEv; +_ZN4cppu16OComponentHelperC1ERN3osl5MutexE; +_ZN4cppu16OComponentHelperC2ERN3osl5MutexE; +_ZN4cppu16OComponentHelperD0Ev; +_ZN4cppu16OComponentHelperD1Ev; +_ZN4cppu16OComponentHelperD2Ev; +_ZN4cppu17OImplementationIdD1Ev; +_ZN4cppu17OImplementationIdD2Ev; +_ZN4cppu18OPropertySetHelper14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZN4cppu18OPropertySetHelper16getPropertyValueERKN3rtl8OUStringE; +_ZN4cppu18OPropertySetHelper16setPropertyValueERKN3rtl8OUStringERKN3com3sun4star3uno3AnyE; +_ZN4cppu18OPropertySetHelper17getPropertyValuesERKN3com3sun4star3uno8SequenceIN3rtl8OUStringEEE; +_ZN4cppu18OPropertySetHelper17setPropertyValuesERKN3com3sun4star3uno8SequenceIN3rtl8OUStringEEERKNS5_INS4_3AnyEEE; +_ZN4cppu18OPropertySetHelper20getFastPropertyValueE?; +_ZN4cppu18OPropertySetHelper20setFastPropertyValueE?RKN3com3sun4star3uno3AnyE; +_ZN4cppu18OPropertySetHelper21createPropertySetInfoERNS_20IPropertyArrayHelperE; +_ZN4cppu18OPropertySetHelper21setFastPropertyValuesE?P?PKN3com3sun4star3uno3AnyE?; +_ZN4cppu18OPropertySetHelper25addPropertyChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XPropertyChangeListenerEEE; +_ZN4cppu18OPropertySetHelper25addVetoableChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XVetoableChangeListenerEEE; +_ZN4cppu18OPropertySetHelper25firePropertiesChangeEventERKN3com3sun4star3uno8SequenceIN3rtl8OUStringEEERKNS4_9ReferenceINS3_5beans25XPropertiesChangeListenerEEE; +_ZN4cppu18OPropertySetHelper27addPropertiesChangeListenerERKN3com3sun4star3uno8SequenceIN3rtl8OUStringEEERKNS4_9ReferenceINS3_5beans25XPropertiesChangeListenerEEE; +_ZN4cppu18OPropertySetHelper28removePropertyChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XPropertyChangeListenerEEE; +_ZN4cppu18OPropertySetHelper28removeVetoableChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XVetoableChangeListenerEEE; +_ZN4cppu18OPropertySetHelper30removePropertiesChangeListenerERKN3com3sun4star3uno9ReferenceINS3_5beans25XPropertiesChangeListenerEEE; +_ZN4cppu18OPropertySetHelper4fireEP?PKN3com3sun4star3uno3AnyES8_?h; +_ZN4cppu18OPropertySetHelper9disposingEv; +_ZN4cppu18OPropertySetHelperC1ERNS_19OBroadcastHelperVarINS_34OMultiTypeInterfaceContainerHelperEN3com3sun4star3uno4TypeEEE; +_ZN4cppu18OPropertySetHelperC2ERNS_19OBroadcastHelperVarINS_34OMultiTypeInterfaceContainerHelperEN3com3sun4star3uno4TypeEEE; +_ZN4cppu18OPropertySetHelperD1Ev; +_ZN4cppu18OPropertySetHelperD2Ev; +_ZN4cppu18bootstrapInitialSFERKN3rtl8OUStringE; +_ZN4cppu18createFactoryProxyERKN3com3sun4star3uno9ReferenceINS2_4lang20XMultiServiceFactoryEEERKNS4_INS5_21XSingleServiceFactoryEEE; +_ZN4cppu19ImplHelper_getTypesEPNS_10class_dataE; +_ZN4cppu19createSingleFactoryERKN3com3sun4star3uno9ReferenceINS2_4lang20XMultiServiceFactoryEEERKN3rtl8OUStringEPFNS4_INS3_10XInterfaceEEES9_ERKNS3_8SequenceISB_EEP16_rtl_ModuleCount; +_ZN4cppu20IPropertyArrayHelperD0Ev; +_ZN4cppu20IPropertyArrayHelperD1Ev; +_ZN4cppu20IPropertyArrayHelperD2Ev; +_ZN4cppu20OPropertyArrayHelper11fillHandlesEP?RKN3com3sun4star3uno8SequenceIN3rtl8OUStringEEE; +_ZN4cppu20OPropertyArrayHelper13getPropertiesEv; +_ZN4cppu20OPropertyArrayHelper15getHandleByNameERKN3rtl8OUStringE; +_ZN4cppu20OPropertyArrayHelper17getPropertyByNameERKN3rtl8OUStringE; +_ZN4cppu20OPropertyArrayHelper17hasPropertyByNameERKN3rtl8OUStringE; +_ZN4cppu20OPropertyArrayHelper27fillPropertyMembersByHandleEPN3rtl8OUStringEPs?; +_ZN4cppu20OPropertyArrayHelper4initEh; +_ZN4cppu20OPropertyArrayHelperC1EPN3com3sun4star5beans8PropertyE?h; +_ZN4cppu20OPropertyArrayHelperC1ERKN3com3sun4star3uno8SequenceINS3_5beans8PropertyEEEh; +_ZN4cppu20OPropertyArrayHelperC2EPN3com3sun4star5beans8PropertyE?h; +_ZN4cppu20OPropertyArrayHelperC2ERKN3com3sun4star3uno8SequenceINS3_5beans8PropertyEEEh; +_ZN4cppu20WeakImplHelper_queryERKN3com3sun4star3uno4TypeEPNS_10class_dataEPvPNS_11OWeakObjectE; +_ZN4cppu20createNestedRegistryERKN3rtl8OUStringE; +_ZN4cppu20createSimpleRegistryERKN3rtl8OUStringE; +_ZN4cppu22ImplInhHelper_getTypesEPNS_10class_dataERKN3com3sun4star3uno8SequenceINS5_4TypeEEE; +_ZN4cppu22createComponentContextEPKNS_17ContextEntry_InitE?RKN3com3sun4star3uno9ReferenceINS6_17XComponentContextEEE; +_ZN4cppu22getImplHelperInitMutexEv; +_ZN4cppu23WeakImplHelper_getTypesEPNS_10class_dataE; +_ZN4cppu24OInterfaceIteratorHelper4nextEv; +_ZN4cppu24OInterfaceIteratorHelper6removeEv; +_ZN4cppu24OInterfaceIteratorHelperC1ERNS_25OInterfaceContainerHelperE; +_ZN4cppu24OInterfaceIteratorHelperC2ERNS_25OInterfaceContainerHelperE; +_ZN4cppu24OInterfaceIteratorHelperD1Ev; +_ZN4cppu24OInterfaceIteratorHelperD2Ev; +_ZN4cppu24createOneInstanceFactoryERKN3com3sun4star3uno9ReferenceINS2_4lang20XMultiServiceFactoryEEERKN3rtl8OUStringEPFNS4_INS3_10XInterfaceEEES9_ERKNS3_8SequenceISB_EEP16_rtl_ModuleCount; +_ZN4cppu25OInterfaceContainerHelper12addInterfaceERKN3com3sun4star3uno9ReferenceINS4_10XInterfaceEEE; +_ZN4cppu25OInterfaceContainerHelper15disposeAndClearERKN3com3sun4star4lang11EventObjectE; +_ZN4cppu25OInterfaceContainerHelper15removeInterfaceERKN3com3sun4star3uno9ReferenceINS4_10XInterfaceEEE; +_ZN4cppu25OInterfaceContainerHelper17copyAndResetInUseEv; +_ZN4cppu25OInterfaceContainerHelper5clearEv; +_ZN4cppu25OInterfaceContainerHelperC1ERN3osl5MutexE; +_ZN4cppu25OInterfaceContainerHelperC2ERN3osl5MutexE; +_ZN4cppu25OInterfaceContainerHelperD1Ev; +_ZN4cppu25OInterfaceContainerHelperD2Ev; +_ZN4cppu25component_writeInfoHelperEPvS0_PKNS_19ImplementationEntryE; +_ZN4cppu26WeakAggImplHelper_getTypesEPNS_10class_dataE; +_ZN4cppu26WeakAggImplHelper_queryAggERKN3com3sun4star3uno4TypeEPNS_10class_dataEPvPNS_14OWeakAggObjectE; +_ZN4cppu26component_getFactoryHelperEPKcPvS2_PKNS_19ImplementationEntryE; +_ZN4cppu27WeakComponentImplHelperBase14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZN4cppu27WeakComponentImplHelperBase16addEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZN4cppu27WeakComponentImplHelperBase19removeEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZN4cppu27WeakComponentImplHelperBase7acquireEv; +_ZN4cppu27WeakComponentImplHelperBase7disposeEv; +_ZN4cppu27WeakComponentImplHelperBase7releaseEv; +_ZN4cppu27WeakComponentImplHelperBase9disposingEv; +_ZN4cppu27WeakComponentImplHelperBaseC1ERN3osl5MutexE; +_ZN4cppu27WeakComponentImplHelperBaseC2ERN3osl5MutexE; +_ZN4cppu27WeakComponentImplHelperBaseD0Ev; +_ZN4cppu27WeakComponentImplHelperBaseD1Ev; +_ZN4cppu27WeakComponentImplHelperBaseD2Ev; +_ZN4cppu27createSingleRegistryFactoryERKN3com3sun4star3uno9ReferenceINS2_4lang20XMultiServiceFactoryEEERKN3rtl8OUStringERKNS4_INS2_8registry12XRegistryKeyEEE; +_ZN4cppu27writeSharedLibComponentInfoERKN3rtl8OUStringES3_RKN3com3sun4star3uno9ReferenceINS6_4lang20XMultiServiceFactoryEEERKNS8_INS6_8registry12XRegistryKeyEEE; +_ZN4cppu28ImplHelper_queryNoXInterfaceERKN3com3sun4star3uno4TypeEPNS_10class_dataEPv; +_ZN4cppu28createRegistryServiceFactoryERKN3rtl8OUStringES3_hS3_; +_ZN4cppu28createSingleComponentFactoryEPFN3com3sun4star3uno9ReferenceINS3_10XInterfaceEEERKNS4_INS3_17XComponentContextEEEERKN3rtl8OUStringERKNS3_8SequenceISE_EEP16_rtl_ModuleCount; +_ZN4cppu29WeakComponentImplHelper_queryERKN3com3sun4star3uno4TypeEPNS_10class_dataEPvPNS_27WeakComponentImplHelperBaseE; +_ZN4cppu29installTypeDescriptionManagerERKN3com3sun4star3uno9ReferenceINS2_9container23XHierarchicalNameAccessEEE; +_ZN4cppu28invokeStaticComponentFactoryEPFvvERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS8_4lang20XMultiServiceFactoryEEERKNSA_INS8_8registry12XRegistryKeyEEES5_; +_ZN4cppu29loadSharedLibComponentFactoryERKN3rtl8OUStringES3_S3_RKN3com3sun4star3uno9ReferenceINS6_4lang20XMultiServiceFactoryEEERKNS8_INS6_8registry12XRegistryKeyEEE; +_ZN4cppu29loadSharedLibComponentFactoryERKN3rtl8OUStringES3_S3_RKN3com3sun4star3uno9ReferenceINS6_4lang20XMultiServiceFactoryEEERKNS8_INS6_8registry12XRegistryKeyEEES3_; +_ZN4cppu30ImplHelper_getImplementationIdEPNS_10class_dataE; +_ZN4cppu30WeakAggComponentImplHelperBase14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZN4cppu30WeakAggComponentImplHelperBase16addEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZN4cppu30WeakAggComponentImplHelperBase16queryAggregationERKN3com3sun4star3uno4TypeE; +_ZN4cppu30WeakAggComponentImplHelperBase19removeEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZN4cppu30WeakAggComponentImplHelperBase7acquireEv; +_ZN4cppu30WeakAggComponentImplHelperBase7disposeEv; +_ZN4cppu30WeakAggComponentImplHelperBase7releaseEv; +_ZN4cppu30WeakAggComponentImplHelperBase9disposingEv; +_ZN4cppu30WeakAggComponentImplHelperBaseC1ERN3osl5MutexE; +_ZN4cppu30WeakAggComponentImplHelperBaseC2ERN3osl5MutexE; +_ZN4cppu30WeakAggComponentImplHelperBaseD0Ev; +_ZN4cppu30WeakAggComponentImplHelperBaseD1Ev; +_ZN4cppu30WeakAggComponentImplHelperBaseD2Ev; +_ZN4cppu31createStandardClassWithSequenceERKN3com3sun4star3uno9ReferenceINS2_4lang20XMultiServiceFactoryEEERKN3rtl8OUStringERKNS4_INS2_10reflection9XIdlClassEEERKNS3_8SequenceISB_EE; +_ZN4cppu32WeakComponentImplHelper_getTypesEPNS_10class_dataE; +_ZN4cppu32createOneInstanceRegistryFactoryERKN3com3sun4star3uno9ReferenceINS2_4lang20XMultiServiceFactoryEEERKN3rtl8OUStringERKNS4_INS2_8registry12XRegistryKeyEEE; +_ZN4cppu33bootstrap_InitialComponentContextERKN3com3sun4star3uno9ReferenceINS2_8registry15XSimpleRegistryEEERKN3rtl8OUStringE; +_ZN4cppu34OMultiTypeInterfaceContainerHelper12addInterfaceERKN3com3sun4star3uno4TypeERKNS4_9ReferenceINS4_10XInterfaceEEE; +_ZN4cppu34OMultiTypeInterfaceContainerHelper15disposeAndClearERKN3com3sun4star4lang11EventObjectE; +_ZN4cppu34OMultiTypeInterfaceContainerHelper15removeInterfaceERKN3com3sun4star3uno4TypeERKNS4_9ReferenceINS4_10XInterfaceEEE; +_ZN4cppu34OMultiTypeInterfaceContainerHelper5clearEv; +_ZN4cppu34OMultiTypeInterfaceContainerHelperC1ERN3osl5MutexE; +_ZN4cppu34OMultiTypeInterfaceContainerHelperC2ERN3osl5MutexE; +_ZN4cppu34OMultiTypeInterfaceContainerHelperD1Ev; +_ZN4cppu34OMultiTypeInterfaceContainerHelperD2Ev; +_ZN4cppu35WeakAggComponentImplHelper_getTypesEPNS_10class_dataE; +_ZN4cppu35WeakAggComponentImplHelper_queryAggERKN3com3sun4star3uno4TypeEPNS_10class_dataEPvPNS_30WeakAggComponentImplHelperBaseE; +_ZN4cppu39OMultiTypeInterfaceContainerHelperInt3212addInterfaceERK?RKN3com3sun4star3uno9ReferenceINS6_10XInterfaceEEE; +_ZN4cppu39OMultiTypeInterfaceContainerHelperInt3215disposeAndClearERKN3com3sun4star4lang11EventObjectE; +_ZN4cppu39OMultiTypeInterfaceContainerHelperInt3215removeInterfaceERK?RKN3com3sun4star3uno9ReferenceINS6_10XInterfaceEEE; +_ZN4cppu39OMultiTypeInterfaceContainerHelperInt325clearEv; +_ZN4cppu39OMultiTypeInterfaceContainerHelperInt32C1ERN3osl5MutexE; +_ZN4cppu39OMultiTypeInterfaceContainerHelperInt32C2ERN3osl5MutexE; +_ZN4cppu39OMultiTypeInterfaceContainerHelperInt32D1Ev; +_ZN4cppu39OMultiTypeInterfaceContainerHelperInt32D2Ev; +_ZN4cppu40defaultBootstrap_InitialComponentContextERKN3rtl8OUStringE; +_ZN4cppu40defaultBootstrap_InitialComponentContextEv; +_ZN4cppu9ClassData15writeTypeOffsetERKN3com3sun4star3uno4TypeE?; +_ZN4cppu9ClassData16initTypeProviderEv; +_ZN4cppu9ClassData19getImplementationIdEv; +_ZN4cppu9ClassData5queryERKN3com3sun4star3uno4TypeEPNS3_4lang13XTypeProviderE; +_ZN4cppu9ClassData8getTypesEv; +_ZNK3com3sun4star3uno19WeakReferenceHelper3getEv; +_ZNK4cppu17OImplementationId19getImplementationIdEv; +_ZNK4cppu20OPropertyArrayHelper8getCountEv; +_ZNK4cppu25OInterfaceContainerHelper11getElementsEv; +_ZNK4cppu25OInterfaceContainerHelper9getLengthEv; +_ZNK4cppu34OMultiTypeInterfaceContainerHelper12getContainerERKN3com3sun4star3uno4TypeE; +_ZNK4cppu34OMultiTypeInterfaceContainerHelper17getContainedTypesEv; +_ZNK4cppu39OMultiTypeInterfaceContainerHelperInt3212getContainerERK?; +_ZNK4cppu39OMultiTypeInterfaceContainerHelperInt3217getContainedTypesEv; +_ZTVN4cppu11OWeakObjectE; +_ZTVN4cppu14OWeakAggObjectE; +_ZTVN4cppu16OComponentHelperE; +_ZTVN4cppu18OPropertySetHelperE; +_ZTVN4cppu20IPropertyArrayHelperE; +_ZTVN4cppu20OPropertyArrayHelperE; +_ZTVN4cppu27WeakComponentImplHelperBaseE; +_ZTVN4cppu30WeakAggComponentImplHelperBaseE; +_ZN4cppu20OPropertyArrayHelperD0Ev; +_ZN4cppu20OPropertyArrayHelperD1Ev; +_ZThn*_N4cppu14OWeakAggObject12setDelegatorERKN3com3sun4star3uno9ReferenceINS4_10XInterfaceEEE; +_ZThn*_N4cppu14OWeakAggObject14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu14OWeakAggObject16queryAggregationERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu14OWeakAggObject7acquireEv; +_ZThn*_N4cppu14OWeakAggObject7releaseEv; +_ZThn*_N4cppu16OComponentHelper14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu16OComponentHelper16queryAggregationERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu16OComponentHelper7acquireEv; +_ZThn*_N4cppu16OComponentHelper7releaseEv; +_ZThn*_N4cppu27WeakComponentImplHelperBase14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu27WeakComponentImplHelperBase16addEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZThn*_N4cppu27WeakComponentImplHelperBase19removeEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZThn*_N4cppu27WeakComponentImplHelperBase7acquireEv; +_ZThn*_N4cppu27WeakComponentImplHelperBase7disposeEv; +_ZThn*_N4cppu27WeakComponentImplHelperBase7releaseEv; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase16queryAggregationERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase7acquireEv; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase7releaseEv; +_ZThn*_N4cppu16OComponentHelper14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu16OComponentHelper7acquireEv; +_ZThn*_N4cppu16OComponentHelper7releaseEv; +_ZThn*_N4cppu16OComponentHelper8getTypesEv; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase16addEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase19removeEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase7acquireEv; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase7disposeEv; +_ZThn*_N4cppu30WeakAggComponentImplHelperBase7releaseEv; +_ZThn*_N4cppu16OComponentHelper14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu16OComponentHelper16addEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZThn*_N4cppu16OComponentHelper19removeEventListenerERKN3com3sun4star3uno9ReferenceINS3_4lang14XEventListenerEEE; +_ZThn*_N4cppu16OComponentHelper7acquireEv; +_ZThn*_N4cppu16OComponentHelper7disposeEv; +_ZThn*_N4cppu16OComponentHelper7releaseEv; +_ZThn*_N4cppu18OPropertySetHelper14queryInterfaceERKN3com3sun4star3uno4TypeE; +_ZThn*_N4cppu18OPropertySetHelper20getFastPropertyValueE?; +_ZThn*_N4cppu18OPropertySetHelper20setFastPropertyValueE?RKN3com3sun4star3uno3AnyE; +_ZThn*_N4cppu18OPropertySetHelper16getPropertyValueERKN3rtl8OUStringE; +_ZThn*_N4cppu18OPropertySetHelper16setPropertyValueERKN3rtl8OUStringERKN3com3sun4star3uno3AnyE; +_ZThn*_N4cppu18OPropertySetHelper25addPropertyChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XPropertyChangeListenerEEE; +_ZThn*_N4cppu18OPropertySetHelper25addVetoableChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XVetoableChangeListenerEEE; +_ZThn*_N4cppu18OPropertySetHelper28removePropertyChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XPropertyChangeListenerEEE; +_ZThn*_N4cppu18OPropertySetHelper28removeVetoableChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XVetoableChangeListenerEEE; + +_ZN4cppu13AccessControl19checkFilePermissionERKN3rtl8OUStringES4_; +_ZN4cppu13AccessControl21checkSocketPermissionERKN3rtl8OUStringES4_; +_ZN4cppu13AccessControl22checkRuntimePermissionERKN3rtl8OUStringE; +_ZN4cppu13AccessControlC1ERKN3com3sun4star3uno9ReferenceINS3_8security17XAccessControllerEEE; +_ZN4cppu13AccessControlC2ERKN3com3sun4star3uno9ReferenceINS3_8security17XAccessControllerEEE; +_ZN4cppu13AccessControlC1ERKN3com3sun4star3uno9ReferenceINS4_17XComponentContextEEE; +_ZN4cppu13AccessControlC2ERKN3com3sun4star3uno9ReferenceINS4_17XComponentContextEEE; +_ZN4cppu13AccessControlC1ERKS0_; +_ZN4cppu13AccessControlC2ERKS0_; + +_ZN4cppu16UnoUrlDescriptorC1ERKN3rtl8OUStringE; +_ZN4cppu16UnoUrlDescriptorC1ERKS0_; +_ZN4cppu16UnoUrlDescriptorC2ERKN3rtl8OUStringE; +_ZN4cppu16UnoUrlDescriptorC2ERKS0_; +_ZN4cppu16UnoUrlDescriptorD1Ev; +_ZN4cppu16UnoUrlDescriptorD2Ev; +_ZN4cppu16UnoUrlDescriptoraSERKS0_; +_ZN4cppu6UnoUrlC1ERKN3rtl8OUStringE; +_ZN4cppu6UnoUrlC1ERKS0_; +_ZN4cppu6UnoUrlC2ERKN3rtl8OUStringE; +_ZN4cppu6UnoUrlC2ERKS0_; +_ZN4cppu6UnoUrlD1Ev; +_ZN4cppu6UnoUrlD2Ev; +_ZN4cppu6UnoUrlaSERKS0_; +_ZNK4cppu16UnoUrlDescriptor12getParameterERKN3rtl8OUStringE; +_ZNK4cppu16UnoUrlDescriptor12hasParameterERKN3rtl8OUStringE; +_ZNK4cppu16UnoUrlDescriptor13getDescriptorEv; +_ZNK4cppu16UnoUrlDescriptor7getNameEv; +_ZNK4cppu6UnoUrl11getProtocolEv; +_ZNK4cppu6UnoUrl13getConnectionEv; +_ZNK4cppu6UnoUrl13getObjectNameEv; + + local: + *; +}; + +UDK_3.1 { + global: + _ZN4cppu18getCaughtExceptionEv; + + _ZN4cppu18OPropertySetHelperC1ERNS_19OBroadcastHelperVarINS_34OMultiTypeInterfaceContainerHelperEN3com3sun4star3uno4TypeEEEb; + _ZN4cppu18OPropertySetHelperC2ERNS_19OBroadcastHelperVarINS_34OMultiTypeInterfaceContainerHelperEN3com3sun4star3uno4TypeEEEb; + + _ZN4cppu9bootstrapEv; + _ZN4cppu18BootstrapExceptionC1Ev; + _ZN4cppu18BootstrapExceptionC2Ev; + _ZN4cppu18BootstrapExceptionC1ERKN3rtl8OUStringE; + _ZN4cppu18BootstrapExceptionC2ERKN3rtl8OUStringE; + _ZN4cppu18BootstrapExceptionC1ERKS0_; + _ZN4cppu18BootstrapExceptionC2ERKS0_; + _ZN4cppu18BootstrapExceptionD0Ev; + _ZN4cppu18BootstrapExceptionD1Ev; + _ZN4cppu18BootstrapExceptionD2Ev; + _ZN4cppu18BootstrapExceptionaSERKS0_; + _ZNK4cppu18BootstrapException10getMessageEv; + # _ZTIN4cppu18BootstrapExceptionE; + # _ZTSN4cppu18BootstrapExceptionE; +} UDK_3_0_0; + +UDK_3.2 { + global: + _ZN4cppu20PropertySetMixinImpl10prepareSetERKN3rtl8OUStringERKN3com3sun4star3uno3AnyESB_PNS0_14BoundListenersE; + _ZN4cppu20PropertySetMixinImpl14BoundListenersC1Ev; + _ZN4cppu20PropertySetMixinImpl14BoundListenersC2Ev; + _ZN4cppu20PropertySetMixinImpl14BoundListenersD1Ev; + _ZN4cppu20PropertySetMixinImpl14BoundListenersD2Ev; + _ZN4cppu20PropertySetMixinImpl14queryInterfaceERKN3com3sun4star3uno4TypeE; + _ZN4cppu20PropertySetMixinImpl16getPropertyValueERKN3rtl8OUStringE; + _ZN4cppu20PropertySetMixinImpl16setPropertyValueERKN3rtl8OUStringERKN3com3sun4star3uno3AnyE; + _ZN4cppu20PropertySetMixinImpl17getPropertyValuesEv; + _ZN4cppu20PropertySetMixinImpl17setPropertyValuesERKN3com3sun4star3uno8SequenceINS3_5beans13PropertyValueEEE; + _ZN4cppu20PropertySetMixinImpl18getPropertySetInfoEv; + _ZN4cppu20PropertySetMixinImpl20getFastPropertyValueE?; + _ZN4cppu20PropertySetMixinImpl20setFastPropertyValueE?RKN3com3sun4star3uno3AnyE; + _ZN4cppu20PropertySetMixinImpl25addPropertyChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XPropertyChangeListenerEEE; + _ZN4cppu20PropertySetMixinImpl25addVetoableChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XVetoableChangeListenerEEE; + _ZN4cppu20PropertySetMixinImpl28removePropertyChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XPropertyChangeListenerEEE; + _ZN4cppu20PropertySetMixinImpl28removeVetoableChangeListenerERKN3rtl8OUStringERKN3com3sun4star3uno9ReferenceINS7_5beans23XVetoableChangeListenerEEE; + _ZN4cppu20PropertySetMixinImpl7disposeEv; + _ZN4cppu20PropertySetMixinImplC1ERKN3com3sun4star3uno9ReferenceINS4_17XComponentContextEEENS0_10ImplementsERKNS4_8SequenceIN3rtl8OUStringEEERKNS4_4TypeE; + _ZN4cppu20PropertySetMixinImplC2ERKN3com3sun4star3uno9ReferenceINS4_17XComponentContextEEENS0_10ImplementsERKNS4_8SequenceIN3rtl8OUStringEEERKNS4_4TypeE; + _ZN4cppu20PropertySetMixinImplD1Ev; + _ZN4cppu20PropertySetMixinImplD2Ev; + _ZNK4cppu20PropertySetMixinImpl14BoundListeners6notifyEv; + _ZThn*_N4cppu20PropertySetMixinImpl14queryInterfaceERKN3com3sun4star3uno4TypeE; + _ZThn*_N4cppu20PropertySetMixinImpl20getFastPropertyValueE?; + _ZThn*_N4cppu20PropertySetMixinImpl20setFastPropertyValueE?RKN3com3sun4star3uno3AnyE; + _ZThn*_N4cppu20PropertySetMixinImpl14queryInterfaceERKN3com3sun4star3uno4TypeE; + _ZThn*_N4cppu20PropertySetMixinImpl17getPropertyValuesEv; + _ZThn*_N4cppu20PropertySetMixinImpl17setPropertyValuesERKN3com3sun4star3uno8SequenceINS3_5beans13PropertyValueEEE; +} UDK_3.1; + +UDK_3.3 { # OOo 2.3 + global: + _ZN4cppu18OPropertySetHelper8getTypesEv; +} UDK_3.2; + +UDK_3.4 { # OOo 2.4 + global: + _ZN4cppu19bootstrap_expandUriERKN3rtl8OUStringE; # OUString cppu::bootstrap_expandUri(OUString const &) +} UDK_3.3; + +UDK_3.5 { # OOo 3.0 + global: + _ZN4cppu18OPropertySetHelperC1ERNS_19OBroadcastHelperVarINS_34OMultiTypeInterfaceContainerHelperEN3com3sun4star3uno4TypeEEEPNS_22IEventNotificationHookEb; + _ZN4cppu18OPropertySetHelperC2ERNS_19OBroadcastHelperVarINS_34OMultiTypeInterfaceContainerHelperEN3com3sun4star3uno4TypeEEEPNS_22IEventNotificationHookEb; +} UDK_3.4; + +UDK_3.6 { # OOo 3.3 + global: + _ZN4cppu11OWeakObject26disposeWeakConnectionPointEv; + _ZN3com3sun4star3uno19WeakReferenceHelperaSERKNS2_9ReferenceINS2_10XInterfaceEEE; + _ZN3com3sun4star3uno19WeakReferenceHelper5clearEv; + _ZN4cppu33createOneInstanceComponentFactoryEPFN3com3sun4star3uno9ReferenceINS3_10XInterfaceEEERKNS4_INS3_17XComponentContextEEEERKN3rtl8OUStringERKNS3_8SequenceISE_EEP16_rtl_ModuleCount; +} UDK_3.5; + + +UDK_3.7 { # OOo 3.4 + global: + _ZN4cppu18OPropertySetHelper29setDependentFastPropertyValueE?RKN3com3sun4star3uno3AnyE; +} UDK_3.6; + +UDK_3.8 { # LibO 3.5 +global: + ## class OPropertySetHelper2 + # constructors + _ZN4cppu19OPropertySetHelper2C1ERNS_19OBroadcastHelperVarINS_34OMultiTypeInterfaceContainerHelperEN3com3sun4star3uno4TypeEEEPNS_22IEventNotificationHookEb; + _ZN4cppu19OPropertySetHelper2C2ERNS_19OBroadcastHelperVarINS_34OMultiTypeInterfaceContainerHelperEN3com3sun4star3uno4TypeEEEPNS_22IEventNotificationHookEb; + # destructors + _ZN4cppu19OPropertySetHelper2D0Ev; + _ZN4cppu19OPropertySetHelper2D1Ev; + _ZN4cppu19OPropertySetHelper2D2Ev; + # queryInterface + _ZN4cppu19OPropertySetHelper214queryInterfaceERKN3com3sun4star3uno4TypeE; + _ZThn*_N4cppu19OPropertySetHelper214queryInterfaceERKN3com3sun4star3uno4TypeE; + # enableChangeListenerNotification + _ZN4cppu19OPropertySetHelper232enableChangeListenerNotificationEh; + _ZThn*_N4cppu19OPropertySetHelper232enableChangeListenerNotificationEh; +} UDK_3.7; + +LIBO_UDK_3.9 { # LibO 3.7 +global: + _ZN4cppu15supportsServiceEPN3com3sun4star4lang12XServiceInfoERKN3rtl8OUStringE; # cppu::supportsService(com::sun::star::lang::XServiceInfo*, OUString const&) +} UDK_3.8; + +LIBO_UDK_5.3 { # LibO 5.3 +global: + _ZN3com3sun4star3uno19WeakReferenceHelperaSEOS3_; # com::sun::star::uno::WeakReferenceHelper::operator=(com::sun::star::uno::WeakReferenceHelper&&) +} LIBO_UDK_3.9; + +# Unique libstdc++ symbols: +GLIBCXX_3.4 { + global: + _ZGVNSt7num_put*; _ZNSt7num_put*; + _ZNSs4_Rep20_S_empty_rep_storageE; +}; diff --git a/cppuhelper/source/implbase.cxx b/cppuhelper/source/implbase.cxx new file mode 100644 index 000000000..1f00accec --- /dev/null +++ b/cppuhelper/source/implbase.cxx @@ -0,0 +1,285 @@ +/* -*- 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 +#include +#include +#include + +#include +#include + +using namespace ::osl; +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; + + +namespace cppu +{ + +// WeakComponentImplHelperBase + +WeakComponentImplHelperBase::WeakComponentImplHelperBase( Mutex & rMutex ) + : rBHelper( rMutex ) +{ +} + +WeakComponentImplHelperBase::~WeakComponentImplHelperBase() +{ +} + +void WeakComponentImplHelperBase::disposing() +{ +} + +Any WeakComponentImplHelperBase::queryInterface( Type const & rType ) +{ + if (rType == cppu::UnoType::get()) + { + void * p = static_cast< lang::XComponent * >( this ); + return Any( &p, rType ); + } + return OWeakObject::queryInterface( rType ); +} + +void WeakComponentImplHelperBase::acquire() + throw () +{ + OWeakObject::acquire(); +} + +void WeakComponentImplHelperBase::release() + throw () +{ + if (osl_atomic_decrement( &m_refCount ) != 0) + return; + + // ensure no other references are created, via the weak connection point, from now on + disposeWeakConnectionPoint(); + // restore reference count: + osl_atomic_increment( &m_refCount ); + if (! rBHelper.bDisposed) { + try { + dispose(); + } + catch (RuntimeException const& exc) { // don't break throw () + SAL_WARN( "cppuhelper", exc ); + } + OSL_ASSERT( rBHelper.bDisposed ); + } + OWeakObject::release(); +} + +void WeakComponentImplHelperBase::dispose() +{ + ClearableMutexGuard aGuard( rBHelper.rMutex ); + if (rBHelper.bDisposed || rBHelper.bInDispose) + return; + + rBHelper.bInDispose = true; + aGuard.clear(); + try + { + // side effect: keeping a reference to this + lang::EventObject aEvt( static_cast< OWeakObject * >( this ) ); + try + { + rBHelper.aLC.disposeAndClear( aEvt ); + disposing(); + } + catch (...) + { + MutexGuard aGuard2( rBHelper.rMutex ); + // bDisposed and bInDispose must be set in this order: + rBHelper.bDisposed = true; + rBHelper.bInDispose = false; + throw; + } + MutexGuard aGuard2( rBHelper.rMutex ); + // bDisposed and bInDispose must be set in this order: + rBHelper.bDisposed = true; + rBHelper.bInDispose = false; + } + catch (RuntimeException &) + { + throw; + } + catch (Exception & exc) + { + css::uno::Any anyEx = cppu::getCaughtException(); + throw lang::WrappedTargetRuntimeException( + "unexpected UNO exception caught: " + exc.Message, + nullptr, anyEx ); + } +} + +void WeakComponentImplHelperBase::addEventListener( + Reference< lang::XEventListener > const & xListener ) +{ + ClearableMutexGuard aGuard( rBHelper.rMutex ); + if (rBHelper.bDisposed || rBHelper.bInDispose) + { + aGuard.clear(); + lang::EventObject aEvt( static_cast< OWeakObject * >( this ) ); + xListener->disposing( aEvt ); + } + else + { + rBHelper.addListener( cppu::UnoType::get(), xListener ); + } +} + +void WeakComponentImplHelperBase::removeEventListener( + Reference< lang::XEventListener > const & xListener ) +{ + rBHelper.removeListener( cppu::UnoType::get(), xListener ); +} + +// WeakAggComponentImplHelperBase + +WeakAggComponentImplHelperBase::WeakAggComponentImplHelperBase( Mutex & rMutex ) + : rBHelper( rMutex ) +{ +} + +WeakAggComponentImplHelperBase::~WeakAggComponentImplHelperBase() +{ +} + +void WeakAggComponentImplHelperBase::disposing() +{ +} + +Any WeakAggComponentImplHelperBase::queryInterface( Type const & rType ) +{ + return OWeakAggObject::queryInterface( rType ); +} + +Any WeakAggComponentImplHelperBase::queryAggregation( Type const & rType ) +{ + if (rType == cppu::UnoType::get()) + { + void * p = static_cast< lang::XComponent * >( this ); + return Any( &p, rType ); + } + return OWeakAggObject::queryAggregation( rType ); +} + +void WeakAggComponentImplHelperBase::acquire() + throw () +{ + OWeakAggObject::acquire(); +} + +void WeakAggComponentImplHelperBase::release() + throw () +{ + Reference const xDelegator_(xDelegator); + if (xDelegator_.is()) { + OWeakAggObject::release(); + } + else if (osl_atomic_decrement( &m_refCount ) == 0) { + // ensure no other references are created, via the weak connection point, from now on + disposeWeakConnectionPoint(); + // restore reference count: + osl_atomic_increment( &m_refCount ); + if (! rBHelper.bDisposed) { + try { + dispose(); + } + catch (RuntimeException const& exc) { // don't break throw () + SAL_WARN( "cppuhelper", exc ); + } + OSL_ASSERT( rBHelper.bDisposed ); + } + OWeakAggObject::release(); + } +} + +void WeakAggComponentImplHelperBase::dispose() +{ + ClearableMutexGuard aGuard( rBHelper.rMutex ); + if (rBHelper.bDisposed || rBHelper.bInDispose) + return; + + rBHelper.bInDispose = true; + aGuard.clear(); + try + { + // side effect: keeping a reference to this + lang::EventObject aEvt( static_cast< OWeakObject * >( this ) ); + try + { + rBHelper.aLC.disposeAndClear( aEvt ); + disposing(); + } + catch (...) + { + MutexGuard aGuard2( rBHelper.rMutex ); + // bDisposed and bInDispose must be set in this order: + rBHelper.bDisposed = true; + rBHelper.bInDispose = false; + throw; + } + MutexGuard aGuard2( rBHelper.rMutex ); + // bDisposed and bInDispose must be set in this order: + rBHelper.bDisposed = true; + rBHelper.bInDispose = false; + } + catch (RuntimeException &) + { + throw; + } + catch (Exception & exc) + { + css::uno::Any anyEx = cppu::getCaughtException(); + throw lang::WrappedTargetRuntimeException( + "unexpected UNO exception caught: " + exc.Message, + nullptr, anyEx ); + } +} + +void WeakAggComponentImplHelperBase::addEventListener( + Reference< lang::XEventListener > const & xListener ) +{ + ClearableMutexGuard aGuard( rBHelper.rMutex ); + if (rBHelper.bDisposed || rBHelper.bInDispose) + { + aGuard.clear(); + lang::EventObject aEvt( static_cast< OWeakObject * >( this ) ); + xListener->disposing( aEvt ); + } + else + { + rBHelper.addListener( cppu::UnoType::get(), xListener ); + } +} + +void WeakAggComponentImplHelperBase::removeEventListener( + Reference< lang::XEventListener > const & xListener ) +{ + // if we have disposed, then we have cleared the list already + MutexGuard aGuard( rBHelper.rMutex ); + if (!rBHelper.bDisposed) + rBHelper.removeListener( cppu::UnoType::get(), xListener ); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/implbase_ex.cxx b/cppuhelper/source/implbase_ex.cxx new file mode 100644 index 000000000..00eeaf376 --- /dev/null +++ b/cppuhelper/source/implbase_ex.cxx @@ -0,0 +1,413 @@ +/* -*- 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 +#include +#include +#include + +#include + +using namespace ::cppu; +using namespace ::osl; +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; + +namespace +{ + class theImplHelperInitMutex : public rtl::Static{}; +} + +namespace cppu +{ + +/** Shared mutex for implementation helper initialization. + Not for public use. +*/ +static ::osl::Mutex & getImplHelperInitMutex() +{ + return theImplHelperInitMutex::get(); +} + + +static void checkInterface( Type const & rType ) +{ + if (TypeClass_INTERFACE != rType.getTypeClass()) + { + OUString msg( "querying for interface \"" + rType.getTypeName() + "\": no interface type!" ); + SAL_WARN( "cppuhelper", msg ); + throw RuntimeException( msg ); + } +} + +static bool isXInterface( rtl_uString * pStr ) +{ + return OUString::unacquired(&pStr) == "com.sun.star.uno.XInterface"; +} + +static void * makeInterface( sal_IntPtr nOffset, void * that ) +{ + return (static_cast(that) + nOffset); +} + +static bool td_equals( + typelib_TypeDescriptionReference const * pTDR1, + typelib_TypeDescriptionReference const * pTDR2 ) +{ + return ((pTDR1 == pTDR2) || + OUString::unacquired(&pTDR1->pTypeName) == OUString::unacquired(&pTDR2->pTypeName)); +} + +static type_entry * getTypeEntries( class_data * cd ) +{ + type_entry * pEntries = cd->m_typeEntries; + if (! cd->m_storedTypeRefs) // not inited? + { + MutexGuard guard( getImplHelperInitMutex() ); + if (! cd->m_storedTypeRefs) // not inited? + { + // get all types + for ( sal_Int32 n = cd->m_nTypes; n--; ) + { + type_entry * pEntry = &pEntries[ n ]; + Type const & rType = (*pEntry->m_type.getCppuType)( nullptr ); + OSL_ENSURE( rType.getTypeClass() == TypeClass_INTERFACE, "### wrong helper init: expected interface!" ); + OSL_ENSURE( ! isXInterface( rType.getTypeLibType()->pTypeName ), "### want to implement XInterface: template argument is XInterface?!?!?!" ); + if (rType.getTypeClass() != TypeClass_INTERFACE) + { + OUString msg( "type \"" + rType.getTypeName() + "\" is no interface type!" ); + SAL_WARN( "cppuhelper", msg ); + throw RuntimeException( msg ); + } + // ref is statically held by getCppuType() + pEntry->m_type.typeRef = rType.getTypeLibType(); + } + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + cd->m_storedTypeRefs = true; + } + } + else + { + OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); + } + return pEntries; +} + +static void fillTypes( Type * types, class_data * cd ) +{ + type_entry * pEntries = getTypeEntries( cd ); + for ( sal_Int32 n = cd->m_nTypes; n--; ) + { + types[ n ] = pEntries[ n ].m_type.typeRef; + } +} + +namespace { + +bool recursivelyFindType( + typelib_TypeDescriptionReference const * demandedType, + typelib_InterfaceTypeDescription const * type, sal_IntPtr * offset) +{ + // This code assumes that the vtables of a multiple-inheritance class (the + // offset amount by which to adjust the this pointer) follow one another in + // the object layout, and that they contain slots for the inherited classes + // in a specific order. In theory, that need not hold for any given + // platform; in practice, it seems to work well on all supported platforms: + next: + for (sal_Int32 i = 0; i < type->nBaseTypes; ++i) { + if (i > 0) { + *offset += sizeof (void *); + } + typelib_InterfaceTypeDescription const * base = type->ppBaseTypes[i]; + // ignore XInterface: + if (base->nBaseTypes > 0) { + if (td_equals( + reinterpret_cast< + typelib_TypeDescriptionReference const * >(base), + demandedType)) + { + return true; + } + // Profiling showed that it is important to speed up the common case + // of only one base: + if (type->nBaseTypes == 1) { + type = base; + goto next; + } + if (recursivelyFindType(demandedType, base, offset)) { + return true; + } + } + } + return false; +} + +} + +static void * queryDeepNoXInterface( + typelib_TypeDescriptionReference const * pDemandedTDR, class_data * cd, void * that ) +{ + type_entry * pEntries = getTypeEntries( cd ); + sal_Int32 nTypes = cd->m_nTypes; + sal_Int32 n; + + // try top interfaces without getting td + for ( n = 0; n < nTypes; ++n ) + { + if (td_equals( pEntries[ n ].m_type.typeRef, pDemandedTDR )) + { + return makeInterface( pEntries[ n ].m_offset, that ); + } + } + // query deep getting td + for ( n = 0; n < nTypes; ++n ) + { + typelib_TypeDescription * pTD = nullptr; + TYPELIB_DANGER_GET( &pTD, pEntries[ n ].m_type.typeRef ); + if (pTD) + { + // exclude top (already tested) and bottom (XInterface) interface + OSL_ENSURE( + reinterpret_cast< typelib_InterfaceTypeDescription * >(pTD)-> + nBaseTypes > 0, + "### want to implement XInterface:" + " template argument is XInterface?!?!?!" ); + sal_IntPtr offset = pEntries[n].m_offset; + bool found = recursivelyFindType( + pDemandedTDR, + reinterpret_cast< typelib_InterfaceTypeDescription * >(pTD), + &offset); + TYPELIB_DANGER_RELEASE( pTD ); + if (found) { + return makeInterface( offset, that ); + } + } + else + { + OUString msg( "cannot get type description for type \"" + OUString::unacquired(&pEntries[ n ].m_type.typeRef->pTypeName) + "\"!" ); + SAL_WARN( "cppuhelper", msg ); + throw RuntimeException( msg ); + } + } + return nullptr; +} + +// ImplHelper + +Any SAL_CALL ImplHelper_query( + Type const & rType, class_data * cd, void * that ) +{ + checkInterface( rType ); + typelib_TypeDescriptionReference * pTDR = rType.getTypeLibType(); + + void * p; + // shortcut for XInterface + if (isXInterface( pTDR->pTypeName )) + { + // take first one + p = makeInterface( cd->m_typeEntries[ 0 ].m_offset, that ); + } + else + { + p = queryDeepNoXInterface( pTDR, cd, that ); + if (! p) + { + return Any(); + } + } + return Any( &p, pTDR ); +} + +Any SAL_CALL ImplHelper_queryNoXInterface( + Type const & rType, class_data * cd, void * that ) +{ + checkInterface( rType ); + typelib_TypeDescriptionReference * pTDR = rType.getTypeLibType(); + + void * p = queryDeepNoXInterface( pTDR, cd, that ); + if (p) + { + return Any( &p, pTDR ); + } + return Any(); +} + +css::uno::Sequence ImplHelper_getImplementationId( + SAL_UNUSED_PARAMETER class_data *) +{ + return css::uno::Sequence(); +} + +Sequence< Type > SAL_CALL ImplHelper_getTypes( + class_data * cd ) +{ + Sequence< Type > types( cd->m_nTypes ); + Type * pTypes = types.getArray(); + fillTypes( pTypes, cd ); + return types; +} + +Sequence< Type > SAL_CALL ImplInhHelper_getTypes( + class_data * cd, Sequence< Type > const & rAddTypes ) +{ + sal_Int32 nImplTypes = cd->m_nTypes; + sal_Int32 nAddTypes = rAddTypes.getLength(); + Sequence< Type > types( nImplTypes + nAddTypes ); + Type * pTypes = types.getArray(); + fillTypes( pTypes, cd ); + // append base types + Type const * pAddTypes = rAddTypes.getConstArray(); + while (nAddTypes--) + { + pTypes[ nImplTypes + nAddTypes ] = pAddTypes[ nAddTypes ]; + } + return types; +} + +// WeakImplHelper + +Any SAL_CALL WeakImplHelper_query( + Type const & rType, class_data * cd, void * that, OWeakObject * pBase ) +{ + checkInterface( rType ); + typelib_TypeDescriptionReference * pTDR = rType.getTypeLibType(); + + // shortcut XInterface to OWeakObject + if (! isXInterface( pTDR->pTypeName )) + { + void * p = queryDeepNoXInterface( pTDR, cd, that ); + if (p) + { + return Any( &p, pTDR ); + } + } + return pBase->OWeakObject::queryInterface( rType ); +} + +Sequence< Type > SAL_CALL WeakImplHelper_getTypes( + class_data * cd ) +{ + sal_Int32 nTypes = cd->m_nTypes; + Sequence< Type > types( nTypes +1 ); + Type * pTypes = types.getArray(); + fillTypes( pTypes, cd ); + pTypes[ nTypes ] = cppu::UnoType::get(); + return types; +} + +// WeakAggImplHelper + +Any SAL_CALL WeakAggImplHelper_queryAgg( + Type const & rType, class_data * cd, void * that, OWeakAggObject * pBase ) +{ + checkInterface( rType ); + typelib_TypeDescriptionReference * pTDR = rType.getTypeLibType(); + + // shortcut XInterface to OWeakAggObject + if (! isXInterface( pTDR->pTypeName )) + { + void * p = queryDeepNoXInterface( pTDR, cd, that ); + if (p) + { + return Any( &p, pTDR ); + } + } + return pBase->OWeakAggObject::queryAggregation( rType ); +} + +Sequence< Type > SAL_CALL WeakAggImplHelper_getTypes( + class_data * cd ) +{ + sal_Int32 nTypes = cd->m_nTypes; + Sequence< Type > types( nTypes +2 ); + Type * pTypes = types.getArray(); + fillTypes( pTypes, cd ); + pTypes[ nTypes++ ] = cppu::UnoType::get(); + pTypes[ nTypes ] = cppu::UnoType::get(); + return types; +} + +// WeakComponentImplHelper + +Any SAL_CALL WeakComponentImplHelper_query( + Type const & rType, class_data * cd, void * that, WeakComponentImplHelperBase * pBase ) +{ + checkInterface( rType ); + typelib_TypeDescriptionReference * pTDR = rType.getTypeLibType(); + + // shortcut XInterface to WeakComponentImplHelperBase + if (! isXInterface( pTDR->pTypeName )) + { + void * p = queryDeepNoXInterface( pTDR, cd, that ); + if (p) + { + return Any( &p, pTDR ); + } + } + return pBase->WeakComponentImplHelperBase::queryInterface( rType ); +} + +Sequence< Type > SAL_CALL WeakComponentImplHelper_getTypes( + class_data * cd ) +{ + sal_Int32 nTypes = cd->m_nTypes; + Sequence< Type > types( nTypes +2 ); + Type * pTypes = types.getArray(); + fillTypes( pTypes, cd ); + pTypes[ nTypes++ ] = cppu::UnoType::get(); + pTypes[ nTypes ] = cppu::UnoType::get(); + return types; +} + +// WeakAggComponentImplHelper + +Any SAL_CALL WeakAggComponentImplHelper_queryAgg( + Type const & rType, class_data * cd, void * that, WeakAggComponentImplHelperBase * pBase ) +{ + checkInterface( rType ); + typelib_TypeDescriptionReference * pTDR = rType.getTypeLibType(); + + // shortcut XInterface to WeakAggComponentImplHelperBase + if (! isXInterface( pTDR->pTypeName )) + { + void * p = queryDeepNoXInterface( pTDR, cd, that ); + if (p) + { + return Any( &p, pTDR ); + } + } + return pBase->WeakAggComponentImplHelperBase::queryAggregation( rType ); +} + +Sequence< Type > SAL_CALL WeakAggComponentImplHelper_getTypes( + class_data * cd ) +{ + sal_Int32 nTypes = cd->m_nTypes; + Sequence< Type > types( nTypes +3 ); + Type * pTypes = types.getArray(); + fillTypes( pTypes, cd ); + pTypes[ nTypes++ ] = cppu::UnoType::get(); + pTypes[ nTypes++ ] = cppu::UnoType::get(); + pTypes[ nTypes ] = cppu::UnoType::get(); + return types; +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/implementationentry.cxx b/cppuhelper/source/implementationentry.cxx new file mode 100644 index 000000000..f28547dfa --- /dev/null +++ b/cppuhelper/source/implementationentry.cxx @@ -0,0 +1,94 @@ +/* -*- 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 +#include +#include + +#include + +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::registry; + +namespace cppu { + +sal_Bool component_writeInfoHelper( + SAL_UNUSED_PARAMETER void *, void * pRegistryKey, + const struct ImplementationEntry entries[]) +{ + bool bRet = false; + try + { + if( pRegistryKey ) + { + for( sal_Int32 i = 0; entries[i].create ; i ++ ) + { + OUString sKey = "/" + entries[i].getImplementationName() + "/UNO/SERVICES"; + Reference< XRegistryKey > xNewKey( + static_cast< XRegistryKey * >( pRegistryKey )->createKey( sKey ) ); + + Sequence< OUString > seq = entries[i].getSupportedServiceNames(); + const OUString *pArray = seq.getConstArray(); + for ( sal_Int32 nPos = 0 ; nPos < seq.getLength(); nPos ++ ) + xNewKey->createKey( pArray[nPos] ); + } + bRet = true; + } + } + catch ( InvalidRegistryException & ) + { + OSL_FAIL( "### InvalidRegistryException!" ); + } + return bRet; +} + + +void * component_getFactoryHelper( + char const * pImplName, SAL_UNUSED_PARAMETER void *, + SAL_UNUSED_PARAMETER void *, const struct ImplementationEntry entries[]) +{ + + void * pRet = nullptr; + Reference< XSingleComponentFactory > xFactory; + + for( sal_Int32 i = 0 ; entries[i].create ; i ++ ) + { + OUString implName = entries[i].getImplementationName(); + if( implName.equalsAscii( pImplName ) ) + { + xFactory = entries[i].createFactory( + entries[i].create, + implName, + entries[i].getSupportedServiceNames(), + entries[i].moduleCounter ); + } + } + + if( xFactory.is() ) + { + xFactory->acquire(); + pRet = xFactory.get(); + } + return pRet; +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/interfacecontainer.cxx b/cppuhelper/source/interfacecontainer.cxx new file mode 100644 index 000000000..035f93848 --- /dev/null +++ b/cppuhelper/source/interfacecontainer.cxx @@ -0,0 +1,595 @@ +/* -*- 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 +#include +#include + +#include +#include +#include + +#include + +#include + + +using namespace osl; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; + +namespace cppu +{ + +OInterfaceIteratorHelper::OInterfaceIteratorHelper( OInterfaceContainerHelper & rCont_ ) + : rCont( rCont_ ) +{ + MutexGuard aGuard( rCont.rMutex ); + if( rCont.bInUse ) + // worst case, two iterators at the same time + rCont.copyAndResetInUse(); + bIsList = rCont_.bIsList; + aData = rCont_.aData; + if( bIsList ) + { + rCont.bInUse = true; + nRemain = aData.pAsVector->size(); + } + else if( aData.pAsInterface ) + { + aData.pAsInterface->acquire(); + nRemain = 1; + } + else + nRemain = 0; +} + +OInterfaceIteratorHelper::~OInterfaceIteratorHelper() +{ + bool bShared; + { + MutexGuard aGuard( rCont.rMutex ); + // bResetInUse protect the iterator against recursion + bShared = aData.pAsVector == rCont.aData.pAsVector && rCont.bIsList; + if( bShared ) + { + OSL_ENSURE( rCont.bInUse, "OInterfaceContainerHelper must be in use" ); + rCont.bInUse = false; + } + } + + if( !bShared ) + { + if( bIsList ) + // Sequence owned by the iterator + delete aData.pAsVector; + else if( aData.pAsInterface ) + // Interface is acquired by the iterator + aData.pAsInterface->release(); + } +} + +XInterface * OInterfaceIteratorHelper::next() +{ + if( nRemain ) + { + nRemain--; + if( bIsList ) + // typecase to const,so the getArray method is faster + return (*aData.pAsVector)[nRemain].get(); + if( aData.pAsInterface ) + return aData.pAsInterface; + } + // exception + return nullptr; +} + +void OInterfaceIteratorHelper::remove() +{ + if( bIsList ) + { + OSL_ASSERT( nRemain >= 0 && + nRemain < static_cast(aData.pAsVector->size()) ); + XInterface * p = (*aData.pAsVector)[nRemain].get(); + rCont.removeInterface( * reinterpret_cast< const Reference< XInterface > * >( &p ) ); + } + else + { + OSL_ASSERT( 0 == nRemain ); + rCont.removeInterface( * reinterpret_cast< const Reference< XInterface > * >(&aData.pAsInterface)); + } +} + +OInterfaceContainerHelper::OInterfaceContainerHelper( Mutex & rMutex_ ) + : rMutex( rMutex_ ) + , bInUse( false ) + , bIsList( false ) +{ +} + +OInterfaceContainerHelper::~OInterfaceContainerHelper() +{ + OSL_ENSURE( !bInUse, "~OInterfaceContainerHelper but is in use" ); + if( bIsList ) + delete aData.pAsVector; + else if( aData.pAsInterface ) + aData.pAsInterface->release(); +} + +sal_Int32 OInterfaceContainerHelper::getLength() const +{ + MutexGuard aGuard( rMutex ); + if( bIsList ) + return aData.pAsVector->size(); + if( aData.pAsInterface ) + return 1; + return 0; +} + +Sequence< Reference > OInterfaceContainerHelper::getElements() const +{ + MutexGuard aGuard( rMutex ); + if( bIsList ) + return comphelper::containerToSequence(*aData.pAsVector); + if( aData.pAsInterface ) + { + Reference x( aData.pAsInterface ); + return Sequence< Reference< XInterface > >( &x, 1 ); + } + return Sequence< Reference< XInterface > >(); +} + +void OInterfaceContainerHelper::copyAndResetInUse() +{ + OSL_ENSURE( bInUse, "OInterfaceContainerHelper not in use" ); + if( bInUse ) + { + // this should be the worst case. If an iterator is active + // and a new Listener is added. + if( bIsList ) + aData.pAsVector= new std::vector< Reference< XInterface > >( *aData.pAsVector ); + else if( aData.pAsInterface ) + aData.pAsInterface->acquire(); + + bInUse = false; + } +} + +sal_Int32 OInterfaceContainerHelper::addInterface( const Reference & rListener ) +{ + SAL_WARN_IF( !rListener.is(), "cppuhelper", "rListener is empty" ); + MutexGuard aGuard( rMutex ); + if( bInUse ) + copyAndResetInUse(); + + if( bIsList ) + { + aData.pAsVector->push_back(rListener); + return aData.pAsVector->size(); + } + if( aData.pAsInterface ) + { + Reference tmp(aData.pAsInterface); + aData.pAsInterface->release(); + aData.pAsVector = new std::vector>(2); + (*aData.pAsVector)[0] = std::move(tmp); + (*aData.pAsVector)[1] = rListener; + bIsList = true; + return 2; + } + aData.pAsInterface = rListener.get(); + if( rListener.is() ) + rListener->acquire(); + return 1; +} + +sal_Int32 OInterfaceContainerHelper::removeInterface( const Reference & rListener ) +{ + SAL_WARN_IF( !rListener.is(), "cppuhelper", "rListener is empty" ); + MutexGuard aGuard( rMutex ); + if( bInUse ) + copyAndResetInUse(); + + if( bIsList ) + { + // It is not valid to compare the pointer directly, but it's faster. + auto findIt = std::find_if(aData.pAsVector->begin(), aData.pAsVector->end(), + [&](const Reference& r) + { return r.get() == rListener.get(); }); + if (findIt != aData.pAsVector->end()) + { + aData.pAsVector->erase(findIt); + } + else + { + // interface not found, use the correct compare method + for( auto it = aData.pAsVector->begin(); it != aData.pAsVector->end(); ++it ) + { + if( *it == rListener ) + { + aData.pAsVector->erase(it); + break; + } + } + } + + if( aData.pAsVector->size() == 1 ) + { + XInterface * p = (*aData.pAsVector)[0].get(); + p->acquire(); + delete aData.pAsVector; + aData.pAsInterface = p; + bIsList = false; + return 1; + } + return aData.pAsVector->size(); + } + if( aData.pAsInterface && Reference( aData.pAsInterface ) == rListener ) + { + aData.pAsInterface->release(); + aData.pAsInterface = nullptr; + } + return aData.pAsInterface ? 1 : 0; +} + +void OInterfaceContainerHelper::disposeAndClear( const EventObject & rEvt ) +{ + ClearableMutexGuard aGuard( rMutex ); + OInterfaceIteratorHelper aIt( *this ); + // Release container, in case new entries come while disposing + OSL_ENSURE( !bIsList || bInUse, "OInterfaceContainerHelper not in use" ); + if( !bIsList && aData.pAsInterface ) + aData.pAsInterface->release(); + // set the member to null, use the iterator to delete the values + aData.pAsInterface = nullptr; + bIsList = false; + bInUse = false; + aGuard.clear(); + while( aIt.hasMoreElements() ) + { + try + { + Reference xLst( aIt.next(), UNO_QUERY ); + if( xLst.is() ) + xLst->disposing( rEvt ); + } + catch ( RuntimeException & ) + { + // be robust, if e.g. a remote bridge has disposed already. + // there is no way to delegate the error to the caller :o(. + } + } +} + + +void OInterfaceContainerHelper::clear() +{ + MutexGuard aGuard( rMutex ); + // Release container, in case new entries come while disposing + OSL_ENSURE( !bIsList || bInUse, "OInterfaceContainerHelper not in use" ); + if (bInUse) + copyAndResetInUse(); + if (bIsList) + delete aData.pAsVector; + else if (aData.pAsInterface) + aData.pAsInterface->release(); + aData.pAsInterface = nullptr; + bIsList = false; +} + +// specialized class for type + +typedef std::vector< std::pair < Type , void* > > t_type2ptr; + +OMultiTypeInterfaceContainerHelper::OMultiTypeInterfaceContainerHelper( Mutex & rMutex_ ) + : rMutex( rMutex_ ) +{ + m_pMap = new t_type2ptr; +} + +OMultiTypeInterfaceContainerHelper::~OMultiTypeInterfaceContainerHelper() +{ + t_type2ptr * pMap = static_cast(m_pMap); + + for (auto& rItem : *pMap) + { + delete static_cast(rItem.second); + rItem.second = nullptr; + } + delete pMap; +} + +Sequence< Type > OMultiTypeInterfaceContainerHelper::getContainedTypes() const +{ + t_type2ptr * pMap = static_cast(m_pMap); + t_type2ptr::size_type nSize; + + ::osl::MutexGuard aGuard( rMutex ); + nSize = pMap->size(); + if( nSize ) + { + css::uno::Sequence< Type > aInterfaceTypes( nSize ); + Type * pArray = aInterfaceTypes.getArray(); + + sal_Int32 i = 0; + for (const auto& rItem : *pMap) + { + // are interfaces added to this container? + if( static_cast(rItem.second)->getLength() ) + // yes, put the type in the array + pArray[i++] = rItem.first; + } + if( static_cast(i) != nSize ) { + // may be empty container, reduce the sequence to the right size + aInterfaceTypes = css::uno::Sequence< Type >( pArray, i ); + } + return aInterfaceTypes; + } + return css::uno::Sequence< Type >(); +} + +static t_type2ptr::iterator findType(t_type2ptr *pMap, const Type & rKey ) +{ + return std::find_if(pMap->begin(), pMap->end(), + [&rKey](const t_type2ptr::value_type& rItem) { return rItem.first == rKey; }); +} + +OInterfaceContainerHelper * OMultiTypeInterfaceContainerHelper::getContainer( const Type & rKey ) const +{ + ::osl::MutexGuard aGuard( rMutex ); + + t_type2ptr * pMap = static_cast(m_pMap); + t_type2ptr::iterator iter = findType( pMap, rKey ); + if( iter != pMap->end() ) + return static_cast((*iter).second); + return nullptr; +} + +sal_Int32 OMultiTypeInterfaceContainerHelper::addInterface( + const Type & rKey, const Reference< XInterface > & rListener ) +{ + ::osl::MutexGuard aGuard( rMutex ); + t_type2ptr * pMap = static_cast(m_pMap); + t_type2ptr::iterator iter = findType( pMap, rKey ); + if( iter == pMap->end() ) + { + OInterfaceContainerHelper * pLC = new OInterfaceContainerHelper( rMutex ); + pMap->push_back(std::pair(rKey, pLC)); + return pLC->addInterface( rListener ); + } + return static_cast((*iter).second)->addInterface( rListener ); +} + +sal_Int32 OMultiTypeInterfaceContainerHelper::removeInterface( + const Type & rKey, const Reference< XInterface > & rListener ) +{ + ::osl::MutexGuard aGuard( rMutex ); + + // search container with id nUik + t_type2ptr * pMap = static_cast(m_pMap); + t_type2ptr::iterator iter = findType( pMap, rKey ); + // container found? + if( iter != pMap->end() ) + return static_cast((*iter).second)->removeInterface( rListener ); + + // no container with this id. Always return 0 + return 0; +} + +void OMultiTypeInterfaceContainerHelper::disposeAndClear( const EventObject & rEvt ) +{ + t_type2ptr::size_type nSize = 0; + std::unique_ptr ppListenerContainers; + { + ::osl::MutexGuard aGuard( rMutex ); + t_type2ptr * pMap = static_cast(m_pMap); + nSize = pMap->size(); + if( nSize ) + { + typedef OInterfaceContainerHelper* ppp; + ppListenerContainers.reset(new ppp[nSize]); + //ppListenerContainers = new (ListenerContainer*)[nSize]; + + t_type2ptr::size_type i = 0; + for (const auto& rItem : *pMap) + { + ppListenerContainers[i++] = static_cast(rItem.second); + } + } + } + + // create a copy, because do not fire event in a guarded section + for( t_type2ptr::size_type i = 0; + i < nSize; i++ ) + { + if( ppListenerContainers[i] ) + ppListenerContainers[i]->disposeAndClear( rEvt ); + } +} + +void OMultiTypeInterfaceContainerHelper::clear() +{ + ::osl::MutexGuard aGuard( rMutex ); + t_type2ptr * pMap = static_cast(m_pMap); + + for (auto& rItem : *pMap) + { + static_cast(rItem.second)->clear(); + } +} + +// specialized class for long + +typedef std::vector< std::pair < sal_Int32 , void* > > t_long2ptr; + +static t_long2ptr::iterator findLong(t_long2ptr *pMap, sal_Int32 nKey ) +{ + return std::find_if(pMap->begin(), pMap->end(), + [&nKey](const t_long2ptr::value_type& rItem) { return rItem.first == nKey; }); +} + +OMultiTypeInterfaceContainerHelperInt32::OMultiTypeInterfaceContainerHelperInt32( Mutex & rMutex_ ) + : m_pMap( nullptr ) + , rMutex( rMutex_ ) +{ + // delay pMap allocation until necessary. +} + +OMultiTypeInterfaceContainerHelperInt32::~OMultiTypeInterfaceContainerHelperInt32() +{ + if (!m_pMap) + return; + + t_long2ptr * pMap = static_cast(m_pMap); + + for (auto& rItem : *pMap) + { + delete static_cast(rItem.second); + rItem.second = nullptr; + } + delete pMap; +} + +Sequence< sal_Int32 > OMultiTypeInterfaceContainerHelperInt32::getContainedTypes() const +{ + t_long2ptr * pMap = static_cast(m_pMap); + t_long2ptr::size_type nSize; + + ::osl::MutexGuard aGuard( rMutex ); + nSize = pMap ? pMap->size() : 0; + if( nSize ) + { + css::uno::Sequence< sal_Int32 > aInterfaceTypes( nSize ); + sal_Int32 * pArray = aInterfaceTypes.getArray(); + + sal_Int32 i = 0; + for (const auto& rItem : *pMap) + { + // are interfaces added to this container? + if( static_cast(rItem.second)->getLength() ) + // yes, put the type in the array + pArray[i++] = rItem.first; + } + if( static_cast(i) != nSize ) { + // may be empty container, reduce the sequence to the right size + aInterfaceTypes = css::uno::Sequence< sal_Int32 >( pArray, i ); + } + return aInterfaceTypes; + } + return css::uno::Sequence< sal_Int32 >(); +} + +OInterfaceContainerHelper * OMultiTypeInterfaceContainerHelperInt32::getContainer( const sal_Int32 & rKey ) const +{ + ::osl::MutexGuard aGuard( rMutex ); + + if (!m_pMap) + return nullptr; + t_long2ptr * pMap = static_cast(m_pMap); + t_long2ptr::iterator iter = findLong( pMap, rKey ); + if( iter != pMap->end() ) + return static_cast((*iter).second); + return nullptr; +} + +sal_Int32 OMultiTypeInterfaceContainerHelperInt32::addInterface( + const sal_Int32 & rKey, const Reference< XInterface > & rListener ) +{ + ::osl::MutexGuard aGuard( rMutex ); + if (!m_pMap) + m_pMap = new t_long2ptr; + t_long2ptr * pMap = static_cast(m_pMap); + t_long2ptr::iterator iter = findLong( pMap, rKey ); + if( iter == pMap->end() ) + { + OInterfaceContainerHelper * pLC = new OInterfaceContainerHelper( rMutex ); + pMap->push_back(std::pair< sal_Int32, void* >(rKey, pLC)); + return pLC->addInterface( rListener ); + } + return static_cast((*iter).second)->addInterface( rListener ); +} + +sal_Int32 OMultiTypeInterfaceContainerHelperInt32::removeInterface( + const sal_Int32 & rKey, const Reference< XInterface > & rListener ) +{ + ::osl::MutexGuard aGuard( rMutex ); + + if (!m_pMap) + return 0; + // search container with id nUik + t_long2ptr * pMap = static_cast(m_pMap); + t_long2ptr::iterator iter = findLong( pMap, rKey ); + // container found? + if( iter != pMap->end() ) + return static_cast((*iter).second)->removeInterface( rListener ); + + // no container with this id. Always return 0 + return 0; +} + +void OMultiTypeInterfaceContainerHelperInt32::disposeAndClear( const EventObject & rEvt ) +{ + t_long2ptr::size_type nSize = 0; + std::unique_ptr ppListenerContainers; + { + ::osl::MutexGuard aGuard( rMutex ); + if (!m_pMap) + return; + + t_long2ptr * pMap = static_cast(m_pMap); + nSize = pMap->size(); + if( nSize ) + { + typedef OInterfaceContainerHelper* ppp; + ppListenerContainers.reset(new ppp[nSize]); + + t_long2ptr::size_type i = 0; + for (const auto& rItem : *pMap) + { + ppListenerContainers[i++] = static_cast(rItem.second); + } + } + } + + // create a copy, because do not fire event in a guarded section + for( t_long2ptr::size_type i = 0; + i < nSize; i++ ) + { + if( ppListenerContainers[i] ) + ppListenerContainers[i]->disposeAndClear( rEvt ); + } +} + +void OMultiTypeInterfaceContainerHelperInt32::clear() +{ + ::osl::MutexGuard aGuard( rMutex ); + if (!m_pMap) + return; + t_long2ptr * pMap = static_cast(m_pMap); + + for (auto& rItem : *pMap) + { + static_cast(rItem.second)->clear(); + } +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/loadsharedlibcomponentfactory.hxx b/cppuhelper/source/loadsharedlibcomponentfactory.hxx new file mode 100644 index 000000000..033fc8f32 --- /dev/null +++ b/cppuhelper/source/loadsharedlibcomponentfactory.hxx @@ -0,0 +1,44 @@ +/* -*- 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/. + */ + +#ifndef INCLUDED_CPPUHELPER_SOURCE_LOADSHAREDLIBCOMPONENTFACTORY_HXX +#define INCLUDED_CPPUHELPER_SOURCE_LOADSHAREDLIBCOMPONENTFACTORY_HXX + +#include + +#include + +#include "servicemanager.hxx" + +namespace com::sun::star { + namespace lang { class XMultiServiceFactory; } + namespace uno { + class Environment; + class XInterface; + } +} + +namespace cppuhelper::detail { + +css::uno::Environment getEnvironment( + OUString const & name, OUString const & implementation); + +void loadSharedLibComponentFactory( + OUString const & uri, OUString const & environment, + OUString const & prefix, OUString const & implementation, + OUString const & constructor, + css::uno::Reference const & serviceManager, + WrapperConstructorFn * constructorFunction, + css::uno::Reference * factory); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/macro_expander.cxx b/cppuhelper/source/macro_expander.cxx new file mode 100644 index 000000000..e9a6cce3f --- /dev/null +++ b/cppuhelper/source/macro_expander.cxx @@ -0,0 +1,182 @@ +/* -*- 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 + +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include "macro_expander.hxx" +#include "paths.hxx" + +#define SERVICE_NAME_A "com.sun.star.lang.MacroExpander" +#define SERVICE_NAME_B "com.sun.star.lang.BootstrapMacroExpander" +#define IMPL_NAME "com.sun.star.lang.comp.cppuhelper.BootstrapMacroExpander" + +using namespace ::osl; +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; + +using rtl::Bootstrap; + +namespace cppu +{ + +static Bootstrap const & get_unorc() +{ + static rtlBootstrapHandle s_bstrap = rtl_bootstrap_args_open(getUnoIniUri().pData); + return *reinterpret_cast(&s_bstrap); +} + +} + +namespace cppuhelper::detail { + +OUString expandMacros(OUString const & text) { + OUString t(text); + rtl_bootstrap_expandMacros_from_handle( + cppu::get_unorc().getHandle(), &t.pData); + return t; +} + +} + +namespace +{ + +class ImplNames +{ +private: + Sequence m_aNames; +public: + ImplNames() : m_aNames(2) + { + m_aNames[0] = SERVICE_NAME_A; + m_aNames[1] = SERVICE_NAME_B; + } + const Sequence& getNames() const { return m_aNames; } +}; + +class theImplNames : public rtl::Static {}; + +OUString s_impl_name() +{ + return IMPL_NAME; +} + +Sequence< OUString > const & s_get_service_names() +{ + return theImplNames::get().getNames(); +} + +typedef cppu::WeakComponentImplHelper< + util::XMacroExpander, lang::XServiceInfo > t_uno_impl; + +struct mutex_holder +{ + Mutex m_mutex; +}; + +class Bootstrap_MacroExpander : public mutex_holder, public t_uno_impl +{ +protected: + virtual void SAL_CALL disposing() override; + +public: + Bootstrap_MacroExpander() + : t_uno_impl( m_mutex ) + {} + + // XMacroExpander impl + virtual OUString SAL_CALL expandMacros( OUString const & exp ) override; + // XServiceInfo impl + virtual OUString SAL_CALL getImplementationName() override; + virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName ) override; + virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() override; +}; + + +void Bootstrap_MacroExpander::disposing() +{} + +// XServiceInfo impl + +OUString Bootstrap_MacroExpander::getImplementationName() +{ + return s_impl_name(); +} + +sal_Bool Bootstrap_MacroExpander::supportsService( OUString const & serviceName ) +{ + return cppu::supportsService(this, serviceName); +} + +Sequence< OUString > Bootstrap_MacroExpander::getSupportedServiceNames() +{ + return s_get_service_names(); +} + +// XMacroExpander impl + +OUString Bootstrap_MacroExpander::expandMacros( OUString const & exp ) +{ + return cppuhelper::detail::expandMacros( exp ); +} + + +Reference< XInterface > service_create( + SAL_UNUSED_PARAMETER Reference< XComponentContext > const & ) +{ + return static_cast< ::cppu::OWeakObject * >( new Bootstrap_MacroExpander ); +} + +} + +namespace cppuhelper::detail { + +Reference< lang::XSingleComponentFactory > create_bootstrap_macro_expander_factory() +{ + Reference< lang::XSingleComponentFactory > free(::cppu::createSingleComponentFactory( + service_create, + s_impl_name(), + s_get_service_names() )); + + uno::Environment curr_env(Environment::getCurrent()); + uno::Environment target_env(CPPU_CURRENT_LANGUAGE_BINDING_NAME); + + uno::Mapping target2curr(target_env, curr_env); + + return Reference( + static_cast( + target2curr.mapInterface(free.get(), cppu::UnoType::get())), + SAL_NO_ACQUIRE); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/macro_expander.hxx b/cppuhelper/source/macro_expander.hxx new file mode 100644 index 000000000..4a2740beb --- /dev/null +++ b/cppuhelper/source/macro_expander.hxx @@ -0,0 +1,59 @@ +/* -*- 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 . + */ + +#ifndef INCLUDED_CPPUHELPER_SOURCE_MACRO_EXPANDER_HXX +#define INCLUDED_CPPUHELPER_SOURCE_MACRO_EXPANDER_HXX + +#include + +#include + +namespace com::sun::star::lang { class XSingleComponentFactory; } + +namespace cppuhelper { + +namespace detail { + +/** + * Helper function to expand macros based on the unorc/uno.ini. + * + * @internal + * + * @param text + * Some text. + * + * @return + * The expanded text. + * + * @exception com::sun::star::lang::IllegalArgumentException + * If uriReference is a vnd.sun.star.expand URL reference that contains unknown + * macros. + */ +OUString expandMacros(OUString const & text); + +css::uno::Reference< css::lang::XSingleComponentFactory > +create_bootstrap_macro_expander_factory(); + +} + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/paths.cxx b/cppuhelper/source/paths.cxx new file mode 100644 index 000000000..49144f715 --- /dev/null +++ b/cppuhelper/source/paths.cxx @@ -0,0 +1,135 @@ +/* -*- 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 + +#include + +#include + +#include +#include +#include +#include +#include + +#include "paths.hxx" + +namespace { + +#ifndef ANDROID +OUString get_this_libpath() { + static OUString s_uri = []() { + OUString uri; + osl::Module::getUrlFromAddress(reinterpret_cast(get_this_libpath), uri); + sal_Int32 i = uri.lastIndexOf('/'); + if (i == -1) + { + throw css::uno::DeploymentException("URI " + uri + " is expected to contain a slash"); + } + return uri.copy(0, i); + }(); + + return s_uri; +} +#endif +} + +OUString cppu::getUnoIniUri() { +#if defined ANDROID + // Wouldn't it be lovely to avoid this ugly hard-coding. + // The problem is that the 'create_bootstrap_macro_expander_factory()' + // required for bootstrapping services, calls cppu::get_unorc directly + // instead of re-using the BootstrapHandle from: + // defaultBootstrap_InitialComponentContext + // and since rtlBootstrapHandle is not ref-counted doing anything + // clean here is hardish. + OUString uri("file:///assets/program"); +#else + OUString uri(get_this_libpath()); +#ifdef MACOSX + // We keep both the LO and URE dylibs directly in "Frameworks" + // (that is, LIBO_LIB_FOLDER) and rc files in "Resources" + // (LIBO_ETC_FOLDER). Except for unorc, of which there are two, + // the "LO" one (which is in "Resources") and the "URE" one (which + // is in "Resources/ure/etc" (LIBO_URE_ETC_FOLDER)). As this code + // goes into the cppuhelper library which is part of URE, we are + // looking for the latter one here. I think... + if (uri.endsWith( "/" LIBO_LIB_FOLDER ) ) + { + uri = uri.copy( 0, uri.getLength() - (sizeof(LIBO_LIB_FOLDER)-1) ) + LIBO_URE_ETC_FOLDER; + } +#endif +#endif + return uri + "/" SAL_CONFIGFILE("uno"); +} + +bool cppu::nextDirectoryItem(osl::Directory & directory, OUString * url) { + assert(url != nullptr); + for (;;) { + osl::DirectoryItem i; + switch (directory.getNextItem(i, SAL_MAX_UINT32)) { + case osl::FileBase::E_None: + break; + case osl::FileBase::E_NOENT: + return false; + default: + throw css::uno::DeploymentException( + "Cannot iterate directory"); + } + osl::FileStatus stat( + osl_FileStatus_Mask_Type | osl_FileStatus_Mask_FileName | + osl_FileStatus_Mask_FileURL); + if (i.getFileStatus(stat) != osl::FileBase::E_None) { + throw css::uno::DeploymentException( + "Cannot stat in directory"); + } + if (stat.getFileType() != osl::FileStatus::Directory) { //TODO: symlinks + // Ignore backup files: + OUString name(stat.getFileName()); + if (!(name.match(".") || name.endsWith("~"))) { + *url = stat.getFileURL(); + return true; + } + } + } +} + +void cppu::decodeRdbUri(OUString * uri, bool * optional, bool * directory) +{ + assert(uri != nullptr && optional != nullptr && directory != nullptr); + if(!(uri->isEmpty())) + { + *optional = (*uri)[0] == '?'; + if (*optional) { + *uri = uri->copy(1); + } + *directory = uri->startsWith("<") && uri->endsWith(">*"); + if (*directory) { + *uri = uri->copy(1, uri->getLength() - 3); + } + } + else + { + *optional = false; + *directory = false; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/paths.hxx b/cppuhelper/source/paths.hxx new file mode 100644 index 000000000..baad8c68c --- /dev/null +++ b/cppuhelper/source/paths.hxx @@ -0,0 +1,40 @@ +/* -*- 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 . + */ + +#ifndef INCLUDED_CPPUHELPER_SOURCE_PATHS_HXX +#define INCLUDED_CPPUHELPER_SOURCE_PATHS_HXX + +#include +#include + +namespace osl { class Directory; } + +namespace cppu { + +OUString getUnoIniUri(); + +bool nextDirectoryItem(osl::Directory & directory, OUString * url); + +void decodeRdbUri(OUString * uri, bool * optional, bool * directory); + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/propertysetmixin.cxx b/cppuhelper/source/propertysetmixin.cxx new file mode 100644 index 000000000..c7c815489 --- /dev/null +++ b/cppuhelper/source/propertysetmixin.cxx @@ -0,0 +1,1140 @@ +/* -*- 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 + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using cppu::PropertySetMixinImpl; + +namespace { + +struct PropertyData { + explicit PropertyData( + css::beans::Property const & theProperty, bool thePresent): + property(theProperty), present(thePresent) {} + + css::beans::Property property; + bool present; +}; + +struct Data: public salhelper::SimpleReferenceObject { + typedef std::map< OUString, PropertyData > PropertyMap; + + PropertyMap properties; + + PropertyMap::const_iterator get( + css::uno::Reference< css::uno::XInterface > const & object, + OUString const & name) const; + +protected: + void initProperties( + css::uno::Reference< css::reflection::XTypeDescription > const & type, + css::uno::Sequence< OUString > const & absentOptional, + std::vector< OUString > * handleNames) + { + std::set seen; + initProperties(type, absentOptional, handleNames, &seen); + } + +private: + void initProperties( + css::uno::Reference< css::reflection::XTypeDescription > const & type, + css::uno::Sequence< OUString > const & absentOptional, + std::vector< OUString > * handleNames, std::set * seen); + + static css::uno::Reference< css::reflection::XTypeDescription > + resolveTypedefs( + css::uno::Reference< css::reflection::XTypeDescription > const & type); +}; + +Data::PropertyMap::const_iterator Data::get( + css::uno::Reference< css::uno::XInterface > const & object, + OUString const & name) const +{ + PropertyMap::const_iterator i(properties.find(name)); + if (i == properties.end() || !i->second.present) { + throw css::beans::UnknownPropertyException(name, object); + } + return i; +} + +void Data::initProperties( + css::uno::Reference< css::reflection::XTypeDescription > const & type, + css::uno::Sequence< OUString > const & absentOptional, + std::vector< OUString > * handleNames, std::set * seen) +{ + css::uno::Reference< css::reflection::XInterfaceTypeDescription2 > ifc( + resolveTypedefs(type), css::uno::UNO_QUERY_THROW); + if (!seen->insert(ifc->getName()).second) + return; + + const css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > bases( + ifc->getBaseTypes()); + for (const auto & i : bases) { + initProperties(i, absentOptional, handleNames, seen); + } + const css::uno::Sequence< + css::uno::Reference< + css::reflection::XInterfaceMemberTypeDescription > > members( + ifc->getMembers()); + OUString const * absentBegin = absentOptional.getConstArray(); + OUString const * absentEnd = + absentBegin + absentOptional.getLength(); + for (const auto & m : members) { + if (m->getTypeClass() + == css::uno::TypeClass_INTERFACE_ATTRIBUTE) + { + css::uno::Reference< + css::reflection::XInterfaceAttributeTypeDescription2 > attr( + m, css::uno::UNO_QUERY_THROW); + sal_Int16 attrAttribs = 0; + if (attr->isBound()) { + attrAttribs |= css::beans::PropertyAttribute::BOUND; + } + bool bSetUnknown = false; + if (attr->isReadOnly()) { + attrAttribs |= css::beans::PropertyAttribute::READONLY; + bSetUnknown = true; + } + css::uno::Sequence< + css::uno::Reference< + css::reflection::XCompoundTypeDescription > > excs( + attr->getGetExceptions()); + bool bGetUnknown = false; + //XXX Special interpretation of getter/setter exceptions only + // works if the specified exceptions are of the exact type, not + // of a supertype: + for (const auto & ex : std::as_const(excs)) { + if ( ex->getName() == "com.sun.star.beans.UnknownPropertyException" ) + { + bGetUnknown = true; + break; + } + } + excs = attr->getSetExceptions(); + for (const auto & ex : std::as_const(excs)) { + if ( ex->getName() == "com.sun.star.beans.UnknownPropertyException" ) + { + bSetUnknown = true; + } else if ( ex->getName() == "com.sun.star.beans.PropertyVetoException" ) + { + attrAttribs + |= css::beans::PropertyAttribute::CONSTRAINED; + } + } + if (bGetUnknown && bSetUnknown) { + attrAttribs |= css::beans::PropertyAttribute::OPTIONAL; + } + css::uno::Reference< css::reflection::XTypeDescription > t( + attr->getType()); + for (;;) + { + t = resolveTypedefs(t); + sal_Int16 n; + if (t->getName().startsWith( + "com.sun.star.beans.Ambiguous<")) + { + n = css::beans::PropertyAttribute::MAYBEAMBIGUOUS; + } else if (t->getName().startsWith( + "com.sun.star.beans.Defaulted<")) + { + n = css::beans::PropertyAttribute::MAYBEDEFAULT; + } else if (t->getName().startsWith( + "com.sun.star.beans.Optional<")) + { + n = css::beans::PropertyAttribute::MAYBEVOID; + } else { + break; + } + if ((attrAttribs & n) != 0) { + break; + } + attrAttribs |= n; + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + args( + css::uno::Reference< + css::reflection::XStructTypeDescription >( + t, css::uno::UNO_QUERY_THROW)-> + getTypeArguments()); + if (args.getLength() != 1) { + throw css::uno::RuntimeException( + "inconsistent UNO type registry"); + } + t = args[0]; + } + std::vector< OUString >::size_type handles + = handleNames->size(); + if (handles > SAL_MAX_INT32) { + throw css::uno::RuntimeException( + "interface type has too many attributes"); + } + OUString name(m->getMemberName()); + if (!properties.emplace( + name, + PropertyData( + css::beans::Property( + name, static_cast< sal_Int32 >(handles), + css::uno::Type( + t->getTypeClass(), t->getName()), + attrAttribs), + (std::find(absentBegin, absentEnd, name) + == absentEnd))). + second) + { + throw css::uno::RuntimeException( + "inconsistent UNO type registry"); + } + handleNames->push_back(name); + } + } +} + +css::uno::Reference< css::reflection::XTypeDescription > Data::resolveTypedefs( + css::uno::Reference< css::reflection::XTypeDescription > const & type) +{ + css::uno::Reference< css::reflection::XTypeDescription > t(type); + while (t->getTypeClass() == css::uno::TypeClass_TYPEDEF) { + t = css::uno::Reference< css::reflection::XIndirectTypeDescription >( + t, css::uno::UNO_QUERY_THROW)->getReferencedType(); + } + return t; +} + +class Info: public cppu::WeakImplHelper< css::beans::XPropertySetInfo > { +public: + explicit Info(Data * data): m_data(data) {} + + virtual css::uno::Sequence< css::beans::Property > SAL_CALL getProperties() override; + + virtual css::beans::Property SAL_CALL getPropertyByName( + OUString const & name) override; + + virtual sal_Bool SAL_CALL hasPropertyByName(OUString const & name) override; + +private: + rtl::Reference< Data > m_data; +}; + +css::uno::Sequence< css::beans::Property > Info::getProperties() +{ + assert(m_data->properties.size() <= SAL_MAX_INT32); + css::uno::Sequence< css::beans::Property > s( + static_cast< sal_Int32 >(m_data->properties.size())); + sal_Int32 n = 0; + for (const auto& rEntry : m_data->properties) + { + if (rEntry.second.present) { + s[n++] = rEntry.second.property; + } + } + s.realloc(n); + return s; +} + +css::beans::Property Info::getPropertyByName(OUString const & name) +{ + return m_data->get(static_cast< cppu::OWeakObject * >(this), name)-> + second.property; +} + +sal_Bool Info::hasPropertyByName(OUString const & name) +{ + Data::PropertyMap::iterator i(m_data->properties.find(name)); + return i != m_data->properties.end() && i->second.present; +} + +typedef +std::multiset< css::uno::Reference< css::beans::XPropertyChangeListener > > +BoundListenerBag; + +} + +class PropertySetMixinImpl::BoundListeners::Impl { +public: + BoundListenerBag specificListeners; + BoundListenerBag unspecificListeners; + css::beans::PropertyChangeEvent event; +}; + +PropertySetMixinImpl::BoundListeners::BoundListeners(): m_impl(new Impl) {} + +PropertySetMixinImpl::BoundListeners::~BoundListeners() { + delete m_impl; +} + +void PropertySetMixinImpl::BoundListeners::notify() const { + for (const auto& rxListener : m_impl->specificListeners) + { + try { + rxListener->propertyChange(m_impl->event); + } catch (css::lang::DisposedException &) {} + } + for (const auto& rxListener : m_impl->unspecificListeners) + { + try { + rxListener->propertyChange(m_impl->event); + } catch (css::lang::DisposedException &) {} + } +} + +class PropertySetMixinImpl::Impl: public Data { +public: + Impl( + css::uno::Reference< css::uno::XComponentContext > const & context, + Implements theImplements, + css::uno::Sequence< OUString > const & absentOptional, + css::uno::Type const & type); + + OUString const & translateHandle( + css::uno::Reference< css::uno::XInterface > const & object, + sal_Int32 handle) const; + + void setProperty( + css::uno::Reference< css::uno::XInterface > const & object, + OUString const & name, css::uno::Any const & value, + bool isAmbiguous, bool isDefaulted, sal_Int16 illegalArgumentPosition) + const; + + css::uno::Any getProperty( + css::uno::Reference< css::uno::XInterface > const & object, + OUString const & name, css::beans::PropertyState * state) const; + + PropertySetMixinImpl::Implements implements; + css::uno::Sequence< OUString > handleMap; + + typedef std::map< OUString, BoundListenerBag > BoundListenerMap; + + typedef + std::multiset< css::uno::Reference< css::beans::XVetoableChangeListener > > + VetoListenerBag; + + typedef std::map< OUString, VetoListenerBag > VetoListenerMap; + + mutable osl::Mutex mutex; + BoundListenerMap boundListeners; + VetoListenerMap vetoListeners; + bool disposed; + +private: + css::uno::Reference< css::reflection::XIdlClass > getReflection( + OUString const & typeName) const; + + static css::uno::Any wrapValue( + css::uno::Reference< css::uno::XInterface > const & object, + css::uno::Any const & value, + css::uno::Reference< css::reflection::XIdlClass > const & type, + bool wrapAmbiguous, bool isAmbiguous, bool wrapDefaulted, + bool isDefaulted, bool wrapOptional); + + css::uno::Reference< css::uno::XComponentContext > const & m_context; + css::uno::Type m_type; + css::uno::Reference< css::reflection::XIdlClass > m_idlClass; +}; + +PropertySetMixinImpl::Impl::Impl( + css::uno::Reference< css::uno::XComponentContext > const & context, + Implements theImplements, + css::uno::Sequence< OUString > const & absentOptional, + css::uno::Type const & type): + implements(theImplements), disposed(false), m_context(context), + m_type(type) +{ + assert(context.is()); + assert( + (implements + & ~(IMPLEMENTS_PROPERTY_SET | IMPLEMENTS_FAST_PROPERTY_SET + | IMPLEMENTS_PROPERTY_ACCESS)) + == 0); + m_idlClass = getReflection(m_type.getTypeName()); + css::uno::Reference< css::reflection::XTypeDescription > ifc; + try { + ifc.set( + css::uno::Reference< css::container::XHierarchicalNameAccess >( + m_context->getValueByName( + "/singletons/com.sun.star.reflection." + "theTypeDescriptionManager"), + css::uno::UNO_QUERY_THROW)->getByHierarchicalName( + m_type.getTypeName()), + css::uno::UNO_QUERY_THROW); + } catch (css::container::NoSuchElementException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.container.NoSuchElementException: " + + e.Message, + nullptr, anyEx ); + } + std::vector< OUString > handleNames; + initProperties(ifc, absentOptional, &handleNames); + std::vector< OUString >::size_type size = handleNames.size(); + assert(size <= SAL_MAX_INT32); + handleMap.realloc(static_cast< sal_Int32 >(size)); + std::copy(handleNames.begin(), handleNames.end(), handleMap.getArray()); +} + +OUString const & PropertySetMixinImpl::Impl::translateHandle( + css::uno::Reference< css::uno::XInterface > const & object, + sal_Int32 handle) const +{ + if (handle < 0 || handle >= handleMap.getLength()) { + throw css::beans::UnknownPropertyException( + "bad handle " + OUString::number(handle), object); + } + return handleMap[handle]; +} + +void PropertySetMixinImpl::Impl::setProperty( + css::uno::Reference< css::uno::XInterface > const & object, + OUString const & name, css::uno::Any const & value, bool isAmbiguous, + bool isDefaulted, sal_Int16 illegalArgumentPosition) const +{ + PropertyMap::const_iterator i(properties.find(name)); + if (i == properties.end()) { + throw css::beans::UnknownPropertyException(name, object); + } + if ((isAmbiguous + && ((i->second.property.Attributes + & css::beans::PropertyAttribute::MAYBEAMBIGUOUS) + == 0)) + || (isDefaulted + && ((i->second.property.Attributes + & css::beans::PropertyAttribute::MAYBEDEFAULT) + == 0))) + { + throw css::lang::IllegalArgumentException( + ("flagging as ambiguous/defaulted non-ambiguous/defaulted property " + + name), + object, illegalArgumentPosition); + } + css::uno::Reference< css::reflection::XIdlField2 > f( + m_idlClass->getField(name), css::uno::UNO_QUERY_THROW); + css::uno::Any o(object->queryInterface(m_type)); + css::uno::Any v( + wrapValue( + object, value, + (css::uno::Reference< css::reflection::XIdlField2 >( + m_idlClass->getField(name), css::uno::UNO_QUERY_THROW)-> + getType()), + ((i->second.property.Attributes + & css::beans::PropertyAttribute::MAYBEAMBIGUOUS) + != 0), + isAmbiguous, + ((i->second.property.Attributes + & css::beans::PropertyAttribute::MAYBEDEFAULT) + != 0), + isDefaulted, + ((i->second.property.Attributes + & css::beans::PropertyAttribute::MAYBEVOID) + != 0))); + try { + f->set(o, v); + } catch (css::lang::IllegalArgumentException & e) { + if (e.ArgumentPosition == 1) { + throw css::lang::IllegalArgumentException( + e.Message, object, illegalArgumentPosition); + } else { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalArgumentException: " + + e.Message, + object, anyEx ); + } + } catch (css::lang::IllegalAccessException &) { + //TODO Clarify whether PropertyVetoException is the correct exception + // to throw when trying to set a read-only property: + throw css::beans::PropertyVetoException( + "cannot set read-only property " + name, object); + } catch (css::lang::WrappedTargetRuntimeException & e) { + //FIXME A WrappedTargetRuntimeException from XIdlField2.get is not + // guaranteed to originate directly within XIdlField2.get (and thus have + // the expected semantics); it might also be passed through from lower + // layers. + if (e.TargetException.isExtractableTo( + cppu::UnoType::get()) + && ((i->second.property.Attributes + & css::beans::PropertyAttribute::OPTIONAL) + != 0)) + { + throw css::beans::UnknownPropertyException(name, object); + } else if (e.TargetException.isExtractableTo( + cppu::UnoType::get()) + && ((i->second.property.Attributes + & css::beans::PropertyAttribute::CONSTRAINED) + != 0)) + { + css::beans::PropertyVetoException exc; + e.TargetException >>= exc; + if (exc.Message.isEmpty() ) + throw css::beans::PropertyVetoException("Invalid " + name, object); + else + throw exc; + } else { + throw css::lang::WrappedTargetException( + e.Message, object, e.TargetException); + } + } +} + +css::uno::Any PropertySetMixinImpl::Impl::getProperty( + css::uno::Reference< css::uno::XInterface > const & object, + OUString const & name, css::beans::PropertyState * state) const +{ + PropertyMap::const_iterator i(properties.find(name)); + if (i == properties.end()) { + throw css::beans::UnknownPropertyException(name, object); + } + css::uno::Reference< css::reflection::XIdlField2 > field( + m_idlClass->getField(name), css::uno::UNO_QUERY_THROW); + css::uno::Any value; + try { + value = field->get(object->queryInterface(m_type)); + } catch (css::lang::IllegalArgumentException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalArgumentException: " + + e.Message, + object, anyEx ); + } catch (css::lang::WrappedTargetRuntimeException & e) { + //FIXME A WrappedTargetRuntimeException from XIdlField2.get is not + // guaranteed to originate directly within XIdlField2.get (and thus have + // the expected semantics); it might also be passed through from lower + // layers. + if (e.TargetException.isExtractableTo( + cppu::UnoType::get()) + && ((i->second.property.Attributes + & css::beans::PropertyAttribute::OPTIONAL) + != 0)) + { + throw css::beans::UnknownPropertyException(name, object); + } else { + throw css::lang::WrappedTargetException( + e.Message, object, e.TargetException); + } + } + bool undoAmbiguous + = ((i->second.property.Attributes + & css::beans::PropertyAttribute::MAYBEAMBIGUOUS) + != 0); + bool undoDefaulted + = ((i->second.property.Attributes + & css::beans::PropertyAttribute::MAYBEDEFAULT) + != 0); + bool undoOptional + = ((i->second.property.Attributes + & css::beans::PropertyAttribute::MAYBEVOID) + != 0); + bool isAmbiguous = false; + bool isDefaulted = false; + while (undoAmbiguous || undoDefaulted || undoOptional) { + if (undoAmbiguous + && value.getValueTypeName().startsWith( + "com.sun.star.beans.Ambiguous<")) + { + css::uno::Reference< css::reflection::XIdlClass > ambiguous( + getReflection(value.getValueTypeName())); + try { + if (!(css::uno::Reference< css::reflection::XIdlField2 >( + ambiguous->getField("IsAmbiguous"), + css::uno::UNO_QUERY_THROW)->get(value) + >>= isAmbiguous)) + { + throw css::uno::RuntimeException( + ("unexpected type of com.sun.star.beans.Ambiguous" + " IsAmbiguous member"), + object); + } + value = css::uno::Reference< css::reflection::XIdlField2 >( + ambiguous->getField("Value"), css::uno::UNO_QUERY_THROW)-> + get(value); + } catch (css::lang::IllegalArgumentException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalArgumentException: " + + e.Message, + object, anyEx ); + } + undoAmbiguous = false; + } else if (undoDefaulted + && value.getValueTypeName().startsWith( + "com.sun.star.beans.Defaulted<")) + { + css::uno::Reference< css::reflection::XIdlClass > defaulted( + getReflection(value.getValueTypeName())); + try { + + if (!(css::uno::Reference< css::reflection::XIdlField2 >( + defaulted->getField("IsDefaulted"), + css::uno::UNO_QUERY_THROW)->get(value) + >>= isDefaulted)) + { + throw css::uno::RuntimeException( + ("unexpected type of com.sun.star.beans.Defaulted" + " IsDefaulted member"), + object); + } + value = css::uno::Reference< css::reflection::XIdlField2 >( + defaulted->getField("Value"), css::uno::UNO_QUERY_THROW)-> + get(value); + } catch (css::lang::IllegalArgumentException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalArgumentException: " + + e.Message, + object, anyEx ); + } + undoDefaulted = false; + } else if (undoOptional + && value.getValueTypeName().startsWith( + "com.sun.star.beans.Optional<")) + { + css::uno::Reference< css::reflection::XIdlClass > optional( + getReflection(value.getValueTypeName())); + try { + bool present = false; + if (!(css::uno::Reference< css::reflection::XIdlField2 >( + optional->getField("IsPresent"), + css::uno::UNO_QUERY_THROW)->get(value) + >>= present)) + { + throw css::uno::RuntimeException( + ("unexpected type of com.sun.star.beans.Optional" + " IsPresent member"), + object); + } + if (!present) { + value.clear(); + break; + } + value = css::uno::Reference< css::reflection::XIdlField2 >( + optional->getField("Value"), css::uno::UNO_QUERY_THROW)-> + get(value); + } catch (css::lang::IllegalArgumentException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalArgumentException: " + + e.Message, + object, anyEx ); + } + undoOptional = false; + } else { + throw css::uno::RuntimeException( + "unexpected type of attribute " + name, object); + } + } + if (state != nullptr) { + //XXX If isAmbiguous && isDefaulted, arbitrarily choose AMBIGUOUS_VALUE + // over DEFAULT_VALUE: + *state = isAmbiguous + ? css::beans::PropertyState_AMBIGUOUS_VALUE + : isDefaulted + ? css::beans::PropertyState_DEFAULT_VALUE + : css::beans::PropertyState_DIRECT_VALUE; + } + return value; +} + +css::uno::Reference< css::reflection::XIdlClass > +PropertySetMixinImpl::Impl::getReflection(OUString const & typeName) const +{ + return css::uno::Reference< css::reflection::XIdlClass >( + css::reflection::theCoreReflection::get(m_context)->forName(typeName), + css::uno::UNO_SET_THROW); +} + +css::uno::Any PropertySetMixinImpl::Impl::wrapValue( + css::uno::Reference< css::uno::XInterface > const & object, + css::uno::Any const & value, + css::uno::Reference< css::reflection::XIdlClass > const & type, + bool wrapAmbiguous, bool isAmbiguous, bool wrapDefaulted, bool isDefaulted, + bool wrapOptional) +{ + assert(wrapAmbiguous || !isAmbiguous); + assert(wrapDefaulted || !isDefaulted); + if (wrapAmbiguous + && type->getName().startsWith("com.sun.star.beans.Ambiguous<")) + { + css::uno::Any strct; + type->createObject(strct); + try { + css::uno::Reference< css::reflection::XIdlField2 > field( + type->getField("Value"), css::uno::UNO_QUERY_THROW); + field->set( + strct, + wrapValue( + object, value, field->getType(), false, false, + wrapDefaulted, isDefaulted, wrapOptional)); + css::uno::Reference< css::reflection::XIdlField2 >( + type->getField("IsAmbiguous"), css::uno::UNO_QUERY_THROW)->set( + strct, css::uno::Any(isAmbiguous)); + } catch (css::lang::IllegalArgumentException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalArgumentException: " + + e.Message, + object, anyEx ); + } catch (css::lang::IllegalAccessException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalAccessException: " + + e.Message, + object, anyEx ); + } + return strct; + } + if (wrapDefaulted + && type->getName().startsWith("com.sun.star.beans.Defaulted<")) + { + css::uno::Any strct; + type->createObject(strct); + try { + css::uno::Reference< css::reflection::XIdlField2 > field( + type->getField("Value"), css::uno::UNO_QUERY_THROW); + field->set( + strct, + wrapValue( + object, value, field->getType(), wrapAmbiguous, isAmbiguous, + false, false, wrapOptional)); + css::uno::Reference< css::reflection::XIdlField2 >( + type->getField("IsDefaulted"), css::uno::UNO_QUERY_THROW)->set( + strct, css::uno::Any(isDefaulted)); + } catch (css::lang::IllegalArgumentException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalArgumentException: " + + e.Message, + object, anyEx ); + } catch (css::lang::IllegalAccessException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalAccessException: " + + e.Message, + object, anyEx ); + } + return strct; + } + if (wrapOptional + && type->getName().startsWith("com.sun.star.beans.Optional<")) + { + css::uno::Any strct; + type->createObject(strct); + bool present = value.hasValue(); + try { + css::uno::Reference< css::reflection::XIdlField2 >( + type->getField("IsPresent"), css::uno::UNO_QUERY_THROW)->set( + strct, css::uno::Any(present)); + if (present) { + css::uno::Reference< css::reflection::XIdlField2 > field( + type->getField("Value"), css::uno::UNO_QUERY_THROW); + field->set( + strct, + wrapValue( + object, value, field->getType(), wrapAmbiguous, + isAmbiguous, wrapDefaulted, isDefaulted, false)); + } + } catch (css::lang::IllegalArgumentException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalArgumentException: " + + e.Message, + object, anyEx ); + } catch (css::lang::IllegalAccessException & e) { + css::uno::Any anyEx = cppu::getCaughtException(); + throw css::lang::WrappedTargetRuntimeException( + "unexpected com.sun.star.lang.IllegalAccessException: " + + e.Message, + object, anyEx ); + } + return strct; + } + if (wrapAmbiguous || wrapDefaulted || wrapOptional) { + throw css::uno::RuntimeException( + "unexpected type of attribute", object); + } + return value; +} + +PropertySetMixinImpl::PropertySetMixinImpl( + css::uno::Reference< css::uno::XComponentContext > const & context, + Implements implements, + css::uno::Sequence< OUString > const & absentOptional, + css::uno::Type const & type) +{ + m_impl = new Impl(context, implements, absentOptional, type); + m_impl->acquire(); +} + +PropertySetMixinImpl::~PropertySetMixinImpl() { + m_impl->release(); +} + +void PropertySetMixinImpl::checkUnknown(OUString const & propertyName) { + if (!propertyName.isEmpty()) { + m_impl->get( + static_cast< css::beans::XPropertySet * >(this), propertyName); + } +} + +void PropertySetMixinImpl::prepareSet( + OUString const & propertyName, css::uno::Any const & oldValue, + css::uno::Any const & newValue, BoundListeners * boundListeners) +{ + Impl::PropertyMap::const_iterator it(m_impl->properties.find(propertyName)); + assert(it != m_impl->properties.end()); + Impl::VetoListenerBag specificVeto; + Impl::VetoListenerBag unspecificVeto; + { + osl::MutexGuard g(m_impl->mutex); + if (m_impl->disposed) { + throw css::lang::DisposedException( + "disposed", static_cast< css::beans::XPropertySet * >(this)); + } + if ((it->second.property.Attributes + & css::beans::PropertyAttribute::CONSTRAINED) + != 0) + { + Impl::VetoListenerMap::const_iterator i( + m_impl->vetoListeners.find(propertyName)); + if (i != m_impl->vetoListeners.end()) { + specificVeto = i->second; + } + i = m_impl->vetoListeners.find(""); + if (i != m_impl->vetoListeners.end()) { + unspecificVeto = i->second; + } + } + if ((it->second.property.Attributes + & css::beans::PropertyAttribute::BOUND) + != 0) + { + assert(boundListeners != nullptr); + Impl::BoundListenerMap::const_iterator i( + m_impl->boundListeners.find(propertyName)); + if (i != m_impl->boundListeners.end()) { + boundListeners->m_impl->specificListeners = i->second; + } + i = m_impl->boundListeners.find(""); + if (i != m_impl->boundListeners.end()) { + boundListeners->m_impl->unspecificListeners = i->second; + } + } + } + if ((it->second.property.Attributes + & css::beans::PropertyAttribute::CONSTRAINED) + != 0) + { + css::beans::PropertyChangeEvent event( + static_cast< css::beans::XPropertySet * >(this), propertyName, + false, it->second.property.Handle, oldValue, newValue); + for (auto& rxVetoListener : specificVeto) + { + try { + rxVetoListener->vetoableChange(event); + } catch (css::lang::DisposedException &) {} + } + for (auto& rxVetoListener : unspecificVeto) + { + try { + rxVetoListener->vetoableChange(event); + } catch (css::lang::DisposedException &) {} + } + } + if ((it->second.property.Attributes & css::beans::PropertyAttribute::BOUND) + != 0) + { + assert(boundListeners != nullptr); + boundListeners->m_impl->event = css::beans::PropertyChangeEvent( + static_cast< css::beans::XPropertySet * >(this), propertyName, + false, it->second.property.Handle, oldValue, newValue); + } +} + +void PropertySetMixinImpl::dispose() { + Impl::BoundListenerMap boundListeners; + Impl::VetoListenerMap vetoListeners; + { + osl::MutexGuard g(m_impl->mutex); + boundListeners.swap(m_impl->boundListeners); + vetoListeners.swap(m_impl->vetoListeners); + m_impl->disposed = true; + } + css::lang::EventObject event( + static_cast< css::beans::XPropertySet * >(this)); + for (const auto& rEntry : boundListeners) + { + for (auto& rxBoundListener : rEntry.second) + { + rxBoundListener->disposing(event); + } + } + for (const auto& rEntry : vetoListeners) + { + for (auto& rxVetoListener : rEntry.second) + { + rxVetoListener->disposing(event); + } + } +} + +css::uno::Any PropertySetMixinImpl::queryInterface(css::uno::Type const & type) +{ + if ((m_impl->implements & IMPLEMENTS_PROPERTY_SET) != 0 + && type == css::beans::XPropertySet::static_type()) + { + css::uno::Reference< css::uno::XInterface > ifc( + static_cast< css::beans::XPropertySet * >(this)); + return css::uno::Any(&ifc, type); + } + if ((m_impl->implements & IMPLEMENTS_FAST_PROPERTY_SET) != 0 + && type == css::beans::XFastPropertySet::static_type()) + { + css::uno::Reference< css::uno::XInterface > ifc( + static_cast< css::beans::XFastPropertySet * >(this)); + return css::uno::Any(&ifc, type); + } + if ((m_impl->implements & IMPLEMENTS_PROPERTY_ACCESS) != 0 + && type == css::beans::XPropertyAccess::static_type()) + { + css::uno::Reference< css::uno::XInterface > ifc( + static_cast< css::beans::XPropertyAccess * >(this)); + return css::uno::Any(&ifc, type); + } + return css::uno::Any(); +} + +css::uno::Reference< css::beans::XPropertySetInfo > +PropertySetMixinImpl::getPropertySetInfo() +{ + return new Info(m_impl); +} + +void PropertySetMixinImpl::setPropertyValue( + OUString const & propertyName, css::uno::Any const & value) +{ + m_impl->setProperty( + static_cast< css::beans::XPropertySet * >(this), propertyName, value, + false, false, 1); +} + +css::uno::Any PropertySetMixinImpl::getPropertyValue( + OUString const & propertyName) +{ + return m_impl->getProperty( + static_cast< css::beans::XPropertySet * >(this), propertyName, nullptr); +} + +void PropertySetMixinImpl::addPropertyChangeListener( + OUString const & propertyName, + css::uno::Reference< css::beans::XPropertyChangeListener > const & listener) +{ + css::uno::Reference< css::beans::XPropertyChangeListener >( + listener, css::uno::UNO_SET_THROW); // reject NULL listener + checkUnknown(propertyName); + bool disposed; + { + osl::MutexGuard g(m_impl->mutex); + disposed = m_impl->disposed; + if (!disposed) { + m_impl->boundListeners[propertyName].insert(listener); + } + } + if (disposed) { + listener->disposing( + css::lang::EventObject( + static_cast< css::beans::XPropertySet * >(this))); + } +} + +void PropertySetMixinImpl::removePropertyChangeListener( + OUString const & propertyName, + css::uno::Reference< css::beans::XPropertyChangeListener > const & listener) +{ + assert(listener.is()); + checkUnknown(propertyName); + osl::MutexGuard g(m_impl->mutex); + Impl::BoundListenerMap::iterator i( + m_impl->boundListeners.find(propertyName)); + if (i != m_impl->boundListeners.end()) { + BoundListenerBag::iterator j(i->second.find(listener)); + if (j != i->second.end()) { + i->second.erase(j); + } + } +} + +void PropertySetMixinImpl::addVetoableChangeListener( + OUString const & propertyName, + css::uno::Reference< css::beans::XVetoableChangeListener > const & listener) +{ + css::uno::Reference< css::beans::XVetoableChangeListener >( + listener, css::uno::UNO_SET_THROW); // reject NULL listener + checkUnknown(propertyName); + bool disposed; + { + osl::MutexGuard g(m_impl->mutex); + disposed = m_impl->disposed; + if (!disposed) { + m_impl->vetoListeners[propertyName].insert(listener); + } + } + if (disposed) { + listener->disposing( + css::lang::EventObject( + static_cast< css::beans::XPropertySet * >(this))); + } +} + +void PropertySetMixinImpl::removeVetoableChangeListener( + OUString const & propertyName, + css::uno::Reference< css::beans::XVetoableChangeListener > const & listener) +{ + assert(listener.is()); + checkUnknown(propertyName); + osl::MutexGuard g(m_impl->mutex); + Impl::VetoListenerMap::iterator i(m_impl->vetoListeners.find(propertyName)); + if (i != m_impl->vetoListeners.end()) { + Impl::VetoListenerBag::iterator j(i->second.find(listener)); + if (j != i->second.end()) { + i->second.erase(j); + } + } +} + +void PropertySetMixinImpl::setFastPropertyValue( + sal_Int32 handle, css::uno::Any const & value) +{ + m_impl->setProperty( + static_cast< css::beans::XPropertySet * >(this), + m_impl->translateHandle( + static_cast< css::beans::XPropertySet * >(this), handle), + value, false, false, 1); +} + +css::uno::Any PropertySetMixinImpl::getFastPropertyValue(sal_Int32 handle) +{ + return m_impl->getProperty( + static_cast< css::beans::XPropertySet * >(this), + m_impl->translateHandle( + static_cast< css::beans::XPropertySet * >(this), handle), + nullptr); +} + +css::uno::Sequence< css::beans::PropertyValue > +PropertySetMixinImpl::getPropertyValues() +{ + css::uno::Sequence< css::beans::PropertyValue > s( + m_impl->handleMap.getLength()); + sal_Int32 n = 0; + for (sal_Int32 i = 0; i < m_impl->handleMap.getLength(); ++i) { + try { + s[n].Value = m_impl->getProperty( + static_cast< css::beans::XPropertySet * >(this), + m_impl->handleMap[i], &s[n].State); + } catch (css::beans::UnknownPropertyException &) { + continue; + } catch (css::lang::WrappedTargetException & e) { + throw css::lang::WrappedTargetRuntimeException( + e.Message, static_cast< css::beans::XPropertySet * >(this), + e.TargetException); + } + s[n].Name = m_impl->handleMap[i]; + s[n].Handle = i; + ++n; + } + s.realloc(n); + return s; +} + +void PropertySetMixinImpl::setPropertyValues( + css::uno::Sequence< css::beans::PropertyValue > const & props) +{ + for (const auto & p : props) { + if (p.Handle != -1 + && (p.Name + != m_impl->translateHandle( + static_cast< css::beans::XPropertySet * >(this), + p.Handle))) + { + throw css::beans::UnknownPropertyException( + ("name " + p.Name + " does not match handle " + + OUString::number(p.Handle)), + static_cast< css::beans::XPropertySet * >(this)); + } + m_impl->setProperty( + static_cast< css::beans::XPropertySet * >(this), p.Name, + p.Value, + p.State == css::beans::PropertyState_AMBIGUOUS_VALUE, + p.State == css::beans::PropertyState_DEFAULT_VALUE, 0); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/propshlp.cxx b/cppuhelper/source/propshlp.cxx new file mode 100644 index 000000000..3af4cda49 --- /dev/null +++ b/cppuhelper/source/propshlp.cxx @@ -0,0 +1,1184 @@ +/* -*- 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 +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace osl; +using namespace com::sun::star::uno; +using namespace com::sun::star::beans; +using namespace com::sun::star::lang; +using namespace cppu; + +namespace cppu { + +IPropertyArrayHelper::~IPropertyArrayHelper() +{ +} + +static const css::uno::Type & getPropertyTypeIdentifier( ) +{ + return cppu::UnoType::get(); +} +static const css::uno::Type & getPropertiesTypeIdentifier() +{ + return cppu::UnoType::get(); +} +static const css::uno::Type & getVetoableTypeIdentifier() +{ + return cppu::UnoType::get(); +} + +extern "C" { + +static int compare_OUString_Property_Impl( const void *arg1, const void *arg2 ) + SAL_THROW_EXTERN_C() +{ + return static_cast(arg1)->compareTo( static_cast(arg2)->Name ); +} + +} + +/** + * The class which implements the PropertySetInfo interface. + */ + +namespace { + +class OPropertySetHelperInfo_Impl + : public WeakImplHelper< css::beans::XPropertySetInfo > +{ + Sequence < Property > aInfos; + +public: + explicit OPropertySetHelperInfo_Impl( IPropertyArrayHelper & rHelper_ ); + + // XPropertySetInfo-methods + virtual Sequence< Property > SAL_CALL getProperties() override; + virtual Property SAL_CALL getPropertyByName(const OUString& PropertyName) override; + virtual sal_Bool SAL_CALL hasPropertyByName(const OUString& PropertyName) override; +}; + +} + +/** + * Create an object that implements XPropertySetInfo IPropertyArrayHelper. + */ +OPropertySetHelperInfo_Impl::OPropertySetHelperInfo_Impl( + IPropertyArrayHelper & rHelper_ ) + :aInfos( rHelper_.getProperties() ) +{ +} + +/** + * Return the sequence of properties, which are provided through the constructor. + */ +Sequence< Property > OPropertySetHelperInfo_Impl::getProperties() +{ + return aInfos; +} + +/** + * Return the sequence of properties, which are provided through the constructor. + */ +Property OPropertySetHelperInfo_Impl::getPropertyByName( const OUString & PropertyName ) +{ + Property * pR; + pR = static_cast(bsearch( &PropertyName, aInfos.getConstArray(), aInfos.getLength(), + sizeof( Property ), + compare_OUString_Property_Impl )); + if( !pR ) { + throw UnknownPropertyException(PropertyName); + } + + return *pR; +} + +/** + * Return the sequence of properties, which are provided through the constructor. + */ +sal_Bool OPropertySetHelperInfo_Impl::hasPropertyByName( const OUString & PropertyName ) +{ + Property * pR; + pR = static_cast(bsearch( &PropertyName, aInfos.getConstArray(), aInfos.getLength(), + sizeof( Property ), + compare_OUString_Property_Impl )); + return pR != nullptr; +} + + + +class OPropertySetHelper::Impl { + +public: + Impl( bool i_bIgnoreRuntimeExceptionsWhileFiring, + IEventNotificationHook *i_pFireEvents + ) + :m_bIgnoreRuntimeExceptionsWhileFiring( i_bIgnoreRuntimeExceptionsWhileFiring ) + ,m_bFireEvents(true) + ,m_pFireEvents( i_pFireEvents ) + { + } + + bool m_bIgnoreRuntimeExceptionsWhileFiring; + bool m_bFireEvents; + class IEventNotificationHook * const m_pFireEvents; + + std::vector< sal_Int32 > m_handles; + std::vector< Any > m_newValues; + std::vector< Any > m_oldValues; +}; + + + +OPropertySetHelper::OPropertySetHelper( + OBroadcastHelper & rBHelper_ ) + : rBHelper( rBHelper_ ), + aBoundLC( rBHelper_.rMutex ), + aVetoableLC( rBHelper_.rMutex ), + m_pReserved( new Impl(false, nullptr) ) +{ +} + +OPropertySetHelper::OPropertySetHelper( + OBroadcastHelper & rBHelper_, bool bIgnoreRuntimeExceptionsWhileFiring ) + : rBHelper( rBHelper_ ), + aBoundLC( rBHelper_.rMutex ), + aVetoableLC( rBHelper_.rMutex ), + m_pReserved( new Impl( bIgnoreRuntimeExceptionsWhileFiring, nullptr ) ) +{ +} + +OPropertySetHelper::OPropertySetHelper( + OBroadcastHelper & rBHelper_, IEventNotificationHook * i_pFireEvents, + bool bIgnoreRuntimeExceptionsWhileFiring) + : rBHelper( rBHelper_ ), + aBoundLC( rBHelper_.rMutex ), + aVetoableLC( rBHelper_.rMutex ), + m_pReserved( + new Impl( bIgnoreRuntimeExceptionsWhileFiring, i_pFireEvents) ) +{ +} + +OPropertySetHelper2::OPropertySetHelper2( + OBroadcastHelper & irBHelper, + IEventNotificationHook *i_pFireEvents, + bool bIgnoreRuntimeExceptionsWhileFiring) + :OPropertySetHelper( irBHelper, i_pFireEvents, bIgnoreRuntimeExceptionsWhileFiring ) +{ +} + +/** + * You must call disposing before. + */ +OPropertySetHelper::~OPropertySetHelper() +{ + delete m_pReserved; +} +OPropertySetHelper2::~OPropertySetHelper2() +{ +} + +// XInterface +Any OPropertySetHelper::queryInterface( const css::uno::Type & rType ) +{ + return ::cppu::queryInterface( + rType, + static_cast< XPropertySet * >( this ), + static_cast< XMultiPropertySet * >( this ), + static_cast< XFastPropertySet * >( this ) ); +} + +Any OPropertySetHelper2::queryInterface( const css::uno::Type & rType ) +{ + Any cnd(cppu::queryInterface(rType, static_cast< XPropertySetOption * >(this))); + if ( cnd.hasValue() ) + return cnd; + return OPropertySetHelper::queryInterface(rType); +} + +/** + * called from the derivee's XTypeProvider::getTypes implementation + */ +css::uno::Sequence< css::uno::Type > OPropertySetHelper::getTypes() +{ + return { + UnoType::get(), + UnoType::get(), + UnoType::get()}; +} + +// ComponentHelper +void OPropertySetHelper::disposing() +{ + // Create an event with this as sender + Reference < XPropertySet > rSource = this; + EventObject aEvt; + aEvt.Source = rSource; + + // inform all listeners to release this object + // The listener containers are automatically cleared + aBoundLC.disposeAndClear( aEvt ); + aVetoableLC.disposeAndClear( aEvt ); +} + +Reference < XPropertySetInfo > OPropertySetHelper::createPropertySetInfo( + IPropertyArrayHelper & rProperties ) +{ + return new OPropertySetHelperInfo_Impl(rProperties); +} + +// XPropertySet +void OPropertySetHelper::setPropertyValue( + const OUString& rPropertyName, const Any& rValue ) +{ + // get the map table + IPropertyArrayHelper & rPH = getInfoHelper(); + // map the name to the handle + sal_Int32 nHandle = rPH.getHandleByName( rPropertyName ); + // call the method of the XFastPropertySet interface + setFastPropertyValue( nHandle, rValue ); +} + +// XPropertySet +Any OPropertySetHelper::getPropertyValue( + const OUString& rPropertyName ) +{ + // get the map table + IPropertyArrayHelper & rPH = getInfoHelper(); + // map the name to the handle + sal_Int32 nHandle = rPH.getHandleByName( rPropertyName ); + // call the method of the XFastPropertySet interface + return getFastPropertyValue( nHandle ); +} + +// XPropertySet +void OPropertySetHelper::addPropertyChangeListener( + const OUString& rPropertyName, + const Reference < XPropertyChangeListener > & rxListener ) +{ + MutexGuard aGuard( rBHelper.rMutex ); + OSL_ENSURE( !rBHelper.bInDispose, "do not addPropertyChangeListener in the dispose call" ); + OSL_ENSURE( !rBHelper.bDisposed, "object is disposed" ); + if( rBHelper.bInDispose || rBHelper.bDisposed ) + return; + + // only add listeners if you are not disposed + // a listener with no name means all properties + if( !rPropertyName.isEmpty() ) + { + // get the map table + IPropertyArrayHelper & rPH = getInfoHelper(); + // map the name to the handle + sal_Int32 nHandle = rPH.getHandleByName( rPropertyName ); + if( nHandle == -1 ) { + // property not known throw exception + throw UnknownPropertyException(rPropertyName); + } + + sal_Int16 nAttributes; + rPH.fillPropertyMembersByHandle( nullptr, &nAttributes, nHandle ); + if( !(nAttributes & css::beans::PropertyAttribute::BOUND) ) + { + OSL_FAIL( "add listener to an unbound property" ); + // silent ignore this + return; + } + // add the change listener to the helper container + + aBoundLC.addInterface( nHandle, rxListener ); + } + else + // add the change listener to the helper container + rBHelper.aLC.addInterface( + getPropertyTypeIdentifier( ), + rxListener + ); +} + + +// XPropertySet +void OPropertySetHelper::removePropertyChangeListener( + const OUString& rPropertyName, + const Reference < XPropertyChangeListener >& rxListener ) +{ + MutexGuard aGuard( rBHelper.rMutex ); + OSL_ENSURE( !rBHelper.bDisposed, "object is disposed" ); + // all listeners are automatically released in a dispose call + if( rBHelper.bInDispose || rBHelper.bDisposed ) + return; + + if( !rPropertyName.isEmpty() ) + { + // get the map table + IPropertyArrayHelper & rPH = getInfoHelper(); + // map the name to the handle + sal_Int32 nHandle = rPH.getHandleByName( rPropertyName ); + if( nHandle == -1 ) + // property not known throw exception + throw UnknownPropertyException(rPropertyName); + aBoundLC.removeInterface( nHandle, rxListener ); + } + else { + // remove the change listener to the helper container + rBHelper.aLC.removeInterface( + getPropertyTypeIdentifier( ), + rxListener + ); + } +} + +// XPropertySet +void OPropertySetHelper::addVetoableChangeListener( + const OUString& rPropertyName, + const Reference< XVetoableChangeListener > & rxListener ) +{ + MutexGuard aGuard( rBHelper.rMutex ); + OSL_ENSURE( !rBHelper.bInDispose, "do not addVetoableChangeListener in the dispose call" ); + OSL_ENSURE( !rBHelper.bDisposed, "object is disposed" ); + if( rBHelper.bInDispose || rBHelper.bDisposed ) + return; + + // only add listeners if you are not disposed + // a listener with no name means all properties + if( !rPropertyName.isEmpty() ) + { + // get the map table + IPropertyArrayHelper & rPH = getInfoHelper(); + // map the name to the handle + sal_Int32 nHandle = rPH.getHandleByName( rPropertyName ); + if( nHandle == -1 ) { + // property not known throw exception + throw UnknownPropertyException(rPropertyName); + } + + sal_Int16 nAttributes; + rPH.fillPropertyMembersByHandle( nullptr, &nAttributes, nHandle ); + if( !(nAttributes & PropertyAttribute::CONSTRAINED) ) + { + OSL_FAIL( "addVetoableChangeListener, and property is not constrained" ); + // silent ignore this + return; + } + // add the vetoable listener to the helper container + aVetoableLC.addInterface( nHandle, rxListener ); + } + else + // add the vetoable listener to the helper container + rBHelper.aLC.addInterface( + getVetoableTypeIdentifier( ), + rxListener + ); +} + +// XPropertySet +void OPropertySetHelper::removeVetoableChangeListener( + const OUString& rPropertyName, + const Reference < XVetoableChangeListener > & rxListener ) +{ + MutexGuard aGuard( rBHelper.rMutex ); + OSL_ENSURE( !rBHelper.bDisposed, "object is disposed" ); + // all listeners are automatically released in a dispose call + if( rBHelper.bInDispose || rBHelper.bDisposed ) + return; + + if( !rPropertyName.isEmpty() ) + { + // get the map table + IPropertyArrayHelper & rPH = getInfoHelper(); + // map the name to the handle + sal_Int32 nHandle = rPH.getHandleByName( rPropertyName ); + if( nHandle == -1 ) { + // property not known throw exception + throw UnknownPropertyException(rPropertyName); + } + // remove the vetoable listener to the helper container + aVetoableLC.removeInterface( nHandle, rxListener ); + } + else + // add the vetoable listener to the helper container + rBHelper.aLC.removeInterface( + getVetoableTypeIdentifier( ), + rxListener + ); +} + +void OPropertySetHelper::setDependentFastPropertyValue( sal_Int32 i_handle, const css::uno::Any& i_value ) +{ + //OSL_PRECOND( rBHelper.rMutex.isAcquired(), "OPropertySetHelper::setDependentFastPropertyValue: to be called with a locked mutex only!" ); + // there is no such thing as Mutex.isAcquired, sadly ... + + sal_Int16 nAttributes(0); + IPropertyArrayHelper& rInfo = getInfoHelper(); + if ( !rInfo.fillPropertyMembersByHandle( nullptr, &nAttributes, i_handle ) ) + // unknown property + throw UnknownPropertyException(OUString::number(i_handle)); + + // no need to check for READONLY-ness of the property. The method is intended to be called internally, which + // implies it might be invoked for properties which are read-only to the instance's clients, but well allowed + // to change their value. + + Any aConverted, aOld; + bool bChanged = convertFastPropertyValue( aConverted, aOld, i_handle, i_value ); + if ( !bChanged ) + return; + + // don't fire vetoable events. This method is called with our mutex locked, so calling into listeners would not be + // a good idea. The caller is responsible for not invoking this for constrained properties. + OSL_ENSURE( ( nAttributes & PropertyAttribute::CONSTRAINED ) == 0, + "OPropertySetHelper::setDependentFastPropertyValue: not to be used for constrained properties!" ); + + // actually set the new value + try + { + setFastPropertyValue_NoBroadcast( i_handle, aConverted ); + } + catch (const UnknownPropertyException& ) { throw; /* allowed to leave */ } + catch (const PropertyVetoException& ) { throw; /* allowed to leave */ } + catch (const IllegalArgumentException& ) { throw; /* allowed to leave */ } + catch (const WrappedTargetException& ) { throw; /* allowed to leave */ } + catch (const RuntimeException& ) { throw; /* allowed to leave */ } + catch (const Exception& ) + { + // not allowed to leave this method + WrappedTargetException aWrapped; + aWrapped.TargetException = ::cppu::getCaughtException(); + aWrapped.Context = static_cast< XPropertySet* >( this ); + throw aWrapped; + } + + // remember the handle/values, for the events to be fired later + m_pReserved->m_handles.push_back( i_handle ); + m_pReserved->m_newValues.push_back( aConverted ); // TODO: setFastPropertyValue notifies the unconverted value here ...? + m_pReserved->m_oldValues.push_back( aOld ); +} + +// XFastPropertySet +void OPropertySetHelper::setFastPropertyValue( sal_Int32 nHandle, const Any& rValue ) +{ + OSL_ENSURE( !rBHelper.bInDispose, "do not setFastPropertyValue in the dispose call" ); + OSL_ENSURE( !rBHelper.bDisposed, "object is disposed" ); + + IPropertyArrayHelper & rInfo = getInfoHelper(); + sal_Int16 nAttributes; + if( !rInfo.fillPropertyMembersByHandle( nullptr, &nAttributes, nHandle ) ) { + // unknown property + throw UnknownPropertyException(OUString::number(nHandle)); + } + if( nAttributes & PropertyAttribute::READONLY ) + throw PropertyVetoException(); + + Any aConvertedVal; + Any aOldVal; + + // Will the property change? + bool bChanged; + { + MutexGuard aGuard( rBHelper.rMutex ); + bChanged = convertFastPropertyValue( aConvertedVal, aOldVal, nHandle, rValue ); + // release guard to fire events + } + if( !bChanged ) + return; + + // Is it a constrained property? + if( nAttributes & PropertyAttribute::CONSTRAINED ) + { + // In aValue is the converted rValue + // fire a constrained event + // second parameter NULL means constrained + fire( &nHandle, &rValue, &aOldVal, 1, true ); + } + + { + MutexGuard aGuard( rBHelper.rMutex ); + try + { + // set the property to the new value + setFastPropertyValue_NoBroadcast( nHandle, aConvertedVal ); + } + catch (const css::beans::UnknownPropertyException& ) { throw; /* allowed to leave */ } + catch (const css::beans::PropertyVetoException& ) { throw; /* allowed to leave */ } + catch (const css::lang::IllegalArgumentException& ) { throw; /* allowed to leave */ } + catch (const css::lang::WrappedTargetException& ) { throw; /* allowed to leave */ } + catch (const css::uno::RuntimeException& ) { throw; /* allowed to leave */ } + catch (const css::uno::Exception& e ) + { + // not allowed to leave this method + css::lang::WrappedTargetException aWrap; + aWrap.Context = static_cast< css::beans::XPropertySet* >( this ); + aWrap.TargetException <<= e; + + throw aWrap; + } + + // release guard to fire events + } + // file a change event, if the value changed + impl_fireAll( &nHandle, &rValue, &aOldVal, 1 ); +} + +// XFastPropertySet +Any OPropertySetHelper::getFastPropertyValue( sal_Int32 nHandle ) + +{ + IPropertyArrayHelper & rInfo = getInfoHelper(); + if( !rInfo.fillPropertyMembersByHandle( nullptr, nullptr, nHandle ) ) + // unknown property + throw UnknownPropertyException(OUString::number(nHandle)); + + Any aRet; + MutexGuard aGuard( rBHelper.rMutex ); + getFastPropertyValue( aRet, nHandle ); + return aRet; +} + + +void OPropertySetHelper::impl_fireAll( sal_Int32* i_handles, const Any* i_newValues, const Any* i_oldValues, sal_Int32 i_count ) +{ + ClearableMutexGuard aGuard( rBHelper.rMutex ); + if ( m_pReserved->m_handles.empty() ) + { + aGuard.clear(); + fire( i_handles, i_newValues, i_oldValues, i_count, false ); + return; + } + + const size_t additionalEvents = m_pReserved->m_handles.size(); + OSL_ENSURE( additionalEvents == m_pReserved->m_newValues.size() + && additionalEvents == m_pReserved->m_oldValues.size(), + "OPropertySetHelper::impl_fireAll: inconsistency!" ); + + std::vector< sal_Int32 > allHandles( additionalEvents + i_count ); + std::copy( m_pReserved->m_handles.begin(), m_pReserved->m_handles.end(), allHandles.begin() ); + std::copy( i_handles, i_handles + i_count, allHandles.begin() + additionalEvents ); + + std::vector< Any > allNewValues( additionalEvents + i_count ); + std::copy( m_pReserved->m_newValues.begin(), m_pReserved->m_newValues.end(), allNewValues.begin() ); + std::copy( i_newValues, i_newValues + i_count, allNewValues.begin() + additionalEvents ); + + std::vector< Any > allOldValues( additionalEvents + i_count ); + std::copy( m_pReserved->m_oldValues.begin(), m_pReserved->m_oldValues.end(), allOldValues.begin() ); + std::copy( i_oldValues, i_oldValues + i_count, allOldValues.begin() + additionalEvents ); + + m_pReserved->m_handles.clear(); + m_pReserved->m_newValues.clear(); + m_pReserved->m_oldValues.clear(); + + aGuard.clear(); + fire( allHandles.data(), allNewValues.data(), allOldValues.data(), additionalEvents + i_count, false ); +} + + +void OPropertySetHelper::fire +( + sal_Int32 * pnHandles, + const Any * pNewValues, + const Any * pOldValues, + sal_Int32 nHandles, // This is the Count of the array + sal_Bool bVetoable +) +{ + if (! m_pReserved->m_bFireEvents) + return; + + if (m_pReserved->m_pFireEvents) { + m_pReserved->m_pFireEvents->fireEvents( + pnHandles, nHandles, bVetoable, + m_pReserved->m_bIgnoreRuntimeExceptionsWhileFiring); + } + + // Only fire, if one or more properties changed + if( !nHandles ) + return; + + // create the event sequence of all changed properties + Sequence< PropertyChangeEvent > aEvts( nHandles ); + PropertyChangeEvent * pEvts = aEvts.getArray(); + Reference < XInterface > xSource( static_cast(this), UNO_QUERY ); + sal_Int32 i; + sal_Int32 nChangesLen = 0; + // Loop over all changed properties to fill the event struct + for( i = 0; i < nHandles; i++ ) + { + // Vetoable fire and constrained attribute set or + // Change fire and Changed and bound attribute set + IPropertyArrayHelper & rInfo = getInfoHelper(); + sal_Int16 nAttributes; + OUString aPropName; + rInfo.fillPropertyMembersByHandle( &aPropName, &nAttributes, pnHandles[i] ); + + if( + (bVetoable && (nAttributes & PropertyAttribute::CONSTRAINED)) || + (!bVetoable && (nAttributes & PropertyAttribute::BOUND)) + ) + { + pEvts[nChangesLen].Source = xSource; + pEvts[nChangesLen].PropertyName = aPropName; + pEvts[nChangesLen].PropertyHandle = pnHandles[i]; + pEvts[nChangesLen].OldValue = pOldValues[i]; + pEvts[nChangesLen].NewValue = pNewValues[i]; + nChangesLen++; + } + } + + bool bIgnoreRuntimeExceptionsWhileFiring = + m_pReserved->m_bIgnoreRuntimeExceptionsWhileFiring; + + // fire the events for all changed properties + for( i = 0; i < nChangesLen; i++ ) + { + // get the listener container for the property name + OInterfaceContainerHelper * pLC; + if( bVetoable ) // fire change Events? + pLC = aVetoableLC.getContainer( pEvts[i].PropertyHandle ); + else + pLC = aBoundLC.getContainer( pEvts[i].PropertyHandle ); + if( pLC ) + { + // Iterate over all listeners and send events + OInterfaceIteratorHelper aIt( *pLC); + while( aIt.hasMoreElements() ) + { + XInterface * pL = aIt.next(); + try + { + try + { + if( bVetoable ) // fire change Events? + { + static_cast(pL)->vetoableChange( + pEvts[i] ); + } + else + { + static_cast(pL)->propertyChange( + pEvts[i] ); + } + } + catch (DisposedException & exc) + { + OSL_ENSURE( exc.Context.is(), + "DisposedException without Context!" ); + if (exc.Context == pL) + aIt.remove(); + else + throw; + } + } + catch (RuntimeException & exc) + { + SAL_INFO("cppuhelper", "caught RuntimeException while firing listeners: " << exc); + if (! bIgnoreRuntimeExceptionsWhileFiring) + throw; + } + } + } + // broadcast to all listeners with "" property name + if( bVetoable ){ + // fire change Events? + pLC = rBHelper.aLC.getContainer( + getVetoableTypeIdentifier() + ); + } + else { + pLC = rBHelper.aLC.getContainer( + getPropertyTypeIdentifier( ) + ); + } + if( pLC ) + { + // Iterate over all listeners and send events. + OInterfaceIteratorHelper aIt( *pLC); + while( aIt.hasMoreElements() ) + { + XInterface * pL = aIt.next(); + try + { + try + { + if( bVetoable ) // fire change Events? + { + static_cast(pL)->vetoableChange( + pEvts[i] ); + } + else + { + static_cast(pL)->propertyChange( + pEvts[i] ); + } + } + catch (DisposedException & exc) + { + OSL_ENSURE( exc.Context.is(), + "DisposedException without Context!" ); + if (exc.Context == pL) + aIt.remove(); + else + throw; + } + } + catch (RuntimeException & exc) + { + SAL_INFO("cppuhelper", "caught RuntimeException while firing listeners: " << exc); + if (! bIgnoreRuntimeExceptionsWhileFiring) + throw; + } + } + } + } + + // reduce array to changed properties + aEvts.realloc( nChangesLen ); + + if( bVetoable ) + return; + + auto pCont = rBHelper.aLC.getContainer(getPropertiesTypeIdentifier()); + if (!pCont) + return; + + // Here is a Bug, unbound properties are also fired + OInterfaceIteratorHelper aIt( *pCont ); + while( aIt.hasMoreElements() ) + { + XPropertiesChangeListener * pL = + static_cast(aIt.next()); + try + { + try + { + // fire the whole event sequence to the + // XPropertiesChangeListener's + pL->propertiesChange( aEvts ); + } + catch (DisposedException & exc) + { + OSL_ENSURE( exc.Context.is(), + "DisposedException without Context!" ); + if (exc.Context == pL) + aIt.remove(); + else + throw; + } + } + catch (RuntimeException & exc) + { + SAL_INFO("cppuhelper", "caught RuntimeException while firing listeners: " << exc); + if (! bIgnoreRuntimeExceptionsWhileFiring) + throw; + } + } +} + +// OPropertySetHelper +void OPropertySetHelper::setFastPropertyValues( + sal_Int32 nSeqLen, + sal_Int32 * pHandles, + const Any * pValues, + sal_Int32 nHitCount ) +{ + OSL_ENSURE( !rBHelper.bInDispose, "do not getFastPropertyValue in the dispose call" ); + OSL_ENSURE( !rBHelper.bDisposed, "object is disposed" ); + + // get the map table + IPropertyArrayHelper & rPH = getInfoHelper(); + + std::unique_ptr pConvertedValues(new Any[ nHitCount ]); + std::unique_ptr pOldValues(new Any[ nHitCount ]); + sal_Int32 n = 0; + sal_Int32 i; + + { + // must lock the mutex outside the loop. So all values are consistent. + MutexGuard aGuard( rBHelper.rMutex ); + for( i = 0; i < nSeqLen; i++ ) + { + if( pHandles[i] != -1 ) + { + sal_Int16 nAttributes; + rPH.fillPropertyMembersByHandle( nullptr, &nAttributes, pHandles[i] ); + if( nAttributes & PropertyAttribute::READONLY ) { + throw PropertyVetoException(); + } + // Will the property change? + if( convertFastPropertyValue( pConvertedValues[ n ], pOldValues[n], + pHandles[i], pValues[i] ) ) + { + // only increment if the property really change + pHandles[n] = pHandles[i]; + n++; + } + } + } + // release guard to fire events + } + + // fire vetoable events + fire( pHandles, pConvertedValues.get(), pOldValues.get(), n, true ); + + { + // must lock the mutex outside the loop. + MutexGuard aGuard( rBHelper.rMutex ); + // Loop over all changed properties + for( i = 0; i < n; i++ ) + { + // Will the property change? + setFastPropertyValue_NoBroadcast( pHandles[i], pConvertedValues[i] ); + } + // release guard to fire events + } + + // fire change events + impl_fireAll( pHandles, pConvertedValues.get(), pOldValues.get(), n ); +} + +// XMultiPropertySet +/** + * The sequence may be contain not known properties. The implementation + * must ignore these properties. + */ +void OPropertySetHelper::setPropertyValues( + const Sequence& rPropertyNames, + const Sequence& rValues ) +{ + sal_Int32 nSeqLen = rPropertyNames.getLength(); + std::unique_ptr pHandles(new sal_Int32[ nSeqLen ]); + // get the map table + IPropertyArrayHelper & rPH = getInfoHelper(); + // fill the handle array + sal_Int32 nHitCount = rPH.fillHandles( pHandles.get(), rPropertyNames ); + if( nHitCount != 0 ) + setFastPropertyValues( nSeqLen, pHandles.get(), rValues.getConstArray(), nHitCount ); +} + +// XMultiPropertySet +Sequence OPropertySetHelper::getPropertyValues( const Sequence& rPropertyNames ) +{ + sal_Int32 nSeqLen = rPropertyNames.getLength(); + std::unique_ptr pHandles(new sal_Int32[ nSeqLen ]); + Sequence< Any > aValues( nSeqLen ); + + // get the map table + IPropertyArrayHelper & rPH = getInfoHelper(); + // fill the handle array + rPH.fillHandles( pHandles.get(), rPropertyNames ); + + Any * pValues = aValues.getArray(); + + MutexGuard aGuard( rBHelper.rMutex ); + // fill the sequence with the values + for( sal_Int32 i = 0; i < nSeqLen; i++ ) + getFastPropertyValue( pValues[i], pHandles[i] ); + + return aValues; +} + +// XMultiPropertySet +void OPropertySetHelper::addPropertiesChangeListener( + const Sequence & , + const Reference < XPropertiesChangeListener > & rListener ) +{ + rBHelper.addListener( cppu::UnoType::get(), rListener ); +} + +// XMultiPropertySet +void OPropertySetHelper::removePropertiesChangeListener( + const Reference < XPropertiesChangeListener > & rListener ) +{ + rBHelper.removeListener( cppu::UnoType::get(), rListener ); +} + +// XMultiPropertySet +void OPropertySetHelper::firePropertiesChangeEvent( + const Sequence& rPropertyNames, + const Reference < XPropertiesChangeListener >& rListener ) +{ + sal_Int32 nLen = rPropertyNames.getLength(); + std::unique_ptr pHandles(new sal_Int32[nLen]); + IPropertyArrayHelper & rPH = getInfoHelper(); + rPH.fillHandles( pHandles.get(), rPropertyNames ); + const OUString* pNames = rPropertyNames.getConstArray(); + + // get the count of matching properties + sal_Int32 nFireLen = 0; + sal_Int32 i; + for( i = 0; i < nLen; i++ ) + if( pHandles[i] != -1 ) + nFireLen++; + + Sequence aChanges( nFireLen ); + PropertyChangeEvent* pChanges = aChanges.getArray(); + + { + // must lock the mutex outside the loop. So all values are consistent. + MutexGuard aGuard( rBHelper.rMutex ); + Reference < XInterface > xSource( static_cast(this), UNO_QUERY ); + sal_Int32 nFirePos = 0; + for( i = 0; i < nLen; i++ ) + { + if( pHandles[i] != -1 ) + { + pChanges[nFirePos].Source = xSource; + pChanges[nFirePos].PropertyName = pNames[i]; + pChanges[nFirePos].PropertyHandle = pHandles[i]; + getFastPropertyValue( pChanges[nFirePos].OldValue, pHandles[i] ); + pChanges[nFirePos].NewValue = pChanges[nFirePos].OldValue; + nFirePos++; + } + } + // release guard to fire events + } + if( nFireLen ) + rListener->propertiesChange( aChanges ); +} + +void OPropertySetHelper2::enableChangeListenerNotification( sal_Bool bEnable ) +{ + m_pReserved->m_bFireEvents = bEnable; +} + +extern "C" { + +static int compare_Property_Impl( const void *arg1, const void *arg2 ) + SAL_THROW_EXTERN_C() +{ + return static_cast(arg1)->Name.compareTo( static_cast(arg2)->Name ); +} + +} + +void OPropertyArrayHelper::init( sal_Bool bSorted ) +{ + sal_Int32 i, nElements = aInfos.getLength(); + const Property* pProperties = aInfos.getConstArray(); + + for( i = 1; i < nElements; i++ ) + { + if( pProperties[i-1].Name > pProperties[i].Name ) + { + if (bSorted) { + OSL_FAIL( "Property array is not sorted" ); + } + // not sorted + qsort( aInfos.getArray(), nElements, sizeof( Property ), + compare_Property_Impl ); + pProperties = aInfos.getConstArray(); + break; + } + } + for( i = 0; i < nElements; i++ ) + if( pProperties[i].Handle != i ) + return; + // The handle is the index + bRightOrdered = true; +} + +OPropertyArrayHelper::OPropertyArrayHelper( + Property * pProps, + sal_Int32 nEle, + sal_Bool bSorted ) + : m_pReserved(nullptr) + , aInfos(pProps, nEle) + , bRightOrdered( false ) +{ + init( bSorted ); +} + +OPropertyArrayHelper::OPropertyArrayHelper( + const Sequence< Property > & aProps, + sal_Bool bSorted ) + : m_pReserved(nullptr) + , aInfos(aProps) + , bRightOrdered( false ) +{ + init( bSorted ); +} + + +sal_Int32 OPropertyArrayHelper::getCount() const +{ + return aInfos.getLength(); +} + + +sal_Bool OPropertyArrayHelper::fillPropertyMembersByHandle +( + OUString * pPropName, + sal_Int16 * pAttributes, + sal_Int32 nHandle +) +{ + const Property* pProperties = aInfos.getConstArray(); + sal_Int32 nElements = aInfos.getLength(); + + if( bRightOrdered ) + { + if( nHandle < 0 || nHandle >= nElements ) + return false; + if( pPropName ) + *pPropName = pProperties[ nHandle ].Name; + if( pAttributes ) + *pAttributes = pProperties[ nHandle ].Attributes; + return true; + } + // normally the array is sorted + for( sal_Int32 i = 0; i < nElements; i++ ) + { + if( pProperties[i].Handle == nHandle ) + { + if( pPropName ) + *pPropName = pProperties[ i ].Name; + if( pAttributes ) + *pAttributes = pProperties[ i ].Attributes; + return true; + } + } + return false; +} + + +Sequence< Property > OPropertyArrayHelper::getProperties() +{ + return aInfos; +} + + +Property OPropertyArrayHelper::getPropertyByName(const OUString& aPropertyName) +{ + Property * pR; + pR = static_cast(bsearch( &aPropertyName, aInfos.getConstArray(), aInfos.getLength(), + sizeof( Property ), + compare_OUString_Property_Impl )); + if( !pR ) { + throw UnknownPropertyException(aPropertyName); + } + return *pR; +} + + +sal_Bool OPropertyArrayHelper::hasPropertyByName(const OUString& aPropertyName) +{ + Property * pR; + pR = static_cast(bsearch( &aPropertyName, aInfos.getConstArray(), aInfos.getLength(), + sizeof( Property ), + compare_OUString_Property_Impl )); + return pR != nullptr; +} + + +sal_Int32 OPropertyArrayHelper::getHandleByName( const OUString & rPropName ) +{ + Property * pR; + pR = static_cast(bsearch( &rPropName, aInfos.getConstArray(), aInfos.getLength(), + sizeof( Property ), + compare_OUString_Property_Impl )); + return pR ? pR->Handle : -1; +} + + +sal_Int32 OPropertyArrayHelper::fillHandles( sal_Int32 * pHandles, const Sequence< OUString > & rPropNames ) +{ + sal_Int32 nHitCount = 0; + const OUString * pReqProps = rPropNames.getConstArray(); + sal_Int32 nReqLen = rPropNames.getLength(); + const Property * pCur = aInfos.getConstArray(); + const Property * pEnd = pCur + aInfos.getLength(); + + for( sal_Int32 i = 0; i < nReqLen; i++ ) + { + // Calculate logarithm + sal_Int32 n = static_cast(pEnd - pCur); + sal_Int32 nLog = 0; + while( n ) + { + nLog += 1; + n = n >> 1; + } + + // Number of properties to search for * Log2 of the number of remaining + // properties to search in. + if( (nReqLen - i) * nLog >= pEnd - pCur ) + { + // linear search is better + while( pCur < pEnd && pReqProps[i] > pCur->Name ) + { + pCur++; + } + if( pCur < pEnd && pReqProps[i] == pCur->Name ) + { + pHandles[i] = pCur->Handle; + nHitCount++; + } + else + pHandles[i] = -1; + } + else + { + // binary search is better + sal_Int32 nCompVal = 1; + const Property * pOldEnd = pEnd--; + const Property * pMid = pCur; + + while( nCompVal != 0 && pCur <= pEnd ) + { + pMid = (pEnd - pCur) / 2 + pCur; + + nCompVal = pReqProps[i].compareTo( pMid->Name ); + + if( nCompVal > 0 ) + pCur = pMid + 1; + else + pEnd = pMid - 1; + } + + if( nCompVal == 0 ) + { + pHandles[i] = pMid->Handle; + nHitCount++; + pCur = pMid +1; + } + else if( nCompVal > 0 ) + { + pHandles[i] = -1; + pCur = pMid +1; + } + else + { + pHandles[i] = -1; + pCur = pMid; + } + pEnd = pOldEnd; + } + } + return nHitCount; +} + +} // end namespace cppu + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/servicemanager.cxx b/cppuhelper/source/servicemanager.cxx new file mode 100644 index 000000000..2ba6ae51a --- /dev/null +++ b/cppuhelper/source/servicemanager.cxx @@ -0,0 +1,1988 @@ +/* -*- 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/. + */ + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "loadsharedlibcomponentfactory.hxx" + +#include +#include + +#include "paths.hxx" +#include "servicemanager.hxx" + +namespace { + +void insertImplementationMap( + cppuhelper::ServiceManager::Data::ImplementationMap * destination, + cppuhelper::ServiceManager::Data::ImplementationMap const & source) +{ + assert(destination != nullptr); + for (const auto& [rName, rImpls] : source) + { + std::vector< + std::shared_ptr< + cppuhelper::ServiceManager::Data::Implementation > > & impls + = (*destination)[rName]; + impls.insert(impls.end(), rImpls.begin(), rImpls.end()); + } +} + +void removeFromImplementationMap( + cppuhelper::ServiceManager::Data::ImplementationMap * map, + std::vector< OUString > const & elements, + std::shared_ptr< cppuhelper::ServiceManager::Data::Implementation > + const & implementation) +{ + // The underlying data structures make this function somewhat inefficient, + // but the assumption is that it is rarely called: + assert(map != nullptr); + for (const auto& rElement : elements) + { + cppuhelper::ServiceManager::Data::ImplementationMap::iterator j( + map->find(rElement)); + assert(j != map->end()); + std::vector< + std::shared_ptr< + cppuhelper::ServiceManager::Data::Implementation > >::iterator + k(std::find(j->second.begin(), j->second.end(), implementation)); + assert(k != j->second.end()); + j->second.erase(k); + if (j->second.empty()) { + map->erase(j); + } + } +} + +// For simplicity, this code keeps throwing +// css::registry::InvalidRegistryException for invalid XML rdbs (even though +// that does not fit the exception's name): +class Parser { +public: + Parser( + OUString const & uri, + css::uno::Reference< css::uno::XComponentContext > const & alienContext, + cppuhelper::ServiceManager::Data * data); + + Parser(const Parser&) = delete; + const Parser& operator=(const Parser&) = delete; + +private: + void handleComponent(); + + void handleImplementation(); + + void handleService(); + + void handleSingleton(); + + OUString getNameAttribute(); + + xmlreader::XmlReader reader_; + css::uno::Reference< css::uno::XComponentContext > alienContext_; + cppuhelper::ServiceManager::Data * data_; + OUString attrLoader_; + OUString attrUri_; + OUString attrEnvironment_; + OUString attrPrefix_; + std::shared_ptr< cppuhelper::ServiceManager::Data::Implementation > + implementation_; +}; + +Parser::Parser( + OUString const & uri, + css::uno::Reference< css::uno::XComponentContext > const & alienContext, + cppuhelper::ServiceManager::Data * data): + reader_(uri), alienContext_(alienContext), data_(data) +{ + assert(data != nullptr); + int ucNsId = reader_.registerNamespaceIri( + xmlreader::Span( + RTL_CONSTASCII_STRINGPARAM( + "http://openoffice.org/2010/uno-components"))); + enum State { + STATE_BEGIN, STATE_END, STATE_COMPONENTS, STATE_COMPONENT_INITIAL, + STATE_COMPONENT, STATE_IMPLEMENTATION, STATE_SERVICE, STATE_SINGLETON }; + for (State state = STATE_BEGIN;;) { + xmlreader::Span name; + int nsId; + xmlreader::XmlReader::Result res = reader_.nextItem( + xmlreader::XmlReader::Text::NONE, &name, &nsId); + switch (state) { + case STATE_BEGIN: + if (res == xmlreader::XmlReader::Result::Begin && nsId == ucNsId + && name.equals(RTL_CONSTASCII_STRINGPARAM("components"))) + { + state = STATE_COMPONENTS; + break; + } + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": unexpected item in outer level"); + case STATE_END: + if (res == xmlreader::XmlReader::Result::Done) { + return; + } + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": unexpected item in outer level"); + case STATE_COMPONENTS: + if (res == xmlreader::XmlReader::Result::End) { + state = STATE_END; + break; + } + if (res == xmlreader::XmlReader::Result::Begin && nsId == ucNsId + && name.equals(RTL_CONSTASCII_STRINGPARAM("component"))) + { + handleComponent(); + state = STATE_COMPONENT_INITIAL; + break; + } + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": unexpected item in "); + case STATE_COMPONENT: + if (res == xmlreader::XmlReader::Result::End) { + state = STATE_COMPONENTS; + break; + } + [[fallthrough]]; + case STATE_COMPONENT_INITIAL: + if (res == xmlreader::XmlReader::Result::Begin && nsId == ucNsId + && name.equals(RTL_CONSTASCII_STRINGPARAM("implementation"))) + { + handleImplementation(); + state = STATE_IMPLEMENTATION; + break; + } + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": unexpected item in "); + case STATE_IMPLEMENTATION: + if (res == xmlreader::XmlReader::Result::End) { + state = STATE_COMPONENT; + break; + } + if (res == xmlreader::XmlReader::Result::Begin && nsId == ucNsId + && name.equals(RTL_CONSTASCII_STRINGPARAM("service"))) + { + handleService(); + state = STATE_SERVICE; + break; + } + if (res == xmlreader::XmlReader::Result::Begin && nsId == ucNsId + && name.equals(RTL_CONSTASCII_STRINGPARAM("singleton"))) + { + handleSingleton(); + state = STATE_SINGLETON; + break; + } + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": unexpected item in "); + case STATE_SERVICE: + if (res == xmlreader::XmlReader::Result::End) { + state = STATE_IMPLEMENTATION; + break; + } + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": unexpected item in "); + case STATE_SINGLETON: + if (res == xmlreader::XmlReader::Result::End) { + state = STATE_IMPLEMENTATION; + break; + } + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": unexpected item in "); + } + } +} + +void Parser::handleComponent() { + attrLoader_ = OUString(); + attrUri_ = OUString(); + attrEnvironment_ = OUString(); + attrPrefix_ = OUString(); + xmlreader::Span name; + int nsId; + while (reader_.nextAttribute(&nsId, &name)) { + if (nsId == xmlreader::XmlReader::NAMESPACE_NONE + && name.equals(RTL_CONSTASCII_STRINGPARAM("loader"))) + { + if (!attrLoader_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has multiple \"loader\" attributes"); + } + attrLoader_ = reader_.getAttributeValue(false).convertFromUtf8(); + if (attrLoader_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has empty \"loader\" attribute"); + } + } else if (nsId == xmlreader::XmlReader::NAMESPACE_NONE + && name.equals(RTL_CONSTASCII_STRINGPARAM("uri"))) + { + if (!attrUri_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has multiple \"uri\" attributes"); + } + attrUri_ = reader_.getAttributeValue(false).convertFromUtf8(); + if (attrUri_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has empty \"uri\" attribute"); + } + } else if (nsId == xmlreader::XmlReader::NAMESPACE_NONE + && name.equals(RTL_CONSTASCII_STRINGPARAM("environment"))) + { + if (!attrEnvironment_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has multiple \"environment\" attributes"); + } + attrEnvironment_ = reader_.getAttributeValue(false) + .convertFromUtf8(); + if (attrEnvironment_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has empty \"environment\" attribute"); + } + } else if (nsId == xmlreader::XmlReader::NAMESPACE_NONE + && name.equals(RTL_CONSTASCII_STRINGPARAM("prefix"))) + { + if (!attrPrefix_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has multiple \"prefix\" attributes"); + } + attrPrefix_ = reader_.getAttributeValue(false).convertFromUtf8(); + if (attrPrefix_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has empty \"prefix\" attribute"); + } + } else { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": unexpected attribute \"" + + name.convertFromUtf8() + "\" in "); + } + } + if (attrLoader_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": is missing \"loader\" attribute"); + } + if (attrUri_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": is missing \"uri\" attribute"); + } +#ifndef DISABLE_DYNLOADING + try { + attrUri_ = rtl::Uri::convertRelToAbs(reader_.getUrl(), attrUri_); + } catch (const rtl::MalformedUriException & e) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": bad \"uri\" attribute: " + e.getMessage()); + } +#endif +} + +void Parser::handleImplementation() { + OUString attrName; + OUString attrConstructor; + xmlreader::Span name; + int nsId; + while (reader_.nextAttribute(&nsId, &name)) { + if (nsId == xmlreader::XmlReader::NAMESPACE_NONE + && name.equals(RTL_CONSTASCII_STRINGPARAM("name"))) + { + if (!attrName.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has multiple \"name\" attributes"); + } + attrName = reader_.getAttributeValue(false).convertFromUtf8(); + if (attrName.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has empty \"name\" attribute"); + } + } else if (nsId == xmlreader::XmlReader::NAMESPACE_NONE + && name.equals(RTL_CONSTASCII_STRINGPARAM("constructor"))) + { + if (!attrConstructor.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has multiple \"constructor\"" + " attributes"); + } + attrConstructor = reader_.getAttributeValue(false) + .convertFromUtf8(); + if (attrConstructor.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": element has empty \"constructor\" attribute"); + } + if (attrEnvironment_.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": has \"constructor\" attribute but" + " has no \"environment\" attribute"); + } + } else { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": unexpected element attribute \"" + + name.convertFromUtf8() + "\" in "); + } + } + if (attrName.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": is missing \"name\" attribute"); + } + implementation_ = + std::make_shared( + attrName, attrLoader_, attrUri_, attrEnvironment_, attrConstructor, + attrPrefix_, alienContext_, reader_.getUrl()); + if (!data_->namedImplementations.emplace(attrName, implementation_). + second) + { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": duplicate "); + } +} + +void Parser::handleService() { + OUString name(getNameAttribute()); + implementation_->services.push_back(name); + data_->services[name].push_back(implementation_); +} + +void Parser::handleSingleton() { + OUString name(getNameAttribute()); + implementation_->singletons.push_back(name); + data_->singletons[name].push_back(implementation_); +} + +OUString Parser::getNameAttribute() { + OUString attrName; + xmlreader::Span name; + int nsId; + while (reader_.nextAttribute(&nsId, &name)) { + if (nsId != xmlreader::XmlReader::NAMESPACE_NONE + || !name.equals(RTL_CONSTASCII_STRINGPARAM("name"))) + { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": expected element attribute \"name\""); + } + if (!attrName.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + + ": element has multiple \"name\" attributes"); + } + attrName = reader_.getAttributeValue(false).convertFromUtf8(); + if (attrName.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": element has empty \"name\" attribute"); + } + } + if (attrName.isEmpty()) { + throw css::registry::InvalidRegistryException( + reader_.getUrl() + ": element is missing \"name\" attribute"); + } + return attrName; +} + +class ContentEnumeration: + public cppu::WeakImplHelper< css::container::XEnumeration > +{ +public: + explicit ContentEnumeration(std::vector< css::uno::Any > const & factories): + factories_(factories), iterator_(factories_.begin()) {} + + ContentEnumeration(const ContentEnumeration&) = delete; + const ContentEnumeration& operator=(const ContentEnumeration&) = delete; + +private: + virtual ~ContentEnumeration() override {} + + virtual sal_Bool SAL_CALL hasMoreElements() override; + + virtual css::uno::Any SAL_CALL nextElement() override; + + osl::Mutex mutex_; + std::vector< css::uno::Any > factories_; + std::vector< css::uno::Any >::const_iterator iterator_; +}; + +sal_Bool ContentEnumeration::hasMoreElements() +{ + osl::MutexGuard g(mutex_); + return iterator_ != factories_.end(); +} + +css::uno::Any ContentEnumeration::nextElement() +{ + osl::MutexGuard g(mutex_); + if (iterator_ == factories_.end()) { + throw css::container::NoSuchElementException( + "Bootstrap service manager service enumerator has no more elements", + static_cast< cppu::OWeakObject * >(this)); + } + return *iterator_++; +} + +css::beans::Property getDefaultContextProperty() { + return css::beans::Property( + "DefaultContext", -1, + cppu::UnoType< css::uno::XComponentContext >::get(), + css::beans::PropertyAttribute::READONLY); +} + +class SingletonFactory: + public cppu::WeakImplHelper +{ +public: + SingletonFactory( + rtl::Reference< cppuhelper::ServiceManager > const & manager, + std::shared_ptr< + cppuhelper::ServiceManager::Data::Implementation > const & + implementation): + manager_(manager), implementation_(implementation) + { assert(manager.is()); assert(implementation.get() != nullptr); } + + SingletonFactory(const SingletonFactory&) = delete; + const SingletonFactory& operator=(const SingletonFactory&) = delete; + +private: + virtual ~SingletonFactory() override {} + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL + createInstanceWithContext( + css::uno::Reference< css::uno::XComponentContext > const & Context) override; + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL + createInstanceWithArgumentsAndContext( + css::uno::Sequence< css::uno::Any > const & Arguments, + css::uno::Reference< css::uno::XComponentContext > const & Context) override; + + rtl::Reference< cppuhelper::ServiceManager > manager_; + std::shared_ptr< cppuhelper::ServiceManager::Data::Implementation > + implementation_; +}; + +css::uno::Reference< css::uno::XInterface > +SingletonFactory::createInstanceWithContext( + css::uno::Reference< css::uno::XComponentContext > const & Context) +{ + manager_->loadImplementation(Context, implementation_); + return implementation_->createInstance(Context, true); +} + +css::uno::Reference< css::uno::XInterface > +SingletonFactory::createInstanceWithArgumentsAndContext( + css::uno::Sequence< css::uno::Any > const & Arguments, + css::uno::Reference< css::uno::XComponentContext > const & Context) +{ + manager_->loadImplementation(Context, implementation_); + return implementation_->createInstanceWithArguments( + Context, true, Arguments); +} + +class ImplementationWrapper: + public cppu::WeakImplHelper< + css::lang::XSingleComponentFactory, css::lang::XSingleServiceFactory, + css::lang::XServiceInfo > +{ +public: + ImplementationWrapper( + rtl::Reference< cppuhelper::ServiceManager > const & manager, + std::shared_ptr< + cppuhelper::ServiceManager::Data::Implementation > const & + implementation): + manager_(manager), implementation_(implementation) + { assert(manager.is()); assert(implementation.get() != nullptr); } + + ImplementationWrapper(const ImplementationWrapper&) = delete; + const ImplementationWrapper& operator=(const ImplementationWrapper&) = delete; + +private: + virtual ~ImplementationWrapper() override {} + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL + createInstanceWithContext( + css::uno::Reference< css::uno::XComponentContext > const & Context) override; + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL + createInstanceWithArgumentsAndContext( + css::uno::Sequence< css::uno::Any > const & Arguments, + css::uno::Reference< css::uno::XComponentContext > const & Context) override; + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL + createInstance() override; + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL + createInstanceWithArguments( + css::uno::Sequence< css::uno::Any > const & Arguments) override; + + virtual OUString SAL_CALL getImplementationName() override; + + virtual sal_Bool SAL_CALL supportsService(OUString const & ServiceName) override; + + virtual css::uno::Sequence< OUString > SAL_CALL + getSupportedServiceNames() override; + + rtl::Reference< cppuhelper::ServiceManager > manager_; + std::weak_ptr< cppuhelper::ServiceManager::Data::Implementation > + implementation_; +}; + +css::uno::Reference< css::uno::XInterface > +ImplementationWrapper::createInstanceWithContext( + css::uno::Reference< css::uno::XComponentContext > const & Context) +{ + std::shared_ptr< cppuhelper::ServiceManager::Data::Implementation > impl = implementation_.lock(); + assert(impl); + manager_->loadImplementation(Context, impl); + return impl->createInstance(Context, false); +} + +css::uno::Reference< css::uno::XInterface > +ImplementationWrapper::createInstanceWithArgumentsAndContext( + css::uno::Sequence< css::uno::Any > const & Arguments, + css::uno::Reference< css::uno::XComponentContext > const & Context) +{ + std::shared_ptr< cppuhelper::ServiceManager::Data::Implementation > impl = implementation_.lock(); + assert(impl); + manager_->loadImplementation(Context, impl); + return impl->createInstanceWithArguments( + Context, false, Arguments); +} + +css::uno::Reference< css::uno::XInterface > +ImplementationWrapper::createInstance() +{ + return createInstanceWithContext(manager_->getContext()); +} + +css::uno::Reference< css::uno::XInterface > +ImplementationWrapper::createInstanceWithArguments( + css::uno::Sequence< css::uno::Any > const & Arguments) +{ + return createInstanceWithArgumentsAndContext( + Arguments, manager_->getContext()); +} + +OUString ImplementationWrapper::getImplementationName() +{ + std::shared_ptr< cppuhelper::ServiceManager::Data::Implementation > impl = implementation_.lock(); + assert(impl); + return impl->name; +} + +sal_Bool ImplementationWrapper::supportsService(OUString const & ServiceName) +{ + return cppu::supportsService(this, ServiceName); +} + +css::uno::Sequence< OUString > +ImplementationWrapper::getSupportedServiceNames() +{ + std::shared_ptr< cppuhelper::ServiceManager::Data::Implementation > impl = implementation_.lock(); + assert(impl); + if (impl->services.size() + > o3tl::make_unsigned(SAL_MAX_INT32)) + { + throw css::uno::RuntimeException( + ("Implementation " + impl->name + + " supports too many services"), + static_cast< cppu::OWeakObject * >(this)); + } + return comphelper::containerToSequence(impl->services); +} + +} + +css::uno::Reference +cppuhelper::ServiceManager::Data::Implementation::createInstance( + css::uno::Reference const & context, + bool singletonRequest) +{ + css::uno::Reference inst; + if (constructorFn) { + inst.set( + constructorFn(context.get(), css::uno::Sequence()), + SAL_NO_ACQUIRE); + } else if (factory1.is()) { + inst = factory1->createInstanceWithContext(context); + } else { + assert(factory2.is()); + inst = factory2->createInstance(); + } + updateDisposeSingleton(singletonRequest, inst); + return inst; +} + +css::uno::Reference +cppuhelper::ServiceManager::Data::Implementation::createInstanceWithArguments( + css::uno::Reference const & context, + bool singletonRequest, css::uno::Sequence const & arguments) +{ + css::uno::Reference inst; + if (constructorFn) { + inst.set(constructorFn(context.get(), arguments), SAL_NO_ACQUIRE); + //HACK: The constructor will either observe arguments and return inst + // that does not implement XInitialization (or null), or ignore + // arguments and return inst that implements XInitialization; this + // should be removed again once XInitialization-based implementations + // have become rare: + css::uno::Reference init( + inst, css::uno::UNO_QUERY); + if (init.is()) { + init->initialize(arguments); + } + } else if (factory1.is()) { + inst = factory1->createInstanceWithArgumentsAndContext( + arguments, context); + } else { + assert(factory2.is()); + inst = factory2->createInstanceWithArguments(arguments); + } + updateDisposeSingleton(singletonRequest, inst); + return inst; +} + +void cppuhelper::ServiceManager::Data::Implementation::updateDisposeSingleton( + bool singletonRequest, + css::uno::Reference const & instance) +{ + // This is an optimization, to only call dispose once (from the component + // context) on a singleton that is obtained both via the component context + // and via the service manager; however, there is a harmless race here that + // may cause two calls to dispose nevertheless (also, this calls dispose on + // at most one of the instances obtained via the service manager, in case + // the implementation hands out different instances): + if (singletonRequest) { + osl::MutexGuard g(mutex); + disposeSingleton.clear(); + dispose = false; + } else if (!singletons.empty()) { + css::uno::Reference comp( + instance, css::uno::UNO_QUERY); + if (comp.is()) { + osl::MutexGuard g(mutex); + if (dispose) { + disposeSingleton = comp; + } + } + } +} + +void cppuhelper::ServiceManager::addSingletonContextEntries( + std::vector< cppu::ContextEntry_Init > * entries) +{ + assert(entries != nullptr); + for (const auto& [rName, rImpls] : data_.singletons) + { + assert(!rImpls.empty()); + assert(rImpls[0].get() != nullptr); + SAL_INFO_IF( + rImpls.size() > 1, "cppuhelper", + "Arbitrarily choosing " << rImpls[0]->name + << " among multiple implementations for " << rName); + entries->push_back( + cppu::ContextEntry_Init( + "/singletons/" + rName, + css::uno::makeAny< + css::uno::Reference >( + new SingletonFactory(this, rImpls[0])), + true)); + } +} + +void cppuhelper::ServiceManager::loadImplementation( + css::uno::Reference< css::uno::XComponentContext > const & context, + std::shared_ptr< Data::Implementation > const & implementation) +{ + assert(implementation.get() != nullptr); + { + osl::MutexGuard g(rBHelper.rMutex); + if (implementation->status == Data::Implementation::STATUS_LOADED) { + return; + } + } + OUString uri; + try { + uri = cppu::bootstrap_expandUri(implementation->uri); + } catch (css::lang::IllegalArgumentException & e) { + throw css::uno::DeploymentException( + "Cannot expand URI" + implementation->uri + ": " + e.Message, + static_cast< cppu::OWeakObject * >(this)); + } + cppuhelper::WrapperConstructorFn ctor; + css::uno::Reference< css::uno::XInterface > f0; + // Special handling of SharedLibrary loader, with support for environment, + // constructor, and prefix arguments: + if (!implementation->alienContext.is() + && implementation->loader == "com.sun.star.loader.SharedLibrary") + { + cppuhelper::detail::loadSharedLibComponentFactory( + uri, implementation->environment, + implementation->prefix, implementation->name, + implementation->constructorName, this, &ctor, &f0); + if (ctor) { + assert(!implementation->environment.isEmpty()); + } + } else { + SAL_WARN_IF( + !implementation->environment.isEmpty(), "cppuhelper", + "Loader " << implementation->loader + << " and non-empty environment " + << implementation->environment); + SAL_WARN_IF( + !implementation->prefix.isEmpty(), "cppuhelper", + "Loader " << implementation->loader + << " and non-empty constructor " + << implementation->constructorName); + SAL_WARN_IF( + !implementation->prefix.isEmpty(), "cppuhelper", + "Loader " << implementation->loader + << " and non-empty prefix " << implementation->prefix); + css::uno::Reference< css::uno::XComponentContext > ctxt; + css::uno::Reference< css::lang::XMultiComponentFactory > smgr; + if (implementation->alienContext.is()) { + ctxt = implementation->alienContext; + smgr.set(ctxt->getServiceManager(), css::uno::UNO_SET_THROW); + } else { + assert(context.is()); + ctxt = context; + smgr = this; + } + css::uno::Reference< css::loader::XImplementationLoader > loader( + smgr->createInstanceWithContext(implementation->loader, ctxt), + css::uno::UNO_QUERY_THROW); + f0 = loader->activate( + implementation->name, OUString(), uri, + css::uno::Reference< css::registry::XRegistryKey >()); + } + css::uno::Reference f1; + css::uno::Reference f2; + if (!ctor) { + f1.set(f0, css::uno::UNO_QUERY); + if (!f1.is()) { + f2.set(f0, css::uno::UNO_QUERY); + if (!f2.is()) { + throw css::uno::DeploymentException( + ("Implementation " + implementation->name + + " does not provide a constructor or factory"), + static_cast< cppu::OWeakObject * >(this)); + } + } + } + //TODO: There is a race here, as the relevant service factory can be removed + // while the mutex is unlocked and loading can thus fail, as the entity from + // which to load can disappear once the service factory is removed. + osl::MutexGuard g(rBHelper.rMutex); + if (!(isDisposed() + || implementation->status == Data::Implementation::STATUS_LOADED)) + { + implementation->status = Data::Implementation::STATUS_LOADED; + implementation->constructorFn = ctor; + implementation->factory1 = f1; + implementation->factory2 = f2; + } +} + +void cppuhelper::ServiceManager::disposing() { + std::vector< css::uno::Reference > sngls; + std::vector< css::uno::Reference< css::lang::XComponent > > comps; + Data clear; + { + osl::MutexGuard g(rBHelper.rMutex); + for (const auto& rEntry : data_.namedImplementations) + { + assert(rEntry.second.get() != nullptr); + if (!rEntry.second->singletons.empty()) { + osl::MutexGuard g2(rEntry.second->mutex); + if (rEntry.second->disposeSingleton.is()) { + sngls.push_back(rEntry.second->disposeSingleton); + } + } + } + for (const auto& rEntry : data_.dynamicImplementations) + { + assert(rEntry.second.get() != nullptr); + if (!rEntry.second->singletons.empty()) { + osl::MutexGuard g2(rEntry.second->mutex); + if (rEntry.second->disposeSingleton.is()) { + sngls.push_back(rEntry.second->disposeSingleton); + } + } + if (rEntry.second->component.is()) { + comps.push_back(rEntry.second->component); + } + } + data_.namedImplementations.swap(clear.namedImplementations); + data_.dynamicImplementations.swap(clear.dynamicImplementations); + data_.services.swap(clear.services); + data_.singletons.swap(clear.singletons); + } + for (const auto& rxSngl : sngls) + { + try { + rxSngl->dispose(); + } catch (css::uno::RuntimeException & e) { + SAL_WARN("cppuhelper", "Ignoring " << e << " while disposing singleton"); + } + } + for (const auto& rxComp : comps) + { + removeEventListenerFromComponent(rxComp); + } +} + +void cppuhelper::ServiceManager::initialize( + css::uno::Sequence const & aArguments) +{ + OUString arg; + if (aArguments.getLength() != 1 || !(aArguments[0] >>= arg) + || arg != "preload") + { + throw css::lang::IllegalArgumentException( + "invalid ServiceManager::initialize argument", + css::uno::Reference(), 0); + } + preloadImplementations(); +} + +OUString cppuhelper::ServiceManager::getImplementationName() +{ + return + "com.sun.star.comp.cppuhelper.bootstrap.ServiceManager"; +} + +sal_Bool cppuhelper::ServiceManager::supportsService( + OUString const & ServiceName) +{ + return cppu::supportsService(this, ServiceName); +} + +css::uno::Sequence< OUString > +cppuhelper::ServiceManager::getSupportedServiceNames() +{ + return { "com.sun.star.lang.MultiServiceFactory", "com.sun.star.lang.ServiceManager" }; +} + +css::uno::Reference< css::uno::XInterface > +cppuhelper::ServiceManager::createInstance( + OUString const & aServiceSpecifier) +{ + assert(context_.is()); + return createInstanceWithContext(aServiceSpecifier, context_); +} + +css::uno::Reference< css::uno::XInterface > +cppuhelper::ServiceManager::createInstanceWithArguments( + OUString const & ServiceSpecifier, + css::uno::Sequence< css::uno::Any > const & Arguments) +{ + assert(context_.is()); + return createInstanceWithArgumentsAndContext( + ServiceSpecifier, Arguments, context_); +} + +css::uno::Sequence< OUString > +cppuhelper::ServiceManager::getAvailableServiceNames() +{ + osl::MutexGuard g(rBHelper.rMutex); + if (isDisposed()) { + return css::uno::Sequence< OUString >(); + } + if (data_.services.size() > o3tl::make_unsigned(SAL_MAX_INT32)) { + throw css::uno::RuntimeException( + "getAvailableServiceNames: too many services", + static_cast< cppu::OWeakObject * >(this)); + } + return comphelper::mapKeysToSequence(data_.services); +} + +css::uno::Reference< css::uno::XInterface > +cppuhelper::ServiceManager::createInstanceWithContext( + OUString const & aServiceSpecifier, + css::uno::Reference< css::uno::XComponentContext > const & Context) +{ + std::shared_ptr< Data::Implementation > impl( + findServiceImplementation(Context, aServiceSpecifier)); + return impl == nullptr ? css::uno::Reference() + : impl->createInstance(Context, false); +} + +css::uno::Reference< css::uno::XInterface > +cppuhelper::ServiceManager::createInstanceWithArgumentsAndContext( + OUString const & ServiceSpecifier, + css::uno::Sequence< css::uno::Any > const & Arguments, + css::uno::Reference< css::uno::XComponentContext > const & Context) +{ + std::shared_ptr< Data::Implementation > impl( + findServiceImplementation(Context, ServiceSpecifier)); + return impl == nullptr ? css::uno::Reference() + : impl->createInstanceWithArguments(Context, false, Arguments); +} + +css::uno::Type cppuhelper::ServiceManager::getElementType() +{ + return css::uno::Type(); +} + +sal_Bool cppuhelper::ServiceManager::hasElements() +{ + osl::MutexGuard g(rBHelper.rMutex); + return + !(data_.namedImplementations.empty() + && data_.dynamicImplementations.empty()); +} + +css::uno::Reference< css::container::XEnumeration > +cppuhelper::ServiceManager::createEnumeration() +{ + throw css::uno::RuntimeException( + "ServiceManager createEnumeration: method not supported", + static_cast< cppu::OWeakObject * >(this)); +} + +sal_Bool cppuhelper::ServiceManager::has(css::uno::Any const &) +{ + throw css::uno::RuntimeException( + "ServiceManager has: method not supported", + static_cast< cppu::OWeakObject * >(this)); +} + +void cppuhelper::ServiceManager::insert(css::uno::Any const & aElement) +{ + css::uno::Sequence< css::beans::NamedValue > args; + if (aElement >>= args) { + std::vector< OUString > uris; + css::uno::Reference< css::uno::XComponentContext > alienContext; + for (const auto & arg : std::as_const(args)) { + if (arg.Name == "uri") { + OUString uri; + if (!(arg.Value >>= uri)) { + throw css::lang::IllegalArgumentException( + "Bad uri argument", + static_cast< cppu::OWeakObject * >(this), 0); + } + uris.push_back(uri); + } else if (arg.Name == "component-context") { + if (alienContext.is()) { + throw css::lang::IllegalArgumentException( + "Multiple component-context arguments", + static_cast< cppu::OWeakObject * >(this), 0); + } + if (!(arg.Value >>= alienContext) || !alienContext.is()) { + throw css::lang::IllegalArgumentException( + "Bad component-context argument", + static_cast< cppu::OWeakObject * >(this), 0); + } + } else { + throw css::lang::IllegalArgumentException( + "Bad argument " + arg.Name, + static_cast< cppu::OWeakObject * >(this), 0); + } + } + insertRdbFiles(uris, alienContext); + return; + } + css::uno::Reference< css::lang::XServiceInfo > info; + if ((aElement >>= info) && info.is()) { + insertLegacyFactory(info); + return; + } +// At least revisions up to 1.7 of LanguageTool.oxt (incl. the bundled 1.4.0 in +// module languagetool) contain an (actively registered) factory that does not +// implement XServiceInfo (see "SingletonFactory should +// implement XServiceInfo"); the old OServiceManager::insert +// (stoc/source/servicemanager/servicemanager.cxx) silently did not add such +// broken factories to its m_ImplementationNameMap, so ignore them here for +// backwards compatibility of live-insertion of extensions, too. + +// (The plan was that this warning would go away (and we would do the +// throw instead) for the incompatible LO 4, but we changed our mind): + css::uno::Reference< css::lang::XSingleComponentFactory > legacy; + if ((aElement >>= legacy) && legacy.is()) { + SAL_WARN( + "cppuhelper", + "Ignored XSingleComponentFactory not implementing XServiceInfo"); + return; + } + + throw css::lang::IllegalArgumentException( + "Bad insert element", static_cast< cppu::OWeakObject * >(this), 0); +} + +void cppuhelper::ServiceManager::remove(css::uno::Any const & aElement) +{ + css::uno::Sequence< css::beans::NamedValue > args; + if (aElement >>= args) { + std::vector< OUString > uris; + for (const auto & i : std::as_const(args)) { + if (i.Name != "uri") { + throw css::lang::IllegalArgumentException( + "Bad argument " + i.Name, + static_cast< cppu::OWeakObject * >(this), 0); + } + OUString uri; + if (!(i.Value >>= uri)) { + throw css::lang::IllegalArgumentException( + "Bad uri argument", + static_cast< cppu::OWeakObject * >(this), 0); + } + uris.push_back(uri); + } + removeRdbFiles(uris); + return; + } + css::uno::Reference< css::lang::XServiceInfo > info; + if ((aElement >>= info) && info.is()) { + if (!removeLegacyFactory(info, true)) { + throw css::container::NoSuchElementException( + "Remove non-inserted factory object", + static_cast< cppu::OWeakObject * >(this)); + } + return; + } + OUString impl; + if (aElement >>= impl) { + // For live-removal of extensions: + removeImplementation(impl); + return; + } + throw css::lang::IllegalArgumentException( + "Bad remove element", static_cast< cppu::OWeakObject * >(this), 0); +} + +css::uno::Reference< css::container::XEnumeration > +cppuhelper::ServiceManager::createContentEnumeration( + OUString const & aServiceName) +{ + std::vector< std::shared_ptr< Data::Implementation > > impls; + { + osl::MutexGuard g(rBHelper.rMutex); + Data::ImplementationMap::const_iterator i( + data_.services.find(aServiceName)); + if (i != data_.services.end()) { + impls = i->second; + } + } + std::vector< css::uno::Any > factories; + for (const auto& rxImpl : impls) + { + Data::Implementation * impl = rxImpl.get(); + assert(impl != nullptr); + { + osl::MutexGuard g(rBHelper.rMutex); + if (isDisposed()) { + factories.clear(); + break; + } + if (impl->status == Data::Implementation::STATUS_NEW) { + // Postpone actual implementation instantiation as long as + // possible (so that e.g. opening LO's "Tools - Macros" menu + // does not try to instantiate a JVM, which can lead to a + // synchronous error dialog when no JVM is specified, and + // showing the dialog while hovering over a menu can cause + // trouble): + impl->factory1 = new ImplementationWrapper(this, rxImpl); + impl->status = Data::Implementation::STATUS_WRAPPER; + } + if (impl->constructorFn != nullptr && !impl->factory1.is()) { + impl->factory1 = new ImplementationWrapper(this, rxImpl); + } + } + if (impl->factory1.is()) { + factories.push_back(css::uno::Any(impl->factory1)); + } else { + assert(impl->factory2.is()); + factories.push_back(css::uno::Any(impl->factory2)); + } + } + return new ContentEnumeration(factories); +} + +css::uno::Reference< css::beans::XPropertySetInfo > +cppuhelper::ServiceManager::getPropertySetInfo() +{ + return this; +} + +void cppuhelper::ServiceManager::setPropertyValue( + OUString const & aPropertyName, css::uno::Any const &) +{ + if (aPropertyName == "DefaultContext") { + throw css::beans::PropertyVetoException( + aPropertyName, static_cast< cppu::OWeakObject * >(this)); + } else { + throw css::beans::UnknownPropertyException( + aPropertyName, static_cast< cppu::OWeakObject * >(this)); + } +} + +css::uno::Any cppuhelper::ServiceManager::getPropertyValue( + OUString const & PropertyName) +{ + if (PropertyName != "DefaultContext") { + throw css::beans::UnknownPropertyException( + PropertyName, static_cast< cppu::OWeakObject * >(this)); + } + assert(context_.is()); + return css::uno::Any(context_); +} + +void cppuhelper::ServiceManager::addPropertyChangeListener( + OUString const & aPropertyName, + css::uno::Reference< css::beans::XPropertyChangeListener > const & + xListener) +{ + if (!aPropertyName.isEmpty() && aPropertyName != "DefaultContext") { + throw css::beans::UnknownPropertyException( + aPropertyName, static_cast< cppu::OWeakObject * >(this)); + } + // DefaultContext does not change, so just treat it as an event listener: + return addEventListener(xListener); +} + +void cppuhelper::ServiceManager::removePropertyChangeListener( + OUString const & aPropertyName, + css::uno::Reference< css::beans::XPropertyChangeListener > const & + aListener) +{ + if (!aPropertyName.isEmpty() && aPropertyName != "DefaultContext") { + throw css::beans::UnknownPropertyException( + aPropertyName, static_cast< cppu::OWeakObject * >(this)); + } + // DefaultContext does not change, so just treat it as an event listener: + return removeEventListener(aListener); +} + +void cppuhelper::ServiceManager::addVetoableChangeListener( + OUString const & PropertyName, + css::uno::Reference< css::beans::XVetoableChangeListener > const & + aListener) +{ + if (!PropertyName.isEmpty() && PropertyName != "DefaultContext") { + throw css::beans::UnknownPropertyException( + PropertyName, static_cast< cppu::OWeakObject * >(this)); + } + // DefaultContext does not change, so just treat it as an event listener: + return addEventListener(aListener); +} + +void cppuhelper::ServiceManager::removeVetoableChangeListener( + OUString const & PropertyName, + css::uno::Reference< css::beans::XVetoableChangeListener > const & + aListener) +{ + if (!PropertyName.isEmpty() && PropertyName != "DefaultContext") { + throw css::beans::UnknownPropertyException( + PropertyName, static_cast< cppu::OWeakObject * >(this)); + } + // DefaultContext does not change, so just treat it as an event listener: + return removeEventListener(aListener); +} + +css::uno::Sequence< css::beans::Property > +cppuhelper::ServiceManager::getProperties() { + css::uno::Sequence< css::beans::Property > props(1); + props[0] = getDefaultContextProperty(); + return props; +} + +css::beans::Property cppuhelper::ServiceManager::getPropertyByName( + OUString const & aName) +{ + if (aName != "DefaultContext") { + throw css::beans::UnknownPropertyException( + aName, static_cast< cppu::OWeakObject * >(this)); + } + return getDefaultContextProperty(); +} + +sal_Bool cppuhelper::ServiceManager::hasPropertyByName( + OUString const & Name) +{ + return Name == "DefaultContext"; +} + +cppuhelper::ServiceManager::~ServiceManager() {} + +void cppuhelper::ServiceManager::disposing( + css::lang::EventObject const & Source) +{ + removeLegacyFactory( + css::uno::Reference< css::lang::XServiceInfo >( + Source.Source, css::uno::UNO_QUERY_THROW), + false); +} + +void cppuhelper::ServiceManager::removeEventListenerFromComponent( + css::uno::Reference< css::lang::XComponent > const & component) +{ + assert(component.is()); + try { + component->removeEventListener(this); + } catch (css::uno::RuntimeException & e) { + SAL_INFO( + "cppuhelper", + "Ignored removeEventListener RuntimeException " + e.Message); + } +} + +void cppuhelper::ServiceManager::init(OUString const & rdbUris) { + for (sal_Int32 i = 0; i != -1;) { + OUString uri(rdbUris.getToken(0, ' ', i)); + if (uri.isEmpty()) { + continue; + } + bool optional; + bool directory; + cppu::decodeRdbUri(&uri, &optional, &directory); + if (directory) { + readRdbDirectory(uri, optional); + } else { + readRdbFile(uri, optional); + } + } +} + +void cppuhelper::ServiceManager::readRdbDirectory( + OUString const & uri, bool optional) +{ + osl::Directory dir(uri); + switch (dir.open()) { + case osl::FileBase::E_None: + break; + case osl::FileBase::E_NOENT: + if (optional) { + SAL_INFO("cppuhelper", "Ignored optional " << uri); + return; + } + [[fallthrough]]; + default: + throw css::uno::DeploymentException( + "Cannot open directory " + uri, + static_cast< cppu::OWeakObject * >(this)); + } + for (;;) { + OUString url; + if (!cppu::nextDirectoryItem(dir, &url)) { + break; + } + readRdbFile(url, false); + } +} + +void cppuhelper::ServiceManager::readRdbFile( + OUString const & uri, bool optional) +{ + try { + Parser( + uri, css::uno::Reference< css::uno::XComponentContext >(), &data_); + } catch (css::container::NoSuchElementException &) { + if (!optional) { + throw css::uno::DeploymentException( + uri + ": no such file", + static_cast< cppu::OWeakObject * >(this)); + } + SAL_INFO("cppuhelper", "Ignored optional " << uri); + } catch (css::registry::InvalidRegistryException & e) { + if (!readLegacyRdbFile(uri)) { + throw css::uno::DeploymentException( + "InvalidRegistryException: " + e.Message, + static_cast< cppu::OWeakObject * >(this)); + } + } catch (css::uno::RuntimeException &) { + if (!readLegacyRdbFile(uri)) { + throw; + } + } +} + +bool cppuhelper::ServiceManager::readLegacyRdbFile(OUString const & uri) { + Registry reg; + switch (reg.open(uri, RegAccessMode::READONLY)) { + case RegError::NO_ERROR: + break; + case RegError::REGISTRY_NOT_EXISTS: + case RegError::INVALID_REGISTRY: + { + // Ignore empty rdb files (which are at least seen by subordinate + // uno processes during extension registration; Registry::open can + // fail on them if mmap(2) returns EINVAL for a zero length): + osl::DirectoryItem item; + if (osl::DirectoryItem::get(uri, item) == osl::FileBase::E_None) { + osl::FileStatus status(osl_FileStatus_Mask_FileSize); + if (item.getFileStatus(status) == osl::FileBase::E_None + && status.getFileSize() == 0) + { + return true; + } + } + } + [[fallthrough]]; + default: + return false; + } + RegistryKey rootKey; + if (reg.openRootKey(rootKey) != RegError::NO_ERROR) { + throw css::uno::DeploymentException( + "Failure reading legacy rdb file " + uri, + static_cast< cppu::OWeakObject * >(this)); + } + RegistryKeyArray impls; + switch (rootKey.openSubKeys("IMPLEMENTATIONS", impls)) { + case RegError::NO_ERROR: + break; + case RegError::KEY_NOT_EXISTS: + return true; + default: + throw css::uno::DeploymentException( + "Failure reading legacy rdb file " + uri, + static_cast< cppu::OWeakObject * >(this)); + } + for (sal_uInt32 i = 0; i != impls.getLength(); ++i) { + RegistryKey implKey(impls.getElement(i)); + assert(implKey.getName().match("/IMPLEMENTATIONS/")); + OUString name( + implKey.getName().copy(RTL_CONSTASCII_LENGTH("/IMPLEMENTATIONS/"))); + std::shared_ptr< Data::Implementation > impl = + std::make_shared( + name, readLegacyRdbString(uri, implKey, "UNO/ACTIVATOR"), + readLegacyRdbString(uri, implKey, "UNO/LOCATION"), "", "", "", + css::uno::Reference< css::uno::XComponentContext >(), uri); + if (!data_.namedImplementations.emplace(name, impl).second) + { + throw css::registry::InvalidRegistryException( + uri + ": duplicate "); + } + readLegacyRdbStrings( + uri, implKey, "UNO/SERVICES", &impl->services); + for (const auto& rService : impl->services) + { + data_.services[rService].push_back(impl); + } + readLegacyRdbStrings( + uri, implKey, "UNO/SINGLETONS", &impl->singletons); + for (const auto& rSingleton : impl->singletons) + { + data_.singletons[rSingleton].push_back(impl); + } + } + return true; +} + +OUString cppuhelper::ServiceManager::readLegacyRdbString( + OUString const & uri, RegistryKey & key, OUString const & path) +{ + RegistryKey subkey; + RegValueType t; + sal_uInt32 s(0); + if (key.openKey(path, subkey) != RegError::NO_ERROR + || subkey.getValueInfo(OUString(), &t, &s) != RegError::NO_ERROR + || t != RegValueType::STRING + || s == 0 || s > o3tl::make_unsigned(SAL_MAX_INT32)) + { + throw css::uno::DeploymentException( + "Failure reading legacy rdb file " + uri, + static_cast< cppu::OWeakObject * >(this)); + } + OUString val; + std::vector< char > v(s); // assuming sal_uInt32 fits into vector::size_type + if (subkey.getValue(OUString(), v.data()) != RegError::NO_ERROR + || v.back() != '\0' + || !rtl_convertStringToUString( + &val.pData, v.data(), static_cast< sal_Int32 >(s - 1), + RTL_TEXTENCODING_UTF8, + (RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_ERROR + | RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_ERROR + | RTL_TEXTTOUNICODE_FLAGS_INVALID_ERROR))) + { + throw css::uno::DeploymentException( + "Failure reading legacy rdb file " + uri, + static_cast< cppu::OWeakObject * >(this)); + } + return val; +} + +void cppuhelper::ServiceManager::readLegacyRdbStrings( + OUString const & uri, RegistryKey & key, OUString const & path, + std::vector< OUString > * strings) +{ + assert(strings != nullptr); + RegistryKey subkey; + switch (key.openKey(path, subkey)) { + case RegError::NO_ERROR: + break; + case RegError::KEY_NOT_EXISTS: + return; + default: + throw css::uno::DeploymentException( + "Failure reading legacy rdb file " + uri, + static_cast< cppu::OWeakObject * >(this)); + } + OUString prefix(subkey.getName() + "/"); + RegistryKeyNames names; + if (subkey.getKeyNames(OUString(), names) != RegError::NO_ERROR) { + throw css::uno::DeploymentException( + "Failure reading legacy rdb file " + uri, + static_cast< cppu::OWeakObject * >(this)); + } + for (sal_uInt32 i = 0; i != names.getLength(); ++i) { + assert(names.getElement(i).match(prefix)); + strings->push_back(names.getElement(i).copy(prefix.getLength())); + } +} + +void cppuhelper::ServiceManager::insertRdbFiles( + std::vector< OUString > const & uris, + css::uno::Reference< css::uno::XComponentContext > const & alienContext) +{ + Data extra; + for (const auto& rUri : uris) + { + try { + Parser(rUri, alienContext, &extra); + } catch (css::container::NoSuchElementException &) { + throw css::lang::IllegalArgumentException( + rUri + ": no such file", static_cast< cppu::OWeakObject * >(this), + 0); + } catch (css::registry::InvalidRegistryException & e) { + throw css::lang::IllegalArgumentException( + "InvalidRegistryException: " + e.Message, + static_cast< cppu::OWeakObject * >(this), 0); + } + } + insertExtraData(extra); +} + +void cppuhelper::ServiceManager::insertLegacyFactory( + css::uno::Reference< css::lang::XServiceInfo > const & factoryInfo) +{ + assert(factoryInfo.is()); + OUString name(factoryInfo->getImplementationName()); + css::uno::Reference< css::lang::XSingleComponentFactory > f1( + factoryInfo, css::uno::UNO_QUERY); + css::uno::Reference< css::lang::XSingleServiceFactory > f2; + if (!f1.is()) { + f2.set(factoryInfo, css::uno::UNO_QUERY); + if (!f2.is()) { + throw css::lang::IllegalArgumentException( + ("Bad XServiceInfo argument implements neither" + " XSingleComponentFactory nor XSingleServiceFactory"), + static_cast< cppu::OWeakObject * >(this), 0); + } + } + css::uno::Reference< css::lang::XComponent > comp( + factoryInfo, css::uno::UNO_QUERY); + std::shared_ptr< Data::Implementation > impl = + std::make_shared(name, f1, f2, comp); + Data extra; + if (!name.isEmpty()) { + extra.namedImplementations.emplace(name, impl); + } + extra.dynamicImplementations.emplace(factoryInfo, impl); + const css::uno::Sequence< OUString > services( + factoryInfo->getSupportedServiceNames()); + for (const auto & i : services) { + impl->services.push_back(i); + extra.services[i].push_back(impl); + } + if (insertExtraData(extra) && comp.is()) { + comp->addEventListener(this); + } +} + +bool cppuhelper::ServiceManager::insertExtraData(Data const & extra) { + { + osl::MutexGuard g(rBHelper.rMutex); + if (isDisposed()) { + return false; + } + auto i = std::find_if(extra.namedImplementations.begin(), extra.namedImplementations.end(), + [this](const Data::NamedImplementations::value_type& rEntry) { + return data_.namedImplementations.find(rEntry.first) != data_.namedImplementations.end(); }); + if (i != extra.namedImplementations.end()) + { + throw css::lang::IllegalArgumentException( + "Insert duplicate implementation name " + i->first, + static_cast< cppu::OWeakObject * >(this), 0); + } + bool bDuplicate = std::any_of(extra.dynamicImplementations.begin(), extra.dynamicImplementations.end(), + [this](const Data::DynamicImplementations::value_type& rEntry) { + return data_.dynamicImplementations.find(rEntry.first) != data_.dynamicImplementations.end(); }); + if (bDuplicate) + { + throw css::lang::IllegalArgumentException( + "Insert duplicate factory object", + static_cast< cppu::OWeakObject * >(this), 0); + } + //TODO: The below leaves data_ in an inconsistent state upon exceptions: + data_.namedImplementations.insert( + extra.namedImplementations.begin(), + extra.namedImplementations.end()); + data_.dynamicImplementations.insert( + extra.dynamicImplementations.begin(), + extra.dynamicImplementations.end()); + insertImplementationMap(&data_.services, extra.services); + insertImplementationMap(&data_.singletons, extra.singletons); + } + //TODO: Updating the component context singleton data should be part of the + // atomic service manager update: + if (!extra.singletons.empty()) { + assert(context_.is()); + css::uno::Reference< css::container::XNameContainer > cont( + context_, css::uno::UNO_QUERY_THROW); + for (const auto& [rName, rImpls] : extra.singletons) + { + OUString name("/singletons/" + rName); + //TODO: Update should be atomic: + try { + cont->removeByName(name + "/arguments"); + } catch (const css::container::NoSuchElementException &) {} + assert(!rImpls.empty()); + assert(rImpls[0].get() != nullptr); + SAL_INFO_IF( + rImpls.size() > 1, "cppuhelper", + "Arbitrarily choosing " << rImpls[0]->name + << " among multiple implementations for singleton " + << rName); + try { + cont->insertByName( + name + "/service", css::uno::Any(rImpls[0]->name)); + } catch (css::container::ElementExistException &) { + cont->replaceByName( + name + "/service", css::uno::Any(rImpls[0]->name)); + } + try { + cont->insertByName(name, css::uno::Any()); + } catch (css::container::ElementExistException &) { + SAL_INFO("cppuhelper", "Overwriting singleton " << rName); + cont->replaceByName(name, css::uno::Any()); + } + } + } + return true; +} + +void cppuhelper::ServiceManager::removeRdbFiles( + std::vector< OUString > const & uris) +{ + // The underlying data structures make this function somewhat inefficient, + // but the assumption is that it is rarely called (and that if it is called, + // it is called with a uris vector of size one): + std::vector< std::shared_ptr< Data::Implementation > > clear; + { + osl::MutexGuard g(rBHelper.rMutex); + for (const auto& rUri : uris) + { + for (Data::NamedImplementations::iterator j( + data_.namedImplementations.begin()); + j != data_.namedImplementations.end();) + { + assert(j->second.get() != nullptr); + if (j->second->rdbFile == rUri) { + clear.push_back(j->second); + //TODO: The below leaves data_ in an inconsistent state upon + // exceptions: + removeFromImplementationMap( + &data_.services, j->second->services, j->second); + removeFromImplementationMap( + &data_.singletons, j->second->singletons, + j->second); + j = data_.namedImplementations.erase(j); + } else { + ++j; + } + } + } + } + //TODO: Update the component context singleton data +} + +bool cppuhelper::ServiceManager::removeLegacyFactory( + css::uno::Reference< css::lang::XServiceInfo > const & factoryInfo, + bool removeListener) +{ + assert(factoryInfo.is()); + std::shared_ptr< Data::Implementation > clear; + css::uno::Reference< css::lang::XComponent > comp; + { + osl::MutexGuard g(rBHelper.rMutex); + Data::DynamicImplementations::iterator i( + data_.dynamicImplementations.find(factoryInfo)); + if (i == data_.dynamicImplementations.end()) { + return isDisposed(); + } + assert(i->second.get() != nullptr); + clear = i->second; + if (removeListener) { + comp = i->second->component; + } + //TODO: The below leaves data_ in an inconsistent state upon exceptions: + removeFromImplementationMap( + &data_.services, i->second->services, i->second); + removeFromImplementationMap( + &data_.singletons, i->second->singletons, i->second); + if (!i->second->name.isEmpty()) { + data_.namedImplementations.erase(i->second->name); + } + data_.dynamicImplementations.erase(i); + } + if (comp.is()) { + removeEventListenerFromComponent(comp); + } + return true; +} + +void cppuhelper::ServiceManager::removeImplementation(const OUString & name) { + // The underlying data structures make this function somewhat inefficient, + // but the assumption is that it is rarely called: + std::shared_ptr< Data::Implementation > clear; + { + osl::MutexGuard g(rBHelper.rMutex); + if (isDisposed()) { + return; + } + Data::NamedImplementations::iterator i( + data_.namedImplementations.find(name)); + if (i == data_.namedImplementations.end()) { + throw css::container::NoSuchElementException( + "Remove non-inserted implementation " + name, + static_cast< cppu::OWeakObject * >(this)); + } + assert(i->second.get() != nullptr); + clear = i->second; + //TODO: The below leaves data_ in an inconsistent state upon exceptions: + removeFromImplementationMap( + &data_.services, i->second->services, i->second); + removeFromImplementationMap( + &data_.singletons, i->second->singletons, i->second); + auto j = std::find_if(data_.dynamicImplementations.begin(), data_.dynamicImplementations.end(), + [&i](const Data::DynamicImplementations::value_type& rEntry) { return rEntry.second == i->second; }); + if (j != data_.dynamicImplementations.end()) + data_.dynamicImplementations.erase(j); + data_.namedImplementations.erase(i); + } +} + +std::shared_ptr< cppuhelper::ServiceManager::Data::Implementation > +cppuhelper::ServiceManager::findServiceImplementation( + css::uno::Reference< css::uno::XComponentContext > const & context, + OUString const & specifier) +{ + std::shared_ptr< Data::Implementation > impl; + bool loaded; + { + osl::MutexGuard g(rBHelper.rMutex); + Data::ImplementationMap::const_iterator i( + data_.services.find(specifier)); + if (i == data_.services.end()) { + Data::NamedImplementations::const_iterator j( + data_.namedImplementations.find(specifier)); + if (j == data_.namedImplementations.end()) { + SAL_INFO("cppuhelper", "No implementation for " << specifier); + return std::shared_ptr< Data::Implementation >(); + } + impl = j->second; + } else { + assert(!i->second.empty()); + SAL_INFO_IF( + i->second.size() > 1, "cppuhelper", + "Arbitrarily choosing " << i->second[0]->name + << " among multiple implementations for " << i->first); + impl = i->second[0]; + } + assert(impl.get() != nullptr); + loaded = impl->status == Data::Implementation::STATUS_LOADED; + } + if (!loaded) { + loadImplementation(context, impl); + } + return impl; +} + +/// Make a simpler unique name for preload / progress reporting. +#ifndef DISABLE_DYNLOADING +static OUString simplifyModule(const OUString &uri) +{ + sal_Int32 nIdx; + OUStringBuffer edit(uri); + if ((nIdx = edit.lastIndexOf('/')) > 0) + edit.remove(0,nIdx+1); + if ((nIdx = edit.lastIndexOf(':')) > 0) + edit.remove(0,nIdx+1); + if ((nIdx = edit.lastIndexOf("lo.so")) > 0) + edit.truncate(nIdx); + if ((nIdx = edit.lastIndexOf(".3")) > 0) + edit.truncate(nIdx); + if ((nIdx = edit.lastIndexOf("gcc3.so")) > 0) + edit.truncate(nIdx); + if ((nIdx = edit.lastIndexOf(".so")) > 0) + edit.truncate(nIdx); + if ((nIdx = edit.lastIndexOf("_uno")) > 0) + edit.truncate(nIdx); + if ((nIdx = edit.lastIndexOf(".jar")) > 0) + edit.truncate(nIdx); + if (edit.indexOf("lib") == 0) + edit.remove(0,3); + return edit.makeStringAndClear(); +} +#endif + +/// Used only by LibreOfficeKit when used by Online to pre-initialize +void cppuhelper::ServiceManager::preloadImplementations() { +#ifdef DISABLE_DYNLOADING + abort(); +#else + OUString aUri; + osl::MutexGuard g(rBHelper.rMutex); + css::uno::Environment aSourceEnv(css::uno::Environment::getCurrent()); + + std::cerr << "preload:"; + std::vector aReported; + std::vector aDisabled; + OUStringBuffer aDisabledMsg; + OUStringBuffer aMissingMsg; + + /// Allow external callers & testers to disable certain components + const char *pDisable = getenv("UNODISABLELIBRARY"); + if (pDisable) + { + OUString aDisable(pDisable, strlen(pDisable), RTL_TEXTENCODING_UTF8); + for (sal_Int32 i = 0; i >= 0; ) + { + OUString tok = aDisable.getToken(0, ' ', i); + tok = tok.trim(); + if (!tok.isEmpty()) + aDisabled.push_back(tok); + } + } + + // loop all implementations + for (const auto& rEntry : data_.namedImplementations) + { + if (rEntry.second->loader != "com.sun.star.loader.SharedLibrary" || + rEntry.second->status == Data::Implementation::STATUS_LOADED) + continue; + + OUString simplified; + try + { + const OUString &aLibrary = rEntry.second->uri; + + if (aLibrary.isEmpty()) + continue; + + simplified = simplifyModule(aLibrary); + + bool bDisabled = + std::find(aDisabled.begin(), aDisabled.end(), simplified) != aDisabled.end(); + + if (std::find(aReported.begin(), aReported.end(), aLibrary) == aReported.end()) + { + if (bDisabled) + { + aDisabledMsg.append(simplified); + aDisabledMsg.append(" "); + } + else + { + std::cerr << " " << simplified; + std::cerr.flush(); + } + aReported.push_back(aLibrary); + } + + if (bDisabled) + continue; + + // expand absolute URI implementation component library + aUri = cppu::bootstrap_expandUri(aLibrary); + } + catch (css::lang::IllegalArgumentException& aError) + { + throw css::uno::DeploymentException( + "Cannot expand URI" + rEntry.second->uri + ": " + aError.Message, + static_cast< cppu::OWeakObject * >(this)); + } + + // load component library + osl::Module aModule(aUri, SAL_LOADMODULE_NOW | SAL_LOADMODULE_GLOBAL); + + if (!aModule.is()) + { + aMissingMsg.append(simplified); + aMissingMsg.append(" "); + } + + if (aModule.is() && + !rEntry.second->environment.isEmpty()) + { + OUString aSymFactory; + oslGenericFunction fpFactory; + css::uno::Environment aTargetEnv; + css::uno::Reference xFactory; + + if(rEntry.second->constructorName.isEmpty()) + { + // expand full name component factory symbol + if (rEntry.second->prefix == "direct") + aSymFactory = rEntry.second->name.replace('.', '_') + "_" COMPONENT_GETFACTORY; + else if (!rEntry.second->prefix.isEmpty()) + aSymFactory = rEntry.second->prefix + "_" COMPONENT_GETFACTORY; + else + aSymFactory = COMPONENT_GETFACTORY; + + // get function symbol component factory + fpFactory = aModule.getFunctionSymbol(aSymFactory); + if (fpFactory == nullptr) + { + throw css::loader::CannotActivateFactoryException( + ("no factory symbol \"" + aSymFactory + "\" in component library :" + aUri), + css::uno::Reference()); + } + + aTargetEnv = cppuhelper::detail::getEnvironment(rEntry.second->environment, rEntry.second->name); + component_getFactoryFunc fpComponentFactory = reinterpret_cast(fpFactory); + + if (aSourceEnv.get() == aTargetEnv.get()) + { + // invoke function component factory + OString aImpl(OUStringToOString(rEntry.second->name, RTL_TEXTENCODING_ASCII_US)); + xFactory.set(css::uno::Reference(static_cast( + (*fpComponentFactory)(aImpl.getStr(), this, nullptr)), SAL_NO_ACQUIRE)); + } + } + else + { + // get function symbol component factory + aTargetEnv = cppuhelper::detail::getEnvironment(rEntry.second->environment, rEntry.second->name); + fpFactory = (aSourceEnv.get() == aTargetEnv.get()) ? + aModule.getFunctionSymbol(rEntry.second->constructorName) : nullptr; + } + + css::uno::Reference xSCFactory; + css::uno::Reference xSSFactory; + + // query interface XSingleComponentFactory or XSingleServiceFactory + if (xFactory.is()) + { + xSCFactory.set(xFactory, css::uno::UNO_QUERY); + if (!xSCFactory.is()) + { + xSSFactory.set(xFactory, css::uno::UNO_QUERY); + if (!xSSFactory.is()) + throw css::uno::DeploymentException( + ("Implementation " + rEntry.second->name + + " does not provide a constructor or factory"), + static_cast< cppu::OWeakObject * >(this)); + } + } + + if (!rEntry.second->constructorName.isEmpty() && fpFactory) + rEntry.second->constructorFn = WrapperConstructorFn(reinterpret_cast(fpFactory)); + + rEntry.second->factory1 = xSCFactory; + rEntry.second->factory2 = xSSFactory; + rEntry.second->status = Data::Implementation::STATUS_LOADED; + + } + + // Some libraries use other (non-UNO) libraries requiring preinit + oslGenericFunction fpPreload = aModule.getFunctionSymbol( "lok_preload_hook" ); + if (fpPreload) + { + static std::vector aPreloaded; + if (std::find(aPreloaded.begin(), aPreloaded.end(), fpPreload) == aPreloaded.end()) + { + aPreloaded.push_back(fpPreload); + fpPreload(); + } + } + + // leak aModule + aModule.release(); + } + std::cerr << std::endl; + + if (aMissingMsg.getLength() > 0) + { + OUString aMsg = aMissingMsg.makeStringAndClear(); + std::cerr << "Absent (often optional): " << aMsg << "\n"; + } + if (aDisabledMsg.getLength() > 0) + { + OUString aMsg = aDisabledMsg.makeStringAndClear(); + std::cerr << "Disabled: " << aMsg << "\n"; + } + std::cerr.flush(); + + // Various rather important uno mappings. + static struct { + const char *mpFrom; + const char *mpTo; + const char *mpPurpose; + } const aMappingLoad[] = { + { "gcc3", "uno", "" }, + { "uno", "gcc3", "" }, + }; + + static std::vector maMaps; + for (auto &it : aMappingLoad) + { + maMaps.push_back(css::uno::Mapping( + OUString::createFromAscii(it.mpFrom), + OUString::createFromAscii(it.mpTo), + OUString::createFromAscii(it.mpPurpose))); + } +#endif +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/servicemanager.hxx b/cppuhelper/source/servicemanager.hxx new file mode 100644 index 000000000..ceac7c15a --- /dev/null +++ b/cppuhelper/source/servicemanager.hxx @@ -0,0 +1,351 @@ +/* -*- 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/. + */ + +#ifndef INCLUDED_CPPUHELPER_SOURCE_SERVICEMANAGER_HXX +#define INCLUDED_CPPUHELPER_SOURCE_SERVICEMANAGER_HXX + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star::lang { + class XSingleComponentFactory; +} +namespace cppu { struct ContextEntry_Init; } +namespace com :: sun :: star :: lang { class XSingleServiceFactory; } +namespace com :: sun :: star :: uno { class XComponentContext; } + +class RegistryKey; + +namespace cppuhelper { + +extern "C" { + +typedef css::uno::XInterface * ImplementationConstructorFn( + css::uno::XComponentContext *, css::uno::Sequence const &); + +} + +typedef std::function const&)> WrapperConstructorFn; + +typedef cppu::WeakComponentImplHelper< + css::lang::XServiceInfo, css::lang::XMultiServiceFactory, + css::lang::XMultiComponentFactory, css::container::XSet, + css::container::XContentEnumerationAccess, css::beans::XPropertySet, + css::beans::XPropertySetInfo, css::lang::XEventListener, + css::lang::XInitialization> +ServiceManagerBase; + +class ServiceManager: + private cppu::BaseMutex, public ServiceManagerBase +{ +public: + struct Data { + Data() = default; + Data(const Data&) = delete; + const Data& operator=(const Data&) = delete; + + struct Implementation { + Implementation( + OUString const & theName, OUString const & theLoader, + OUString const & theUri, OUString const & theEnvironment, + OUString const & theConstructorName, + OUString const & thePrefix, + css::uno::Reference< css::uno::XComponentContext > const & + theAlienContext, + OUString const & theRdbFile): + name(theName), loader(theLoader), uri(theUri), environment(theEnvironment), + constructorName(theConstructorName), prefix(thePrefix), + alienContext(theAlienContext), rdbFile(theRdbFile), + constructorFn(nullptr), status(STATUS_NEW), dispose(true) + {} + + Implementation( + OUString const & theName, + css::uno::Reference< css::lang::XSingleComponentFactory > + const & theFactory1, + css::uno::Reference< css::lang::XSingleServiceFactory > const & + theFactory2, + css::uno::Reference< css::lang::XComponent > const & + theComponent): + name(theName), constructorFn(nullptr), + factory1(theFactory1), factory2(theFactory2), + component(theComponent), status(STATUS_LOADED), dispose(true) + { assert(theFactory1.is() || theFactory2.is()); } + + Implementation(const Implementation&) = delete; + const Implementation& operator=(const Implementation&) = delete; + + css::uno::Reference createInstance( + css::uno::Reference const & + context, + bool singletonRequest); + + css::uno::Reference + createInstanceWithArguments( + css::uno::Reference const & + context, + bool singletonRequest, + css::uno::Sequence const & arguments); + + enum Status { STATUS_NEW, STATUS_WRAPPER, STATUS_LOADED }; + + // Logically, exactly one of constructorFn, factory1, factory2 should + // be set. However, there are two exceptions: For one, when + // constructorFn is set, ServiceManager::createContentEnumeration will + // store the necessary ImplementationWrapper in factory1 (so that + // multiple calls to createContentEnumeration will return the same + // wrapper). For another, when factory1 should be set but status is + // STATUS_NEW, factory1 is not yet set (and when status is + // STATUS_WRAPPER, factory1 is merely set to an + // ImplementationWrapper---also due to a + // ServiceManager::createContentEnumeration call---and will be + // loaded later). + OUString name; + OUString loader; + OUString uri; + OUString environment; + OUString constructorName; + OUString prefix; + css::uno::Reference< css::uno::XComponentContext > alienContext; + OUString rdbFile; + std::vector< OUString > services; + std::vector< OUString > singletons; + WrapperConstructorFn constructorFn; + css::uno::Reference< css::lang::XSingleComponentFactory > factory1; + css::uno::Reference< css::lang::XSingleServiceFactory > factory2; + css::uno::Reference< css::lang::XComponent > component; + Status status; + + osl::Mutex mutex; + css::uno::Reference< css::lang::XComponent > disposeSingleton; + bool dispose; + + private: + void updateDisposeSingleton( + bool singletonRequest, + css::uno::Reference const & instance); + }; + + typedef std::map< OUString, std::shared_ptr< Implementation > > + NamedImplementations; + + typedef + std::map< + css::uno::Reference< css::lang::XServiceInfo >, + std::shared_ptr< Implementation > > + DynamicImplementations; + + typedef + std::map< + OUString, + std::vector< std::shared_ptr< Implementation > > > + ImplementationMap; + + NamedImplementations namedImplementations; + DynamicImplementations dynamicImplementations; + ImplementationMap services; + ImplementationMap singletons; + }; + + ServiceManager(): ServiceManagerBase(m_aMutex) {} + + ServiceManager(const ServiceManager&) = delete; + const ServiceManager& operator=(const ServiceManager&) = delete; + + using ServiceManagerBase::acquire; + using ServiceManagerBase::release; + + void init(OUString const & rdbUris); + + void setContext( + css::uno::Reference< css::uno::XComponentContext > const & context) + { + assert(context.is()); + assert(!context_.is()); + context_ = context; + } + + void addSingletonContextEntries( + std::vector< cppu::ContextEntry_Init > * entries); + + css::uno::Reference< css::uno::XComponentContext > const & getContext() + const + { + assert(context_.is()); + return context_; + } + + void loadImplementation( + css::uno::Reference< css::uno::XComponentContext > const & context, + std::shared_ptr< Data::Implementation > const & implementation); + +private: + virtual ~ServiceManager() override; + + virtual void SAL_CALL disposing() override; + + virtual OUString SAL_CALL getImplementationName() override; + + virtual sal_Bool SAL_CALL supportsService(OUString const & ServiceName) override; + + virtual css::uno::Sequence< OUString > SAL_CALL + getSupportedServiceNames() override; + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstance( + OUString const & aServiceSpecifier) override; + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL + createInstanceWithArguments( + OUString const & ServiceSpecifier, + css::uno::Sequence< css::uno::Any > const & Arguments) override; + + virtual css::uno::Sequence< OUString > SAL_CALL + getAvailableServiceNames() override; + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL + createInstanceWithContext( + OUString const & aServiceSpecifier, + css::uno::Reference< css::uno::XComponentContext > const & Context) override; + + virtual css::uno::Reference< css::uno::XInterface > SAL_CALL + createInstanceWithArgumentsAndContext( + OUString const & ServiceSpecifier, + css::uno::Sequence< css::uno::Any > const & Arguments, + css::uno::Reference< css::uno::XComponentContext > const & Context) override; + + virtual css::uno::Type SAL_CALL getElementType() override; + + virtual sal_Bool SAL_CALL hasElements() override; + + virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL + createEnumeration() override; + + virtual sal_Bool SAL_CALL has(css::uno::Any const & aElement) override; + + virtual void SAL_CALL insert(css::uno::Any const & aElement) override; + + virtual void SAL_CALL remove(css::uno::Any const & aElement) override; + + virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL + createContentEnumeration(OUString const & aServiceName) override; + + virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL + getPropertySetInfo() override; + + virtual void SAL_CALL setPropertyValue( + OUString const & aPropertyName, css::uno::Any const & aValue) override; + + virtual css::uno::Any SAL_CALL getPropertyValue( + OUString const & PropertyName) override; + + virtual void SAL_CALL addPropertyChangeListener( + OUString const & aPropertyName, + css::uno::Reference< css::beans::XPropertyChangeListener > const & + xListener) override; + + virtual void SAL_CALL removePropertyChangeListener( + OUString const & aPropertyName, + css::uno::Reference< css::beans::XPropertyChangeListener > const & + aListener) override; + + virtual void SAL_CALL addVetoableChangeListener( + OUString const & PropertyName, + css::uno::Reference< css::beans::XVetoableChangeListener > const & + aListener) override; + + virtual void SAL_CALL removeVetoableChangeListener( + OUString const & PropertyName, + css::uno::Reference< css::beans::XVetoableChangeListener > const & + aListener) override; + + virtual css::uno::Sequence< css::beans::Property > SAL_CALL getProperties() override; + + virtual css::beans::Property SAL_CALL getPropertyByName( + OUString const & aName) override; + + virtual sal_Bool SAL_CALL hasPropertyByName(OUString const & Name) override; + + virtual void SAL_CALL disposing(css::lang::EventObject const & Source) override; + + virtual void SAL_CALL initialize( + css::uno::Sequence const & aArguments) + override; + + // needs to be called with rBHelper.rMutex locked: + bool isDisposed() const { return rBHelper.bDisposed || rBHelper.bInDispose; } + + void removeEventListenerFromComponent( + css::uno::Reference< css::lang::XComponent > const & component); + + void readRdbDirectory(OUString const & uri, bool optional); + + void readRdbFile(OUString const & uri, bool optional); + + bool readLegacyRdbFile(OUString const & uri); + + OUString readLegacyRdbString( + OUString const & uri, RegistryKey & key, + OUString const & path); + + void readLegacyRdbStrings( + OUString const & uri, RegistryKey & key, + OUString const & path, std::vector< OUString > * strings); + + void insertRdbFiles( + std::vector< OUString > const & uris, + css::uno::Reference< css::uno::XComponentContext > const & + alientContext); + + void insertLegacyFactory( + css::uno::Reference< css::lang::XServiceInfo > const & factoryInfo); + + bool insertExtraData(Data const & extra); + + void removeRdbFiles(std::vector< OUString > const & uris); + + bool removeLegacyFactory( + css::uno::Reference< css::lang::XServiceInfo > const & factoryInfo, + bool removeListener); + + void removeImplementation(const OUString & name); + + std::shared_ptr< Data::Implementation > findServiceImplementation( + css::uno::Reference< css::uno::XComponentContext > const & context, + OUString const & specifier); + + void preloadImplementations(); + + css::uno::Reference< css::uno::XComponentContext > context_; + Data data_; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/shlib.cxx b/cppuhelper/source/shlib.cxx new file mode 100644 index 000000000..89ce8b855 --- /dev/null +++ b/cppuhelper/source/shlib.cxx @@ -0,0 +1,423 @@ +/* -*- 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 + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "loadsharedlibcomponentfactory.hxx" + +#if defined DISABLE_DYNLOADING +#include +#endif + +css::uno::Environment cppuhelper::detail::getEnvironment( + OUString const & name, OUString const & implementation) +{ + OUString n(name); + if (!implementation.isEmpty()) { + static char const * log = std::getenv("UNO_ENV_LOG"); + if (log != nullptr && *log != 0) { + OString imps(log); + for (sal_Int32 i = 0; i != -1;) { + OString imp(imps.getToken(0, ';', i)); + //TODO: this assumes UNO_ENV_LOG only contains ASCII characters: + if (implementation.equalsAsciiL(imp.getStr(), imp.getLength())) + { + n += ":log"; + break; + } + } + } + } + return css::uno::Environment(n); +} + +namespace { + +#if !defined DISABLE_DYNLOADING + +css::uno::Environment getEnvironmentFromModule( + osl::Module const & module, css::uno::Environment const & target, + OUString const & implementation, OUString const & prefix) +{ + char const * name = nullptr; + css::uno::Environment env; + OUString fullPrefix(prefix); + if (!fullPrefix.isEmpty()) { + fullPrefix += "_"; + } + component_getImplementationEnvironmentExtFunc fp1 + = reinterpret_cast( + module.getFunctionSymbol(fullPrefix + COMPONENT_GETENVEXT)); + if (fp1 != nullptr) { + (*fp1)( + &name, reinterpret_cast(&env), + (OUStringToOString(implementation, RTL_TEXTENCODING_ASCII_US) + .getStr()), + target.get()); + } else { + component_getImplementationEnvironmentFunc fp2 + = reinterpret_cast( + module.getFunctionSymbol(fullPrefix + COMPONENT_GETENV)); + if (fp2 != nullptr) { + (*fp2)(&name, reinterpret_cast(&env)); + } else { + name = CPPU_CURRENT_LANGUAGE_BINDING_NAME; //TODO: fail + } + } + if (!env.is() && name != nullptr) { + env = cppuhelper::detail::getEnvironment( + OUString::createFromAscii(name), implementation); + } + return env; +} + +#endif + +extern "C" void getFactory(va_list * args) { + component_getFactoryFunc fn = va_arg(*args, component_getFactoryFunc); + OString const * implementation = va_arg(*args, OString const *); + void * smgr = va_arg(*args, void *); + void ** factory = va_arg(*args, void **); + *factory = (*fn)(implementation->getStr(), smgr, nullptr); +} + +css::uno::Reference invokeComponentFactory( + css::uno::Environment const & source, css::uno::Environment const & target, + component_getFactoryFunc function, OUString const & uri, + OUString const & implementation, + css::uno::Reference const & serviceManager) +{ + if (!(source.is() && target.is())) { + throw css::loader::CannotActivateFactoryException( + "cannot get environments", + css::uno::Reference()); + } + OString impl( + OUStringToOString(implementation, RTL_TEXTENCODING_ASCII_US)); + if (source.get() == target.get()) { + return css::uno::Reference( + static_cast( + (*function)(impl.getStr(), serviceManager.get(), nullptr)), + SAL_NO_ACQUIRE); + } + css::uno::Mapping mapTo(source, target); + css::uno::Mapping mapFrom(target, source); + if (!(mapTo.is() && mapFrom.is())) { + throw css::loader::CannotActivateFactoryException( + "cannot get mappings", + css::uno::Reference()); + } + void * smgr = mapTo.mapInterface( + serviceManager.get(), + cppu::UnoType::get()); + void * factory = nullptr; + target.invoke(getFactory, function, &impl, smgr, &factory); + if (smgr != nullptr) { + (*target.get()->pExtEnv->releaseInterface)( + target.get()->pExtEnv, smgr); + } + if (factory == nullptr) { + throw css::loader::CannotActivateFactoryException( + ("calling factory function for \"" + implementation + "\" in <" + + uri + "> returned null"), + css::uno::Reference()); + } + css::uno::Reference res; + mapFrom.mapInterface( + reinterpret_cast(&res), factory, + cppu::UnoType::get()); + (*target.get()->pExtEnv->releaseInterface)( + target.get()->pExtEnv, factory); + return res; +} + +#if !defined DISABLE_DYNLOADING + +extern "C" void getInstance(va_list * args) { + cppuhelper::ImplementationConstructorFn * fn = va_arg(*args, cppuhelper::ImplementationConstructorFn *); + void * ctxt = va_arg(*args, void *); + assert(ctxt); + void * argseq = va_arg(*args, void *); + assert(argseq); + void ** instance = va_arg(*args, void **); + assert(instance); + assert(*instance == nullptr); + *instance = (*fn)(static_cast(ctxt), + *static_cast const*>(argseq)); +} + +cppuhelper::WrapperConstructorFn mapConstructorFn( + css::uno::Environment const & source, css::uno::Environment const & target, + cppuhelper::ImplementationConstructorFn *const constructorFunction) +{ + if (!(source.is() && target.is())) { + throw css::loader::CannotActivateFactoryException( + "cannot get environments", + css::uno::Reference()); + } + if (source.get() == target.get()) { + return cppuhelper::WrapperConstructorFn(constructorFunction); + } + // note: it should be valid to capture these mappings because they are + // ref-counted, and the returned closure will always be invoked in the + // "source" environment + css::uno::Mapping mapTo(source, target); + css::uno::Mapping mapFrom(target, source); + if (!(mapTo.is() && mapFrom.is())) { + throw css::loader::CannotActivateFactoryException( + "cannot get mappings", + css::uno::Reference()); + } + return [mapFrom, mapTo, target, constructorFunction] + (css::uno::XComponentContext *const context, css::uno::Sequence const& args) + { + void *const ctxt = mapTo.mapInterface( + context, + cppu::UnoType::get()); + if (args.hasElements()) { + std::abort(); // TODO map args + } + void * instance = nullptr; + target.invoke(getInstance, constructorFunction, ctxt, &args, &instance); + if (ctxt != nullptr) { + (*target.get()->pExtEnv->releaseInterface)( + target.get()->pExtEnv, ctxt); + } + css::uno::XInterface * res = nullptr; + if (instance == nullptr) { + return res; + } + mapFrom.mapInterface( + reinterpret_cast(&res), instance, + cppu::UnoType::get()); + (*target.get()->pExtEnv->releaseInterface)( + target.get()->pExtEnv, instance); + return res; + }; +} + +#endif + +} + +void cppuhelper::detail::loadSharedLibComponentFactory( + OUString const & uri, OUString const & environment, + OUString const & prefix, OUString const & implementation, + OUString const & constructor, + css::uno::Reference const & serviceManager, + WrapperConstructorFn * constructorFunction, + css::uno::Reference * factory) +{ + assert(constructor.isEmpty() || !environment.isEmpty()); + assert( + (constructorFunction == nullptr && constructor.isEmpty()) + || !*constructorFunction); + assert(factory != nullptr && !factory->is()); +#if defined DISABLE_DYNLOADING + assert(!environment.isEmpty()); + if (constructor.isEmpty()) { + css::uno::Environment curEnv(css::uno::Environment::getCurrent()); + css::uno::Environment env(getEnvironment(environment, implementation)); + if (!(curEnv.is() && env.is())) { + throw css::loader::CannotActivateFactoryException( + "cannot get environments", + css::uno::Reference()); + } + if (curEnv.get() != env.get()) { + std::abort();//TODO + } + SAL_INFO("cppuhelper.shlib", "prefix=" << prefix << " implementation=" << implementation << " uri=" << uri); + lib_to_factory_mapping const * map = lo_get_factory_map(); + component_getFactoryFunc fp = 0; + for (int i = 0; map[i].name != 0; ++i) { + if (uri.equalsAscii(map[i].name)) { + fp = map[i].component_getFactory_function; + break; + } + } + if (fp == 0) { + SAL_WARN("cppuhelper", "unknown factory name \"" << uri << "\""); + throw css::loader::CannotActivateFactoryException( + "unknown factory name \"" + uri + "\"", + css::uno::Reference()); + } + *factory = invokeComponentFactory( + css::uno::Environment::getCurrent(), + getEnvironment(environment, implementation), fp, uri, + implementation, serviceManager); + } else { + SAL_INFO("cppuhelper.shlib", "constructor=" << constructor); + lib_to_constructor_mapping const * map = lo_get_constructor_map(); + for (int i = 0; map[i].name != 0; ++i) { + if (constructor.equalsAscii(map[i].name)) { + *constructorFunction + = reinterpret_cast( + map[i].constructor_function); + return; + } + } + SAL_WARN("cppuhelper", "unknown constructor name \"" << constructor << "\""); + throw css::loader::CannotActivateFactoryException( + "unknown constructor name \"" + constructor + "\"", + css::uno::Reference()); + } +#else + osl::Module mod(uri, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL); + if (!mod.is()) { + throw css::loader::CannotActivateFactoryException( + "loading component library <" + uri + "> failed", + css::uno::Reference()); + } + if (constructor.isEmpty()) { + OUString sym; + SAL_INFO("cppuhelper.shlib", "prefix=" << prefix << " implementation=" << implementation << " uri=" << uri); + if (!prefix.isEmpty()) { + sym = prefix + "_" COMPONENT_GETFACTORY; + } else { + sym = COMPONENT_GETFACTORY; + } + oslGenericFunction fp = mod.getFunctionSymbol(sym); + if (fp == nullptr) { + throw css::loader::CannotActivateFactoryException( + ("no factory symbol \"" + sym + "\" in component library <" + + uri + ">"), + css::uno::Reference()); + } + css::uno::Environment curEnv(css::uno::Environment::getCurrent()); + *factory = invokeComponentFactory( + curEnv, + (environment.isEmpty() + ? getEnvironmentFromModule(mod, curEnv, implementation, prefix) + : getEnvironment(environment, implementation)), + reinterpret_cast(fp), uri, implementation, + serviceManager); + } else { + SAL_INFO("cppuhelper.shlib", "constructor=" << constructor); + oslGenericFunction fp = mod.getFunctionSymbol(constructor); + if (fp == nullptr) { + throw css::loader::CannotActivateFactoryException( + ("no constructor symbol \"" + constructor + + "\" in component library <" + uri + ">"), + css::uno::Reference()); + } + css::uno::Environment curEnv(css::uno::Environment::getCurrent()); + *constructorFunction = mapConstructorFn( + curEnv, + (environment.isEmpty() + ? getEnvironmentFromModule(mod, curEnv, implementation, prefix) + : getEnvironment(environment, implementation)), + reinterpret_cast(fp)); + } + mod.release(); +#endif +} + +css::uno::Reference cppu::loadSharedLibComponentFactory( + OUString const & uri, OUString const & rPath, + OUString const & rImplName, + css::uno::Reference const & xMgr, + css::uno::Reference const & xKey) +{ + assert(rPath.isEmpty()); (void) rPath; + assert(!xKey.is()); (void) xKey; + css::uno::Reference fac; + cppuhelper::detail::loadSharedLibComponentFactory( + uri, "", "", rImplName, "", xMgr, nullptr, &fac); + return fac; +} + +#if !defined DISABLE_DYNLOADING + +namespace { + +extern "C" void writeInfo(va_list * args) { + component_writeInfoFunc fn = va_arg(*args, component_writeInfoFunc); + void * smgr = va_arg(*args, void *); + void * key = va_arg(*args, void *); + sal_Bool * ok = va_arg(*args, sal_Bool *); + *ok = (*fn)(smgr, key); +} + +} + +void cppu::writeSharedLibComponentInfo( + OUString const & uri, OUString const & rPath, + css::uno::Reference const & xMgr, + css::uno::Reference const & xKey) +{ + assert(rPath.isEmpty()); (void) rPath; + osl::Module mod(uri, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL); + if (!mod.is()) { + throw css::registry::CannotRegisterImplementationException( + "loading component library <" + uri + "> failed", + css::uno::Reference()); + } + oslGenericFunction fp = mod.getFunctionSymbol(COMPONENT_WRITEINFO); + if (fp == nullptr) { + throw css::registry::CannotRegisterImplementationException( + ("no symbol \"" COMPONENT_WRITEINFO "\" in component library <" + + uri + ">"), + css::uno::Reference()); + } + css::uno::Environment curEnv(css::uno::Environment::getCurrent()); + css::uno::Environment env(getEnvironmentFromModule(mod, curEnv, "", "")); + if (!(curEnv.is() && env.is())) { + throw css::registry::CannotRegisterImplementationException( + "cannot get environments", + css::uno::Reference()); + } + css::uno::Mapping map(curEnv, env); + if (!map.is()) { + throw css::registry::CannotRegisterImplementationException( + "cannot get mapping", css::uno::Reference()); + } + void * smgr = map.mapInterface( + xMgr.get(), cppu::UnoType::get()); + void * key = map.mapInterface( + xKey.get(), cppu::UnoType::get()); + sal_Bool ok; + env.invoke(writeInfo, fp, smgr, key, &ok); + (*env.get()->pExtEnv->releaseInterface)(env.get()->pExtEnv, key); + if (smgr != nullptr) { + (*env.get()->pExtEnv->releaseInterface)(env.get()->pExtEnv, smgr); + } + if (!ok) { + throw css::registry::CannotRegisterImplementationException( + ("calling \"" COMPONENT_WRITEINFO "\" in component library <" + uri + + "> returned false"), + css::uno::Reference()); + } +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/supportsservice.cxx b/cppuhelper/source/supportsservice.cxx new file mode 100644 index 000000000..eea82602a --- /dev/null +++ b/cppuhelper/source/supportsservice.cxx @@ -0,0 +1,30 @@ +/* -*- 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/. + */ + +#include + +#include +#include + +#include +#include +#include +#include +#include + +bool cppu::supportsService( + css::lang::XServiceInfo * implementation, OUString const & name) +{ + assert(implementation != nullptr); + const css::uno::Sequence< OUString > s( + implementation->getSupportedServiceNames()); + return std::find(s.begin(), s.end(), name) != s.end(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/tdmgr.cxx b/cppuhelper/source/tdmgr.cxx new file mode 100644 index 000000000..1e5826e24 --- /dev/null +++ b/cppuhelper/source/tdmgr.cxx @@ -0,0 +1,660 @@ +/* -*- 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 +#include + +#include + +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using namespace ::com::sun::star; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::reflection; + +namespace cppu +{ + +static typelib_TypeDescription * createCTD( + Reference< container::XHierarchicalNameAccess > const & access, + const Reference< XTypeDescription > & xType ); + + +static typelib_TypeDescription * createCTD( + const Reference< XCompoundTypeDescription > & xType ) +{ + typelib_TypeDescription * pRet = nullptr; + if (xType.is()) + { + typelib_TypeDescription * pBaseType = createCTD( + Reference< XCompoundTypeDescription >::query( xType->getBaseType() ) ); + if (pBaseType) + typelib_typedescription_register( &pBaseType ); + + // construct member init array + const Sequence > & rMemberTypes = xType->getMemberTypes(); + const Sequence< OUString > & rMemberNames = xType->getMemberNames(); + + const Reference< XTypeDescription > * pMemberTypes = rMemberTypes.getConstArray(); + const OUString * pMemberNames = rMemberNames.getConstArray(); + + sal_Int32 nMembers = rMemberTypes.getLength(); + OSL_ENSURE( nMembers == rMemberNames.getLength(), "### lens differ!" ); + + OUString aTypeName( xType->getName() ); + + typelib_CompoundMember_Init * pMemberInits = static_cast(alloca( + sizeof(typelib_CompoundMember_Init) * nMembers )); + + sal_Int32 nPos; + for ( nPos = nMembers; nPos--; ) + { + typelib_CompoundMember_Init & rInit = pMemberInits[nPos]; + rInit.eTypeClass = static_cast(pMemberTypes[nPos]->getTypeClass()); + + OUString aMemberTypeName( pMemberTypes[nPos]->getName() ); + rInit.pTypeName = aMemberTypeName.pData; + rtl_uString_acquire( rInit.pTypeName ); + + // string is held by rMemberNames + rInit.pMemberName = pMemberNames[nPos].pData; + } + + typelib_typedescription_new( + &pRet, + static_cast(xType->getTypeClass()), + aTypeName.pData, + (pBaseType ? pBaseType->pWeakRef : nullptr), + nMembers, pMemberInits ); + + // cleanup + for ( nPos = nMembers; nPos--; ) + { + rtl_uString_release( pMemberInits[nPos].pTypeName ); + } + if (pBaseType) + typelib_typedescription_release( pBaseType ); + } + return pRet; +} + +static typelib_TypeDescription * createCTD( + Reference< container::XHierarchicalNameAccess > const & access, + const Reference< XStructTypeDescription > & xType ) +{ + typelib_TypeDescription * pRet = nullptr; + if (xType.is() && !xType->getTypeParameters().hasElements()) + { + typelib_TypeDescription * pBaseType = createCTD( + access, xType->getBaseType() ); + if (pBaseType) + typelib_typedescription_register( &pBaseType ); + + // construct member init array + const Sequence > & rMemberTypes = xType->getMemberTypes(); + const Sequence< OUString > & rMemberNames = xType->getMemberNames(); + + const Reference< XTypeDescription > * pMemberTypes = rMemberTypes.getConstArray(); + const OUString * pMemberNames = rMemberNames.getConstArray(); + + sal_Int32 nMembers = rMemberTypes.getLength(); + OSL_ENSURE( nMembers == rMemberNames.getLength(), "### lens differ!" ); + + OUString aTypeName( xType->getName() ); + + typelib_StructMember_Init * pMemberInits = static_cast(alloca( + sizeof(typelib_StructMember_Init) * nMembers )); + + Sequence< Reference< XTypeDescription > > templateMemberTypes; + sal_Int32 i = aTypeName.indexOf('<'); + if (i >= 0) { + Reference< XStructTypeDescription > templateDesc( + access->getByHierarchicalName(aTypeName.copy(0, i)), + UNO_QUERY_THROW); + OSL_ASSERT( + templateDesc->getTypeParameters().getLength() + == xType->getTypeArguments().getLength()); + templateMemberTypes = templateDesc->getMemberTypes(); + OSL_ASSERT(templateMemberTypes.getLength() == nMembers); + } + + sal_Int32 nPos; + for ( nPos = nMembers; nPos--; ) + { + typelib_StructMember_Init & rInit = pMemberInits[nPos]; + rInit.aBase.eTypeClass + = static_cast(pMemberTypes[nPos]->getTypeClass()); + + OUString aMemberTypeName( pMemberTypes[nPos]->getName() ); + rInit.aBase.pTypeName = aMemberTypeName.pData; + rtl_uString_acquire( rInit.aBase.pTypeName ); + + // string is held by rMemberNames + rInit.aBase.pMemberName = pMemberNames[nPos].pData; + + rInit.bParameterizedType = templateMemberTypes.hasElements() + && (templateMemberTypes[nPos]->getTypeClass() + == TypeClass_UNKNOWN); + } + + typelib_typedescription_newStruct( + &pRet, + aTypeName.pData, + (pBaseType ? pBaseType->pWeakRef : nullptr), + nMembers, pMemberInits ); + + // cleanup + for ( nPos = nMembers; nPos--; ) + { + rtl_uString_release( pMemberInits[nPos].aBase.pTypeName ); + } + if (pBaseType) + typelib_typedescription_release( pBaseType ); + } + return pRet; +} + +static typelib_TypeDescription * createCTD( + const Reference< XInterfaceAttributeTypeDescription2 > & xAttribute ) +{ + typelib_TypeDescription * pRet = nullptr; + if (xAttribute.is()) + { + OUString aMemberName( xAttribute->getName() ); + Reference< XTypeDescription > xType( xAttribute->getType() ); + OUString aMemberTypeName( xType->getName() ); + std::vector< rtl_uString * > getExc; + const Sequence< Reference< XCompoundTypeDescription > > getExcs( + xAttribute->getGetExceptions() ); + for (const auto & ctd : getExcs) + { + OSL_ASSERT( ctd.is() ); + getExc.push_back( ctd->getName().pData ); + } + std::vector< rtl_uString * > setExc; + const Sequence< Reference< XCompoundTypeDescription > > setExcs( + xAttribute->getSetExceptions() ); + for (const auto & ctd : setExcs) + { + OSL_ASSERT( ctd.is() ); + setExc.push_back( ctd->getName().pData ); + } + typelib_typedescription_newExtendedInterfaceAttribute( + reinterpret_cast(&pRet), + xAttribute->getPosition(), + aMemberName.pData, // name + static_cast(xType->getTypeClass()), + aMemberTypeName.pData, // type name + xAttribute->isReadOnly(), + getExc.size(), getExc.data(), + setExc.size(), setExc.data() ); + } + return pRet; +} + +static typelib_TypeDescription * createCTD( + const Reference< XInterfaceMethodTypeDescription > & xMethod ) +{ + typelib_TypeDescription * pRet = nullptr; + if (xMethod.is()) + { + Reference< XTypeDescription > xReturnType( xMethod->getReturnType() ); + + // init all params + const Sequence > & rParams = xMethod->getParameters(); + const Reference< XMethodParameter > * pParams = rParams.getConstArray(); + sal_Int32 nParams = rParams.getLength(); + + typelib_Parameter_Init * pParamInit = static_cast(alloca( + sizeof(typelib_Parameter_Init) * nParams )); + + sal_Int32 nPos; + for ( nPos = nParams; nPos--; ) + { + const Reference< XMethodParameter > & xParam = pParams[nPos]; + const Reference< XTypeDescription > & xType = xParam->getType(); + typelib_Parameter_Init & rInit = pParamInit[xParam->getPosition()]; + + rInit.eTypeClass = static_cast(xType->getTypeClass()); + OUString aParamTypeName( xType->getName() ); + rInit.pTypeName = aParamTypeName.pData; + rtl_uString_acquire( rInit.pTypeName ); + OUString aParamName( xParam->getName() ); + rInit.pParamName = aParamName.pData; + rtl_uString_acquire( rInit.pParamName ); + rInit.bIn = xParam->isIn(); + rInit.bOut = xParam->isOut(); + } + + // init all exception strings + const Sequence > & rExceptions = xMethod->getExceptions(); + const Reference< XTypeDescription > * pExceptions = rExceptions.getConstArray(); + sal_Int32 nExceptions = rExceptions.getLength(); + rtl_uString ** ppExceptionNames = static_cast(alloca( + sizeof(rtl_uString *) * nExceptions )); + + for ( nPos = nExceptions; nPos--; ) + { + OUString aExceptionTypeName( pExceptions[nPos]->getName() ); + ppExceptionNames[nPos] = aExceptionTypeName.pData; + rtl_uString_acquire( ppExceptionNames[nPos] ); + } + + OUString aTypeName( xMethod->getName() ); + OUString aReturnTypeName( xReturnType->getName() ); + + typelib_typedescription_newInterfaceMethod( + reinterpret_cast(&pRet), + xMethod->getPosition(), + xMethod->isOneway(), + aTypeName.pData, + static_cast(xReturnType->getTypeClass()), + aReturnTypeName.pData, + nParams, pParamInit, + nExceptions, ppExceptionNames ); + + for ( nPos = nParams; nPos--; ) + { + rtl_uString_release( pParamInit[nPos].pTypeName ); + rtl_uString_release( pParamInit[nPos].pParamName ); + } + for ( nPos = nExceptions; nPos--; ) + { + rtl_uString_release( ppExceptionNames[nPos] ); + } + } + return pRet; +} + +static typelib_TypeDescription * createCTD( + Reference< container::XHierarchicalNameAccess > const & access, + const Reference< XInterfaceTypeDescription2 > & xType ) +{ + typelib_TypeDescription * pRet = nullptr; + if (xType.is()) + { + Sequence< Reference< XTypeDescription > > aBases(xType->getBaseTypes()); + sal_Int32 nBases = aBases.getLength(); + // Exploit the fact that a typelib_TypeDescription for an interface type + // is also the typelib_TypeDescriptionReference for that type: + std::unique_ptr< typelib_TypeDescription * []> aBaseTypes( + new typelib_TypeDescription *[nBases]); + for (sal_Int32 i = 0; i < nBases; ++i) { + typelib_TypeDescription * p = createCTD(access, aBases[i]); + OSL_ASSERT( + !TYPELIB_TYPEDESCRIPTIONREFERENCE_ISREALLYWEAK(p->eTypeClass)); + typelib_typedescription_register(&p); + aBaseTypes[i] = p; + } + typelib_TypeDescriptionReference ** pBaseTypeRefs + = reinterpret_cast< typelib_TypeDescriptionReference ** >( + aBaseTypes.get()); + + // construct all member refs + const Sequence > & rMembers = xType->getMembers(); + sal_Int32 nMembers = rMembers.getLength(); + + typelib_TypeDescriptionReference ** ppMemberRefs = static_cast(alloca( + sizeof(typelib_TypeDescriptionReference *) * nMembers )); + + const Reference< XInterfaceMemberTypeDescription > * pMembers = rMembers.getConstArray(); + + OUString aTypeName( xType->getName() ); + + sal_Int32 nPos; + for ( nPos = nMembers; nPos--; ) + { + OUString aMemberTypeName( pMembers[nPos]->getName() ); + ppMemberRefs[nPos] = nullptr; + typelib_typedescriptionreference_new( + ppMemberRefs + nPos, + static_cast(pMembers[nPos]->getTypeClass()), + aMemberTypeName.pData ); + } + + typelib_typedescription_newMIInterface( + reinterpret_cast(&pRet), + aTypeName.pData, + 0, 0, 0, 0, 0, + nBases, pBaseTypeRefs, + nMembers, ppMemberRefs ); + + // cleanup refs and base type + for (int i = 0; i < nBases; ++i) { + typelib_typedescription_release(aBaseTypes[i]); + } + + for ( nPos = nMembers; nPos--; ) + { + typelib_typedescriptionreference_release( ppMemberRefs[nPos] ); + } + } + return pRet; +} + +static typelib_TypeDescription * createCTD( const Reference< XEnumTypeDescription > & xType ) +{ + typelib_TypeDescription * pRet = nullptr; + if (xType.is()) + { + OUString aTypeName( xType->getName() ); + Sequence< OUString > aNames( xType->getEnumNames() ); + OSL_ASSERT( sizeof(OUString) == sizeof(rtl_uString *) ); // !!! + Sequence< sal_Int32 > aValues( xType->getEnumValues() ); + + typelib_typedescription_newEnum( + &pRet, aTypeName.pData, xType->getDefaultEnumValue(), + aNames.getLength(), + const_cast(reinterpret_cast(aNames.getConstArray())), + const_cast< sal_Int32 * >( aValues.getConstArray() ) ); + } + return pRet; +} + +static typelib_TypeDescription * createCTD( + Reference< container::XHierarchicalNameAccess > const & access, + const Reference< XIndirectTypeDescription > & xType ) +{ + typelib_TypeDescription * pRet = nullptr; + if (xType.is()) + { + typelib_TypeDescription * pRefType = createCTD( + access, xType->getReferencedType() ); + typelib_typedescription_register( &pRefType ); + + OUString aTypeName( xType->getName() ); + + typelib_typedescription_new( + &pRet, + static_cast(xType->getTypeClass()), + aTypeName.pData, + pRefType->pWeakRef, + 0, nullptr ); + + // cleanup + typelib_typedescription_release( pRefType ); + } + return pRet; +} + + +static typelib_TypeDescription * createCTD( + Reference< container::XHierarchicalNameAccess > const & access, + const Reference< XTypeDescription > & xType ) +{ + typelib_TypeDescription * pRet = nullptr; + + if (xType.is()) + { + switch (xType->getTypeClass()) + { + // built in types + case TypeClass_VOID: + { + OUString aTypeName("void"); + typelib_typedescription_new( &pRet, typelib_TypeClass_VOID, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_CHAR: + { + OUString aTypeName("char"); + typelib_typedescription_new( &pRet, typelib_TypeClass_CHAR, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_BOOLEAN: + { + OUString aTypeName("boolean"); + typelib_typedescription_new( &pRet, typelib_TypeClass_BOOLEAN, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_BYTE: + { + OUString aTypeName("byte"); + typelib_typedescription_new( &pRet, typelib_TypeClass_BYTE, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_SHORT: + { + OUString aTypeName("short"); + typelib_typedescription_new( &pRet, typelib_TypeClass_SHORT, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_UNSIGNED_SHORT: + { + OUString aTypeName("unsigned short"); + typelib_typedescription_new( &pRet, typelib_TypeClass_UNSIGNED_SHORT, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_LONG: + { + OUString aTypeName("long"); + typelib_typedescription_new( &pRet, typelib_TypeClass_LONG, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_UNSIGNED_LONG: + { + OUString aTypeName("unsigned long"); + typelib_typedescription_new( &pRet, typelib_TypeClass_UNSIGNED_LONG, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_HYPER: + { + OUString aTypeName("hyper"); + typelib_typedescription_new( &pRet, typelib_TypeClass_HYPER, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_UNSIGNED_HYPER: + { + OUString aTypeName("unsigned hyper"); + typelib_typedescription_new( &pRet, typelib_TypeClass_UNSIGNED_HYPER, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_FLOAT: + { + OUString aTypeName("float"); + typelib_typedescription_new( &pRet, typelib_TypeClass_FLOAT, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_DOUBLE: + { + OUString aTypeName("double"); + typelib_typedescription_new( &pRet, typelib_TypeClass_DOUBLE, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_STRING: + { + OUString aTypeName("string"); + typelib_typedescription_new( &pRet, typelib_TypeClass_STRING, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_TYPE: + { + OUString aTypeName("type"); + typelib_typedescription_new( &pRet, typelib_TypeClass_TYPE, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + case TypeClass_ANY: + { + OUString aTypeName("any"); + typelib_typedescription_new( &pRet, typelib_TypeClass_ANY, aTypeName.pData, nullptr, 0, nullptr ); + break; + } + + case TypeClass_EXCEPTION: + pRet = createCTD( Reference< XCompoundTypeDescription >::query( xType ) ); + break; + case TypeClass_STRUCT: + pRet = createCTD( + access, Reference< XStructTypeDescription >::query( xType ) ); + break; + case TypeClass_ENUM: + pRet = createCTD( Reference< XEnumTypeDescription >::query( xType ) ); + break; + case TypeClass_TYPEDEF: + { + Reference< XIndirectTypeDescription > xTypedef( xType, UNO_QUERY ); + if (xTypedef.is()) + pRet = createCTD( access, xTypedef->getReferencedType() ); + break; + } + case TypeClass_SEQUENCE: + pRet = createCTD( + access, Reference< XIndirectTypeDescription >::query( xType ) ); + break; + case TypeClass_INTERFACE: + pRet = createCTD( + access, + Reference< XInterfaceTypeDescription2 >::query( xType ) ); + break; + case TypeClass_INTERFACE_METHOD: + pRet = createCTD( Reference< XInterfaceMethodTypeDescription >::query( xType ) ); + break; + case TypeClass_INTERFACE_ATTRIBUTE: + pRet = createCTD( Reference< XInterfaceAttributeTypeDescription2 >::query( xType ) ); + break; + default: + break; + } + } + + return pRet; +} + + +extern "C" +{ +static void typelib_callback( + void * pContext, typelib_TypeDescription ** ppRet, rtl_uString * pTypeName ) +{ + OSL_ENSURE( pContext && ppRet && pTypeName, "### null ptr!" ); + if (!ppRet) + return; + + if (*ppRet) + { + ::typelib_typedescription_release( *ppRet ); + *ppRet = nullptr; + } + if (!(pContext && pTypeName)) + return; + + Reference< container::XHierarchicalNameAccess > access( + static_cast< container::XHierarchicalNameAccess * >( + pContext)); + try + { + OUString const & rTypeName = OUString::unacquired( &pTypeName ); + Reference< XTypeDescription > xTD; + if (access->getByHierarchicalName(rTypeName ) >>= xTD) + { + *ppRet = createCTD( access, xTD ); + } + } + catch (const container::NoSuchElementException & exc) + { + SAL_INFO("cppuhelper", "typelibrary type not available: " << exc ); + } + catch (const Exception & exc) + { + SAL_INFO("cppuhelper", exc ); + } +} +} + +namespace { + +class EventListenerImpl + : public WeakImplHelper< lang::XEventListener > +{ + Reference< container::XHierarchicalNameAccess > m_xTDMgr; + +public: + explicit EventListenerImpl( + Reference< container::XHierarchicalNameAccess > const & xTDMgr ) + : m_xTDMgr( xTDMgr ) + {} + + // XEventListener + virtual void SAL_CALL disposing( lang::EventObject const & rEvt ) override; +}; + +} + +void EventListenerImpl::disposing( lang::EventObject const & rEvt ) +{ + if (rEvt.Source != m_xTDMgr) { + OSL_ASSERT(false); + } + // deregister of c typelib callback + ::typelib_typedescription_revokeCallback( m_xTDMgr.get(), typelib_callback ); +} + + +sal_Bool SAL_CALL installTypeDescriptionManager( + Reference< container::XHierarchicalNameAccess > const & xTDMgr_c ) +{ + uno::Environment curr_env(Environment::getCurrent()); + uno::Environment target_env(CPPU_CURRENT_LANGUAGE_BINDING_NAME); + + uno::Mapping curr2target(curr_env, target_env); + + + Reference xTDMgr( + static_cast( + curr2target.mapInterface(xTDMgr_c.get(), cppu::UnoType::get())), + SAL_NO_ACQUIRE); + + Reference< lang::XComponent > xComp( xTDMgr, UNO_QUERY ); + if (xComp.is()) + { + xComp->addEventListener( new EventListenerImpl( xTDMgr ) ); + // register c typelib callback + ::typelib_typedescription_registerCallback( xTDMgr.get(), typelib_callback ); + return true; + } + return false; +} + +} // end namespace cppu + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/typemanager.cxx b/cppuhelper/source/typemanager.cxx new file mode 100644 index 000000000..3a3866b60 --- /dev/null +++ b/cppuhelper/source/typemanager.cxx @@ -0,0 +1,2279 @@ +/* -*- 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/. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "paths.hxx" +#include "typemanager.hxx" + +namespace { + +OUString makePrefix(OUString const & name) { + return name.isEmpty() ? name : name + "."; +} + +css::uno::Any resolveTypedefs(css::uno::Any const & type) { + for (css::uno::Any t(type);;) { + css::uno::Reference< css::reflection::XIndirectTypeDescription > ind( + type, css::uno::UNO_QUERY); + if (!ind.is() || ind->getTypeClass() != css::uno::TypeClass_TYPEDEF) { + return t; + } + t <<= ind->getReferencedType(); + } +} + +class SimpleTypeDescription: + public cppu::WeakImplHelper< css::reflection::XTypeDescription > +{ +public: + SimpleTypeDescription( + css::uno::TypeClass typeClass, OUString const & name): + typeClass_(typeClass), name_(name) + {} + +private: + virtual ~SimpleTypeDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return typeClass_; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + css::uno::TypeClass typeClass_; + OUString name_; +}; + +class SequenceTypeDescription: + public cppu::WeakImplHelper< css::reflection::XIndirectTypeDescription > +{ +public: + SequenceTypeDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, OUString const & componentType): + manager_(manager), name_(name), componentType_(componentType) + { assert(manager.is()); } + +private: + virtual ~SequenceTypeDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_SEQUENCE; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getReferencedType() override + { return manager_->resolve(componentType_); } + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + OUString componentType_; +}; + +class PublishableDescription: + public cppu::WeakImplHelper< css::reflection::XPublished > +{ +protected: + explicit PublishableDescription(bool published): published_(published) {} + + virtual ~PublishableDescription() override {} + +private: + virtual sal_Bool SAL_CALL isPublished() override + { return published_; } + + bool published_; +}; + +class ModuleDescription: + public cppu::WeakImplHelper< css::reflection::XModuleTypeDescription > +{ +public: + ModuleDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::ModuleEntity > const & entity): + manager_(manager), name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~ModuleDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_MODULE; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getMembers() override; + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::ModuleEntity > entity_; +}; + +css::uno::Sequence< css::uno::Reference< css::reflection::XTypeDescription > > +ModuleDescription::getMembers() { + try { + std::vector< OUString > names(entity_->getMemberNames()); + assert(names.size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(names.size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = manager_->resolve(makePrefix(name_) + names[i]); + } + return s; + } catch (unoidl::FileFormatException & e) { + throw css::uno::DeploymentException( + e.getUri() + ": " + e.getDetail(), + static_cast< cppu::OWeakObject * >(this)); + } +} + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XEnumTypeDescription > +EnumTypeDescription_Base; + +class EnumTypeDescription: public EnumTypeDescription_Base { +public: + EnumTypeDescription( + OUString const & name, + rtl::Reference< unoidl::EnumTypeEntity > const & entity): + EnumTypeDescription_Base(entity->isPublished()), name_(name), + entity_(entity) + { assert(entity.is()); } + +private: + virtual ~EnumTypeDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_ENUM; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual sal_Int32 SAL_CALL getDefaultEnumValue() override + { return entity_->getMembers()[0].value; } + + virtual css::uno::Sequence< OUString > SAL_CALL getEnumNames() override; + + virtual css::uno::Sequence< sal_Int32 > SAL_CALL getEnumValues() override; + + OUString name_; + rtl::Reference< unoidl::EnumTypeEntity > entity_; +}; + +css::uno::Sequence< OUString > EnumTypeDescription::getEnumNames() +{ + assert(entity_->getMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getMembers().size()); + css::uno::Sequence< OUString > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = entity_->getMembers()[i].name; + } + return s; +} + +css::uno::Sequence< sal_Int32 > EnumTypeDescription::getEnumValues() +{ + assert(entity_->getMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getMembers().size()); + css::uno::Sequence< sal_Int32 > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = entity_->getMembers()[i].value; + } + return s; +} + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XStructTypeDescription > +PlainStructTypeDescription_Base; + +class PlainStructTypeDescription: public PlainStructTypeDescription_Base { +public: + PlainStructTypeDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::PlainStructTypeEntity > const & entity): + PlainStructTypeDescription_Base(entity->isPublished()), + manager_(manager), name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~PlainStructTypeDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_STRUCT; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getBaseType() override { + return entity_->getDirectBase().isEmpty() + ? css::uno::Reference< css::reflection::XTypeDescription >() + : manager_->resolve(entity_->getDirectBase()); + } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getMemberTypes() override; + + virtual css::uno::Sequence< OUString > SAL_CALL getMemberNames() override; + + virtual css::uno::Sequence< OUString > SAL_CALL getTypeParameters() override + { return css::uno::Sequence< OUString >(); } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getTypeArguments() override { + return css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > >(); + } + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::PlainStructTypeEntity > entity_; +}; + +css::uno::Sequence< css::uno::Reference< css::reflection::XTypeDescription > > +PlainStructTypeDescription::getMemberTypes() +{ + assert(entity_->getDirectMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getDirectMembers().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = manager_->resolve(entity_->getDirectMembers()[i].type); + } + return s; +} + +css::uno::Sequence< OUString > PlainStructTypeDescription::getMemberNames() +{ + assert(entity_->getDirectMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getDirectMembers().size()); + css::uno::Sequence< OUString > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = entity_->getDirectMembers()[i].name; + } + return s; +} + +class ParameterizedMemberTypeDescription: + public cppu::WeakImplHelper< css::reflection::XTypeDescription > +{ +public: + explicit ParameterizedMemberTypeDescription( + OUString const & typeParameterName): + typeParameterName_(typeParameterName) + {} + +private: + virtual ~ParameterizedMemberTypeDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_UNKNOWN; } + + virtual OUString SAL_CALL getName() override + { return typeParameterName_; } + + OUString typeParameterName_; +}; + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XStructTypeDescription > +PolymorphicStructTypeTemplateDescription_Base; + +class PolymorphicStructTypeTemplateDescription: + public PolymorphicStructTypeTemplateDescription_Base +{ +public: + PolymorphicStructTypeTemplateDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::PolymorphicStructTypeTemplateEntity > const & + entity): + PolymorphicStructTypeTemplateDescription_Base(entity->isPublished()), + manager_(manager), name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~PolymorphicStructTypeTemplateDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_STRUCT; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getBaseType() override + { return css::uno::Reference< css::reflection::XTypeDescription >(); } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getMemberTypes() override; + + virtual css::uno::Sequence< OUString > SAL_CALL getMemberNames() override; + + virtual css::uno::Sequence< OUString > SAL_CALL getTypeParameters() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getTypeArguments() override { + return css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > >(); + } + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::PolymorphicStructTypeTemplateEntity > entity_; +}; + +css::uno::Sequence< css::uno::Reference< css::reflection::XTypeDescription > > +PolymorphicStructTypeTemplateDescription::getMemberTypes() +{ + assert(entity_->getMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getMembers().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = entity_->getMembers()[i].parameterized + ? new ParameterizedMemberTypeDescription( + entity_->getMembers()[i].type) + : manager_->resolve(entity_->getMembers()[i].type); + } + return s; +} + +css::uno::Sequence< OUString > +PolymorphicStructTypeTemplateDescription::getMemberNames() +{ + assert(entity_->getMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getMembers().size()); + css::uno::Sequence< OUString > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = entity_->getMembers()[i].name; + } + return s; +} + +css::uno::Sequence< OUString > +PolymorphicStructTypeTemplateDescription::getTypeParameters() +{ + assert(entity_->getTypeParameters().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getTypeParameters().size()); + css::uno::Sequence< OUString > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = entity_->getTypeParameters()[i]; + } + return s; +} + +class InstantiatedPolymorphicStructTypeDescription: + public cppu::WeakImplHelper< css::reflection::XStructTypeDescription > +{ +public: + InstantiatedPolymorphicStructTypeDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::PolymorphicStructTypeTemplateEntity > const & + entity, + std::vector< OUString > const & arguments): + manager_(manager), name_(name), entity_(entity), arguments_(arguments) + { + assert(manager.is()); + assert(entity.is()); + assert(arguments.size() == entity->getTypeParameters().size()); + } + +private: + virtual ~InstantiatedPolymorphicStructTypeDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_STRUCT; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getBaseType() override + { return css::uno::Reference< css::reflection::XTypeDescription >(); } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getMemberTypes() override; + + virtual css::uno::Sequence< OUString > SAL_CALL getMemberNames() override; + + virtual css::uno::Sequence< OUString > SAL_CALL getTypeParameters() override + { return css::uno::Sequence< OUString >(); } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getTypeArguments() override; + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::PolymorphicStructTypeTemplateEntity > entity_; + std::vector< OUString > arguments_; +}; + +css::uno::Sequence< css::uno::Reference< css::reflection::XTypeDescription > > +InstantiatedPolymorphicStructTypeDescription::getMemberTypes() +{ + assert(entity_->getMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getMembers().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + OUString type(entity_->getMembers()[i].type); + if (entity_->getMembers()[i].parameterized) { + auto j = std::find(entity_->getTypeParameters().begin(), entity_->getTypeParameters().end(), type); + if (j != entity_->getTypeParameters().end()) { + type = arguments_[j - entity_->getTypeParameters().begin()]; + goto found; + } + assert(false); // this cannot happen //TODO! + found:; + } + s[i] = manager_->resolve(type); + } + return s; +} + +css::uno::Sequence< OUString > +InstantiatedPolymorphicStructTypeDescription::getMemberNames() +{ + assert(entity_->getMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getMembers().size()); + css::uno::Sequence< OUString > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = entity_->getMembers()[i].name; + } + return s; +} +css::uno::Sequence< css::uno::Reference< css::reflection::XTypeDescription > > +InstantiatedPolymorphicStructTypeDescription::getTypeArguments() +{ + assert(arguments_.size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(arguments_.size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = manager_->resolve(arguments_[i]); + } + return s; +} + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XCompoundTypeDescription > +ExceptionTypeDescription_Base; + +class ExceptionTypeDescription: public ExceptionTypeDescription_Base { +public: + ExceptionTypeDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::ExceptionTypeEntity > const & entity): + ExceptionTypeDescription_Base(entity->isPublished()), manager_(manager), + name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~ExceptionTypeDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_EXCEPTION; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getBaseType() override { + return entity_->getDirectBase().isEmpty() + ? css::uno::Reference< css::reflection::XTypeDescription >() + : manager_->resolve(entity_->getDirectBase()); + } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getMemberTypes() override; + + virtual css::uno::Sequence< OUString > SAL_CALL getMemberNames() override; + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::ExceptionTypeEntity > entity_; +}; + +css::uno::Sequence< css::uno::Reference< css::reflection::XTypeDescription > > +ExceptionTypeDescription::getMemberTypes() { + assert(entity_->getDirectMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getDirectMembers().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = manager_->resolve(entity_->getDirectMembers()[i].type); + } + return s; +} + +css::uno::Sequence< OUString > ExceptionTypeDescription::getMemberNames() +{ + assert(entity_->getDirectMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getDirectMembers().size()); + css::uno::Sequence< OUString > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = entity_->getDirectMembers()[i].name; + } + return s; +} + +class AttributeDescription: + public cppu::WeakImplHelper< + css::reflection::XInterfaceAttributeTypeDescription2 > +{ +public: + AttributeDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + unoidl::InterfaceTypeEntity::Attribute const & attribute, + sal_Int32 position): + manager_(manager), name_(name), attribute_(attribute), + position_(position) + { assert(manager.is()); } + +private: + virtual ~AttributeDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_INTERFACE_ATTRIBUTE; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual OUString SAL_CALL getMemberName() override + { return attribute_.name; } + + virtual sal_Int32 SAL_CALL getPosition() override + { return position_; } + + virtual sal_Bool SAL_CALL isReadOnly() override + { return attribute_.readOnly; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getType() override + { return manager_->resolve(attribute_.type); } + + virtual sal_Bool SAL_CALL isBound() override + { return attribute_.bound; } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XCompoundTypeDescription > > + SAL_CALL getGetExceptions() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XCompoundTypeDescription > > + SAL_CALL getSetExceptions() override; + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + unoidl::InterfaceTypeEntity::Attribute attribute_; + sal_Int32 position_; +}; + +css::uno::Sequence< + css::uno::Reference< css::reflection::XCompoundTypeDescription > > +AttributeDescription::getGetExceptions() { + assert(attribute_.getExceptions.size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(attribute_.getExceptions.size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XCompoundTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i].set( + manager_->resolve(attribute_.getExceptions[i]), + css::uno::UNO_QUERY_THROW); + } + return s; +} + +css::uno::Sequence< + css::uno::Reference< css::reflection::XCompoundTypeDescription > > +AttributeDescription::getSetExceptions() { + assert(attribute_.setExceptions.size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(attribute_.setExceptions.size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XCompoundTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i].set( + manager_->resolve(attribute_.setExceptions[i]), + css::uno::UNO_QUERY_THROW); + } + return s; +} + +class MethodParameter: + public cppu::WeakImplHelper< css::reflection::XMethodParameter > +{ +public: + MethodParameter( + rtl::Reference< cppuhelper::TypeManager > const & manager, + unoidl::InterfaceTypeEntity::Method::Parameter const & parameter, + sal_Int32 position): + manager_(manager), parameter_(parameter), position_(position) + { assert(manager.is()); } + +private: + virtual ~MethodParameter() override {} + + virtual OUString SAL_CALL getName() override + { return parameter_.name; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getType() override + { return manager_->resolve(parameter_.type); } + + virtual sal_Bool SAL_CALL isIn() override { + return + (parameter_.direction + == unoidl::InterfaceTypeEntity::Method::Parameter::DIRECTION_IN) + || (parameter_.direction + == unoidl::InterfaceTypeEntity::Method::Parameter:: + DIRECTION_IN_OUT); + } + + virtual sal_Bool SAL_CALL isOut() override { + return + (parameter_.direction + == unoidl::InterfaceTypeEntity::Method::Parameter::DIRECTION_OUT) + || (parameter_.direction + == unoidl::InterfaceTypeEntity::Method::Parameter:: + DIRECTION_IN_OUT); + } + + virtual sal_Int32 SAL_CALL getPosition() override + { return position_; } + + rtl::Reference< cppuhelper::TypeManager > manager_; + unoidl::InterfaceTypeEntity::Method::Parameter parameter_; + sal_Int32 position_; +}; + +class MethodDescription: + public cppu::WeakImplHelper< + css::reflection::XInterfaceMethodTypeDescription > +{ +public: + MethodDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + unoidl::InterfaceTypeEntity::Method const & method, sal_Int32 position): + manager_(manager), name_(name), method_(method), position_(position) + { assert(manager.is()); } + +private: + virtual ~MethodDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_INTERFACE_METHOD; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual OUString SAL_CALL getMemberName() override + { return method_.name; } + + virtual sal_Int32 SAL_CALL getPosition() override + { return position_; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getReturnType() override + { return manager_->resolve(method_.returnType); } + + virtual sal_Bool SAL_CALL isOneway() override + { return false; } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XMethodParameter > > + SAL_CALL getParameters() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getExceptions() override; + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + unoidl::InterfaceTypeEntity::Method method_; + sal_Int32 position_; +}; + +css::uno::Sequence< css::uno::Reference< css::reflection::XMethodParameter > > +MethodDescription::getParameters() { + assert(method_.parameters.size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(method_.parameters.size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XMethodParameter > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = new MethodParameter(manager_, method_.parameters[i], i); + } + return s; +} + +css::uno::Sequence< css::uno::Reference< css::reflection::XTypeDescription > > +MethodDescription::getExceptions() { + assert(method_.exceptions.size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(method_.exceptions.size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = manager_->resolve(method_.exceptions[i]); + } + return s; +} + +class BaseOffset { +public: + explicit BaseOffset( + css::uno::Reference< css::reflection::XInterfaceTypeDescription2 > + const & description); + + BaseOffset(const BaseOffset&) = delete; + const BaseOffset& operator=(const BaseOffset&) = delete; + + sal_Int32 get() const { return offset_; } + +private: + void calculateBases( + css::uno::Reference< css::reflection::XInterfaceTypeDescription2 > + const & description); + + void calculate( + css::uno::Reference< css::reflection::XInterfaceTypeDescription2 > + const & description); + + std::set< OUString > set_; + sal_Int32 offset_; +}; + +BaseOffset::BaseOffset( + css::uno::Reference< css::reflection::XInterfaceTypeDescription2 > const & + description): + offset_(0) +{ + calculateBases(description); +} + +void BaseOffset::calculateBases( + css::uno::Reference< css::reflection::XInterfaceTypeDescription2 > const & + description) +{ + const css::uno::Sequence< + css::uno::Reference < css::reflection::XTypeDescription > > bases( + description->getBaseTypes()); + for (const auto & i : bases) { + calculate( + css::uno::Reference< css::reflection::XInterfaceTypeDescription2 >( + resolveTypedefs(css::uno::makeAny(i)), + css::uno::UNO_QUERY_THROW)); + } +} + +void BaseOffset::calculate( + css::uno::Reference< css::reflection::XInterfaceTypeDescription2 > const & + description) +{ + if (set_.insert(description->getName()).second) { + calculateBases(description); + offset_ += description->getMembers().getLength(); + } +} + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XInterfaceTypeDescription2 > +InterfaceTypeDescription_Base; + +class InterfaceTypeDescription: public InterfaceTypeDescription_Base { +public: + InterfaceTypeDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::InterfaceTypeEntity > const & entity): + InterfaceTypeDescription_Base(entity->isPublished()), manager_(manager), + name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~InterfaceTypeDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_INTERFACE; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getBaseType() override { + return entity_->getDirectMandatoryBases().empty() + ? css::uno::Reference< css::reflection::XTypeDescription >() + : manager_->resolve(entity_->getDirectMandatoryBases()[0].name); + } + + virtual css::uno::Uik SAL_CALL getUik() override + { return css::uno::Uik(); } + + virtual + css::uno::Sequence< + css::uno::Reference< + css::reflection::XInterfaceMemberTypeDescription > > + SAL_CALL getMembers() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getBaseTypes() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > + SAL_CALL getOptionalBaseTypes() override; + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::InterfaceTypeEntity > entity_; +}; + +css::uno::Sequence< + css::uno::Reference< css::reflection::XInterfaceMemberTypeDescription > > +InterfaceTypeDescription::getMembers() { + assert( + entity_->getDirectAttributes().size() <= SAL_MAX_INT32 + && (entity_->getDirectMethods().size() + <= SAL_MAX_INT32 - entity_->getDirectAttributes().size())); + sal_Int32 n1 = static_cast< sal_Int32 >( + entity_->getDirectAttributes().size()); + sal_Int32 n2 = static_cast< sal_Int32 >(entity_->getDirectMethods().size()); + css::uno::Sequence< + css::uno::Reference< + css::reflection::XInterfaceMemberTypeDescription > > s(n1 + n2); + sal_Int32 off = BaseOffset(this).get(); + for (sal_Int32 i = 0; i != n1; ++i) { + s[i] = new AttributeDescription( + manager_, name_ + "::" + entity_->getDirectAttributes()[i].name, + entity_->getDirectAttributes()[i], off + i); + } + for (sal_Int32 i = 0; i != n2; ++i) { + s[n1 + i] = new MethodDescription( + manager_, name_ + "::" + entity_->getDirectMethods()[i].name, + entity_->getDirectMethods()[i], off + n1 + i); + } + return s; +} + +css::uno::Sequence< css::uno::Reference< css::reflection::XTypeDescription > > +InterfaceTypeDescription::getBaseTypes() { + assert(entity_->getDirectMandatoryBases().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >( + entity_->getDirectMandatoryBases().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = manager_->resolve(entity_->getDirectMandatoryBases()[i].name); + } + return s; +} + +css::uno::Sequence< css::uno::Reference< css::reflection::XTypeDescription > > +InterfaceTypeDescription::getOptionalBaseTypes() +{ + assert(entity_->getDirectOptionalBases().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >( + entity_->getDirectOptionalBases().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = manager_->resolve(entity_->getDirectOptionalBases()[i].name); + } + return s; +} + +class ConstantDescription: + public cppu::WeakImplHelper< css::reflection::XConstantTypeDescription > +{ +public: + ConstantDescription( + OUString const & constantGroupName, + unoidl::ConstantGroupEntity::Member const & member); + +private: + virtual ~ConstantDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_CONSTANT; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Any SAL_CALL getConstantValue() override + { return value_; } + + OUString name_; + css::uno::Any value_; +}; + +ConstantDescription::ConstantDescription( + OUString const & constantGroupName, + unoidl::ConstantGroupEntity::Member const & member): + name_(makePrefix(constantGroupName) + member.name) +{ + switch (member.value.type) { + case unoidl::ConstantValue::TYPE_BOOLEAN: + value_ <<= member.value.booleanValue; + break; + case unoidl::ConstantValue::TYPE_BYTE: + value_ <<= member.value.byteValue; + break; + case unoidl::ConstantValue::TYPE_SHORT: + value_ <<= member.value.shortValue; + break; + case unoidl::ConstantValue::TYPE_UNSIGNED_SHORT: + value_ <<= member.value.unsignedShortValue; + break; + case unoidl::ConstantValue::TYPE_LONG: + value_ <<= member.value.longValue; + break; + case unoidl::ConstantValue::TYPE_UNSIGNED_LONG: + value_ <<= member.value.unsignedLongValue; + break; + case unoidl::ConstantValue::TYPE_HYPER: + value_ <<= member.value.hyperValue; + break; + case unoidl::ConstantValue::TYPE_UNSIGNED_HYPER: + value_ <<= member.value.unsignedHyperValue; + break; + case unoidl::ConstantValue::TYPE_FLOAT: + value_ <<= member.value.floatValue; + break; + case unoidl::ConstantValue::TYPE_DOUBLE: + value_ <<= member.value.doubleValue; + break; + default: + for (;;) { std::abort(); } // this cannot happen + } +} + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XConstantsTypeDescription > +ConstantGroupDescription_Base; + +class ConstantGroupDescription: public ConstantGroupDescription_Base { +public: + ConstantGroupDescription( + OUString const & name, + rtl::Reference< unoidl::ConstantGroupEntity > const & entity): + ConstantGroupDescription_Base(entity->isPublished()), name_(name), + entity_(entity) + { assert(entity.is()); } + +private: + virtual ~ConstantGroupDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_CONSTANTS; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XConstantTypeDescription > > + SAL_CALL getConstants() override; + + OUString name_; + rtl::Reference< unoidl::ConstantGroupEntity > entity_; +}; + +css::uno::Sequence< + css::uno::Reference< css::reflection::XConstantTypeDescription > > +ConstantGroupDescription::getConstants() { + assert(entity_->getMembers().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getMembers().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XConstantTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = new ConstantDescription(name_, entity_->getMembers()[i]); + } + return s; +} + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XIndirectTypeDescription > +TypedefDescription_Base; + +class TypedefDescription: public TypedefDescription_Base { +public: + TypedefDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::TypedefEntity > const & entity): + TypedefDescription_Base(entity->isPublished()), manager_(manager), + name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~TypedefDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_TYPEDEF; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getReferencedType() override + { return manager_->resolve(entity_->getType()); } + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::TypedefEntity > entity_; +}; + +class ConstructorParameter: + public cppu::WeakImplHelper< css::reflection::XParameter > +{ +public: + ConstructorParameter( + rtl::Reference< cppuhelper::TypeManager > const & manager, + unoidl::SingleInterfaceBasedServiceEntity::Constructor::Parameter + const & parameter, + sal_Int32 position): + manager_(manager), parameter_(parameter), position_(position) + { assert(manager.is()); } + +private: + virtual ~ConstructorParameter() override {} + + virtual OUString SAL_CALL getName() override + { return parameter_.name; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getType() override + { return manager_->resolve(parameter_.type); } + + virtual sal_Bool SAL_CALL isIn() override + { return true; } + + virtual sal_Bool SAL_CALL isOut() override + { return false; } + + virtual sal_Int32 SAL_CALL getPosition() override + { return position_; } + + virtual sal_Bool SAL_CALL isRestParameter() override + { return parameter_.rest; } + + rtl::Reference< cppuhelper::TypeManager > manager_; + unoidl::SingleInterfaceBasedServiceEntity::Constructor::Parameter + parameter_; + sal_Int32 position_; +}; + +class ConstructorDescription: + public cppu::WeakImplHelper< + css::reflection::XServiceConstructorDescription > +{ +public: + ConstructorDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + unoidl::SingleInterfaceBasedServiceEntity::Constructor const & + constructor): + manager_(manager), constructor_(constructor) + { assert(manager.is()); } + +private: + virtual ~ConstructorDescription() override {} + + virtual sal_Bool SAL_CALL isDefaultConstructor() override + { return constructor_.defaultConstructor; } + + virtual OUString SAL_CALL getName() override + { return constructor_.name; } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XParameter > > + SAL_CALL getParameters() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XCompoundTypeDescription > > + SAL_CALL getExceptions() override; + + rtl::Reference< cppuhelper::TypeManager > manager_; + unoidl::SingleInterfaceBasedServiceEntity::Constructor constructor_; +}; + +css::uno::Sequence< css::uno::Reference< css::reflection::XParameter > > +ConstructorDescription::getParameters() { + assert(constructor_.parameters.size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(constructor_.parameters.size()); + css::uno::Sequence< css::uno::Reference< css::reflection::XParameter > > s( + n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = new ConstructorParameter( + manager_, constructor_.parameters[i], i); + } + return s; +} + +css::uno::Sequence< + css::uno::Reference< css::reflection::XCompoundTypeDescription > > +ConstructorDescription::getExceptions() { + assert(constructor_.exceptions.size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(constructor_.exceptions.size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XCompoundTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i].set( + manager_->resolve(constructor_.exceptions[i]), + css::uno::UNO_QUERY_THROW); + } + return s; +} + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XServiceTypeDescription2 > +SingleInterfaceBasedServiceDescription_Base; + +class SingleInterfaceBasedServiceDescription: + public SingleInterfaceBasedServiceDescription_Base +{ +public: + SingleInterfaceBasedServiceDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::SingleInterfaceBasedServiceEntity > const & + entity): + SingleInterfaceBasedServiceDescription_Base(entity->isPublished()), + manager_(manager), name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~SingleInterfaceBasedServiceDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_SERVICE; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > > + SAL_CALL getMandatoryServices() override + { + return css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > >(); + } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > > + SAL_CALL getOptionalServices() override + { + return css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > >(); + } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XInterfaceTypeDescription > > + SAL_CALL getMandatoryInterfaces() override + { + return css::uno::Sequence< + css::uno::Reference< + css::reflection::XInterfaceTypeDescription > >(); + } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XInterfaceTypeDescription > > + SAL_CALL getOptionalInterfaces() override + { + return css::uno::Sequence< + css::uno::Reference< + css::reflection::XInterfaceTypeDescription > >(); + } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XPropertyTypeDescription > > + SAL_CALL getProperties() override + { + return css::uno::Sequence< + css::uno::Reference< + css::reflection::XPropertyTypeDescription > >(); + } + + virtual sal_Bool SAL_CALL isSingleInterfaceBased() override + { return true; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getInterface() override + { return manager_->resolve(entity_->getBase()); } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceConstructorDescription > > + SAL_CALL getConstructors() override; + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::SingleInterfaceBasedServiceEntity > entity_; +}; + +css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceConstructorDescription > > +SingleInterfaceBasedServiceDescription::getConstructors() +{ + assert(entity_->getConstructors().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >(entity_->getConstructors().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceConstructorDescription > > + s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = new ConstructorDescription( + manager_, entity_->getConstructors()[i]); + } + return s; +} + +class PropertyDescription: + public cppu::WeakImplHelper< css::reflection::XPropertyTypeDescription > +{ +public: + PropertyDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + unoidl::AccumulationBasedServiceEntity::Property const & property): + manager_(manager), property_(property) + { assert(manager.is()); } + +private: + virtual ~PropertyDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_PROPERTY; } + + virtual OUString SAL_CALL getName() override + { return property_.name; } + + virtual sal_Int16 SAL_CALL getPropertyFlags() override + { return property_.attributes; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getPropertyTypeDescription() override + { return manager_->resolve(property_.type); } + + rtl::Reference< cppuhelper::TypeManager > manager_; + unoidl::AccumulationBasedServiceEntity::Property property_; +}; + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XServiceTypeDescription2 > +AccumulationBasedServiceDescription_Base; + +class AccumulationBasedServiceDescription: + public AccumulationBasedServiceDescription_Base +{ +public: + AccumulationBasedServiceDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::AccumulationBasedServiceEntity > const & + entity): + AccumulationBasedServiceDescription_Base(entity->isPublished()), + manager_(manager), name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~AccumulationBasedServiceDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_SERVICE; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > > + SAL_CALL getMandatoryServices() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > > + SAL_CALL getOptionalServices() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XInterfaceTypeDescription > > + SAL_CALL getMandatoryInterfaces() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XInterfaceTypeDescription > > + SAL_CALL getOptionalInterfaces() override; + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XPropertyTypeDescription > > + SAL_CALL getProperties() override; + + virtual sal_Bool SAL_CALL isSingleInterfaceBased() override + { return false; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + getInterface() override + { return css::uno::Reference< css::reflection::XTypeDescription >(); } + + virtual + css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceConstructorDescription > > + SAL_CALL getConstructors() override + { + return css::uno::Sequence< + css::uno::Reference< + css::reflection::XServiceConstructorDescription > >(); + } + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::AccumulationBasedServiceEntity > entity_; +}; + +css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > > +AccumulationBasedServiceDescription::getMandatoryServices() +{ + assert(entity_->getDirectMandatoryBaseServices().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >( + entity_->getDirectMandatoryBaseServices().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i].set( + manager_->resolve( + entity_->getDirectMandatoryBaseServices()[i].name), + css::uno::UNO_QUERY_THROW); + } + return s; +} + +css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > > +AccumulationBasedServiceDescription::getOptionalServices() +{ + assert(entity_->getDirectOptionalBaseServices().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >( + entity_->getDirectOptionalBaseServices().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XServiceTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i].set( + manager_->resolve(entity_->getDirectOptionalBaseServices()[i].name), + css::uno::UNO_QUERY_THROW); + } + return s; +} + +css::uno::Sequence< + css::uno::Reference< css::reflection::XInterfaceTypeDescription > > +AccumulationBasedServiceDescription::getMandatoryInterfaces() +{ + assert(entity_->getDirectMandatoryBaseInterfaces().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >( + entity_->getDirectMandatoryBaseInterfaces().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XInterfaceTypeDescription > > s( + n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i].set( + resolveTypedefs( + manager_->find( + entity_->getDirectMandatoryBaseInterfaces()[i].name)), + css::uno::UNO_QUERY_THROW); + } + return s; +} + +css::uno::Sequence< + css::uno::Reference< css::reflection::XInterfaceTypeDescription > > +AccumulationBasedServiceDescription::getOptionalInterfaces() +{ + assert(entity_->getDirectOptionalBaseInterfaces().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >( + entity_->getDirectOptionalBaseInterfaces().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XInterfaceTypeDescription > > s( + n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i].set( + resolveTypedefs( + manager_->find( + entity_->getDirectOptionalBaseInterfaces()[i].name)), + css::uno::UNO_QUERY_THROW); + } + return s; +} + +css::uno::Sequence< + css::uno::Reference< css::reflection::XPropertyTypeDescription > > +AccumulationBasedServiceDescription::getProperties() +{ + assert(entity_->getDirectProperties().size() <= SAL_MAX_INT32); + sal_Int32 n = static_cast< sal_Int32 >( + entity_->getDirectProperties().size()); + css::uno::Sequence< + css::uno::Reference< css::reflection::XPropertyTypeDescription > > s(n); + for (sal_Int32 i = 0; i != n; ++i) { + s[i] = new PropertyDescription( + manager_, entity_->getDirectProperties()[i]); + } + return s; +} + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XSingletonTypeDescription2 > +InterfaceBasedSingletonDescription_Base; + +class InterfaceBasedSingletonDescription: + public InterfaceBasedSingletonDescription_Base +{ +public: + InterfaceBasedSingletonDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::InterfaceBasedSingletonEntity > const & entity): + InterfaceBasedSingletonDescription_Base(entity->isPublished()), + manager_(manager), name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~InterfaceBasedSingletonDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_SINGLETON; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Reference< css::reflection::XServiceTypeDescription > + SAL_CALL getService() override + { + return + css::uno::Reference< css::reflection::XServiceTypeDescription >(); + } + + virtual sal_Bool SAL_CALL isInterfaceBased() override + { return true; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > + SAL_CALL getInterface() override + { return manager_->resolve(entity_->getBase()); } + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::InterfaceBasedSingletonEntity > entity_; +}; + +typedef cppu::ImplInheritanceHelper< + PublishableDescription, css::reflection::XSingletonTypeDescription2 > +ServiceBasedSingletonDescription_Base; + +class ServiceBasedSingletonDescription: + public ServiceBasedSingletonDescription_Base +{ +public: + ServiceBasedSingletonDescription( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & name, + rtl::Reference< unoidl::ServiceBasedSingletonEntity > const & entity): + ServiceBasedSingletonDescription_Base(entity_->isPublished()), + manager_(manager), name_(name), entity_(entity) + { assert(manager.is()); assert(entity.is()); } + +private: + virtual ~ServiceBasedSingletonDescription() override {} + + virtual css::uno::TypeClass SAL_CALL getTypeClass() override + { return css::uno::TypeClass_SINGLETON; } + + virtual OUString SAL_CALL getName() override + { return name_; } + + virtual css::uno::Reference< css::reflection::XServiceTypeDescription > + SAL_CALL getService() override + { + return css::uno::Reference< css::reflection::XServiceTypeDescription >( + manager_->resolve(entity_->getBase()), css::uno::UNO_QUERY_THROW); + } + + virtual sal_Bool SAL_CALL isInterfaceBased() override + { return false; } + + virtual css::uno::Reference< css::reflection::XTypeDescription > + SAL_CALL getInterface() override + { return css::uno::Reference< css::reflection::XTypeDescription >(); } + + rtl::Reference< cppuhelper::TypeManager > manager_; + OUString name_; + rtl::Reference< unoidl::ServiceBasedSingletonEntity > entity_; +}; + +class Enumeration: + public cppu::WeakImplHelper< css::reflection::XTypeDescriptionEnumeration > +{ +public: + Enumeration( + rtl::Reference< cppuhelper::TypeManager > const & manager, + OUString const & prefix, + rtl::Reference< unoidl::MapCursor > const & cursor, + css::uno::Sequence< css::uno::TypeClass > const & types, bool deep): + manager_(manager), types_(types), deep_(deep) + { + assert(manager.is()); + positions_.push(Position(prefix, cursor)); + findNextMatch(); + } + +private: + virtual ~Enumeration() override {} + + virtual sal_Bool SAL_CALL hasMoreElements() override + { return !positions_.empty(); } + + virtual css::uno::Any SAL_CALL nextElement() override + { return css::uno::makeAny(nextTypeDescription()); } + + virtual css::uno::Reference< css::reflection::XTypeDescription > SAL_CALL + nextTypeDescription() override; + + bool matches(css::uno::TypeClass tc) const; + + void findNextMatch(); + + struct Position { + Position( + OUString const & thePrefix, + rtl::Reference< unoidl::MapCursor > const & theCursor): + prefix(thePrefix), cursor(theCursor) + { assert(theCursor.is()); } + + Position( + OUString const & thePrefix, + rtl::Reference< unoidl::ConstantGroupEntity > const & + theConstantGroup): + prefix(thePrefix), constantGroup(theConstantGroup), + constantGroupIndex(constantGroup->getMembers().begin()) + { assert(theConstantGroup.is()); } + + Position(Position const & other): + prefix(other.prefix), cursor(other.cursor), + constantGroup(other.constantGroup) + { + if (constantGroup.is()) { + constantGroupIndex = other.constantGroupIndex; + } + } + + OUString prefix; + rtl::Reference< unoidl::MapCursor > cursor; + rtl::Reference< unoidl::ConstantGroupEntity > constantGroup; + std::vector< unoidl::ConstantGroupEntity::Member >::const_iterator + constantGroupIndex; + }; + + rtl::Reference< cppuhelper::TypeManager > manager_; + css::uno::Sequence< css::uno::TypeClass > types_; + bool deep_; + + osl::Mutex mutex_; + std::stack< Position > positions_; + OUString current_; +}; + +css::uno::Reference< css::reflection::XTypeDescription > +Enumeration::nextTypeDescription() +{ + OUString name; + { + osl::MutexGuard g(mutex_); + if (positions_.empty()) { + throw css::container::NoSuchElementException( + "exhausted XTypeDescriptionEnumeration", + static_cast< cppu::OWeakObject * >(this)); + } + name = current_; + findNextMatch(); + } + return manager_->resolve(name); +} + +bool Enumeration::matches(css::uno::TypeClass tc) const { + if (!types_.hasElements()) { + return true; + } + for (const auto & i : types_) { + if (i == tc) { + return true; + } + } + return false; +} + +void Enumeration::findNextMatch() { + try { + for (;;) { + assert(!positions_.empty()); + OUString name; + if (positions_.top().cursor.is()) { // root or module + rtl::Reference< unoidl::Entity > ent( + positions_.top().cursor->getNext(&name)); + if (!ent.is()) { + positions_.pop(); + if (positions_.empty()) { + break; + } + continue; + } + name = positions_.top().prefix + name; + css::uno::TypeClass tc; + switch (ent->getSort()) { + case unoidl::Entity::SORT_MODULE: + tc = css::uno::TypeClass_MODULE; + if (deep_) { + positions_.push( + Position( + makePrefix(name), + static_cast< unoidl::ModuleEntity * >( + ent.get())->createCursor())); + } + break; + case unoidl::Entity::SORT_ENUM_TYPE: + tc = css::uno::TypeClass_ENUM; + break; + case unoidl::Entity::SORT_PLAIN_STRUCT_TYPE: + case unoidl::Entity::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE: + tc = css::uno::TypeClass_STRUCT; + break; + case unoidl::Entity::SORT_EXCEPTION_TYPE: + tc = css::uno::TypeClass_EXCEPTION; + break; + case unoidl::Entity::SORT_INTERFACE_TYPE: + tc = css::uno::TypeClass_INTERFACE; + break; + case unoidl::Entity::SORT_TYPEDEF: + tc = css::uno::TypeClass_TYPEDEF; + break; + case unoidl::Entity::SORT_CONSTANT_GROUP: + tc = css::uno::TypeClass_CONSTANTS; + if (deep_ && matches(css::uno::TypeClass_CONSTANT)) { + positions_.push( + Position( + makePrefix(name), + static_cast< unoidl::ConstantGroupEntity * >( + ent.get()))); + } + break; + case unoidl::Entity::SORT_SINGLE_INTERFACE_BASED_SERVICE: + case unoidl::Entity::SORT_ACCUMULATION_BASED_SERVICE: + tc = css::uno::TypeClass_SERVICE; + break; + case unoidl::Entity::SORT_INTERFACE_BASED_SINGLETON: + case unoidl::Entity::SORT_SERVICE_BASED_SINGLETON: + tc = css::uno::TypeClass_SINGLETON; + break; + default: + for (;;) { std::abort(); } // this cannot happen + } + if (matches(tc)) { + current_ = name; + break; + } + } else { // constant group + if (positions_.top().constantGroupIndex + == positions_.top().constantGroup->getMembers().end()) + { + positions_.pop(); + if (positions_.empty()) { + break; + } + continue; + } + current_ = positions_.top().prefix + + positions_.top().constantGroupIndex++->name; + break; + } + } + } catch (unoidl::FileFormatException & e) { + throw css::uno::DeploymentException( + e.getUri() + ": " + e.getDetail(), + static_cast< cppu::OWeakObject * >(this)); + } +} + +} + +cppuhelper::TypeManager::TypeManager(): + TypeManager_Base(m_aMutex), + manager_(new unoidl::Manager) +{} + +css::uno::Any cppuhelper::TypeManager::find(OUString const & name) { + //TODO: caching? (here or in unoidl::Manager?) + struct Simple { + OUStringLiteral name; + css::uno::TypeClass typeClass; + }; + static Simple const simple[] = { + { OUStringLiteral("void"), css::uno::TypeClass_VOID }, + { OUStringLiteral("boolean"), css::uno::TypeClass_BOOLEAN }, + { OUStringLiteral("byte"), css::uno::TypeClass_BYTE }, + { OUStringLiteral("short"), css::uno::TypeClass_SHORT }, + { OUStringLiteral("unsigned short"), + css::uno::TypeClass_UNSIGNED_SHORT }, + { OUStringLiteral("long"), css::uno::TypeClass_LONG }, + { OUStringLiteral("unsigned long"), css::uno::TypeClass_UNSIGNED_LONG }, + { OUStringLiteral("hyper"), css::uno::TypeClass_HYPER }, + { OUStringLiteral("unsigned hyper"), + css::uno::TypeClass_UNSIGNED_HYPER }, + { OUStringLiteral("float"), css::uno::TypeClass_FLOAT }, + { OUStringLiteral("double"), css::uno::TypeClass_DOUBLE }, + { OUStringLiteral("char"), css::uno::TypeClass_CHAR }, + { OUStringLiteral("string"), css::uno::TypeClass_STRING }, + { OUStringLiteral("type"), css::uno::TypeClass_TYPE }, + { OUStringLiteral("any"), css::uno::TypeClass_ANY } }; + for (std::size_t i = 0; i != SAL_N_ELEMENTS(simple); ++i) { + if (name == simple[i].name) { + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new SimpleTypeDescription(simple[i].typeClass, name)); + } + } + if (name.startsWith("[]")) { + return getSequenceType(name); + } + sal_Int32 i = name.indexOf('<'); + if (i != -1) { + return getInstantiatedStruct(name, i); + } + i = name.indexOf("::"); + if (i != -1) { + return getInterfaceMember(name, i); + } + rtl::Reference< unoidl::Entity > ent(findEntity(name)); + if (ent.is()) { + return getNamed(name, ent); + } + i = name.lastIndexOf('.'); + if (i != -1) { + OUString parent(name.copy(0, i)); + ent = findEntity(parent); + if (ent.is()) { + switch (ent->getSort()) { + case unoidl::Entity::SORT_ENUM_TYPE: + return getEnumMember( + static_cast< unoidl::EnumTypeEntity * >(ent.get()), + name.copy(i + 1)); + case unoidl::Entity::SORT_CONSTANT_GROUP: + return getConstant( + parent, + static_cast< unoidl::ConstantGroupEntity * >(ent.get()), + name.copy(i + 1)); + default: + break; + } + } + } + return css::uno::Any(); +} + +css::uno::Reference< css::reflection::XTypeDescription > +cppuhelper::TypeManager::resolve(OUString const & name) { + css::uno::Reference< css::reflection::XTypeDescription > desc( + find(name), css::uno::UNO_QUERY); + if (!desc.is()) { + throw css::uno::DeploymentException( + "cannot resolve type \"" + name + "\"", + static_cast< cppu::OWeakObject * >(this)); + } + return desc; +} + +cppuhelper::TypeManager::~TypeManager() throw () {} + +void cppuhelper::TypeManager::disposing() {} //TODO + +OUString cppuhelper::TypeManager::getImplementationName() +{ + return + "com.sun.star.comp.cppuhelper.bootstrap.TypeManager"; +} + +sal_Bool cppuhelper::TypeManager::supportsService( + OUString const & ServiceName) +{ + return cppu::supportsService(this, ServiceName); +} + +css::uno::Sequence< OUString > +cppuhelper::TypeManager::getSupportedServiceNames() +{ + css::uno::Sequence names { "com.sun.star.reflection.TypeDescriptionManager" }; //TODO + return names; +} + +css::uno::Any cppuhelper::TypeManager::getByHierarchicalName( + OUString const & aName) +{ + css::uno::Any desc(find(aName)); + if (!desc.hasValue()) { + throw css::container::NoSuchElementException( + aName, static_cast< cppu::OWeakObject * >(this)); + } + return desc; +} + +sal_Bool cppuhelper::TypeManager::hasByHierarchicalName( + OUString const & aName) +{ + return find(aName).hasValue(); +} + +css::uno::Type cppuhelper::TypeManager::getElementType() +{ + return cppu::UnoType< OUString >::get(); +} + +sal_Bool cppuhelper::TypeManager::hasElements() +{ + throw css::uno::RuntimeException( + "TypeManager hasElements: method not supported", + static_cast< cppu::OWeakObject * >(this)); +} + +css::uno::Reference< css::container::XEnumeration > +cppuhelper::TypeManager::createEnumeration() +{ + throw css::uno::RuntimeException( + "TypeManager createEnumeration: method not supported", + static_cast< cppu::OWeakObject * >(this)); +} + +sal_Bool cppuhelper::TypeManager::has(css::uno::Any const &) +{ + throw css::uno::RuntimeException( + "TypeManager has: method not supported", + static_cast< cppu::OWeakObject * >(this)); +} + +void cppuhelper::TypeManager::insert(css::uno::Any const & aElement) +{ + OUString uri; + if (!(aElement >>= uri)) { + throw css::lang::IllegalArgumentException( + ("css.uno.theTypeDescriptionManager.insert expects a string URI" + " argument"), + static_cast< cppu::OWeakObject * >(this), 0); + } + //TODO: check for ElementExistException + //TODO: check for consistency with existing data + readRdbFile(uri, false); +} + +void cppuhelper::TypeManager::remove(css::uno::Any const & aElement) +{ + OUString uri; + if (!(aElement >>= uri)) { + throw css::lang::IllegalArgumentException( + ("css.uno.theTypeDescriptionManager.remove expects a string URI" + " argument"), + static_cast< cppu::OWeakObject * >(this), 0); + } + //TODO: remove requests are silently ignored for now +} + +css::uno::Reference< css::reflection::XTypeDescriptionEnumeration > +cppuhelper::TypeManager::createTypeDescriptionEnumeration( + OUString const & moduleName, + css::uno::Sequence< css::uno::TypeClass > const & types, + css::reflection::TypeDescriptionSearchDepth depth) +{ + rtl::Reference< unoidl::MapCursor > cursor; + try { + cursor = manager_->createCursor(moduleName); + } catch (unoidl::FileFormatException & e) { + throw css::uno::DeploymentException( + ("unoidl::FileFormatException for <" + e.getUri() + ">: " + + e.getDetail()), + static_cast< cppu::OWeakObject * >(this)); + } + if (!cursor.is()) { + //TODO: css::reflection::InvalidTypeNameException if moduleName names a + // non-module + throw css::reflection::NoSuchTypeNameException( + moduleName, static_cast< cppu::OWeakObject * >(this)); + } + return new Enumeration( + this, makePrefix(moduleName), cursor, types, + depth == css::reflection::TypeDescriptionSearchDepth_INFINITE); +} + +void cppuhelper::TypeManager::init(OUString const & rdbUris) { + for (sal_Int32 i = 0; i != -1;) { + OUString uri(rdbUris.getToken(0, ' ', i)); + if (uri.isEmpty()) { + continue; + } + bool optional; + bool directory; + cppu::decodeRdbUri(&uri, &optional, &directory); + if (directory) { + readRdbDirectory(uri, optional); + } else { + readRdbFile(uri, optional); + } + } +} + +void cppuhelper::TypeManager::readRdbDirectory( + OUString const & uri, bool optional) +{ + osl::Directory dir(uri); + switch (dir.open()) { + case osl::FileBase::E_None: + break; + case osl::FileBase::E_NOENT: + if (optional) { + SAL_INFO("cppuhelper", "Ignored optional " << uri); + return; + } + [[fallthrough]]; + default: + throw css::uno::DeploymentException( + "Cannot open directory " + uri, + static_cast< cppu::OWeakObject * >(this)); + } + for (;;) { + OUString url; + if (!cppu::nextDirectoryItem(dir, &url)) { + break; + } + readRdbFile(url, false); + } +} + +void cppuhelper::TypeManager::readRdbFile( + OUString const & uri, bool optional) +{ + try { + manager_->addProvider(uri); + } catch (unoidl::NoSuchFileException &) { + if (!optional) { + throw css::uno::DeploymentException( + uri + ": no such file", + static_cast< cppu::OWeakObject * >(this)); + } + SAL_INFO("cppuhelper", "Ignored optional " << uri); + } catch (unoidl::FileFormatException & e) { + throw css::uno::DeploymentException( + ("unoidl::FileFormatException for <" + e.getUri() + ">: " + + e.getDetail()), + static_cast< cppu::OWeakObject * >(this)); + } +} + +css::uno::Any cppuhelper::TypeManager::getSequenceType( + OUString const & name) +{ + assert(name.startsWith("[]")); + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new SequenceTypeDescription( + this, name, name.copy(std::strlen("[]")))); +} + +css::uno::Any cppuhelper::TypeManager::getInstantiatedStruct( + OUString const & name, sal_Int32 separator) +{ + assert(name.indexOf('<') == separator && separator != -1); + rtl::Reference< unoidl::Entity > ent(findEntity(name.copy(0, separator))); + if (!ent.is() + || (ent->getSort() + != unoidl::Entity::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE)) + { + return css::uno::Any(); + } + rtl::Reference< unoidl::PolymorphicStructTypeTemplateEntity > ent2( + static_cast< unoidl::PolymorphicStructTypeTemplateEntity * >( + ent.get())); + std::vector< OUString > args; + sal_Int32 i = separator; + do { + ++i; // skip '<' or ',' + sal_Int32 j = i; + for (sal_Int32 level = 0; j != name.getLength(); ++j) { + sal_Unicode c = name[j]; + if (c == ',') { + if (level == 0) { + break; + } + } else if (c == '<') { + ++level; + } else if (c == '>') { + if (level == 0) { + break; + } + --level; + } + } + if (j != name.getLength()) { + args.push_back(name.copy(i, j - i)); + } + i = j; + } while (i != name.getLength() && name[i] != '>'); + if (i != name.getLength() - 1 || name[i] != '>' + || args.size() != ent2->getTypeParameters().size()) + { + return css::uno::Any(); + } + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new InstantiatedPolymorphicStructTypeDescription( + this, name, ent2, args)); +} + +css::uno::Any cppuhelper::TypeManager::getInterfaceMember( + OUString const & name, sal_Int32 separator) +{ + assert(name.indexOf("::") == separator && separator != -1); + css::uno::Reference< css::reflection::XInterfaceTypeDescription2 > ifc( + resolveTypedefs(find(name.copy(0, separator))), css::uno::UNO_QUERY); + if (!ifc.is()) { + return css::uno::Any(); + } + OUString member(name.copy(separator + std::strlen("::"))); + const css::uno::Sequence< + css::uno::Reference< + css::reflection::XInterfaceMemberTypeDescription > > mems( + ifc->getMembers()); + for (const auto & m : mems) { + if (m->getMemberName() == member) { + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >(m); + } + } + return css::uno::Any(); +} + +css::uno::Any cppuhelper::TypeManager::getNamed( + OUString const & name, rtl::Reference< unoidl::Entity > const & entity) +{ + assert(entity.is()); + switch (entity->getSort()) { + case unoidl::Entity::SORT_MODULE: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new ModuleDescription( + this, name, + static_cast< unoidl::ModuleEntity * >(entity.get()))); + case unoidl::Entity::SORT_ENUM_TYPE: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new EnumTypeDescription( + name, + static_cast< unoidl::EnumTypeEntity * >(entity.get()))); + case unoidl::Entity::SORT_PLAIN_STRUCT_TYPE: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new PlainStructTypeDescription( + this, name, + static_cast< unoidl::PlainStructTypeEntity * >( + entity.get()))); + case unoidl::Entity::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new PolymorphicStructTypeTemplateDescription( + this, name, + static_cast< + unoidl::PolymorphicStructTypeTemplateEntity * >( + entity.get()))); + case unoidl::Entity::SORT_EXCEPTION_TYPE: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new ExceptionTypeDescription( + this, name, + static_cast< unoidl::ExceptionTypeEntity * >( + entity.get()))); + case unoidl::Entity::SORT_INTERFACE_TYPE: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new InterfaceTypeDescription( + this, name, + static_cast< unoidl::InterfaceTypeEntity * >( + entity.get()))); + case unoidl::Entity::SORT_TYPEDEF: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new TypedefDescription( + this, name, + static_cast< unoidl::TypedefEntity * >(entity.get()))); + case unoidl::Entity::SORT_CONSTANT_GROUP: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new ConstantGroupDescription( + name, + static_cast< unoidl::ConstantGroupEntity * >( + entity.get()))); + case unoidl::Entity::SORT_SINGLE_INTERFACE_BASED_SERVICE: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new SingleInterfaceBasedServiceDescription( + this, name, + static_cast< unoidl::SingleInterfaceBasedServiceEntity * >( + entity.get()))); + case unoidl::Entity::SORT_ACCUMULATION_BASED_SERVICE: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new AccumulationBasedServiceDescription( + this, name, + static_cast< unoidl::AccumulationBasedServiceEntity * >( + entity.get()))); + case unoidl::Entity::SORT_INTERFACE_BASED_SINGLETON: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new InterfaceBasedSingletonDescription( + this, name, + static_cast< unoidl::InterfaceBasedSingletonEntity * >( + entity.get()))); + case unoidl::Entity::SORT_SERVICE_BASED_SINGLETON: + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new ServiceBasedSingletonDescription( + this, name, + static_cast< unoidl::ServiceBasedSingletonEntity * >( + entity.get()))); + default: + for (;;) { std::abort(); } // this cannot happen + } +} + +css::uno::Any cppuhelper::TypeManager::getEnumMember( + rtl::Reference< unoidl::EnumTypeEntity > const & entity, + OUString const & member) +{ + auto i = std::find_if(entity->getMembers().begin(), entity->getMembers().end(), + [&member](const unoidl::EnumTypeEntity::Member& rMember) { return rMember.name == member; }); + if (i != entity->getMembers().end()) + return css::uno::makeAny(i->value); + return css::uno::Any(); +} + +css::uno::Any cppuhelper::TypeManager::getConstant( + OUString const & constantGroupName, + rtl::Reference< unoidl::ConstantGroupEntity > const & entity, + OUString const & member) +{ + auto i = std::find_if(entity->getMembers().begin(), entity->getMembers().end(), + [&member](const unoidl::ConstantGroupEntity::Member& rMember) { return rMember.name == member; }); + if (i != entity->getMembers().end()) + return css::uno::makeAny< + css::uno::Reference< css::reflection::XTypeDescription > >( + new ConstantDescription(constantGroupName, *i)); + return css::uno::Any(); +} + +rtl::Reference< unoidl::Entity > cppuhelper::TypeManager::findEntity( + OUString const & name) +{ + try { + return manager_->findEntity(name); + } catch (unoidl::FileFormatException & e) { + throw css::uno::DeploymentException( + ("unoidl::FileFormatException for <" + e.getUri() + ">: " + + e.getDetail()), + static_cast< cppu::OWeakObject * >(this)); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/typemanager.hxx b/cppuhelper/source/typemanager.hxx new file mode 100644 index 000000000..bc086693a --- /dev/null +++ b/cppuhelper/source/typemanager.hxx @@ -0,0 +1,128 @@ +/* -*- 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/. + */ + +#ifndef INCLUDED_CPPUHELPER_SOURCE_TYPEMANAGER_HXX +#define INCLUDED_CPPUHELPER_SOURCE_TYPEMANAGER_HXX + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace com::sun::star { + namespace reflection { class XTypeDescription; } +} +namespace unoidl { + class ConstantGroupEntity; + class Entity; + class EnumTypeEntity; + class Manager; +} + +namespace cppuhelper { + +typedef cppu::WeakComponentImplHelper< + css::lang::XServiceInfo, css::container::XHierarchicalNameAccess, + css::container::XSet, css::reflection::XTypeDescriptionEnumerationAccess > +TypeManager_Base; + +class TypeManager: private cppu::BaseMutex, public TypeManager_Base { +public: + TypeManager(); + + using TypeManager_Base::acquire; + using TypeManager_Base::release; + + void init(OUString const & rdbUris); + + css::uno::Any find(OUString const & name); + + css::uno::Reference< css::reflection::XTypeDescription > resolve( + OUString const & name); + +private: + virtual ~TypeManager() throw () override; + + virtual void SAL_CALL disposing() override; + + virtual OUString SAL_CALL getImplementationName() override; + + virtual sal_Bool SAL_CALL supportsService(OUString const & ServiceName) override; + + virtual css::uno::Sequence< OUString > SAL_CALL + getSupportedServiceNames() override; + + virtual css::uno::Any SAL_CALL getByHierarchicalName( + OUString const & aName) override; + + virtual sal_Bool SAL_CALL hasByHierarchicalName(OUString const & aName) override; + + virtual css::uno::Type SAL_CALL getElementType() override; + + virtual sal_Bool SAL_CALL hasElements() override; + + virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL + createEnumeration() override; + + virtual sal_Bool SAL_CALL has(css::uno::Any const & aElement) override; + + virtual void SAL_CALL insert(css::uno::Any const & aElement) override; + + virtual void SAL_CALL remove(css::uno::Any const & aElement) override; + + virtual css::uno::Reference< css::reflection::XTypeDescriptionEnumeration > + SAL_CALL createTypeDescriptionEnumeration( + OUString const & moduleName, + css::uno::Sequence< css::uno::TypeClass > const & types, + css::reflection::TypeDescriptionSearchDepth depth) override; + + void readRdbDirectory(OUString const & uri, bool optional); + + void readRdbFile(OUString const & uri, bool optional); + + css::uno::Any getSequenceType(OUString const & name); + + css::uno::Any getInstantiatedStruct( + OUString const & name, sal_Int32 separator); + + css::uno::Any getInterfaceMember( + OUString const & name, sal_Int32 separator); + + css::uno::Any getNamed( + OUString const & name, + rtl::Reference< unoidl::Entity > const & entity); + + static css::uno::Any getEnumMember( + rtl::Reference< unoidl::EnumTypeEntity > const & entity, + OUString const & member); + + static css::uno::Any getConstant( + OUString const & constantGroupName, + rtl::Reference< unoidl::ConstantGroupEntity > const & entity, + OUString const & member); + + rtl::Reference< unoidl::Entity > findEntity(OUString const & name); + + rtl::Reference< unoidl::Manager > manager_; +}; + +} + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/typeprovider.cxx b/cppuhelper/source/typeprovider.cxx new file mode 100644 index 000000000..c4258ef61 --- /dev/null +++ b/cppuhelper/source/typeprovider.cxx @@ -0,0 +1,305 @@ +/* -*- 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 + +#include +#include + +using namespace osl; +using namespace com::sun::star::uno; + +namespace cppu +{ + + +OImplementationId::~OImplementationId() +{ + delete _pSeq; +} + +Sequence< sal_Int8 > OImplementationId::getImplementationId() const +{ + if (! _pSeq) + { + MutexGuard aGuard( Mutex::getGlobalMutex() ); + if (! _pSeq) + { + Sequence< sal_Int8 > * pSeq = new Sequence< sal_Int8 >( 16 ); + ::rtl_createUuid( reinterpret_cast(pSeq->getArray()), nullptr, _bUseEthernetAddress ); + _pSeq = pSeq; + } + } + return *_pSeq; +} + + +static void copy( Sequence< Type > & rDest, const Sequence< Type > & rSource, sal_Int32 nOffset ) +{ + Type * pDest = rDest.getArray(); + const Type * pSource = rSource.getConstArray(); + + for ( sal_Int32 nPos = rSource.getLength(); nPos--; ) + pDest[nOffset+ nPos] = pSource[nPos]; +} + + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Sequence< Type > & rAddTypes ) + : _aTypes( 1 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + copy( _aTypes, rAddTypes, 1 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Sequence< Type > & rAddTypes ) + : _aTypes( 2 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + copy( _aTypes, rAddTypes, 2 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Sequence< Type > & rAddTypes ) + : _aTypes( 3 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + copy( _aTypes, rAddTypes, 3 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Type & rType4, + const Sequence< Type > & rAddTypes ) + : _aTypes( 4 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + _aTypes[3] = rType4; + copy( _aTypes, rAddTypes, 4 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Type & rType4, + const Type & rType5, + const Sequence< Type > & rAddTypes ) + : _aTypes( 5 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + _aTypes[3] = rType4; + _aTypes[4] = rType5; + copy( _aTypes, rAddTypes, 5 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Type & rType4, + const Type & rType5, + const Type & rType6, + const Sequence< Type > & rAddTypes ) + : _aTypes( 6 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + _aTypes[3] = rType4; + _aTypes[4] = rType5; + _aTypes[5] = rType6; + copy( _aTypes, rAddTypes, 6 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Type & rType4, + const Type & rType5, + const Type & rType6, + const Type & rType7, + const Sequence< Type > & rAddTypes ) + : _aTypes( 7 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + _aTypes[3] = rType4; + _aTypes[4] = rType5; + _aTypes[5] = rType6; + _aTypes[6] = rType7; + copy( _aTypes, rAddTypes, 7 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Type & rType4, + const Type & rType5, + const Type & rType6, + const Type & rType7, + const Type & rType8, + const Sequence< Type > & rAddTypes ) + : _aTypes( 8 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + _aTypes[3] = rType4; + _aTypes[4] = rType5; + _aTypes[5] = rType6; + _aTypes[6] = rType7; + _aTypes[7] = rType8; + copy( _aTypes, rAddTypes, 8 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Type & rType4, + const Type & rType5, + const Type & rType6, + const Type & rType7, + const Type & rType8, + const Type & rType9, + const Sequence< Type > & rAddTypes ) + : _aTypes( 9 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + _aTypes[3] = rType4; + _aTypes[4] = rType5; + _aTypes[5] = rType6; + _aTypes[6] = rType7; + _aTypes[7] = rType8; + _aTypes[8] = rType9; + copy( _aTypes, rAddTypes, 9 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Type & rType4, + const Type & rType5, + const Type & rType6, + const Type & rType7, + const Type & rType8, + const Type & rType9, + const Type & rType10, + const Sequence< Type > & rAddTypes ) + : _aTypes( 10 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + _aTypes[3] = rType4; + _aTypes[4] = rType5; + _aTypes[5] = rType6; + _aTypes[6] = rType7; + _aTypes[7] = rType8; + _aTypes[8] = rType9; + _aTypes[9] = rType10; + copy( _aTypes, rAddTypes, 10 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Type & rType4, + const Type & rType5, + const Type & rType6, + const Type & rType7, + const Type & rType8, + const Type & rType9, + const Type & rType10, + const Type & rType11, + const Sequence< Type > & rAddTypes ) + : _aTypes( 11 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + _aTypes[3] = rType4; + _aTypes[4] = rType5; + _aTypes[5] = rType6; + _aTypes[6] = rType7; + _aTypes[7] = rType8; + _aTypes[8] = rType9; + _aTypes[9] = rType10; + _aTypes[10] = rType11; + copy( _aTypes, rAddTypes, 11 ); +} + +OTypeCollection::OTypeCollection( + const Type & rType1, + const Type & rType2, + const Type & rType3, + const Type & rType4, + const Type & rType5, + const Type & rType6, + const Type & rType7, + const Type & rType8, + const Type & rType9, + const Type & rType10, + const Type & rType11, + const Type & rType12, + const Sequence< Type > & rAddTypes ) + : _aTypes( 12 + rAddTypes.getLength() ) +{ + _aTypes[0] = rType1; + _aTypes[1] = rType2; + _aTypes[2] = rType3; + _aTypes[3] = rType4; + _aTypes[4] = rType5; + _aTypes[5] = rType6; + _aTypes[6] = rType7; + _aTypes[7] = rType8; + _aTypes[8] = rType9; + _aTypes[9] = rType10; + _aTypes[10] = rType11; + _aTypes[11] = rType12; + copy( _aTypes, rAddTypes, 12 ); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/unourl.cxx b/cppuhelper/source/unourl.cxx new file mode 100644 index 000000000..8ee7e593a --- /dev/null +++ b/cppuhelper/source/unourl.cxx @@ -0,0 +1,266 @@ +/* -*- 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 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using cppu::UnoUrl; +using cppu::UnoUrlDescriptor; + +class UnoUrlDescriptor::Impl +{ +public: + typedef std::map< OUString, OUString > Parameters; + + OUString m_aDescriptor; + OUString m_aName; + Parameters m_aParameters; + + /** @exception rtl::MalformedUriException + */ + explicit inline Impl(OUString const & m_aDescriptor); + + Impl * clone() const { return new Impl(*this); } +}; + +inline UnoUrlDescriptor::Impl::Impl(OUString const & rDescriptor) +{ + m_aDescriptor = rDescriptor; + enum State { STATE_NAME0, STATE_NAME, STATE_KEY0, STATE_KEY, STATE_VALUE }; + State eState = STATE_NAME0; + sal_Int32 nStart = 0; + OUString aKey; + for (sal_Int32 i = 0;; ++i) + { + bool bEnd = i == rDescriptor.getLength(); + sal_Unicode c = bEnd ? 0 : rDescriptor[i]; + switch (eState) + { + case STATE_NAME0: + if (bEnd || !rtl::isAsciiAlphanumeric(c)) + throw rtl::MalformedUriException( + "UNO URL contains bad descriptor name"); + nStart = i; + eState = STATE_NAME; + break; + + case STATE_NAME: + if (bEnd || c == 0x2C) // ',' + { + m_aName + = rDescriptor.copy(nStart, i - nStart).toAsciiLowerCase(); + eState = STATE_KEY0; + } + else if (!rtl::isAsciiAlphanumeric(c)) + throw rtl::MalformedUriException( + "UNO URL contains bad descriptor name"); + break; + + case STATE_KEY0: + if (bEnd || !rtl::isAsciiAlphanumeric(c)) + throw rtl::MalformedUriException( + "UNO URL contains bad parameter key"); + nStart = i; + eState = STATE_KEY; + break; + + case STATE_KEY: + if (c == 0x3D) // '=' + { + aKey = rDescriptor.copy(nStart, i - nStart).toAsciiLowerCase(); + nStart = i + 1; + eState = STATE_VALUE; + } + else if (bEnd || !rtl::isAsciiAlphanumeric(c)) + throw rtl::MalformedUriException( + "UNO URL contains bad parameter key"); + break; + + case STATE_VALUE: + if (bEnd || c == 0x2C) // ',' + { + if (!m_aParameters.emplace( + aKey, + rtl::Uri::decode(rDescriptor.copy(nStart, + i - nStart), + rtl_UriDecodeWithCharset, + RTL_TEXTENCODING_UTF8)).second) + throw rtl::MalformedUriException( + "UNO URL contains duplicated parameter"); + eState = STATE_KEY0; + } + break; + } + if (bEnd) + break; + } +} + +UnoUrlDescriptor::UnoUrlDescriptor(OUString const & rDescriptor): + m_pImpl(new Impl(rDescriptor)) +{} + +UnoUrlDescriptor::UnoUrlDescriptor(UnoUrlDescriptor const & rOther): + m_pImpl(rOther.m_pImpl->clone()) +{} + +UnoUrlDescriptor::~UnoUrlDescriptor() +{ + delete m_pImpl; +} + +UnoUrlDescriptor & UnoUrlDescriptor::operator =(UnoUrlDescriptor const & rOther) +{ + if (this != &rOther) + { + std::unique_ptr newImpl(rOther.m_pImpl->clone()); + delete m_pImpl; + m_pImpl = newImpl.release(); + } + return *this; +} + +OUString const & UnoUrlDescriptor::getDescriptor() const +{ + return m_pImpl->m_aDescriptor; +} + +OUString const & UnoUrlDescriptor::getName() const +{ + return m_pImpl->m_aName; +} + +bool UnoUrlDescriptor::hasParameter(OUString const & rKey) const +{ + return m_pImpl->m_aParameters.find(rKey.toAsciiLowerCase()) + != m_pImpl->m_aParameters.end(); +} + +OUString UnoUrlDescriptor::getParameter(OUString const & rKey) const +{ + Impl::Parameters::const_iterator + aIt(m_pImpl->m_aParameters.find(rKey.toAsciiLowerCase())); + return aIt == m_pImpl->m_aParameters.end() ? OUString() : aIt->second; +} + +class UnoUrl::Impl +{ +public: + UnoUrlDescriptor m_aConnection; + UnoUrlDescriptor m_aProtocol; + OUString m_aObjectName; + + Impl * clone() const { return new Impl(*this); } + + /** @exception rtl::MalformedUriException + */ + static inline Impl * create(OUString const & rUrl); + +private: + Impl(OUString const & rConnectionDescriptor, + OUString const & rProtocolDescriptor, + OUString const & rObjectName): + m_aConnection(rConnectionDescriptor), + m_aProtocol(rProtocolDescriptor), + m_aObjectName(rObjectName) + {} +}; + +inline UnoUrl::Impl * UnoUrl::Impl::create(OUString const & rUrl) +{ + if (!rUrl.startsWithIgnoreAsciiCase("uno:")) + throw rtl::MalformedUriException("UNO URL does not start with \"uno:\""); + sal_Int32 i = RTL_CONSTASCII_LENGTH("uno:"); + sal_Int32 j = rUrl.indexOf(';', i); + if (j < 0) + throw rtl::MalformedUriException("UNO URL has too few semicolons"); + OUString aConnection(rUrl.copy(i, j - i)); + i = j + 1; + j = rUrl.indexOf(0x3B, i); // ';' + if (j < 0) + throw rtl::MalformedUriException("UNO URL has too few semicolons"); + OUString aProtocol(rUrl.copy(i, j - i)); + i = j + 1; + if (i == rUrl.getLength()) + throw rtl::MalformedUriException("UNO URL contains empty ObjectName"); + for (j = i; j < rUrl.getLength(); ++j) + { + sal_Unicode c = rUrl[j]; + if (!rtl::isAsciiAlphanumeric(c) && c != 0x21 && c != 0x24 // '!', '$' + && c != 0x26 && c != 0x27 && c != 0x28 // '&', ''', '(' + && c != 0x29 && c != 0x2A && c != 0x2B // ')', '*', '+' + && c != 0x2C && c != 0x2D && c != 0x2E // ',', '-', '.' + && c != 0x2F && c != 0x3A && c != 0x3D // '/', ':', '=' + && c != 0x3F && c != 0x40 && c != 0x5F // '?', '@', '_' + && c != 0x7E) // '~' + throw rtl::MalformedUriException("UNO URL contains invalid ObjectName"); + } + return new Impl(aConnection, aProtocol, rUrl.copy(i)); +} + +UnoUrl::UnoUrl(OUString const & rUrl): m_pImpl(Impl::create(rUrl)) +{} + +UnoUrl::UnoUrl(UnoUrl const & rOther): m_pImpl(rOther.m_pImpl->clone()) +{} + +UnoUrl::~UnoUrl() +{ + delete m_pImpl; +} + +UnoUrl & UnoUrl::operator =(UnoUrl const & rOther) +{ + if (this != &rOther) + { + std::unique_ptr newImpl(rOther.m_pImpl->clone()); + delete m_pImpl; + m_pImpl = newImpl.release(); + } + return *this; +} + +UnoUrlDescriptor const & UnoUrl::getConnection() const +{ + return m_pImpl->m_aConnection; +} + +UnoUrlDescriptor const & UnoUrl::getProtocol() const +{ + return m_pImpl->m_aProtocol; +} + +OUString const & UnoUrl::getObjectName() const +{ + return m_pImpl->m_aObjectName; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/cppuhelper/source/weak.cxx b/cppuhelper/source/weak.cxx new file mode 100644 index 000000000..a11e52bbb --- /dev/null +++ b/cppuhelper/source/weak.cxx @@ -0,0 +1,530 @@ +/* -*- 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 +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include + +using namespace osl; +using namespace com::sun::star::uno; + +/** */ //for docpp +namespace cppu +{ + +// due to static Reflection destruction from usr, there must be a mutex leak (#73272#) +// this is used to lock all instances of OWeakConnectionPoint and OWeakRefListener as well as OWeakObject::m_pWeakConnectionPoint +static Mutex & getWeakMutex() +{ + static Mutex * s_pMutex = new Mutex(); + return *s_pMutex; +} + + +//-- OWeakConnectionPoint ---------------------------------------------------- + +class OWeakConnectionPoint: public XAdapter +{ +public: + /** + Hold the weak object without an acquire (only the pointer). + */ + explicit OWeakConnectionPoint( OWeakObject* pObj ) + : m_aRefCount( 0 ) + , m_pObject(pObj) + {} + + // noncopyable + OWeakConnectionPoint(const OWeakConnectionPoint&) = delete; + const OWeakConnectionPoint& operator=(const OWeakConnectionPoint&) = delete; + + // XInterface + Any SAL_CALL queryInterface( const Type & rType ) override; + void SAL_CALL acquire() throw() override; + void SAL_CALL release() throw() override; + + // XAdapter + css::uno::Reference< css::uno::XInterface > SAL_CALL queryAdapted() override; + void SAL_CALL addReference( const css::uno::Reference< css::uno::XReference >& xRef ) override; + void SAL_CALL removeReference( const css::uno::Reference< css::uno::XReference >& xRef ) override; + + /// Called from the weak object if the reference count goes to zero. + /// + /// @throws css::uno::RuntimeException + void dispose(); + +private: + virtual ~OWeakConnectionPoint() {} + + /// The reference counter. + oslInterlockedCount m_aRefCount; + /// The weak object + OWeakObject* m_pObject; + /// The container to hold the weak references + std::vector> m_aReferences; +}; + +// XInterface +Any SAL_CALL OWeakConnectionPoint::queryInterface( const Type & rType ) +{ + return ::cppu::queryInterface( + rType, static_cast< XAdapter * >( this ), static_cast< XInterface * >( this ) ); +} + +// XInterface +void SAL_CALL OWeakConnectionPoint::acquire() throw() +{ + osl_atomic_increment( &m_aRefCount ); +} + +// XInterface +void SAL_CALL OWeakConnectionPoint::release() throw() +{ + if (! osl_atomic_decrement( &m_aRefCount )) + delete this; +} + +void OWeakConnectionPoint::dispose() +{ + std::vector> aCopy; + { // only hold the mutex while we access the field + MutexGuard aGuard(getWeakMutex()); + // OWeakObject is not the only owner of this, so clear m_pObject + // so that queryAdapted() won't use it now that it's dead + m_pObject = nullptr; + // other code is going to call removeReference while we are doing this, so we need a + // copy, but since we are disposing and going away, we can just take the original data + aCopy.swap(m_aReferences); + } + Any ex; + for (const Reference & i : aCopy ) + { + try + { + i->dispose(); + } + catch (css::lang::DisposedException &) {} + catch (RuntimeException &) + { + ex = cppu::getCaughtException(); + } + } + if (ex.hasValue()) + { + cppu::throwException(ex); + } +} + +// XInterface +Reference< XInterface > SAL_CALL OWeakConnectionPoint::queryAdapted() +{ + Reference< XInterface > ret; + + ClearableMutexGuard guard(getWeakMutex()); + + if (m_pObject) + { + oslInterlockedCount n = osl_atomic_increment( &m_pObject->m_refCount ); + + if (n > 1) + { + // The reference is incremented. The object cannot be destroyed. + // Release the guard at the earliest point. + guard.clear(); + // WeakObject has a (XInterface *) cast operator + ret = *m_pObject; + osl_atomic_decrement( &m_pObject->m_refCount ); + } + else + // Another thread wait in the dispose method at the guard + osl_atomic_decrement( &m_pObject->m_refCount ); + } + + return ret; +} + +// XInterface +void SAL_CALL OWeakConnectionPoint::addReference(const Reference< XReference >& rRef) +{ + MutexGuard aGuard(getWeakMutex()); + m_aReferences.push_back( rRef ); +} + +// XInterface +void SAL_CALL OWeakConnectionPoint::removeReference(const Reference< XReference >& rRef) +{ + MutexGuard aGuard(getWeakMutex()); + // Search from end because the thing that last added a ref is most likely to be the + // first to remove a ref. + // It's not really valid to compare the pointer directly, but it's faster. + auto it = std::find_if(m_aReferences.rbegin(), m_aReferences.rend(), + [&rRef](const Reference& rxRef) { return rxRef.get() == rRef.get(); }); + if (it != m_aReferences.rend()) { + m_aReferences.erase( it.base()-1 ); + return; + } + // interface not found, use the correct compare method + it = std::find(m_aReferences.rbegin(), m_aReferences.rend(), rRef); + if ( it != m_aReferences.rend() ) + m_aReferences.erase( it.base()-1 ); +} + + +//-- OWeakObject ------------------------------------------------------- + + +#ifdef _MSC_VER +// Accidentally occurs in msvc mapfile = > had to be outlined. +OWeakObject::OWeakObject() + : m_refCount( 0 ), + m_pWeakConnectionPoint( nullptr ) +{ +} +#endif + +// XInterface +Any SAL_CALL OWeakObject::queryInterface( const Type & rType ) +{ + return ::cppu::queryInterface( + rType, + static_cast< XWeak * >( this ), static_cast< XInterface * >( this ) ); +} + +// XInterface +void SAL_CALL OWeakObject::acquire() throw() +{ + osl_atomic_increment( &m_refCount ); +} + +// XInterface +void SAL_CALL OWeakObject::release() throw() +{ + if (osl_atomic_decrement( &m_refCount ) == 0) { + // notify/clear all weak-refs before object's dtor is executed + // (which may check weak-refs to this object): + disposeWeakConnectionPoint(); + // destroy object: + delete this; + } +} + +void OWeakObject::disposeWeakConnectionPoint() +{ + OSL_PRECOND( m_refCount == 0, "OWeakObject::disposeWeakConnectionPoint: only to be called with a ref count of 0!" ); + if (m_pWeakConnectionPoint != nullptr) { + OWeakConnectionPoint * const p = m_pWeakConnectionPoint; + m_pWeakConnectionPoint = nullptr; + try { + p->dispose(); + } + catch (RuntimeException const& exc) { + SAL_WARN( "cppuhelper", exc ); + } + p->release(); + } +} + +OWeakObject::~OWeakObject() COVERITY_NOEXCEPT_FALSE +{ +} + +// XWeak +Reference< XAdapter > SAL_CALL OWeakObject::queryAdapter() +{ + if (!m_pWeakConnectionPoint) + { + // only acquire mutex if member is not created + MutexGuard aGuard( getWeakMutex() ); + if( !m_pWeakConnectionPoint ) + { + OWeakConnectionPoint * p = new OWeakConnectionPoint(this); + p->acquire(); + m_pWeakConnectionPoint = p; + } + } + + return m_pWeakConnectionPoint; +} + + +//-- OWeakAggObject ---------------------------------------------------- + +OWeakAggObject::~OWeakAggObject() +{ +} + +// XInterface +void OWeakAggObject::acquire() throw() +{ + Reference x( xDelegator ); + if (x.is()) + x->acquire(); + else + OWeakObject::acquire(); +} + +// XInterface +void OWeakAggObject::release() throw() +{ + Reference x( xDelegator ); + if (x.is()) + x->release(); + else + OWeakObject::release(); +} + +// XInterface +Any OWeakAggObject::queryInterface( const Type & rType ) +{ + Reference< XInterface > x( xDelegator ); // harden ref + return (x.is() ? x->queryInterface( rType ) : queryAggregation( rType )); +} + +// XAggregation +Any OWeakAggObject::queryAggregation( const Type & rType ) +{ + return ::cppu::queryInterface( + rType, + static_cast< XInterface * >( static_cast< OWeakObject * >( this ) ), + static_cast< XAggregation * >( this ), + static_cast< XWeak * >( this ) ); +} + +// XAggregation +void OWeakAggObject::setDelegator( const Reference & rDelegator ) +{ + xDelegator = rDelegator; +} + +} + +/** */ //for docpp +namespace com::sun::star::uno +{ + + +//-- OWeakRefListener ----------------------------------------------------- + +class OWeakRefListener final : public XReference +{ +public: + explicit OWeakRefListener(const Reference< XInterface >& xInt); + virtual ~OWeakRefListener(); + + // noncopyable + OWeakRefListener(const OWeakRefListener&) = delete; + const OWeakRefListener& operator=(const OWeakRefListener&) = delete; + + // XInterface + Any SAL_CALL queryInterface( const Type & rType ) override; + void SAL_CALL acquire() throw() override; + void SAL_CALL release() throw() override; + + // XReference + void SAL_CALL dispose() override; + + /// The reference counter. + oslInterlockedCount m_aRefCount; + /// The connection point of the weak object, guarded by getWeakMutex() + Reference< XAdapter > m_XWeakConnectionPoint; +}; + +OWeakRefListener::OWeakRefListener(const Reference< XInterface >& xInt) + : m_aRefCount( 1 ) +{ + try + { + Reference< XWeak > xWeak( Reference< XWeak >::query( xInt ) ); + + if (xWeak.is()) + { + m_XWeakConnectionPoint = xWeak->queryAdapter(); + + if (m_XWeakConnectionPoint.is()) + { + m_XWeakConnectionPoint->addReference(static_cast(this)); + } + } + } + catch (RuntimeException &) { OSL_ASSERT( false ); } // assert here, but no unexpected() + osl_atomic_decrement( &m_aRefCount ); +} + +OWeakRefListener::~OWeakRefListener() +{ + try + { + if (m_XWeakConnectionPoint.is()) + { + acquire(); // don't die again + m_XWeakConnectionPoint->removeReference(static_cast(this)); + } + } + catch (RuntimeException &) { OSL_ASSERT( false ); } // assert here, but no unexpected() +} + +// XInterface +Any SAL_CALL OWeakRefListener::queryInterface( const Type & rType ) +{ + return ::cppu::queryInterface( + rType, static_cast< XReference * >( this ), static_cast< XInterface * >( this ) ); +} + +// XInterface +void SAL_CALL OWeakRefListener::acquire() throw() +{ + osl_atomic_increment( &m_aRefCount ); +} + +// XInterface +void SAL_CALL OWeakRefListener::release() throw() +{ + if( ! osl_atomic_decrement( &m_aRefCount ) ) + delete this; +} + +void SAL_CALL OWeakRefListener::dispose() +{ + Reference< XAdapter > xAdp; + { + MutexGuard guard(cppu::getWeakMutex()); + if( m_XWeakConnectionPoint.is() ) + { + xAdp = m_XWeakConnectionPoint; + m_XWeakConnectionPoint.clear(); + } + } + + if( xAdp.is() ) + xAdp->removeReference(static_cast(this)); +} + + +//-- WeakReferenceHelper ---------------------------------------------------------- + +WeakReferenceHelper::WeakReferenceHelper(const Reference< XInterface >& xInt) + : m_pImpl( nullptr ) +{ + if (xInt.is()) + { + m_pImpl = new OWeakRefListener(xInt); + m_pImpl->acquire(); + } +} + +WeakReferenceHelper::WeakReferenceHelper(const WeakReferenceHelper& rWeakRef) + : m_pImpl( nullptr ) +{ + Reference< XInterface > xInt( rWeakRef.get() ); + if (xInt.is()) + { + m_pImpl = new OWeakRefListener(xInt); + m_pImpl->acquire(); + } +} + +void WeakReferenceHelper::clear() +{ + try + { + if (m_pImpl) + { + m_pImpl->dispose(); + m_pImpl->release(); + m_pImpl = nullptr; + } + } + catch (RuntimeException &) { OSL_ASSERT( false ); } // assert here, but no unexpected() +} + +WeakReferenceHelper& WeakReferenceHelper::operator=(const WeakReferenceHelper& rWeakRef) +{ + if (this == &rWeakRef) + { + return *this; + } + Reference< XInterface > xInt( rWeakRef.get() ); + return operator = ( xInt ); +} + +WeakReferenceHelper & WeakReferenceHelper::operator =( + WeakReferenceHelper && other) +{ + clear(); + std::swap(m_pImpl, other.m_pImpl); + return *this; +} + +WeakReferenceHelper & SAL_CALL +WeakReferenceHelper::operator= (const Reference< XInterface > & xInt) +{ + try + { + clear(); + if (xInt.is()) + { + m_pImpl = new OWeakRefListener(xInt); + m_pImpl->acquire(); + } + } + catch (RuntimeException &) { OSL_ASSERT( false ); } // assert here, but no unexpected() + return *this; +} + +WeakReferenceHelper::~WeakReferenceHelper() +{ + clear(); +} + +Reference< XInterface > WeakReferenceHelper::get() const +{ + try + { + Reference< XAdapter > xAdp; + { + // must lock to access m_XWeakConnectionPoint + MutexGuard guard(cppu::getWeakMutex()); + if( m_pImpl && m_pImpl->m_XWeakConnectionPoint.is() ) + xAdp = m_pImpl->m_XWeakConnectionPoint; + } + + if (xAdp.is()) + return xAdp->queryAdapted(); + } + catch (RuntimeException &) + { + OSL_ASSERT( false ); + } // assert here, but no unexpected() + + return Reference< XInterface >(); +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ -- cgit v1.2.3