Version 7.6.3.2-android, tag libreoffice-7.6.3.2-android
[LibreOffice.git] / forms / source / misc / InterfaceContainer.cxx
blobf7278117899c06c8aed01ec18bf0606fe513e575
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
21 #include <strings.hrc>
22 #include <frm_resource.hxx>
23 #include <frm_strings.hxx>
24 #include <InterfaceContainer.hxx>
25 #include <componenttools.hxx>
26 #include <services.hxx>
28 #include <com/sun/star/beans/XPropertySet.hpp>
29 #include <com/sun/star/io/WrongFormatException.hpp>
30 #include <com/sun/star/io/XMarkableStream.hpp>
31 #include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
32 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
33 #include <com/sun/star/lang/ServiceNotRegisteredException.hpp>
34 #include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
35 #include <com/sun/star/lang/XComponent.hpp>
36 #include <com/sun/star/uno/XComponentContext.hpp>
37 #include <com/sun/star/util/XCloneable.hpp>
38 #include <com/sun/star/form/XForm.hpp>
40 #include <comphelper/enumhelper.hxx>
41 #include <comphelper/eventattachermgr.hxx>
42 #include <comphelper/property.hxx>
43 #include <comphelper/sequence.hxx>
44 #include <comphelper/types.hxx>
45 #include <cppuhelper/exc_hlp.hxx>
46 #include <o3tl/safeint.hxx>
47 #include <tools/debug.hxx>
48 #include <comphelper/diagnose_ex.hxx>
49 #include <sal/log.hxx>
51 #include <algorithm>
52 #include <memory>
55 #include <com/sun/star/frame/XModel.hpp>
56 #include <com/sun/star/document/XCodeNameQuery.hpp>
57 #include <ooo/vba/XVBAToOOEventDescGen.hpp>
59 namespace frm
63 using namespace ::com::sun::star::frame;
64 using namespace ::com::sun::star::lang;
65 using namespace ::com::sun::star::uno;
66 using namespace ::com::sun::star::beans;
67 using namespace ::com::sun::star::document;
68 using namespace ::com::sun::star::container;
69 using namespace ::com::sun::star::script;
70 using namespace ::com::sun::star::io;
71 using namespace ::com::sun::star::form;
72 using namespace ::com::sun::star::util;
74 namespace
77 void lcl_throwIllegalArgumentException()
79 throw IllegalArgumentException();
83 static bool
84 lcl_hasVbaEvents( const Sequence< ScriptEventDescriptor >& sEvents )
86 for ( auto const& rDesc : sEvents )
88 if ( rDesc.ScriptType == "VBAInterop" )
89 return true;
91 return false;
94 static Sequence< ScriptEventDescriptor >
95 lcl_stripVbaEvents( const Sequence< ScriptEventDescriptor >& sEvents )
97 Sequence< ScriptEventDescriptor > sStripped( sEvents.getLength() );
98 ScriptEventDescriptor* pStripped = sStripped.getArray();
100 sal_Int32 nCopied = 0;
101 for ( auto const& rDesc : sEvents )
103 if ( rDesc.ScriptType != "VBAInterop" )
105 pStripped[ nCopied++ ] = rDesc;
108 sStripped.realloc( nCopied );
109 return sStripped;
112 void OInterfaceContainer::impl_addVbEvents_nolck_nothrow( const sal_Int32 i_nIndex )
114 // we are dealing with form controls
119 Reference< XModel > xDoc( getXModel( static_cast< XContainer *> ( this ) ) );
120 if ( !xDoc.is() )
121 break;
123 Reference< XMultiServiceFactory > xDocFac( xDoc, UNO_QUERY_THROW );
124 Reference< XCodeNameQuery > xNameQuery( xDocFac->createInstance("ooo.vba.VBACodeNameProvider"), UNO_QUERY );
125 if ( !xNameQuery.is() )
126 break;
128 ::osl::MutexGuard aGuard( m_rMutex );
129 bool hasVBABindings = lcl_hasVbaEvents( m_xEventAttacher->getScriptEvents( i_nIndex ) );
130 if ( hasVBABindings )
131 break;
133 Reference< XInterface > xElement( getByIndex( i_nIndex ) , UNO_QUERY_THROW );
134 Reference< XForm > xElementAsForm( xElement, UNO_QUERY );
135 if ( xElementAsForm.is() )
136 break;
138 // Try getting the code name from the container first (faster),
139 // then from the element if that fails (slower).
140 Reference<XInterface> xThis = static_cast<XContainer*>(this);
141 OUString sCodeName = xNameQuery->getCodeNameForContainer(xThis);
142 if (sCodeName.isEmpty())
143 sCodeName = xNameQuery->getCodeNameForObject(xElement);
145 Reference< XPropertySet > xProps( xElement, UNO_QUERY_THROW );
146 OUString sServiceName;
147 xProps->getPropertyValue("DefaultControl") >>= sServiceName;
149 Reference< ooo::vba::XVBAToOOEventDescGen > xDescSupplier( m_xContext->getServiceManager()->createInstanceWithContext("ooo.vba.VBAToOOEventDesc", m_xContext), UNO_QUERY_THROW );
150 Sequence< ScriptEventDescriptor > vbaEvents = xDescSupplier->getEventDescriptions( sServiceName , sCodeName );
152 // register the vba script events
153 m_xEventAttacher->registerScriptEvents( i_nIndex, vbaEvents );
155 while ( false );
157 catch ( const ServiceNotRegisteredException& )
159 // silence this, not all document types support the ooo.vba.VBACodeNameProvider service
161 catch( const Exception& )
163 DBG_UNHANDLED_EXCEPTION("forms.misc");
168 ElementDescription::ElementDescription( )
173 OInterfaceContainer::OInterfaceContainer(
174 const Reference<XComponentContext>& _rxContext,
175 ::osl::Mutex& _rMutex,
176 const Type& _rElementType)
177 :OInterfaceContainer_BASE()
178 ,m_rMutex(_rMutex)
179 ,m_aContainerListeners(_rMutex)
180 ,m_aElementType(_rElementType)
181 ,m_xContext(_rxContext)
183 impl_createEventAttacher_nothrow();
187 OInterfaceContainer::OInterfaceContainer( ::osl::Mutex& _rMutex, const OInterfaceContainer& _cloneSource )
188 :OInterfaceContainer_BASE()
189 ,m_rMutex( _rMutex )
190 ,m_aContainerListeners( _rMutex )
191 ,m_aElementType( _cloneSource.m_aElementType )
192 ,m_xContext( _cloneSource.m_xContext )
194 impl_createEventAttacher_nothrow();
197 void OInterfaceContainer::clonedFrom(const OInterfaceContainer& _cloneSource)
201 const Reference< XIndexAccess > xSourceHierarchy( const_cast< OInterfaceContainer* >( &_cloneSource ) );
202 const sal_Int32 nCount = xSourceHierarchy->getCount();
203 for ( sal_Int32 i=0; i<nCount; ++i )
205 Reference< XCloneable > xCloneable( xSourceHierarchy->getByIndex( i ), UNO_QUERY_THROW );
206 Reference< XInterface > xClone( xCloneable->createClone() );
207 insertByIndex( i, Any( xClone ) );
210 catch (const RuntimeException&)
212 throw;
214 catch (const Exception&)
216 throw WrappedTargetRuntimeException(
217 "Could not clone the given interface hierarchy.",
218 static_cast< XIndexContainer* >( const_cast< OInterfaceContainer* >( &_cloneSource ) ),
219 ::cppu::getCaughtException()
224 void OInterfaceContainer::impl_createEventAttacher_nothrow()
228 m_xEventAttacher.set( ::comphelper::createEventAttacherManager( m_xContext ), UNO_SET_THROW );
230 catch( const Exception& )
232 DBG_UNHANDLED_EXCEPTION("forms.misc");
237 OInterfaceContainer::~OInterfaceContainer()
242 void OInterfaceContainer::disposing()
244 // dispose all elements
245 for (sal_Int32 i = m_aItems.size(); i > 0; --i)
247 Reference<XPropertySet> xSet(m_aItems[i - 1], UNO_QUERY);
248 if (xSet.is())
249 xSet->removePropertyChangeListener(PROPERTY_NAME, this);
251 // revoke event knittings
252 if ( m_xEventAttacher.is() )
254 m_xEventAttacher->detach( i - 1, Reference<XInterface>(xSet, UNO_QUERY) );
255 m_xEventAttacher->removeEntry( i - 1 );
258 Reference<XComponent> xComponent(xSet, UNO_QUERY);
259 if (xComponent.is())
260 xComponent->dispose();
262 m_aMap.clear();
263 m_aItems.clear();
265 css::lang::EventObject aEvt(static_cast<XContainer*>(this));
266 m_aContainerListeners.disposeAndClear(aEvt);
269 // XPersistObject
271 namespace
274 void lcl_saveEvents( ::std::vector< Sequence< ScriptEventDescriptor > >& _rSave,
275 const Reference< XEventAttacherManager >& _rxManager, const sal_Int32 _nItemCount )
277 OSL_ENSURE( _rxManager.is(), "lcl_saveEvents: invalid event attacher manager!" );
278 if ( !_rxManager.is() )
279 return;
281 // reserve the space needed
282 _rSave.reserve( _nItemCount );
284 // copy the events
285 for (sal_Int32 i=0; i<_nItemCount; ++i)
286 _rSave.push_back(_rxManager->getScriptEvents( i ));
290 void lcl_restoreEvents( const ::std::vector< Sequence< ScriptEventDescriptor > >& _rSave,
291 const Reference< XEventAttacherManager >& _rxManager )
293 OSL_ENSURE( _rxManager.is(), "lcl_restoreEvents: invalid event attacher manager!" );
294 if ( !_rxManager.is() )
295 return;
297 sal_Int32 i=0;
298 for (auto const& elem : _rSave)
300 _rxManager->revokeScriptEvents( i );
301 _rxManager->registerScriptEvents(i, elem);
302 ++i;
308 void SAL_CALL OInterfaceContainer::writeEvents(const Reference<XObjectOutputStream>& _rxOutStream)
310 // We're writing a document in SO 5.2 format (or even from earlier versions)
311 // -> convert the events from the new runtime format to the format of the 5.2 files
312 // but before, remember the current script events set for our children
313 ::std::vector< Sequence< ScriptEventDescriptor > > aSave;
314 if ( m_xEventAttacher.is() )
315 lcl_saveEvents( aSave, m_xEventAttacher, m_aItems.size() );
317 transformEvents();
321 Reference<XMarkableStream> xMark(_rxOutStream, UNO_QUERY);
322 sal_Int32 nMark = xMark->createMark();
324 sal_Int32 nObjLen = 0;
325 _rxOutStream->writeLong(nObjLen);
327 Reference<XPersistObject> xScripts(m_xEventAttacher, UNO_QUERY);
328 if (xScripts.is())
329 xScripts->write(_rxOutStream);
331 // Determine length
332 nObjLen = xMark->offsetToMark(nMark) - 4;
333 xMark->jumpToMark(nMark);
334 _rxOutStream->writeLong(nObjLen);
335 xMark->jumpToFurthest();
336 xMark->deleteMark(nMark);
338 catch( const Exception& )
340 // restore the events
341 if ( m_xEventAttacher.is() )
342 lcl_restoreEvents( aSave, m_xEventAttacher );
343 throw;
346 // restore the events
347 if ( m_xEventAttacher.is() )
348 lcl_restoreEvents( aSave, m_xEventAttacher );
351 namespace {
353 struct TransformEventTo52Format
355 void operator()( ScriptEventDescriptor& _rDescriptor )
357 if ( _rDescriptor.ScriptType != "StarBasic" )
358 return;
360 // it's a starbasic macro
361 sal_Int32 nPrefixLength = _rDescriptor.ScriptCode.indexOf( ':' );
362 if ( 0 <= nPrefixLength )
363 { // the macro name does not already contain a :
364 #ifdef DBG_UTIL
365 const OUString sPrefix = _rDescriptor.ScriptCode.copy( 0, nPrefixLength );
366 DBG_ASSERT( sPrefix == "document"
367 || sPrefix == "application",
368 "TransformEventTo52Format: invalid (unknown) prefix!" );
369 #endif
370 // cut the prefix
371 _rDescriptor.ScriptCode = _rDescriptor.ScriptCode.copy( nPrefixLength + 1 );
378 void OInterfaceContainer::transformEvents()
380 OSL_ENSURE( m_xEventAttacher.is(), "OInterfaceContainer::transformEvents: no event attacher manager!" );
381 if ( !m_xEventAttacher.is() )
382 return;
386 // loop through all our children
387 sal_Int32 nItems = m_aItems.size();
388 Sequence< ScriptEventDescriptor > aChildEvents;
390 for (sal_Int32 i=0; i<nItems; ++i)
392 // get the script events for this object
393 aChildEvents = m_xEventAttacher->getScriptEvents( i );
395 if ( aChildEvents.hasElements() )
397 // do the transformation
398 auto [begin, end] = asNonConstRange(aChildEvents);
399 ::std::for_each( begin, end, TransformEventTo52Format() );
401 // revoke the script events
402 m_xEventAttacher->revokeScriptEvents( i );
403 // and re-register them
404 m_xEventAttacher->registerScriptEvents( i, aChildEvents );
408 catch( const Exception& )
410 DBG_UNHANDLED_EXCEPTION("forms.misc");
415 void SAL_CALL OInterfaceContainer::readEvents(const Reference<XObjectInputStream>& _rxInStream)
417 ::osl::MutexGuard aGuard( m_rMutex );
419 // Read scripting info
420 Reference<XMarkableStream> xMark(_rxInStream, UNO_QUERY);
421 sal_Int32 nObjLen = _rxInStream->readLong();
422 if (nObjLen)
424 sal_Int32 nMark = xMark->createMark();
425 Reference<XPersistObject> xObj(m_xEventAttacher, UNO_QUERY);
426 if (xObj.is())
427 xObj->read(_rxInStream);
428 xMark->jumpToMark(nMark);
429 _rxInStream->skipBytes(nObjLen);
430 xMark->deleteMark(nMark);
433 // Read Attachment
434 if ( m_xEventAttacher.is() )
436 sal_Int32 i=0;
437 for (auto const& item : m_aItems)
439 Reference< XInterface > xAsIFace( item, UNO_QUERY ); // important to normalize this...
440 Reference< XPropertySet > xAsSet( xAsIFace, UNO_QUERY );
441 m_xEventAttacher->attach( i++, xAsIFace, Any( xAsSet ) );
447 void SAL_CALL OInterfaceContainer::write( const Reference< XObjectOutputStream >& _rxOutStream )
449 ::osl::MutexGuard aGuard( m_rMutex );
450 sal_Int32 nLen = m_aItems.size();
452 // Write length
453 _rxOutStream->writeLong(nLen);
455 if (!nLen)
456 return;
458 // 1. Version
459 _rxOutStream->writeShort(0x0001);
461 // 2. Objects
462 for (sal_Int32 i = 0; i < nLen; i++)
464 Reference<XPersistObject> xObj(m_aItems[i], UNO_QUERY);
465 if (xObj.is())
466 _rxOutStream->writeObject(xObj);
467 else
469 // Error
473 // 3. Scripts
474 writeEvents(_rxOutStream);
478 namespace
480 Reference< XPersistObject > lcl_createPlaceHolder( const Reference< XComponentContext >& _rxORB )
482 Reference< XPersistObject > xObject( _rxORB->getServiceManager()->createInstanceWithContext(FRM_COMPONENT_HIDDENCONTROL, _rxORB), UNO_QUERY );
483 DBG_ASSERT( xObject.is(), "lcl_createPlaceHolder: could not create a substitute for the unknown object!" );
484 if ( xObject.is() )
486 // set some properties describing what we did
487 Reference< XPropertySet > xObjProps( xObject, UNO_QUERY );
488 if ( xObject.is() )
492 xObjProps->setPropertyValue( PROPERTY_NAME, Any( ResourceManager::loadString(RID_STR_CONTROL_SUBSTITUTED_NAME) ) );
493 xObjProps->setPropertyValue( PROPERTY_TAG, Any( ResourceManager::loadString(RID_STR_CONTROL_SUBSTITUTED_EPXPLAIN) ) );
495 catch(const Exception&)
500 return xObject;
505 void SAL_CALL OInterfaceContainer::read( const Reference< XObjectInputStream >& _rxInStream )
507 ::osl::MutexGuard aGuard( m_rMutex );
509 // after ::read the object is expected to be in the state it was when ::write was called, so we have
510 // to empty ourself here
511 while (getCount())
512 removeByIndex(0);
514 // Only writes depending on the length
515 sal_Int32 nLen = _rxInStream->readLong();
517 if (nLen)
519 // 1. Version
520 _rxInStream->readShort();
522 // 2. Objects
523 for (sal_Int32 i = 0; i < nLen; i++)
525 Reference<XPersistObject> xObj;
528 xObj = _rxInStream->readObject();
530 catch(const WrongFormatException&)
532 // the object could not be read
533 // create an object (so the readEvents below will assign the events to the right controls)
534 xObj = lcl_createPlaceHolder( m_xContext );
535 if ( !xObj.is() )
536 // couldn't handle it
537 throw;
539 catch(const Exception&)
541 // Clear the map
542 while (!m_aItems.empty())
543 removeElementsNoEvents();
545 // Rethrow the exception
546 throw;
549 if ( xObj.is() )
551 Reference< XPropertySet > xElement( xObj, UNO_QUERY );
554 implInsert(
555 m_aItems.size(), // position
556 xElement, // element to insert
557 false, // no event attacher manager handling
558 nullptr, // not yet approved - let implInsert do it
559 true // fire the event
562 catch( const Exception& )
564 SAL_WARN("forms.misc", "OInterfaceContainerHelper3::read: reading succeeded, but not inserting!" );
565 // create a placeholder
566 xElement.set(lcl_createPlaceHolder( m_xContext ), css::uno::UNO_QUERY);
567 if ( !xElement.is() )
568 // couldn't handle it
569 throw;
570 // insert the placeholder
571 implInsert( m_aItems.size(), xElement, false, nullptr, true );
576 readEvents(_rxInStream);
578 else
582 m_xEventAttacher = ::comphelper::createEventAttacherManager( m_xContext );
583 OSL_ENSURE( m_xEventAttacher.is(), "OInterfaceContainer::read: could not create an event attacher manager!" );
585 catch( const Exception& )
587 DBG_UNHANDLED_EXCEPTION("forms.misc");
592 // XContainer
594 void SAL_CALL OInterfaceContainer::addContainerListener(const Reference<XContainerListener>& _rxListener)
596 m_aContainerListeners.addInterface(_rxListener);
600 void SAL_CALL OInterfaceContainer::removeContainerListener(const Reference<XContainerListener>& _rxListener)
602 m_aContainerListeners.removeInterface(_rxListener);
605 // XEventListener
607 void SAL_CALL OInterfaceContainer::disposing(const css::lang::EventObject& _rSource)
609 ::osl::MutexGuard aGuard( m_rMutex );
611 Reference< XInterface > xSource( _rSource.Source, UNO_QUERY );
612 // normalized source
614 OInterfaceArray::iterator j;
615 for ( j = m_aItems.begin(); j != m_aItems.end(); ++j )
617 DBG_ASSERT( j->get() == Reference< XInterface >( *j, UNO_QUERY ).get(),
618 "OInterfaceContainer::disposing: vector element not normalized!" );
620 if ( xSource.get() == j->get() )
621 // found the element
622 break;
625 if ( m_aItems.end() == j )
626 return;
628 m_aItems.erase(j);
630 // look up in, and erase from, m_aMap, too
631 OInterfaceMap::iterator i = m_aMap.begin();
632 while ( i != m_aMap.end() )
634 DBG_ASSERT( i->second.get() == Reference< XInterface >( i->second, UNO_QUERY ).get(),
635 "OInterfaceContainer::disposing: map element not normalized!" );
637 if ( i->second.get() == xSource.get() )
639 // found it
640 m_aMap.erase(i);
641 break;
644 ++i;
646 DBG_ASSERT( i != m_aMap.end(), "OInterfaceContainer::disposing: inconsistency: the element was in m_aItems, but not in m_aMap!" );
650 // XPropertyChangeListener
652 void OInterfaceContainer::propertyChange(const PropertyChangeEvent& evt) {
653 if (evt.PropertyName != PROPERTY_NAME)
654 return;
656 ::osl::MutexGuard aGuard( m_rMutex );
657 auto range = m_aMap.equal_range(::comphelper::getString(evt.OldValue));
658 for (auto it = range.first; it != range.second; ++it)
659 if (it->second == evt.Source)
661 css::uno::Reference<css::uno::XInterface> xCorrectType(it->second);
662 m_aMap.erase(it);
663 m_aMap.insert(::std::pair<const OUString, css::uno::Reference<css::uno::XInterface> >(::comphelper::getString(evt.NewValue),xCorrectType));
664 break;
668 // XElementAccess
670 sal_Bool SAL_CALL OInterfaceContainer::hasElements()
672 return !m_aMap.empty();
676 Type SAL_CALL OInterfaceContainer::getElementType()
678 return m_aElementType;
681 // XEnumerationAccess
683 Reference<XEnumeration> SAL_CALL OInterfaceContainer::createEnumeration()
685 ::osl::MutexGuard aGuard( m_rMutex );
686 return new ::comphelper::OEnumerationByIndex(static_cast<XIndexAccess*>(this));
689 // XNameAccess
691 Any SAL_CALL OInterfaceContainer::getByName( const OUString& _rName )
693 ::std::pair <OInterfaceMap::iterator,
694 OInterfaceMap::iterator> aPair = m_aMap.equal_range(_rName);
696 if (aPair.first == aPair.second)
697 throw NoSuchElementException();
699 return (*aPair.first).second->queryInterface( m_aElementType );
703 css::uno::Sequence<OUString> SAL_CALL OInterfaceContainer::getElementNames()
705 return comphelper::mapKeysToSequence(m_aMap);
709 sal_Bool SAL_CALL OInterfaceContainer::hasByName( const OUString& _rName )
711 ::std::pair <OInterfaceMap::iterator,
712 OInterfaceMap::iterator> aPair = m_aMap.equal_range(_rName);
713 return aPair.first != aPair.second;
716 // XIndexAccess
718 sal_Int32 OInterfaceContainer::getCount()
720 return m_aItems.size();
724 Any OInterfaceContainer::getByIndex(sal_Int32 _nIndex)
726 if (_nIndex < 0 || (o3tl::make_unsigned(_nIndex) >= m_aItems.size()))
727 throw IndexOutOfBoundsException();
729 return m_aItems[_nIndex]->queryInterface( m_aElementType );
733 void OInterfaceContainer::approveNewElement( const Reference< XPropertySet >& _rxObject, ElementDescription* _pElement )
735 // it has to be non-NULL
736 if ( !_rxObject.is() )
737 throw IllegalArgumentException(ResourceManager::loadString(RID_STR_NEED_NON_NULL_OBJECT), static_cast<XContainer*>(this), 1);
739 // it has to support our element type interface
740 Any aCorrectType = _rxObject->queryInterface( m_aElementType );
741 if ( !aCorrectType.hasValue() )
742 lcl_throwIllegalArgumentException();
744 // it has to have a "Name" property
745 if ( !hasProperty( PROPERTY_NAME, _rxObject ) )
746 lcl_throwIllegalArgumentException();
748 // it has to be a child, and it must not have a parent already
749 Reference< XChild > xChild( _rxObject, UNO_QUERY );
750 if ( !xChild.is() || xChild->getParent().is() )
752 lcl_throwIllegalArgumentException();
755 // passed all tests. cache the information we have so far
756 DBG_ASSERT( _pElement, "OInterfaceContainer::approveNewElement: invalid event descriptor!" );
757 if ( _pElement )
759 _pElement->xPropertySet = _rxObject;
760 _pElement->xChild = xChild;
761 _pElement->aElementTypeInterface = aCorrectType;
762 _pElement->xInterface = Reference< XInterface >( _rxObject, UNO_QUERY ); // normalized XInterface
767 void OInterfaceContainer::implInsert(sal_Int32 _nIndex, const Reference< XPropertySet >& _rxElement,
768 bool _bEvents, ElementDescription* _pApprovalResult, bool _bFire )
770 const bool bHandleEvents = _bEvents && m_xEventAttacher.is();
772 // SYNCHRONIZED ----->
773 ::osl::ClearableMutexGuard aGuard( m_rMutex );
775 std::unique_ptr< ElementDescription > aAutoDeleteMetaData;
776 ElementDescription* pElementMetaData = _pApprovalResult;
777 if ( !pElementMetaData )
778 { // not yet approved by the caller -> do ourself
779 pElementMetaData = createElementMetaData();
780 DBG_ASSERT( pElementMetaData, "OInterfaceContainer::implInsert: createElementMetaData returned nonsense!" );
782 // ensure that the meta data structure will be deleted later on
783 aAutoDeleteMetaData.reset( pElementMetaData );
785 // will throw an exception if necessary
786 approveNewElement( _rxElement, pElementMetaData );
790 // approveNewElement (no matter if called here or outside) has ensure that all relevant interfaces
791 // exist
793 // set the name, and add as change listener for the name
794 OUString sName;
795 _rxElement->getPropertyValue(PROPERTY_NAME) >>= sName;
796 _rxElement->addPropertyChangeListener(PROPERTY_NAME, this);
798 // insert the object into our internal structures
799 if (_nIndex > static_cast<sal_Int32>(m_aItems.size())) // Calculate the actual index
801 _nIndex = m_aItems.size();
802 m_aItems.push_back( pElementMetaData->xInterface );
804 else
805 m_aItems.insert( m_aItems.begin() + _nIndex, pElementMetaData->xInterface );
807 m_aMap.insert( ::std::pair< const OUString, css::uno::Reference<css::uno::XInterface> >( sName, pElementMetaData->xInterface ) );
809 // announce ourself as parent to the new element
810 pElementMetaData->xChild->setParent(static_cast<XContainer*>(this));
812 // handle the events
813 if ( bHandleEvents )
815 m_xEventAttacher->insertEntry(_nIndex);
816 m_xEventAttacher->attach( _nIndex, pElementMetaData->xInterface, Any( _rxElement ) );
819 // notify derived classes
820 implInserted( pElementMetaData );
822 aGuard.clear();
823 // <----- SYNCHRONIZED
825 // insert faked VBA events?
826 bool bHandleVbaEvents = false;
829 _rxElement->getPropertyValue("GenerateVbaEvents") >>= bHandleVbaEvents;
831 catch( const Exception& )
834 if ( bHandleVbaEvents )
836 Reference< XEventAttacherManager > xMgr ( pElementMetaData->xInterface, UNO_QUERY );
837 OInterfaceContainer* pIfcMgr = xMgr.is() ? dynamic_cast<OInterfaceContainer*>(xMgr.get()) : nullptr;
838 if (pIfcMgr)
840 sal_Int32 nLen = pIfcMgr->getCount();
841 for (sal_Int32 i = 0; i < nLen; ++i)
843 // add fake events to the control at index i
844 pIfcMgr->impl_addVbEvents_nolck_nothrow( i );
847 else
849 // add fake events to the control at index i
850 impl_addVbEvents_nolck_nothrow( _nIndex );
854 // fire the notification about the change
855 if ( _bFire )
857 // notify listeners
858 ContainerEvent aEvt;
859 aEvt.Source = static_cast<XContainer*>(this);
860 aEvt.Accessor <<= _nIndex;
861 aEvt.Element = pElementMetaData->aElementTypeInterface;
863 m_aContainerListeners.notifyEach( &XContainerListener::elementInserted, aEvt );
868 void OInterfaceContainer::removeElementsNoEvents()
870 OInterfaceArray::iterator i = m_aItems.begin();
871 css::uno::Reference<css::uno::XInterface> xElement(*i);
873 OInterfaceMap::iterator j = std::find_if(m_aMap.begin(), m_aMap.end(),
874 [&xElement](const OInterfaceMap::value_type& rEntry) { return rEntry.second == xElement; });
876 m_aItems.erase(i);
877 m_aMap.erase(j);
879 Reference<XPropertySet> xSet(xElement, UNO_QUERY);
880 if (xSet.is())
881 xSet->removePropertyChangeListener(PROPERTY_NAME, this);
883 Reference<XChild> xChild(xElement, UNO_QUERY);
884 if (xChild.is())
885 xChild->setParent(css::uno::Reference<css::uno::XInterface> ());
889 void OInterfaceContainer::implInserted( const ElementDescription* /*_pElement*/ )
891 // not interested in
895 void OInterfaceContainer::implRemoved( const css::uno::Reference<css::uno::XInterface>& /*_rxObject*/ )
897 // not interested in
901 void OInterfaceContainer::impl_replacedElement( const ContainerEvent& _rEvent, ::osl::ClearableMutexGuard& _rInstanceLock )
903 _rInstanceLock.clear();
904 m_aContainerListeners.notifyEach( &XContainerListener::elementReplaced, _rEvent );
907 // XIndexContainer
909 void SAL_CALL OInterfaceContainer::insertByIndex( sal_Int32 _nIndex, const Any& _rElement )
911 Reference< XPropertySet > xElement;
912 _rElement >>= xElement;
913 implInsert( _nIndex, xElement, true /* event handling */ , nullptr /* not yet approved */ , true /* notification */ );
917 void OInterfaceContainer::implReplaceByIndex( const sal_Int32 _nIndex, const Any& _rNewElement, ::osl::ClearableMutexGuard& _rClearBeforeNotify )
919 OSL_PRECOND( ( _nIndex >= 0 ) && ( o3tl::make_unsigned(_nIndex) < m_aItems.size() ), "OInterfaceContainer::implReplaceByIndex: precondition not met (index)!" );
921 // approve the new object
922 std::unique_ptr< ElementDescription > aElementMetaData( createElementMetaData() );
923 DBG_ASSERT(aElementMetaData,
924 "OInterfaceContainer::implReplaceByIndex: createElementMetaData returned nonsense!");
926 Reference< XPropertySet > xElementProps;
927 _rNewElement >>= xElementProps;
928 approveNewElement( xElementProps, aElementMetaData.get() );
931 // get the old element
932 css::uno::Reference<css::uno::XInterface> xOldElement( m_aItems[ _nIndex ] );
933 DBG_ASSERT( xOldElement.get() == Reference< XInterface >( xOldElement, UNO_QUERY ).get(),
934 "OInterfaceContainer::implReplaceByIndex: elements should be held normalized!" );
936 // locate the old element in the map
937 OInterfaceMap::iterator j = std::find_if(m_aMap.begin(), m_aMap.end(),
938 [&xOldElement](const OInterfaceMap::value_type& rEntry) { return rEntry.second.get() == xOldElement.get(); });
940 // remove event knittings
941 if ( m_xEventAttacher.is() )
943 css::uno::Reference<css::uno::XInterface> xNormalized( xOldElement, UNO_QUERY );
944 m_xEventAttacher->detach( _nIndex, xNormalized );
945 m_xEventAttacher->removeEntry( _nIndex );
948 // don't listen for property changes anymore
949 Reference<XPropertySet> xSet( xOldElement, UNO_QUERY );
950 if (xSet.is())
951 xSet->removePropertyChangeListener(PROPERTY_NAME, this);
953 // give the old element a new (void) parent
954 Reference<XChild> xChild(xOldElement, UNO_QUERY);
955 if (xChild.is())
956 xChild->setParent(css::uno::Reference<css::uno::XInterface> ());
958 // remove the old one
959 m_aMap.erase(j);
961 // examine the new element
962 OUString sName;
963 DBG_ASSERT(aElementMetaData->xPropertySet.is(),
964 "OInterfaceContainer::implReplaceByIndex: what did approveNewElement do?");
966 aElementMetaData->xPropertySet->getPropertyValue(PROPERTY_NAME) >>= sName;
967 aElementMetaData->xPropertySet->addPropertyChangeListener(PROPERTY_NAME, this);
969 // insert the new one
970 m_aMap.insert(::std::pair<const OUString, css::uno::Reference<css::uno::XInterface>>(
971 sName, aElementMetaData->xInterface));
972 m_aItems[_nIndex] = aElementMetaData->xInterface;
974 aElementMetaData->xChild->setParent(static_cast<XContainer*>(this));
976 if ( m_xEventAttacher.is() )
978 m_xEventAttacher->insertEntry( _nIndex );
979 m_xEventAttacher->attach(_nIndex, aElementMetaData->xInterface,
980 Any(aElementMetaData->xPropertySet));
983 ContainerEvent aReplaceEvent;
984 aReplaceEvent.Source = static_cast< XContainer* >( this );
985 aReplaceEvent.Accessor <<= _nIndex;
986 aReplaceEvent.Element = aElementMetaData->xInterface->queryInterface(m_aElementType);
987 aReplaceEvent.ReplacedElement = xOldElement->queryInterface( m_aElementType );
989 impl_replacedElement( aReplaceEvent, _rClearBeforeNotify );
993 void OInterfaceContainer::implCheckIndex( const sal_Int32 _nIndex )
995 if (_nIndex < 0 || o3tl::make_unsigned(_nIndex) >= m_aItems.size())
996 throw IndexOutOfBoundsException();
1000 void SAL_CALL OInterfaceContainer::replaceByIndex(sal_Int32 _nIndex, const Any& Element)
1002 ::osl::ClearableMutexGuard aGuard( m_rMutex );
1003 // check the index
1004 implCheckIndex( _nIndex );
1005 // do the replace
1006 implReplaceByIndex( _nIndex, Element, aGuard );
1010 void OInterfaceContainer::implRemoveByIndex( const sal_Int32 _nIndex, ::osl::ClearableMutexGuard& _rClearBeforeNotify )
1012 OSL_PRECOND( ( _nIndex >= 0 ) && ( o3tl::make_unsigned(_nIndex) < m_aItems.size() ), "OInterfaceContainer::implRemoveByIndex: precondition not met (index)!" );
1014 OInterfaceArray::iterator i = m_aItems.begin() + _nIndex;
1015 css::uno::Reference<css::uno::XInterface> xElement(*i);
1017 OInterfaceMap::iterator j = std::find_if(m_aMap.begin(), m_aMap.end(),
1018 [&xElement](const OInterfaceMap::value_type& rEntry) { return rEntry.second == xElement; });
1020 m_aItems.erase(i);
1021 m_aMap.erase(j);
1023 // remove event knittings
1024 if ( m_xEventAttacher.is() )
1026 css::uno::Reference<css::uno::XInterface> xNormalized( xElement, UNO_QUERY );
1027 m_xEventAttacher->detach( _nIndex, xNormalized );
1028 m_xEventAttacher->removeEntry( _nIndex );
1031 Reference<XPropertySet> xSet(xElement, UNO_QUERY);
1032 if (xSet.is())
1033 xSet->removePropertyChangeListener(PROPERTY_NAME, this);
1035 Reference<XChild> xChild(xElement, UNO_QUERY);
1036 if (xChild.is())
1037 xChild->setParent(css::uno::Reference<css::uno::XInterface> ());
1039 // notify derived classes
1040 implRemoved(xElement);
1042 // notify listeners
1043 ContainerEvent aEvt;
1044 aEvt.Source = static_cast<XContainer*>(this);
1045 aEvt.Element = xElement->queryInterface( m_aElementType );
1046 aEvt.Accessor <<= _nIndex;
1048 _rClearBeforeNotify.clear();
1049 m_aContainerListeners.notifyEach( &XContainerListener::elementRemoved, aEvt );
1053 void SAL_CALL OInterfaceContainer::removeByIndex(sal_Int32 _nIndex)
1055 ::osl::ClearableMutexGuard aGuard( m_rMutex );
1056 // check the index
1057 implCheckIndex( _nIndex );
1058 // do the removal
1059 implRemoveByIndex( _nIndex, aGuard );
1063 ElementDescription* OInterfaceContainer::createElementMetaData( )
1065 return new ElementDescription;
1069 void SAL_CALL OInterfaceContainer::insertByName(const OUString& _rName, const Any& _rElement)
1071 Reference< XPropertySet > xElementProps;
1073 std::unique_ptr< ElementDescription > aElementMetaData( createElementMetaData() );
1074 DBG_ASSERT(aElementMetaData,
1075 "OInterfaceContainer::insertByName: createElementMetaData returned nonsense!");
1077 // ensure the correct name of the element
1080 _rElement >>= xElementProps;
1081 approveNewElement( xElementProps, aElementMetaData.get() );
1083 xElementProps->setPropertyValue( PROPERTY_NAME, Any( _rName ) );
1085 catch( const IllegalArgumentException& )
1087 throw; // allowed to leave
1089 catch( const ElementExistException& )
1091 throw; // allowed to leave
1093 catch( const Exception& )
1095 TOOLS_WARN_EXCEPTION("forms.misc", "OInterfaceContainer::insertByName" );
1097 implInsert( m_aItems.size(), xElementProps, true, aElementMetaData.get(), true );
1101 void SAL_CALL OInterfaceContainer::replaceByName(const OUString& Name, const Any& Element)
1103 ::osl::ClearableMutexGuard aGuard( m_rMutex );
1104 ::std::pair <OInterfaceMap::iterator,
1105 OInterfaceMap::iterator> aPair = m_aMap.equal_range(Name);
1106 if (aPair.first == aPair.second)
1107 throw NoSuchElementException();
1109 if (Element.getValueType().getTypeClass() != TypeClass_INTERFACE)
1110 lcl_throwIllegalArgumentException();
1112 Reference<XPropertySet> xSet;
1113 Element >>= xSet;
1114 if (xSet.is())
1116 if (!hasProperty(PROPERTY_NAME, xSet))
1117 lcl_throwIllegalArgumentException();
1119 xSet->setPropertyValue(PROPERTY_NAME, Any(Name));
1122 // determine the element pos
1123 sal_Int32 nPos = ::std::find(m_aItems.begin(), m_aItems.end(), (*aPair.first).second) - m_aItems.begin();
1125 implReplaceByIndex( nPos, Element, aGuard );
1129 void SAL_CALL OInterfaceContainer::removeByName(const OUString& Name)
1131 ::osl::MutexGuard aGuard( m_rMutex );
1132 ::std::pair <OInterfaceMap::iterator,
1133 OInterfaceMap::iterator> aPair = m_aMap.equal_range(Name);
1134 if (aPair.first == aPair.second)
1135 throw NoSuchElementException();
1137 sal_Int32 nPos = ::std::find(m_aItems.begin(), m_aItems.end(), (*aPair.first).second) - m_aItems.begin();
1138 removeByIndex(nPos);
1142 // XEventAttacherManager
1144 void SAL_CALL OInterfaceContainer::registerScriptEvent( sal_Int32 nIndex, const ScriptEventDescriptor& aScriptEvent )
1146 ::osl::ClearableMutexGuard aGuard( m_rMutex );
1147 if ( m_xEventAttacher.is() )
1149 m_xEventAttacher->registerScriptEvent( nIndex, aScriptEvent );
1150 aGuard.clear();
1151 impl_addVbEvents_nolck_nothrow( nIndex ); // add fake vba events
1156 void SAL_CALL OInterfaceContainer::registerScriptEvents( sal_Int32 nIndex, const Sequence< ScriptEventDescriptor >& aScriptEvents )
1158 ::osl::ClearableMutexGuard aGuard( m_rMutex );
1159 if ( m_xEventAttacher.is() )
1161 m_xEventAttacher->registerScriptEvents( nIndex, aScriptEvents );
1162 aGuard.clear();
1163 impl_addVbEvents_nolck_nothrow( nIndex ); // add fake vba events
1168 void SAL_CALL OInterfaceContainer::revokeScriptEvent( sal_Int32 nIndex, const OUString& aListenerType, const OUString& aEventMethod, const OUString& aRemoveListenerParam )
1170 if ( m_xEventAttacher.is() )
1171 m_xEventAttacher->revokeScriptEvent( nIndex, aListenerType, aEventMethod, aRemoveListenerParam );
1175 void SAL_CALL OInterfaceContainer::revokeScriptEvents( sal_Int32 nIndex )
1177 if ( m_xEventAttacher.is() )
1178 m_xEventAttacher->revokeScriptEvents( nIndex );
1182 void SAL_CALL OInterfaceContainer::insertEntry( sal_Int32 nIndex )
1184 if ( m_xEventAttacher.is() )
1185 m_xEventAttacher->insertEntry( nIndex );
1189 void SAL_CALL OInterfaceContainer::removeEntry( sal_Int32 nIndex )
1191 if ( m_xEventAttacher.is() )
1192 m_xEventAttacher->removeEntry( nIndex );
1196 Sequence< ScriptEventDescriptor > SAL_CALL OInterfaceContainer::getScriptEvents( sal_Int32 nIndex )
1198 Sequence< ScriptEventDescriptor > aReturn;
1199 if ( m_xEventAttacher.is() )
1201 aReturn = m_xEventAttacher->getScriptEvents( nIndex );
1202 if ( lcl_hasVbaEvents( aReturn ) )
1204 aReturn = lcl_stripVbaEvents( aReturn );
1207 return aReturn;
1211 void SAL_CALL OInterfaceContainer::attach( sal_Int32 nIndex, const Reference< XInterface >& xObject, const Any& aHelper )
1213 if ( m_xEventAttacher.is() )
1214 m_xEventAttacher->attach( nIndex, xObject, aHelper );
1218 void SAL_CALL OInterfaceContainer::detach( sal_Int32 nIndex, const Reference< XInterface >& xObject )
1220 if ( m_xEventAttacher.is() )
1221 m_xEventAttacher->detach( nIndex, xObject );
1225 void SAL_CALL OInterfaceContainer::addScriptListener( const Reference< XScriptListener >& xListener )
1227 if ( m_xEventAttacher.is() )
1228 m_xEventAttacher->addScriptListener( xListener );
1232 void SAL_CALL OInterfaceContainer::removeScriptListener( const Reference< XScriptListener >& xListener )
1234 if ( m_xEventAttacher.is() )
1235 m_xEventAttacher->removeScriptListener( xListener );
1239 //= OFormComponents
1242 Any SAL_CALL OFormComponents::queryAggregation(const Type& _rType)
1244 Any aReturn = OFormComponents_BASE::queryInterface(_rType);
1245 if (!aReturn.hasValue())
1247 aReturn = OInterfaceContainer::queryInterface(_rType);
1249 if (!aReturn.hasValue())
1250 aReturn = ::cppu::OComponentHelper::queryAggregation(_rType);
1253 return aReturn;
1257 Sequence<Type> SAL_CALL OFormComponents::getTypes()
1259 return ::comphelper::concatSequences(OInterfaceContainer::getTypes(), ::cppu::OComponentHelper::getTypes(), OFormComponents_BASE::getTypes());
1263 OFormComponents::OFormComponents(const Reference<XComponentContext>& _rxFactory)
1264 : ::cppu::OComponentHelper( m_aMutex )
1265 ,OInterfaceContainer( _rxFactory, m_aMutex, cppu::UnoType<XFormComponent>::get() )
1266 ,OFormComponents_BASE()
1271 OFormComponents::OFormComponents( const OFormComponents& _cloneSource )
1272 : ::cppu::OComponentHelper( m_aMutex )
1273 ,OInterfaceContainer( m_aMutex, _cloneSource )
1274 ,OFormComponents_BASE()
1279 OFormComponents::~OFormComponents()
1281 if (! ::cppu::OComponentHelper::rBHelper.bDisposed)
1283 acquire();
1284 dispose();
1288 // OComponentHelper
1290 void OFormComponents::disposing()
1292 OInterfaceContainer::disposing();
1293 ::cppu::OComponentHelper::disposing();
1294 m_xParent = nullptr;
1297 //XChild
1299 void OFormComponents::setParent(const css::uno::Reference<css::uno::XInterface>& Parent)
1301 ::osl::MutexGuard aGuard( m_aMutex );
1302 m_xParent = Parent;
1306 css::uno::Reference<css::uno::XInterface> OFormComponents::getParent()
1308 return m_xParent;
1312 } // namespace frm
1315 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */