perf: improve ScFlatUInt16RowSegments::dumpAsString()
[LibreOffice.git] / svx / source / form / formcontroller.cxx
blobfa45f354ed12b1128630942c71063c24406b5d5a
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 <fmcontrolbordermanager.hxx>
22 #include <fmcontrollayout.hxx>
23 #include <formcontroller.hxx>
24 #include <formfeaturedispatcher.hxx>
25 #include <fmdocumentclassification.hxx>
26 #include <formcontrolling.hxx>
27 #include <fmprop.hxx>
28 #include <svx/dialmgr.hxx>
29 #include <svx/strings.hrc>
30 #include <fmservs.hxx>
31 #include <svx/fmtools.hxx>
32 #include <fmurl.hxx>
34 #include <com/sun/star/awt/FocusChangeReason.hpp>
35 #include <com/sun/star/awt/XCheckBox.hpp>
36 #include <com/sun/star/awt/XComboBox.hpp>
37 #include <com/sun/star/awt/XListBox.hpp>
38 #include <com/sun/star/awt/XVclWindowPeer.hpp>
39 #include <com/sun/star/awt/TabController.hpp>
40 #include <com/sun/star/beans/PropertyAttribute.hpp>
41 #include <com/sun/star/container/XIdentifierReplace.hpp>
42 #include <com/sun/star/form/TabulatorCycle.hpp>
43 #include <com/sun/star/form/validation/XValidatableFormComponent.hpp>
44 #include <com/sun/star/form/XBoundComponent.hpp>
45 #include <com/sun/star/form/XBoundControl.hpp>
46 #include <com/sun/star/form/XGridControl.hpp>
47 #include <com/sun/star/form/XLoadable.hpp>
48 #include <com/sun/star/form/XReset.hpp>
49 #include <com/sun/star/form/control/FilterControl.hpp>
50 #include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
51 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
52 #include <com/sun/star/lang/NoSupportException.hpp>
53 #include <com/sun/star/sdb/ParametersRequest.hpp>
54 #include <com/sun/star/sdb/RowChangeAction.hpp>
55 #include <com/sun/star/sdb/SQLFilterOperator.hpp>
56 #include <com/sun/star/sdb/XInteractionSupplyParameters.hpp>
57 #include <com/sun/star/sdbc/ColumnValue.hpp>
58 #include <com/sun/star/task/InteractionHandler.hpp>
59 #include <com/sun/star/form/runtime/FormOperations.hpp>
60 #include <com/sun/star/form/runtime/FormFeature.hpp>
61 #include <com/sun/star/container/XContainer.hpp>
62 #include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
63 #include <com/sun/star/util/NumberFormatter.hpp>
64 #include <com/sun/star/sdb/SQLContext.hpp>
65 #include <com/sun/star/sdb/XColumn.hpp>
67 #include <comphelper/enumhelper.hxx>
68 #include <comphelper/interaction.hxx>
69 #include <comphelper/processfactory.hxx>
70 #include <comphelper/property.hxx>
71 #include <comphelper/sequence.hxx>
72 #include <comphelper/flagguard.hxx>
73 #include <comphelper/types.hxx>
74 #include <cppuhelper/supportsservice.hxx>
75 #include <connectivity/IParseContext.hxx>
76 #include <connectivity/dbtools.hxx>
77 #include <connectivity/sqlparse.hxx>
78 #include <toolkit/controls/unocontrol.hxx>
79 #include <toolkit/helper/vclunohelper.hxx>
80 #include <tools/debug.hxx>
81 #include <comphelper/diagnose_ex.hxx>
82 #include <unotools/localedatawrapper.hxx>
83 #include <vcl/svapp.hxx>
84 #include <vcl/settings.hxx>
85 #include <o3tl/safeint.hxx>
86 #include <osl/mutex.hxx>
87 #include <sal/log.hxx>
89 #include <algorithm>
90 #include <iterator>
92 using namespace ::com::sun::star;
93 using namespace ::comphelper;
94 using namespace ::connectivity;
95 using namespace ::dbtools;
98 css::uno::Reference< css::uno::XInterface >
99 FormController_NewInstance_Impl( const css::uno::Reference< css::lang::XMultiServiceFactory > & _rxORB )
101 return *( new ::svxform::FormController( comphelper::getComponentContext(_rxORB) ) );
104 namespace svxform
107 using ::com::sun::star::sdb::XColumn;
108 using ::com::sun::star::awt::XControl;
109 using ::com::sun::star::awt::TabController;
110 using ::com::sun::star::awt::XToolkit;
111 using ::com::sun::star::awt::XWindowPeer;
112 using ::com::sun::star::form::XGrid;
113 using ::com::sun::star::beans::XPropertySet;
114 using ::com::sun::star::uno::UNO_SET_THROW;
115 using ::com::sun::star::uno::UNO_QUERY_THROW;
116 using ::com::sun::star::container::XIndexAccess;
117 using ::com::sun::star::uno::Exception;
118 using ::com::sun::star::uno::XInterface;
119 using ::com::sun::star::uno::UNO_QUERY;
120 using ::com::sun::star::uno::Sequence;
121 using ::com::sun::star::uno::Reference;
122 using ::com::sun::star::beans::XPropertySetInfo;
123 using ::com::sun::star::beans::PropertyValue;
124 using ::com::sun::star::lang::IndexOutOfBoundsException;
125 using ::com::sun::star::sdb::XInteractionSupplyParameters;
126 using ::com::sun::star::awt::XTextComponent;
127 using ::com::sun::star::awt::XTextListener;
128 using ::com::sun::star::uno::Any;
129 using ::com::sun::star::frame::XDispatch;
130 using ::com::sun::star::lang::XMultiServiceFactory;
131 using ::com::sun::star::uno::Type;
132 using ::com::sun::star::lang::IllegalArgumentException;
133 using ::com::sun::star::sdbc::XConnection;
134 using ::com::sun::star::sdbc::XRowSet;
135 using ::com::sun::star::sdbc::XDatabaseMetaData;
136 using ::com::sun::star::util::XNumberFormatsSupplier;
137 using ::com::sun::star::util::NumberFormatter;
138 using ::com::sun::star::util::XNumberFormatter;
139 using ::com::sun::star::sdbcx::XColumnsSupplier;
140 using ::com::sun::star::container::XNameAccess;
141 using ::com::sun::star::lang::EventObject;
142 using ::com::sun::star::beans::Property;
143 using ::com::sun::star::container::XEnumeration;
144 using ::com::sun::star::form::XFormComponent;
145 using ::com::sun::star::form::runtime::XFormOperations;
146 using ::com::sun::star::form::runtime::FilterEvent;
147 using ::com::sun::star::form::runtime::XFilterControllerListener;
148 using ::com::sun::star::awt::XControlContainer;
149 using ::com::sun::star::container::XIdentifierReplace;
150 using ::com::sun::star::form::XFormControllerListener;
151 using ::com::sun::star::awt::XWindow;
152 using ::com::sun::star::sdbc::XResultSet;
153 using ::com::sun::star::awt::XControlModel;
154 using ::com::sun::star::awt::XTabControllerModel;
155 using ::com::sun::star::beans::PropertyChangeEvent;
156 using ::com::sun::star::form::validation::XValidatableFormComponent;
157 using ::com::sun::star::form::XLoadable;
158 using ::com::sun::star::form::XBoundControl;
159 using ::com::sun::star::beans::XPropertyChangeListener;
160 using ::com::sun::star::awt::TextEvent;
161 using ::com::sun::star::form::XBoundComponent;
162 using ::com::sun::star::awt::XCheckBox;
163 using ::com::sun::star::awt::XComboBox;
164 using ::com::sun::star::awt::XListBox;
165 using ::com::sun::star::awt::ItemEvent;
166 using ::com::sun::star::util::XModifyListener;
167 using ::com::sun::star::form::XReset;
168 using ::com::sun::star::frame::XDispatchProviderInterception;
169 using ::com::sun::star::form::XGridControl;
170 using ::com::sun::star::awt::XVclWindowPeer;
171 using ::com::sun::star::form::validation::XValidator;
172 using ::com::sun::star::awt::FocusEvent;
173 using ::com::sun::star::sdb::SQLContext;
174 using ::com::sun::star::container::XChild;
175 using ::com::sun::star::form::TabulatorCycle_RECORDS;
176 using ::com::sun::star::container::ContainerEvent;
177 using ::com::sun::star::lang::DisposedException;
178 using ::com::sun::star::lang::Locale;
179 using ::com::sun::star::lang::NoSupportException;
180 using ::com::sun::star::sdb::RowChangeEvent;
181 using ::com::sun::star::frame::XStatusListener;
182 using ::com::sun::star::frame::XDispatchProviderInterceptor;
183 using ::com::sun::star::sdb::SQLErrorEvent;
184 using ::com::sun::star::form::DatabaseParameterEvent;
185 using ::com::sun::star::sdb::ParametersRequest;
186 using ::com::sun::star::task::XInteractionRequest;
187 using ::com::sun::star::util::URL;
188 using ::com::sun::star::frame::FeatureStateEvent;
189 using ::com::sun::star::form::runtime::XFormControllerContext;
190 using ::com::sun::star::task::InteractionHandler;
191 using ::com::sun::star::task::XInteractionHandler;
192 using ::com::sun::star::form::runtime::FormOperations;
193 using ::com::sun::star::container::XContainer;
194 using ::com::sun::star::sdbc::SQLWarning;
196 namespace ColumnValue = ::com::sun::star::sdbc::ColumnValue;
197 namespace PropertyAttribute = ::com::sun::star::beans::PropertyAttribute;
198 namespace FocusChangeReason = ::com::sun::star::awt::FocusChangeReason;
199 namespace RowChangeAction = ::com::sun::star::sdb::RowChangeAction;
200 namespace FormFeature = ::com::sun::star::form::runtime::FormFeature;
202 namespace {
204 struct ColumnInfo
206 // information about the column itself
207 Reference< XColumn > xColumn;
208 sal_Int32 nNullable;
209 bool bAutoIncrement;
210 bool bReadOnly;
211 OUString sName;
213 // information about the control(s) bound to this column
215 /// the first control which is bound to the given column, and which requires input
216 Reference< XControl > xFirstControlWithInputRequired;
217 /** the first grid control which contains a column which is bound to the given database column, and requires
218 input
220 Reference< XGrid > xFirstGridWithInputRequiredColumn;
221 /** if xFirstControlWithInputRequired is a grid control, then nRequiredGridColumn specifies the position
222 of the grid column which is actually bound
224 sal_Int32 nRequiredGridColumn;
226 ColumnInfo()
227 :nNullable( ColumnValue::NULLABLE_UNKNOWN )
228 ,bAutoIncrement( false )
229 ,bReadOnly( false )
230 ,nRequiredGridColumn( -1 )
237 class ColumnInfoCache
239 public:
240 explicit ColumnInfoCache( const Reference< XColumnsSupplier >& _rxColSupplier );
242 size_t getColumnCount() const { return m_aColumns.size(); }
243 const ColumnInfo& getColumnInfo( size_t _pos );
245 bool controlsInitialized() const { return m_bControlsInitialized; }
246 void initializeControls( const Sequence< Reference< XControl > >& _rControls );
247 void deinitializeControls();
249 private:
250 typedef ::std::vector< ColumnInfo > ColumnInfos;
251 ColumnInfos m_aColumns;
252 bool m_bControlsInitialized;
256 ColumnInfoCache::ColumnInfoCache( const Reference< XColumnsSupplier >& _rxColSupplier )
257 :m_bControlsInitialized( false )
261 m_aColumns.clear();
263 Reference< XIndexAccess > xColumns( _rxColSupplier->getColumns(), UNO_QUERY_THROW );
264 sal_Int32 nColumnCount = xColumns->getCount();
265 m_aColumns.reserve( nColumnCount );
267 Reference< XPropertySet > xColumnProps;
268 for ( sal_Int32 i = 0; i < nColumnCount; ++i )
270 ColumnInfo aColInfo;
271 aColInfo.xColumn.set( xColumns->getByIndex(i), UNO_QUERY_THROW );
273 xColumnProps.set( aColInfo.xColumn, UNO_QUERY_THROW );
274 OSL_VERIFY( xColumnProps->getPropertyValue( FM_PROP_ISNULLABLE ) >>= aColInfo.nNullable );
275 OSL_VERIFY( xColumnProps->getPropertyValue( FM_PROP_AUTOINCREMENT ) >>= aColInfo.bAutoIncrement );
276 OSL_VERIFY( xColumnProps->getPropertyValue( FM_PROP_NAME ) >>= aColInfo.sName );
277 OSL_VERIFY( xColumnProps->getPropertyValue( FM_PROP_ISREADONLY ) >>= aColInfo.bReadOnly );
279 m_aColumns.push_back( aColInfo );
282 catch( const Exception& )
284 DBG_UNHANDLED_EXCEPTION("svx");
289 namespace
291 bool lcl_isBoundTo( const Reference< XPropertySet >& _rxControlModel, const Reference< XInterface >& _rxNormDBField )
293 Reference< XInterface > xNormBoundField( _rxControlModel->getPropertyValue( FM_PROP_BOUNDFIELD ), UNO_QUERY );
294 return ( xNormBoundField == _rxNormDBField );
297 bool lcl_isInputRequired( const Reference< XPropertySet >& _rxControlModel )
299 bool bInputRequired = false;
300 OSL_VERIFY( _rxControlModel->getPropertyValue( FM_PROP_INPUT_REQUIRED ) >>= bInputRequired );
301 return bInputRequired;
304 void lcl_resetColumnControlInfo( ColumnInfo& _rColInfo )
306 _rColInfo.xFirstControlWithInputRequired.clear();
307 _rColInfo.xFirstGridWithInputRequiredColumn.clear();
308 _rColInfo.nRequiredGridColumn = -1;
313 void ColumnInfoCache::deinitializeControls()
315 for (auto& rCol : m_aColumns)
317 lcl_resetColumnControlInfo( rCol );
319 m_bControlsInitialized = false;
323 void ColumnInfoCache::initializeControls( const Sequence< Reference< XControl > >& _rControls )
327 // for every of our known columns, find the controls which are bound to this column
328 for (auto& rCol : m_aColumns)
330 OSL_ENSURE( !rCol.xFirstControlWithInputRequired.is() && !rCol.xFirstGridWithInputRequiredColumn.is()
331 && ( rCol.nRequiredGridColumn == -1 ), "ColumnInfoCache::initializeControls: called me twice?" );
333 lcl_resetColumnControlInfo( rCol );
335 Reference< XInterface > xNormColumn( rCol.xColumn, UNO_QUERY_THROW );
337 const Reference< XControl >* pControl( _rControls.getConstArray() );
338 const Reference< XControl >* pControlEnd( pControl + _rControls.getLength() );
339 for ( ; pControl != pControlEnd; ++pControl )
341 if ( !pControl->is() )
342 continue;
344 Reference< XPropertySet > xModel( (*pControl)->getModel(), UNO_QUERY_THROW );
345 Reference< XPropertySetInfo > xModelPSI( xModel->getPropertySetInfo(), UNO_SET_THROW );
347 // special handling for grid controls
348 Reference< XGrid > xGrid( *pControl, UNO_QUERY );
349 if ( xGrid.is() )
351 Reference< XIndexAccess > xGridColAccess( xModel, UNO_QUERY_THROW );
352 sal_Int32 gridColCount = xGridColAccess->getCount();
353 sal_Int32 gridCol = 0;
354 for ( gridCol = 0; gridCol < gridColCount; ++gridCol )
356 Reference< XPropertySet > xGridColumnModel( xGridColAccess->getByIndex( gridCol ), UNO_QUERY_THROW );
358 if ( !lcl_isBoundTo( xGridColumnModel, xNormColumn )
359 || !lcl_isInputRequired( xGridColumnModel )
361 continue; // with next grid column
363 break;
366 if ( gridCol < gridColCount )
368 // found a grid column which is bound to the given
369 rCol.xFirstGridWithInputRequiredColumn = xGrid;
370 rCol.nRequiredGridColumn = gridCol;
371 break;
374 continue; // with next control
377 if ( !xModelPSI->hasPropertyByName( FM_PROP_BOUNDFIELD )
378 || !lcl_isBoundTo( xModel, xNormColumn )
379 || !lcl_isInputRequired( xModel )
381 continue; // with next control
383 break;
386 if ( pControl == pControlEnd )
387 // did not find a control which is bound to this particular column, and for which the input is required
388 continue; // with next DB column
390 rCol.xFirstControlWithInputRequired = *pControl;
393 catch( const Exception& )
395 DBG_UNHANDLED_EXCEPTION("svx");
398 m_bControlsInitialized = true;
402 const ColumnInfo& ColumnInfoCache::getColumnInfo( size_t _pos )
404 if ( _pos >= m_aColumns.size() )
405 throw IndexOutOfBoundsException();
407 return m_aColumns[ _pos ];
410 namespace {
412 class OParameterContinuation : public OInteraction< XInteractionSupplyParameters >
414 Sequence< PropertyValue > m_aValues;
416 public:
417 OParameterContinuation() { }
419 const Sequence< PropertyValue >& getValues() const { return m_aValues; }
421 // XInteractionSupplyParameters
422 virtual void SAL_CALL setParameters( const Sequence< PropertyValue >& _rValues ) override;
427 void SAL_CALL OParameterContinuation::setParameters( const Sequence< PropertyValue >& _rValues )
429 m_aValues = _rValues;
433 // FmXAutoControl
435 struct FmFieldInfo
437 OUString aFieldName;
438 Reference< XPropertySet > xField;
439 Reference< XTextComponent > xText;
441 FmFieldInfo(const Reference< XPropertySet >& _xField, const Reference< XTextComponent >& _xText)
442 :xField(_xField)
443 ,xText(_xText)
444 {xField->getPropertyValue(FM_PROP_NAME) >>= aFieldName;}
447 namespace {
449 class FmXAutoControl: public UnoControl
452 public:
453 FmXAutoControl()
457 virtual OUString GetComponentServiceName() const override {return u"Edit"_ustr;}
458 virtual void SAL_CALL createPeer( const Reference< XToolkit > & rxToolkit, const Reference< XWindowPeer > & rParentPeer ) override;
460 protected:
461 virtual void ImplSetPeerProperty( const OUString& rPropName, const Any& rVal ) override;
466 void FmXAutoControl::createPeer( const Reference< XToolkit > & rxToolkit, const Reference< XWindowPeer > & rParentPeer )
468 UnoControl::createPeer( rxToolkit, rParentPeer );
470 Reference< XTextComponent > xText(getPeer() , UNO_QUERY);
471 if (xText.is())
473 xText->setText(SvxResId(RID_STR_AUTOFIELD));
474 xText->setEditable(false);
479 void FmXAutoControl::ImplSetPeerProperty( const OUString& rPropName, const Any& rVal )
481 // these properties are ignored
482 if (rPropName == FM_PROP_TEXT)
483 return;
485 UnoControl::ImplSetPeerProperty( rPropName, rVal );
489 IMPL_LINK_NOARG( FormController, OnActivateTabOrder, Timer*, void )
491 activateTabOrder();
494 namespace {
496 struct UpdateAllListeners
498 bool operator()( const Reference< XDispatch >& _rxDispatcher ) const
500 static_cast< svx::OSingleFeatureDispatcher* >( _rxDispatcher.get() )->updateAllListeners();
501 // the return is a dummy only so we can use this struct in a lambda expression
502 return true;
508 IMPL_LINK_NOARG( FormController, OnInvalidateFeatures, Timer*, void )
510 ::osl::MutexGuard aGuard( m_aMutex );
511 for (const auto& rFeature : m_aInvalidFeatures)
513 DispatcherContainer::const_iterator aDispatcherPos = m_aFeatureDispatchers.find( rFeature );
514 if ( aDispatcherPos != m_aFeatureDispatchers.end() )
516 // TODO: for the real and actual listener notifications, we should release
517 // our mutex
518 UpdateAllListeners( )( aDispatcherPos->second );
523 FormController::FormController(const Reference< css::uno::XComponentContext > & _rxORB )
524 :FormController_BASE( m_aMutex )
525 ,OPropertySetHelper( FormController_BASE::rBHelper )
526 ,OSQLParserClient( _rxORB )
527 ,m_xComponentContext( _rxORB )
528 ,m_aActivateListeners(m_aMutex)
529 ,m_aModifyListeners(m_aMutex)
530 ,m_aErrorListeners(m_aMutex)
531 ,m_aDeleteListeners(m_aMutex)
532 ,m_aRowSetApproveListeners(m_aMutex)
533 ,m_aParameterListeners(m_aMutex)
534 ,m_aFilterListeners(m_aMutex)
535 ,m_aTabActivationIdle("svx FormController m_aTabActivationIdle")
536 ,m_aFeatureInvalidationTimer("svx FormController m_aFeatureInvalidationTimer")
537 ,m_aMode( u"DataMode"_ustr )
538 ,m_aLoadEvent( LINK( this, FormController, OnLoad ) )
539 ,m_aToggleEvent( LINK( this, FormController, OnToggleAutoFields ) )
540 ,m_aActivationEvent( LINK( this, FormController, OnActivated ) )
541 ,m_aDeactivationEvent( LINK( this, FormController, OnDeactivated ) )
542 ,m_nCurrentFilterPosition(-1)
543 ,m_bCurrentRecordModified(false)
544 ,m_bCurrentRecordNew(false)
545 ,m_bLocked(false)
546 ,m_bDBConnection(false)
547 ,m_bCycle(false)
548 ,m_bCanInsert(false)
549 ,m_bCanUpdate(false)
550 ,m_bCommitLock(false)
551 ,m_bModified(false)
552 ,m_bControlsSorted(false)
553 ,m_bFiltering(false)
554 ,m_bAttachEvents(true)
555 ,m_bDetachEvents(true)
556 ,m_bAttemptedHandlerCreation( false )
557 ,m_bSuspendFilterTextListening( false )
560 osl_atomic_increment(&m_refCount);
562 m_xTabController = TabController::create( m_xComponentContext );
563 m_xAggregate.set( m_xTabController, UNO_QUERY_THROW );
564 m_xAggregate->setDelegator( *this );
566 osl_atomic_decrement(&m_refCount);
568 m_aTabActivationIdle.SetPriority( TaskPriority::LOWEST );
569 m_aTabActivationIdle.SetInvokeHandler( LINK( this, FormController, OnActivateTabOrder ) );
571 m_aFeatureInvalidationTimer.SetTimeout( 200 );
572 m_aFeatureInvalidationTimer.SetInvokeHandler( LINK( this, FormController, OnInvalidateFeatures ) );
576 FormController::~FormController()
579 ::osl::MutexGuard aGuard( m_aMutex );
581 m_aLoadEvent.CancelPendingCall();
582 m_aToggleEvent.CancelPendingCall();
583 m_aActivationEvent.CancelPendingCall();
584 m_aDeactivationEvent.CancelPendingCall();
586 if ( m_aTabActivationIdle.IsActive() )
587 m_aTabActivationIdle.Stop();
590 if ( m_aFeatureInvalidationTimer.IsActive() )
591 m_aFeatureInvalidationTimer.Stop();
593 disposeAllFeaturesAndDispatchers();
595 if ( m_xFormOperations.is() )
596 m_xFormOperations->dispose();
597 m_xFormOperations.clear();
599 // release of aggregation
600 if ( m_xAggregate.is() )
602 m_xAggregate->setDelegator( nullptr );
603 m_xAggregate.clear();
608 void SAL_CALL FormController::acquire() noexcept
610 FormController_BASE::acquire();
614 void SAL_CALL FormController::release() noexcept
616 FormController_BASE::release();
620 Any SAL_CALL FormController::queryInterface( const Type& _rType )
622 Any aRet = FormController_BASE::queryInterface( _rType );
623 if ( !aRet.hasValue() )
624 aRet = OPropertySetHelper::queryInterface( _rType );
625 if ( !aRet.hasValue() )
626 aRet = m_xAggregate->queryAggregation( _rType );
627 return aRet;
631 Sequence< sal_Int8 > SAL_CALL FormController::getImplementationId()
633 return css::uno::Sequence<sal_Int8>();
636 Sequence< Type > SAL_CALL FormController::getTypes( )
638 return comphelper::concatSequences(
639 FormController_BASE::getTypes(),
640 ::cppu::OPropertySetHelper::getTypes()
644 // XServiceInfo
645 sal_Bool SAL_CALL FormController::supportsService(const OUString& ServiceName)
647 return cppu::supportsService(this, ServiceName);
650 OUString SAL_CALL FormController::getImplementationName()
652 return u"org.openoffice.comp.svx.FormController"_ustr;
655 Sequence< OUString> SAL_CALL FormController::getSupportedServiceNames()
657 // service names which are supported only, but cannot be used to created an
658 // instance at a service factory
659 Sequence<OUString> aNonCreatableServiceNames { u"com.sun.star.form.FormControllerDispatcher"_ustr };
661 // services which can be used to created an instance at a service factory
662 Sequence< OUString > aCreatableServiceNames( getSupportedServiceNames_Static() );
663 return ::comphelper::concatSequences( aCreatableServiceNames, aNonCreatableServiceNames );
667 sal_Bool SAL_CALL FormController::approveReset(const EventObject& /*rEvent*/)
669 return true;
673 void SAL_CALL FormController::resetted(const EventObject& rEvent)
675 ::osl::MutexGuard aGuard(m_aMutex);
676 if (getCurrentControl().is() && (getCurrentControl()->getModel() == rEvent.Source))
677 m_bModified = false;
681 Sequence< OUString> const & FormController::getSupportedServiceNames_Static()
683 static Sequence< OUString> const aServices
685 u"com.sun.star.form.runtime.FormController"_ustr,
686 u"com.sun.star.awt.control.TabController"_ustr
688 return aServices;
692 namespace
694 struct ResetComponentText
696 void operator()( const Reference< XTextComponent >& _rxText )
698 _rxText->setText( OUString() );
702 struct RemoveComponentTextListener
704 explicit RemoveComponentTextListener( const Reference< XTextListener >& _rxListener )
705 :m_xListener( _rxListener )
709 void operator()( const Reference< XTextComponent >& _rxText )
711 _rxText->removeTextListener( m_xListener );
714 private:
715 Reference< XTextListener > m_xListener;
720 void FormController::impl_setTextOnAllFilter_throw()
722 m_bSuspendFilterTextListening = true;
723 ::comphelper::FlagGuard aResetFlag( m_bSuspendFilterTextListening );
725 // reset the text for all controls
726 ::std::for_each( m_aFilterComponents.begin(), m_aFilterComponents.end(), ResetComponentText() );
728 if ( m_aFilterRows.empty() )
729 // nothing to do anymore
730 return;
732 if ( m_nCurrentFilterPosition < 0 )
733 return;
735 // set the text for all filters
736 OSL_ENSURE( m_aFilterRows.size() > o3tl::make_unsigned(m_nCurrentFilterPosition),
737 "FormController::impl_setTextOnAllFilter_throw: m_nCurrentFilterPosition too big" );
739 if ( o3tl::make_unsigned(m_nCurrentFilterPosition) < m_aFilterRows.size() )
741 FmFilterRow& rRow = m_aFilterRows[ m_nCurrentFilterPosition ];
742 for (const auto& rEntry : rRow)
744 rEntry.first->setText( rEntry.second );
748 // OPropertySetHelper
750 sal_Bool FormController::convertFastPropertyValue( Any & /*rConvertedValue*/, Any & /*rOldValue*/,
751 sal_Int32 /*nHandle*/, const Any& /*rValue*/ )
753 return false;
757 void FormController::setFastPropertyValue_NoBroadcast( sal_Int32 /*nHandle*/, const Any& /*rValue*/ )
762 void FormController::getFastPropertyValue( Any& rValue, sal_Int32 nHandle ) const
764 switch (nHandle)
766 case FM_ATTR_FILTER:
768 OUStringBuffer aFilter;
769 Reference<XConnection> xConnection(getConnection(Reference< XRowSet>(m_xModelAsIndex, UNO_QUERY)));
770 if (xConnection.is())
772 Reference< XNumberFormatsSupplier> xFormatSupplier( getNumberFormats( xConnection, true ) );
773 Reference< XNumberFormatter> xFormatter = NumberFormatter::create(m_xComponentContext);
774 xFormatter->attachNumberFormatsSupplier(xFormatSupplier);
776 // now add the filter rows
779 for (const FmFilterRow& rRow : m_aFilterRows)
781 if ( rRow.empty() )
782 continue;
784 OUStringBuffer aRowFilter;
785 for ( FmFilterRow::const_iterator condition = rRow.begin(); condition != rRow.end(); ++condition )
787 // get the field of the controls map
788 Reference< XControl > xControl( condition->first, UNO_QUERY_THROW );
789 Reference< XPropertySet > xModelProps( xControl->getModel(), UNO_QUERY_THROW );
790 Reference< XPropertySet > xField( xModelProps->getPropertyValue( FM_PROP_BOUNDFIELD ), UNO_QUERY_THROW );
792 OUString sFilterValue( condition->second );
794 OUString sErrorMsg;
795 const std::unique_ptr< OSQLParseNode > pParseNode =
796 predicateTree( sErrorMsg, sFilterValue, xFormatter, xField );
797 OSL_ENSURE( pParseNode != nullptr, "FormController::getFastPropertyValue: could not parse the field value predicate!" );
798 if ( pParseNode != nullptr )
800 OUString sCriteria;
801 // don't use a parse context here, we need it unlocalized
802 pParseNode->parseNodeToStr( sCriteria, xConnection );
803 if ( condition != rRow.begin() )
804 aRowFilter.append( " AND " );
805 aRowFilter.append( sCriteria );
808 if ( !aRowFilter.isEmpty() )
810 if ( !aFilter.isEmpty() )
811 aFilter.append( " OR " );
813 aFilter.append( "( " + aRowFilter + " )" );
817 catch( const Exception& )
819 DBG_UNHANDLED_EXCEPTION("svx");
820 aFilter.setLength(0);
823 rValue <<= aFilter.makeStringAndClear();
825 break;
827 case FM_ATTR_FORM_OPERATIONS:
828 rValue <<= m_xFormOperations;
829 break;
834 Reference< XPropertySetInfo > FormController::getPropertySetInfo()
836 static Reference< XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
837 return xInfo;
841 void FormController::fillProperties(
842 Sequence< Property >& /* [out] */ _rProps,
843 Sequence< Property >& /* [out] */ /*_rAggregateProps*/
844 ) const
846 _rProps.realloc(2);
847 sal_Int32 nPos = 0;
848 Property* pDesc = _rProps.getArray();
850 pDesc[nPos++] = Property(FM_PROP_FILTER, FM_ATTR_FILTER,
851 cppu::UnoType<OUString>::get(),
852 PropertyAttribute::READONLY);
853 pDesc[nPos++] = Property(FM_PROP_FORM_OPERATIONS, FM_ATTR_FORM_OPERATIONS,
854 cppu::UnoType<XFormOperations>::get(),
855 PropertyAttribute::READONLY);
859 ::cppu::IPropertyArrayHelper& FormController::getInfoHelper()
861 return *getArrayHelper();
864 // XFilterController
866 void SAL_CALL FormController::addFilterControllerListener( const Reference< XFilterControllerListener >& Listener )
868 m_aFilterListeners.addInterface( Listener );
872 void SAL_CALL FormController::removeFilterControllerListener( const Reference< XFilterControllerListener >& Listener )
874 m_aFilterListeners.removeInterface( Listener );
878 ::sal_Int32 SAL_CALL FormController::getFilterComponents()
880 ::osl::MutexGuard aGuard( m_aMutex );
881 impl_checkDisposed_throw();
883 return m_aFilterComponents.size();
887 ::sal_Int32 SAL_CALL FormController::getDisjunctiveTerms()
889 ::osl::MutexGuard aGuard( m_aMutex );
890 impl_checkDisposed_throw();
892 return m_aFilterRows.size();
896 void SAL_CALL FormController::setPredicateExpression( ::sal_Int32 Component, ::sal_Int32 Term, const OUString& PredicateExpression )
898 ::osl::MutexGuard aGuard( m_aMutex );
899 impl_checkDisposed_throw();
901 if ( ( Component < 0 ) || ( Component >= getFilterComponents() ) || ( Term < 0 ) || ( Term >= getDisjunctiveTerms() ) )
902 throw IndexOutOfBoundsException( OUString(), *this );
904 Reference< XTextComponent > xText( m_aFilterComponents[ Component ] );
905 xText->setText( PredicateExpression );
907 FmFilterRow& rFilterRow = m_aFilterRows[ Term ];
908 if ( !PredicateExpression.isEmpty() )
909 rFilterRow[ xText ] = PredicateExpression;
910 else
911 rFilterRow.erase( xText );
915 Reference< XControl > FormController::getFilterComponent( ::sal_Int32 Component )
917 ::osl::MutexGuard aGuard( m_aMutex );
918 impl_checkDisposed_throw();
920 if ( ( Component < 0 ) || ( Component >= getFilterComponents() ) )
921 throw IndexOutOfBoundsException( OUString(), *this );
923 return Reference< XControl >( m_aFilterComponents[ Component ], UNO_QUERY );
927 Sequence< Sequence< OUString > > FormController::getPredicateExpressions()
929 ::osl::MutexGuard aGuard( m_aMutex );
930 impl_checkDisposed_throw();
932 Sequence< Sequence< OUString > > aExpressions( m_aFilterRows.size() );
933 auto aExpressionsRange = asNonConstRange(aExpressions);
934 sal_Int32 termIndex = 0;
935 for (const FmFilterRow& rRow : m_aFilterRows)
937 Sequence< OUString > aConjunction( m_aFilterComponents.size() );
938 auto aConjunctionRange = asNonConstRange(aConjunction);
939 sal_Int32 componentIndex = 0;
940 for (const auto& rComp : m_aFilterComponents)
942 FmFilterRow::const_iterator predicate = rRow.find( rComp );
943 if ( predicate != rRow.end() )
944 aConjunctionRange[ componentIndex ] = predicate->second;
945 ++componentIndex;
948 aExpressionsRange[ termIndex ] = aConjunction;
949 ++termIndex;
952 return aExpressions;
956 void SAL_CALL FormController::removeDisjunctiveTerm( ::sal_Int32 Term )
958 // SYNCHRONIZED -->
959 ::osl::ClearableMutexGuard aGuard( m_aMutex );
960 impl_checkDisposed_throw();
962 if ( ( Term < 0 ) || ( Term >= getDisjunctiveTerms() ) )
963 throw IndexOutOfBoundsException( OUString(), *this );
965 // if the to-be-deleted row is our current row, we need to shift
966 if ( Term == m_nCurrentFilterPosition )
968 if ( m_nCurrentFilterPosition < sal_Int32( m_aFilterRows.size() - 1 ) )
969 ++m_nCurrentFilterPosition;
970 else
971 --m_nCurrentFilterPosition;
974 FmFilterRows::iterator pos = m_aFilterRows.begin() + Term;
975 m_aFilterRows.erase( pos );
977 // adjust m_nCurrentFilterPosition if the removed row preceded it
978 if ( Term < m_nCurrentFilterPosition )
979 --m_nCurrentFilterPosition;
981 SAL_WARN_IF( !( ( m_nCurrentFilterPosition < 0 ) != ( m_aFilterRows.empty() ) ),
982 "svx.form", "FormController::removeDisjunctiveTerm: inconsistency!" );
984 // update the texts in the filter controls
985 impl_setTextOnAllFilter_throw();
987 FilterEvent aEvent;
988 aEvent.Source = *this;
989 aEvent.DisjunctiveTerm = Term;
990 aGuard.clear();
991 // <-- SYNCHRONIZED
993 m_aFilterListeners.notifyEach( &XFilterControllerListener::disjunctiveTermRemoved, aEvent );
997 void SAL_CALL FormController::appendEmptyDisjunctiveTerm()
999 // SYNCHRONIZED -->
1000 ::osl::ClearableMutexGuard aGuard( m_aMutex );
1001 impl_checkDisposed_throw();
1003 impl_appendEmptyFilterRow( aGuard );
1004 // <-- SYNCHRONIZED
1008 ::sal_Int32 SAL_CALL FormController::getActiveTerm()
1010 ::osl::MutexGuard aGuard( m_aMutex );
1011 impl_checkDisposed_throw();
1013 return m_nCurrentFilterPosition;
1017 void SAL_CALL FormController::setActiveTerm( ::sal_Int32 ActiveTerm )
1019 ::osl::MutexGuard aGuard( m_aMutex );
1020 impl_checkDisposed_throw();
1022 if ( ( ActiveTerm < 0 ) || ( ActiveTerm >= getDisjunctiveTerms() ) )
1023 throw IndexOutOfBoundsException( OUString(), *this );
1025 if ( ActiveTerm == getActiveTerm() )
1026 return;
1028 m_nCurrentFilterPosition = ActiveTerm;
1029 impl_setTextOnAllFilter_throw();
1032 // XElementAccess
1034 sal_Bool SAL_CALL FormController::hasElements()
1036 ::osl::MutexGuard aGuard( m_aMutex );
1037 return !m_aChildren.empty();
1041 Type SAL_CALL FormController::getElementType()
1043 return cppu::UnoType<XFormController>::get();
1047 // XEnumerationAccess
1049 Reference< XEnumeration > SAL_CALL FormController::createEnumeration()
1051 ::osl::MutexGuard aGuard( m_aMutex );
1052 return new ::comphelper::OEnumerationByIndex(this);
1055 // XIndexAccess
1057 sal_Int32 SAL_CALL FormController::getCount()
1059 ::osl::MutexGuard aGuard( m_aMutex );
1060 return m_aChildren.size();
1064 Any SAL_CALL FormController::getByIndex(sal_Int32 Index)
1066 ::osl::MutexGuard aGuard( m_aMutex );
1067 if (Index < 0 ||
1068 o3tl::make_unsigned(Index) >= m_aChildren.size())
1069 throw IndexOutOfBoundsException();
1071 return Any( m_aChildren[ Index ] );
1074 // EventListener
1076 void SAL_CALL FormController::disposing(const EventObject& e)
1078 // has the container been disposed
1079 ::osl::MutexGuard aGuard( m_aMutex );
1080 Reference< XControlContainer > xContainer(e.Source, UNO_QUERY);
1081 if (xContainer.is())
1083 setContainer(Reference< XControlContainer > ());
1085 else
1087 // has a control been disposed
1088 Reference< XControl > xControl(e.Source, UNO_QUERY);
1089 if (xControl.is())
1091 if (getContainer().is())
1092 removeControl(xControl);
1097 // OComponentHelper
1099 void FormController::disposeAllFeaturesAndDispatchers()
1101 for (auto& rDispatcher : m_aFeatureDispatchers)
1105 ::comphelper::disposeComponent( rDispatcher.second );
1107 catch( const Exception& )
1109 DBG_UNHANDLED_EXCEPTION("svx");
1112 m_aFeatureDispatchers.clear();
1116 void FormController::disposing()
1118 EventObject aEvt( *this );
1120 // if we're still active, simulate a "deactivated" event
1121 if ( m_xActiveControl.is() )
1122 m_aActivateListeners.notifyEach( &XFormControllerListener::formDeactivated, aEvt );
1124 // notify all our listeners
1125 m_aActivateListeners.disposeAndClear(aEvt);
1126 m_aModifyListeners.disposeAndClear(aEvt);
1127 m_aErrorListeners.disposeAndClear(aEvt);
1128 m_aDeleteListeners.disposeAndClear(aEvt);
1129 m_aRowSetApproveListeners.disposeAndClear(aEvt);
1130 m_aParameterListeners.disposeAndClear(aEvt);
1131 m_aFilterListeners.disposeAndClear(aEvt);
1133 removeBoundFieldListener();
1134 stopFiltering();
1136 m_aControlBorderManager.restoreAll();
1138 m_aFilterRows.clear();
1140 ::osl::MutexGuard aGuard( m_aMutex );
1141 m_xActiveControl = nullptr;
1142 implSetCurrentControl( nullptr );
1144 // clean up our children
1145 for (const auto& rpChild : m_aChildren)
1147 // search the position of the model within the form
1148 Reference< XFormComponent > xForm(rpChild->getModel(), UNO_QUERY);
1149 sal_uInt32 nPos = m_xModelAsIndex->getCount();
1150 Reference< XFormComponent > xTemp;
1151 for( ; nPos; )
1154 m_xModelAsIndex->getByIndex( --nPos ) >>= xTemp;
1155 if ( xForm.get() == xTemp.get() )
1157 Reference< XInterface > xIfc( rpChild, UNO_QUERY );
1158 m_xModelAsManager->detach( nPos, xIfc );
1159 break;
1163 Reference< XComponent > (rpChild, UNO_QUERY_THROW)->dispose();
1165 m_aChildren.clear();
1167 disposeAllFeaturesAndDispatchers();
1169 if ( m_xFormOperations.is() )
1170 m_xFormOperations->dispose();
1171 m_xFormOperations.clear();
1173 if (m_bDBConnection)
1174 unload();
1176 setContainer( nullptr );
1177 setModel( nullptr );
1178 setParent( nullptr );
1180 ::comphelper::disposeComponent( m_xComposer );
1182 m_bDBConnection = false;
1186 namespace
1188 bool lcl_shouldUseDynamicControlBorder( const Reference< XInterface >& _rxForm, const Any& _rDynamicColorProp )
1190 bool bDoUse = false;
1191 if ( !( _rDynamicColorProp >>= bDoUse ) )
1193 DocumentType eDocType = DocumentClassification::classifyHostDocument( _rxForm );
1194 return ControlLayouter::useDynamicBorderColor( eDocType );
1196 return bDoUse;
1201 void SAL_CALL FormController::propertyChange(const PropertyChangeEvent& evt)
1203 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1204 if ( evt.PropertyName == FM_PROP_BOUNDFIELD )
1206 Reference<XPropertySet> xOldBound;
1207 evt.OldValue >>= xOldBound;
1208 if ( !xOldBound.is() && evt.NewValue.hasValue() )
1210 Reference< XControlModel > xControlModel(evt.Source,UNO_QUERY);
1211 Reference< XControl > xControl = findControl(m_aControls,xControlModel,false,false);
1212 if ( xControl.is() )
1214 startControlModifyListening( xControl );
1215 Reference<XPropertySet> xProp(xControlModel,UNO_QUERY);
1216 if ( xProp.is() )
1217 xProp->removePropertyChangeListener(FM_PROP_BOUNDFIELD, this);
1221 else
1223 bool bModifiedChanged = (evt.PropertyName == FM_PROP_ISMODIFIED);
1224 bool bNewChanged = (evt.PropertyName == FM_PROP_ISNEW);
1225 if (bModifiedChanged || bNewChanged)
1227 ::osl::MutexGuard aGuard( m_aMutex );
1228 if (bModifiedChanged)
1229 m_bCurrentRecordModified = ::comphelper::getBOOL(evt.NewValue);
1230 else
1231 m_bCurrentRecordNew = ::comphelper::getBOOL(evt.NewValue);
1233 // toggle the locking
1234 if (m_bLocked != determineLockState())
1236 m_bLocked = !m_bLocked;
1237 setLocks();
1238 if (isListeningForChanges())
1239 startListening();
1240 else
1241 stopListening();
1244 if ( bNewChanged )
1245 m_aToggleEvent.Call();
1247 if (!m_bCurrentRecordModified)
1248 m_bModified = false;
1250 else if ( evt.PropertyName == FM_PROP_DYNAMIC_CONTROL_BORDER )
1252 bool bEnable = lcl_shouldUseDynamicControlBorder( evt.Source, evt.NewValue );
1253 if ( bEnable )
1255 m_aControlBorderManager.enableDynamicBorderColor();
1256 if ( m_xActiveControl.is() )
1257 m_aControlBorderManager.focusGained( m_xActiveControl );
1259 else
1261 m_aControlBorderManager.disableDynamicBorderColor();
1268 bool FormController::replaceControl( const Reference< XControl >& _rxExistentControl, const Reference< XControl >& _rxNewControl )
1270 bool bSuccess = false;
1273 Reference< XIdentifierReplace > xContainer( getContainer(), UNO_QUERY );
1274 DBG_ASSERT( xContainer.is(), "FormController::replaceControl: yes, it's not required by the service description, but XIdentifierReplace would be nice!" );
1275 if ( xContainer.is() )
1277 // look up the ID of _rxExistentControl
1278 const Sequence< sal_Int32 > aIdentifiers( xContainer->getIdentifiers() );
1279 const sal_Int32* pIdentifiers = std::find_if(aIdentifiers.begin(), aIdentifiers.end(),
1280 [&xContainer, &_rxExistentControl](const sal_Int32 nId) {
1281 Reference< XControl > xCheck( xContainer->getByIdentifier( nId ), UNO_QUERY );
1282 return xCheck == _rxExistentControl;
1284 DBG_ASSERT( pIdentifiers != aIdentifiers.end(), "FormController::replaceControl: did not find the control in the container!" );
1285 if ( pIdentifiers != aIdentifiers.end() )
1287 bool bReplacedWasActive = ( m_xActiveControl.get() == _rxExistentControl.get() );
1288 bool bReplacedWasCurrent = ( m_xCurrentControl.get() == _rxExistentControl.get() );
1290 if ( bReplacedWasActive )
1292 m_xActiveControl = nullptr;
1293 implSetCurrentControl( nullptr );
1295 else if ( bReplacedWasCurrent )
1297 implSetCurrentControl( _rxNewControl );
1300 // carry over the model
1301 _rxNewControl->setModel( _rxExistentControl->getModel() );
1303 xContainer->replaceByIdentifer( *pIdentifiers, Any( _rxNewControl ) );
1304 bSuccess = true;
1306 if ( bReplacedWasActive )
1308 Reference< XWindow > xControlWindow( _rxNewControl, UNO_QUERY );
1309 if ( xControlWindow.is() )
1310 xControlWindow->setFocus();
1315 catch( const Exception& )
1317 DBG_UNHANDLED_EXCEPTION("svx");
1320 Reference< XControl > xDisposeIt( bSuccess ? _rxExistentControl : _rxNewControl );
1321 ::comphelper::disposeComponent( xDisposeIt );
1322 return bSuccess;
1326 void FormController::toggleAutoFields(bool bAutoFields)
1328 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1331 Sequence< Reference< XControl > > aControlsCopy( m_aControls );
1332 const Reference< XControl >* pControls = aControlsCopy.getConstArray();
1333 sal_Int32 nControls = aControlsCopy.getLength();
1335 if (bAutoFields)
1337 // as we don't want new controls to be attached to the scripting environment
1338 // we change attach flags
1339 m_bAttachEvents = false;
1340 for (sal_Int32 i = nControls; i > 0;)
1342 Reference< XControl > xControl = pControls[--i];
1343 if (xControl.is())
1345 Reference< XPropertySet > xSet(xControl->getModel(), UNO_QUERY);
1346 if (xSet.is() && ::comphelper::hasProperty(FM_PROP_BOUNDFIELD, xSet))
1348 // does the model use a bound field ?
1349 Reference< XPropertySet > xField;
1350 xSet->getPropertyValue(FM_PROP_BOUNDFIELD) >>= xField;
1352 // is it an autofield?
1353 if ( xField.is()
1354 && ::comphelper::hasProperty( FM_PROP_AUTOINCREMENT, xField )
1355 && ::comphelper::getBOOL( xField->getPropertyValue( FM_PROP_AUTOINCREMENT ) )
1358 replaceControl( xControl, new FmXAutoControl() );
1363 m_bAttachEvents = true;
1365 else
1367 m_bDetachEvents = false;
1368 for (sal_Int32 i = nControls; i > 0;)
1370 Reference< XControl > xControl = pControls[--i];
1371 if (xControl.is())
1373 Reference< XPropertySet > xSet(xControl->getModel(), UNO_QUERY);
1374 if (xSet.is() && ::comphelper::hasProperty(FM_PROP_BOUNDFIELD, xSet))
1376 // does the model use a bound field ?
1377 Reference< XPropertySet > xField;
1378 xSet->getPropertyValue(FM_PROP_BOUNDFIELD) >>= xField;
1380 // is it an autofield?
1381 if ( xField.is()
1382 && ::comphelper::hasProperty( FM_PROP_AUTOINCREMENT, xField )
1383 && ::comphelper::getBOOL( xField->getPropertyValue(FM_PROP_AUTOINCREMENT ) )
1386 OUString sServiceName;
1387 OSL_VERIFY( xSet->getPropertyValue( FM_PROP_DEFAULTCONTROL ) >>= sServiceName );
1388 Reference< XControl > xNewControl( m_xComponentContext->getServiceManager()->createInstanceWithContext( sServiceName, m_xComponentContext ), UNO_QUERY );
1389 replaceControl( xControl, xNewControl );
1394 m_bDetachEvents = true;
1399 IMPL_LINK_NOARG(FormController, OnToggleAutoFields, void*, void)
1401 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1403 toggleAutoFields(m_bCurrentRecordNew);
1406 // XTextListener
1407 void SAL_CALL FormController::textChanged(const TextEvent& e)
1409 // SYNCHRONIZED -->
1410 ::osl::ClearableMutexGuard aGuard( m_aMutex );
1411 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1412 if ( !m_bFiltering )
1414 impl_onModify();
1415 return;
1418 if ( m_bSuspendFilterTextListening )
1419 return;
1421 Reference< XTextComponent > xText(e.Source,UNO_QUERY);
1422 OUString aText = xText->getText();
1424 if ( m_aFilterRows.empty() )
1425 appendEmptyDisjunctiveTerm();
1427 // find the current row
1428 if ( ( m_nCurrentFilterPosition < 0 ) || ( o3tl::make_unsigned(m_nCurrentFilterPosition) >= m_aFilterRows.size() ) )
1430 OSL_ENSURE( false, "FormController::textChanged: m_nCurrentFilterPosition is wrong!" );
1431 return;
1434 FmFilterRow& rRow = m_aFilterRows[ m_nCurrentFilterPosition ];
1436 // do we have a new filter
1437 if (!aText.isEmpty())
1438 rRow[xText] = aText;
1439 else
1441 // do we have the control in the row
1442 FmFilterRow::iterator iter = rRow.find(xText);
1443 // erase the entry out of the row
1444 if (iter != rRow.end())
1445 rRow.erase(iter);
1448 // multiplex the event to our FilterControllerListeners
1449 FilterEvent aEvent;
1450 aEvent.Source = *this;
1451 aEvent.FilterComponent = ::std::find( m_aFilterComponents.begin(), m_aFilterComponents.end(), xText ) - m_aFilterComponents.begin();
1452 aEvent.DisjunctiveTerm = getActiveTerm();
1453 aEvent.PredicateExpression = aText;
1455 aGuard.clear();
1456 // <-- SYNCHRONIZED
1458 // notify the changed filter expression
1459 m_aFilterListeners.notifyEach( &XFilterControllerListener::predicateExpressionChanged, aEvent );
1462 // XItemListener
1463 void SAL_CALL FormController::itemStateChanged(const ItemEvent& /*rEvent*/)
1465 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1466 impl_onModify();
1469 // XModificationBroadcaster
1470 void SAL_CALL FormController::addModifyListener(const Reference< XModifyListener > & l)
1472 ::osl::MutexGuard aGuard( m_aMutex );
1473 impl_checkDisposed_throw();
1474 m_aModifyListeners.addInterface( l );
1477 void FormController::removeModifyListener(const Reference< XModifyListener > & l)
1479 ::osl::MutexGuard aGuard( m_aMutex );
1480 impl_checkDisposed_throw();
1481 m_aModifyListeners.removeInterface( l );
1484 // XModificationListener
1485 void FormController::modified( const EventObject& _rEvent )
1487 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1491 if ( _rEvent.Source != m_xActiveControl )
1492 { // let this control grab the focus
1493 // (this case may happen if somebody moves the scroll wheel of the mouse over a control
1494 // which does not have the focus)
1495 // 85511 - 29.05.2001 - frank.schoenheit@germany.sun.com
1497 // also, it happens when an image control gets a new image by double-clicking it
1498 // #i88458# / 2009-01-12 / frank.schoenheit@sun.com
1499 Reference< XWindow > xControlWindow( _rEvent.Source, UNO_QUERY_THROW );
1500 xControlWindow->setFocus();
1503 catch( const Exception& )
1505 DBG_UNHANDLED_EXCEPTION("svx");
1508 impl_onModify();
1511 void FormController::impl_checkDisposed_throw() const
1513 if ( impl_isDisposed_nofail() )
1514 throw DisposedException( OUString(), *const_cast< FormController* >( this ) );
1517 void FormController::impl_onModify()
1519 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1522 ::osl::MutexGuard aGuard( m_aMutex );
1523 if ( !m_bModified )
1524 m_bModified = true;
1527 EventObject aEvt(getXWeak());
1528 m_aModifyListeners.notifyEach( &XModifyListener::modified, aEvt );
1531 void FormController::impl_addFilterRow( const FmFilterRow& _row )
1533 m_aFilterRows.push_back( _row );
1535 if ( m_aFilterRows.size() == 1 )
1536 { // that's the first row ever
1537 OSL_ENSURE( m_nCurrentFilterPosition == -1, "FormController::impl_addFilterRow: inconsistency!" );
1538 m_nCurrentFilterPosition = 0;
1542 void FormController::impl_appendEmptyFilterRow( ::osl::ClearableMutexGuard& _rClearBeforeNotify )
1544 // SYNCHRONIZED -->
1545 impl_addFilterRow( FmFilterRow() );
1547 // notify the listeners
1548 FilterEvent aEvent;
1549 aEvent.Source = *this;
1550 aEvent.DisjunctiveTerm = static_cast<sal_Int32>(m_aFilterRows.size()) - 1;
1551 _rClearBeforeNotify.clear();
1552 // <-- SYNCHRONIZED
1553 m_aFilterListeners.notifyEach( &XFilterControllerListener::disjunctiveTermAdded, aEvent );
1556 bool FormController::determineLockState() const
1558 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1559 // a.) in filter mode we are always locked
1560 // b.) if we have no valid model or our model (a result set) is not alive -> we're locked
1561 // c.) if we are inserting everything is OK and we are not locked
1562 // d.) if are not updatable or on invalid position
1563 Reference< XResultSet > xResultSet(m_xModelAsIndex, UNO_QUERY);
1564 if (m_bFiltering || !xResultSet.is() || !isRowSetAlive(xResultSet))
1565 return true;
1566 else
1567 return !(m_bCanInsert && m_bCurrentRecordNew)
1568 && (xResultSet->isBeforeFirst() || xResultSet->isAfterLast() || xResultSet->rowDeleted() || !m_bCanUpdate);
1571 // FocusListener
1572 void FormController::focusGained(const FocusEvent& e)
1574 // SYNCHRONIZED -->
1575 ::osl::ClearableMutexGuard aGuard( m_aMutex );
1576 impl_checkDisposed_throw();
1578 m_aControlBorderManager.focusGained( e.Source );
1580 Reference< XControl > xControl(e.Source, UNO_QUERY);
1581 if (m_bDBConnection)
1583 // do we need to keep the locking of the commit
1584 // we hold the lock as long as the control differs from the current
1585 // otherwise we disabled the lock
1586 m_bCommitLock = m_bCommitLock && xControl.get() != m_xCurrentControl.get();
1587 if (m_bCommitLock)
1588 return;
1590 // when do we have to commit a value to form or a filter
1591 // a.) if the current value is modified
1592 // b.) there must be a current control
1593 // c.) and it must be different from the new focus owning control or
1594 // d.) the focus is moving around (so we have only one control)
1596 if ( ( m_bModified || m_bFiltering )
1597 && m_xCurrentControl.is()
1598 && ( ( xControl.get() != m_xCurrentControl.get() )
1599 || ( ( e.FocusFlags & FocusChangeReason::AROUND )
1600 && ( m_bCycle || m_bFiltering )
1605 // check the old control if the content is ok
1606 #if OSL_DEBUG_LEVEL > 0 && !defined NDEBUG
1607 Reference< XBoundControl > xLockingTest(m_xCurrentControl, UNO_QUERY);
1608 bool bControlIsLocked = xLockingTest.is() && xLockingTest->getLock();
1609 assert(!bControlIsLocked && "FormController::Gained: I'm modified and the current control is locked ? How this ?");
1610 // normally, a locked control should not be modified, so probably my bModified must
1611 // have been set from a different context, which I would not understand ...
1612 #endif
1613 DBG_ASSERT(m_xCurrentControl.is(), "no CurrentControl set");
1614 // first the control ask if it supports the IFace
1615 Reference< XBoundComponent > xBound(m_xCurrentControl, UNO_QUERY);
1616 if (!xBound.is() && m_xCurrentControl.is())
1617 xBound.set(m_xCurrentControl->getModel(), UNO_QUERY);
1619 // lock if we lose the focus during commit
1620 m_bCommitLock = true;
1622 // commit unsuccessful, reset focus
1623 if (xBound.is() && !xBound->commit())
1625 // the commit failed and we don't commit again until the current control
1626 // which couldn't be commit gains the focus again
1627 Reference< XWindow > xWindow(m_xCurrentControl, UNO_QUERY);
1628 if (xWindow.is())
1629 xWindow->setFocus();
1630 return;
1632 else
1634 m_bModified = false;
1635 m_bCommitLock = false;
1639 if (!m_bFiltering && m_bCycle && (e.FocusFlags & FocusChangeReason::AROUND) && m_xCurrentControl.is())
1641 OSL_ENSURE( m_xFormOperations.is(), "FormController::focusGained: hmm?" );
1642 // should have been created in setModel
1645 if ( e.FocusFlags & FocusChangeReason::FORWARD )
1647 if ( m_xFormOperations.is() && m_xFormOperations->isEnabled( FormFeature::MoveToNext ) )
1648 m_xFormOperations->execute( FormFeature::MoveToNext );
1650 else // backward
1652 if ( m_xFormOperations.is() && m_xFormOperations->isEnabled( FormFeature::MoveToPrevious ) )
1653 m_xFormOperations->execute( FormFeature::MoveToPrevious );
1656 catch ( const Exception& )
1658 // don't handle this any further. That's an ... admissible error.
1659 DBG_UNHANDLED_EXCEPTION("svx");
1664 // still one and the same control
1665 if ( ( m_xActiveControl == xControl )
1666 && ( xControl == m_xCurrentControl )
1669 DBG_ASSERT(m_xCurrentControl.is(), "No CurrentControl selected");
1670 return;
1673 bool bActivated = !m_xActiveControl.is() && xControl.is();
1675 m_xActiveControl = xControl;
1677 implSetCurrentControl( xControl );
1678 SAL_WARN_IF( !m_xCurrentControl.is(), "svx.form", "implSetCurrentControl did nonsense!" );
1680 if ( bActivated )
1682 // (asynchronously) call activation handlers
1683 m_aActivationEvent.Call();
1685 // call modify listeners
1686 if ( m_bModified )
1687 m_aModifyListeners.notifyEach( &XModifyListener::modified, EventObject( *this ) );
1690 // invalidate all features which depend on the currently focused control
1691 if ( m_bDBConnection && !m_bFiltering )
1692 implInvalidateCurrentControlDependentFeatures();
1694 if ( !m_xCurrentControl.is() )
1695 return;
1697 // control gets focus, then possibly in the visible range
1698 Reference< XFormControllerContext > xContext( m_xFormControllerContext );
1699 Reference< XControl > xCurrentControl( m_xCurrentControl );
1700 aGuard.clear();
1701 // <-- SYNCHRONIZED
1703 if ( xContext.is() )
1704 xContext->makeVisible( xCurrentControl );
1707 IMPL_LINK_NOARG( FormController, OnActivated, void*, void )
1709 EventObject aEvent;
1710 aEvent.Source = *this;
1711 m_aActivateListeners.notifyEach( &XFormControllerListener::formActivated, aEvent );
1714 IMPL_LINK_NOARG( FormController, OnDeactivated, void*, void )
1716 EventObject aEvent;
1717 aEvent.Source = *this;
1718 m_aActivateListeners.notifyEach( &XFormControllerListener::formDeactivated, aEvent );
1721 void FormController::focusLost(const FocusEvent& e)
1723 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1725 m_aControlBorderManager.focusLost( e.Source );
1727 Reference< XWindowPeer > xNext(e.NextFocus, UNO_QUERY);
1728 // if focus hasn't passed to some other window, e.g. focus in a welded item, don't deactivate
1729 if (!xNext)
1730 return;
1731 Reference< XControl > xNextControl = isInList(xNext);
1732 if (!xNextControl.is())
1734 m_xActiveControl = nullptr;
1735 m_aDeactivationEvent.Call();
1739 void SAL_CALL FormController::mousePressed( const awt::MouseEvent& /*_rEvent*/ )
1741 // not interested in
1744 void SAL_CALL FormController::mouseReleased( const awt::MouseEvent& /*_rEvent*/ )
1746 // not interested in
1749 void SAL_CALL FormController::mouseEntered( const awt::MouseEvent& _rEvent )
1751 m_aControlBorderManager.mouseEntered( _rEvent.Source );
1754 void SAL_CALL FormController::mouseExited( const awt::MouseEvent& _rEvent )
1756 m_aControlBorderManager.mouseExited( _rEvent.Source );
1759 void SAL_CALL FormController::componentValidityChanged( const EventObject& _rSource )
1761 Reference< XControl > xControl( findControl( m_aControls, Reference< XControlModel >( _rSource.Source, UNO_QUERY ), false, false ) );
1762 Reference< XValidatableFormComponent > xValidatable( _rSource.Source, UNO_QUERY );
1764 OSL_ENSURE( xControl.is() && xValidatable.is(), "FormController::componentValidityChanged: huh?" );
1766 if ( xControl.is() && xValidatable.is() )
1767 m_aControlBorderManager.validityChanged( xControl, xValidatable );
1771 void FormController::setModel(const Reference< XTabControllerModel > & Model)
1773 ::osl::MutexGuard aGuard( m_aMutex );
1774 impl_checkDisposed_throw();
1776 DBG_ASSERT(m_xTabController.is(), "FormController::setModel : invalid aggregate !");
1780 // disconnect from the old model
1781 if (m_xModelAsIndex.is())
1783 if (m_bDBConnection)
1785 // we are currently working on the model
1786 EventObject aEvt(m_xModelAsIndex);
1787 unloaded(aEvt);
1790 Reference< XLoadable > xForm(m_xModelAsIndex, UNO_QUERY);
1791 if (xForm.is())
1792 xForm->removeLoadListener(this);
1794 Reference< XSQLErrorBroadcaster > xBroadcaster(m_xModelAsIndex, UNO_QUERY);
1795 if (xBroadcaster.is())
1796 xBroadcaster->removeSQLErrorListener(this);
1798 Reference< XDatabaseParameterBroadcaster > xParamBroadcaster(m_xModelAsIndex, UNO_QUERY);
1799 if (xParamBroadcaster.is())
1800 xParamBroadcaster->removeParameterListener(this);
1804 disposeAllFeaturesAndDispatchers();
1806 if ( m_xFormOperations.is() )
1807 m_xFormOperations->dispose();
1808 m_xFormOperations.clear();
1810 // set the new model wait for the load event
1811 if (m_xTabController.is())
1812 m_xTabController->setModel(Model);
1813 m_xModelAsIndex.set(Model, UNO_QUERY);
1814 m_xModelAsManager.set(Model, UNO_QUERY);
1816 // only if both ifaces exit, the controller will work successful
1817 if (!m_xModelAsIndex.is() || !m_xModelAsManager.is())
1819 m_xModelAsManager = nullptr;
1820 m_xModelAsIndex = nullptr;
1823 if (m_xModelAsIndex.is())
1825 // re-create m_xFormOperations
1826 m_xFormOperations = FormOperations::createWithFormController( m_xComponentContext, this );
1827 m_xFormOperations->setFeatureInvalidation( this );
1829 // adding load and ui interaction listeners
1830 Reference< XLoadable > xForm(Model, UNO_QUERY);
1831 if (xForm.is())
1832 xForm->addLoadListener(this);
1834 Reference< XSQLErrorBroadcaster > xBroadcaster(Model, UNO_QUERY);
1835 if (xBroadcaster.is())
1836 xBroadcaster->addSQLErrorListener(this);
1838 Reference< XDatabaseParameterBroadcaster > xParamBroadcaster(Model, UNO_QUERY);
1839 if (xParamBroadcaster.is())
1840 xParamBroadcaster->addParameterListener(this);
1842 // well, is the database already loaded?
1843 // then we have to simulate a load event
1844 Reference< XLoadable > xCursor(m_xModelAsIndex, UNO_QUERY);
1845 if (xCursor.is() && xCursor->isLoaded())
1847 EventObject aEvt(xCursor);
1848 loaded(aEvt);
1851 Reference< XPropertySet > xModelProps( m_xModelAsIndex, UNO_QUERY );
1852 Reference< XPropertySetInfo > xPropInfo( xModelProps->getPropertySetInfo() );
1853 if ( xPropInfo.is()
1854 && xPropInfo->hasPropertyByName( FM_PROP_DYNAMIC_CONTROL_BORDER )
1855 && xPropInfo->hasPropertyByName( FM_PROP_CONTROL_BORDER_COLOR_FOCUS )
1856 && xPropInfo->hasPropertyByName( FM_PROP_CONTROL_BORDER_COLOR_MOUSE )
1857 && xPropInfo->hasPropertyByName( FM_PROP_CONTROL_BORDER_COLOR_INVALID )
1860 bool bEnableDynamicControlBorder = lcl_shouldUseDynamicControlBorder(
1861 xModelProps, xModelProps->getPropertyValue( FM_PROP_DYNAMIC_CONTROL_BORDER ) );
1862 if ( bEnableDynamicControlBorder )
1863 m_aControlBorderManager.enableDynamicBorderColor();
1864 else
1865 m_aControlBorderManager.disableDynamicBorderColor();
1867 Color nColor;
1868 if ( xModelProps->getPropertyValue( FM_PROP_CONTROL_BORDER_COLOR_FOCUS ) >>= nColor )
1869 m_aControlBorderManager.setStatusColor( ControlStatus::Focused, nColor );
1870 if ( xModelProps->getPropertyValue( FM_PROP_CONTROL_BORDER_COLOR_MOUSE ) >>= nColor )
1871 m_aControlBorderManager.setStatusColor( ControlStatus::MouseHover, nColor );
1872 if ( xModelProps->getPropertyValue( FM_PROP_CONTROL_BORDER_COLOR_INVALID ) >>= nColor )
1873 m_aControlBorderManager.setStatusColor( ControlStatus::Invalid, nColor );
1877 catch( const Exception& )
1879 DBG_UNHANDLED_EXCEPTION("svx");
1884 Reference< XTabControllerModel > FormController::getModel()
1886 ::osl::MutexGuard aGuard( m_aMutex );
1887 impl_checkDisposed_throw();
1889 DBG_ASSERT(m_xTabController.is(), "FormController::getModel : invalid aggregate !");
1890 if (!m_xTabController.is())
1891 return Reference< XTabControllerModel > ();
1892 return m_xTabController->getModel();
1896 void FormController::addToEventAttacher(const Reference< XControl > & xControl)
1898 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1899 OSL_ENSURE( xControl.is(), "FormController::addToEventAttacher: invalid control - how did you reach this?" );
1900 if ( !xControl.is() )
1901 return; /* throw IllegalArgumentException(); */
1903 // register at the event attacher
1904 Reference< XFormComponent > xComp(xControl->getModel(), UNO_QUERY);
1905 if (!(xComp.is() && m_xModelAsIndex.is()))
1906 return;
1908 // and look for the position of the ControlModel in it
1909 sal_uInt32 nPos = m_xModelAsIndex->getCount();
1910 Reference< XFormComponent > xTemp;
1911 for( ; nPos; )
1913 m_xModelAsIndex->getByIndex(--nPos) >>= xTemp;
1914 if (xComp.get() == xTemp.get())
1916 m_xModelAsManager->attach( nPos, Reference<XInterface>( xControl, UNO_QUERY ), Any(xControl) );
1917 break;
1923 void FormController::removeFromEventAttacher(const Reference< XControl > & xControl)
1925 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1926 OSL_ENSURE( xControl.is(), "FormController::removeFromEventAttacher: invalid control - how did you reach this?" );
1927 if ( !xControl.is() )
1928 return; /* throw IllegalArgumentException(); */
1930 // register at the event attacher
1931 Reference< XFormComponent > xComp(xControl->getModel(), UNO_QUERY);
1932 if ( !(xComp.is() && m_xModelAsIndex.is()) )
1933 return;
1935 // and look for the position of the ControlModel in it
1936 sal_uInt32 nPos = m_xModelAsIndex->getCount();
1937 Reference< XFormComponent > xTemp;
1938 for( ; nPos; )
1940 m_xModelAsIndex->getByIndex(--nPos) >>= xTemp;
1941 if (xComp.get() == xTemp.get())
1943 m_xModelAsManager->detach( nPos, Reference<XInterface>( xControl, UNO_QUERY ) );
1944 break;
1950 void FormController::setContainer(const Reference< XControlContainer > & xContainer)
1952 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
1953 Reference< XTabControllerModel > xTabModel(getModel());
1954 DBG_ASSERT(xTabModel.is() || !xContainer.is(), "No Model defined");
1955 // if we have a new container we need a model
1956 DBG_ASSERT(m_xTabController.is(), "FormController::setContainer : invalid aggregate !");
1958 ::osl::MutexGuard aGuard( m_aMutex );
1959 Reference< XContainer > xCurrentContainer;
1960 if (m_xTabController.is())
1961 xCurrentContainer.set(m_xTabController->getContainer(), UNO_QUERY);
1962 if (xCurrentContainer.is())
1964 xCurrentContainer->removeContainerListener(this);
1966 if ( m_aTabActivationIdle.IsActive() )
1967 m_aTabActivationIdle.Stop();
1969 // clear the filter map
1970 ::std::for_each( m_aFilterComponents.begin(), m_aFilterComponents.end(), RemoveComponentTextListener( this ) );
1971 m_aFilterComponents.clear();
1973 // collecting the controls
1974 for (const Reference<XControl>& rControl : m_aControls)
1975 implControlRemoved( rControl, true );
1977 // make database-specific things
1978 if (m_bDBConnection && isListeningForChanges())
1979 stopListening();
1981 m_aControls.realloc( 0 );
1984 if (m_xTabController.is())
1985 m_xTabController->setContainer(xContainer);
1987 // What controls belong to the container?
1988 if (xContainer.is() && xTabModel.is())
1990 const Sequence< Reference< XControlModel > > aModels = xTabModel->getControlModels();
1991 Sequence< Reference< XControl > > aAllControls = xContainer->getControls();
1993 sal_Int32 nCount = aModels.getLength();
1994 m_aControls = Sequence< Reference< XControl > >( nCount );
1995 Reference< XControl > * pControls = m_aControls.getArray();
1997 // collecting the controls
1998 sal_Int32 j = 0;
1999 for (const Reference< XControlModel >& rModel : aModels )
2001 Reference< XControl > xControl = findControl( aAllControls, rModel, false, true );
2002 if ( xControl.is() )
2004 pControls[j++] = xControl;
2005 implControlInserted( xControl, true );
2009 // not every model had an associated control
2010 if (j != nCount)
2011 m_aControls.realloc(j);
2013 // listen at the container
2014 Reference< XContainer > xNewContainer(xContainer, UNO_QUERY);
2015 if (xNewContainer.is())
2016 xNewContainer->addContainerListener(this);
2018 // make database-specific things
2019 if (m_bDBConnection)
2021 m_bLocked = determineLockState();
2022 setLocks();
2023 if (!isLocked())
2024 startListening();
2027 // the controls are in the right order
2028 m_bControlsSorted = true;
2032 Reference< XControlContainer > FormController::getContainer()
2034 ::osl::MutexGuard aGuard( m_aMutex );
2035 impl_checkDisposed_throw();
2037 DBG_ASSERT(m_xTabController.is(), "FormController::getContainer : invalid aggregate !");
2038 if (!m_xTabController.is())
2039 return Reference< XControlContainer > ();
2040 return m_xTabController->getContainer();
2044 Sequence< Reference< XControl > > FormController::getControls()
2046 ::osl::MutexGuard aGuard( m_aMutex );
2047 impl_checkDisposed_throw();
2049 if (!m_bControlsSorted)
2051 Reference< XTabControllerModel > xModel = getModel();
2052 if (!xModel.is())
2053 return m_aControls;
2055 const Sequence< Reference< XControlModel > > aControlModels = xModel->getControlModels();
2056 sal_Int32 nModels = aControlModels.getLength();
2058 Sequence< Reference< XControl > > aNewControls(nModels);
2060 Reference< XControl > * pControls = aNewControls.getArray();
2061 Reference< XControl > xControl;
2063 // rearrange the controls according to the tab order sequence
2064 sal_Int32 j = 0;
2065 for ( const Reference< XControlModel >& rModel : aControlModels )
2067 xControl = findControl( m_aControls, rModel, true, true );
2068 if ( xControl.is() )
2069 pControls[j++] = xControl;
2072 // not every model had an associated control
2073 if ( j != nModels )
2074 aNewControls.realloc( j );
2076 m_aControls = aNewControls;
2077 m_bControlsSorted = true;
2079 return m_aControls;
2083 void FormController::autoTabOrder()
2085 ::osl::MutexGuard aGuard( m_aMutex );
2086 impl_checkDisposed_throw();
2088 DBG_ASSERT(m_xTabController.is(), "FormController::autoTabOrder : invalid aggregate !");
2089 if (m_xTabController.is())
2090 m_xTabController->autoTabOrder();
2094 void FormController::activateTabOrder()
2096 ::osl::MutexGuard aGuard( m_aMutex );
2097 impl_checkDisposed_throw();
2099 DBG_ASSERT(m_xTabController.is(), "FormController::activateTabOrder : invalid aggregate !");
2100 if (m_xTabController.is())
2101 m_xTabController->activateTabOrder();
2105 void FormController::setControlLock(const Reference< XControl > & xControl)
2107 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2108 bool bLocked = isLocked();
2110 // It is locked
2111 // a. if the entire record is locked
2112 // b. if the associated field is locked
2113 Reference< XBoundControl > xBound(xControl, UNO_QUERY);
2114 if (!(xBound.is() &&
2115 ( (bLocked && bLocked != bool(xBound->getLock())) ||
2116 !bLocked))) // always uncheck individual fields when unlocking
2117 return;
2119 // there is a data source
2120 Reference< XPropertySet > xSet(xControl->getModel(), UNO_QUERY);
2121 if (!(xSet.is() && ::comphelper::hasProperty(FM_PROP_BOUNDFIELD, xSet)))
2122 return;
2124 // what about the ReadOnly and Enable properties
2125 bool bTouch = true;
2126 if (::comphelper::hasProperty(FM_PROP_ENABLED, xSet))
2127 bTouch = ::comphelper::getBOOL(xSet->getPropertyValue(FM_PROP_ENABLED));
2128 if (bTouch && ::comphelper::hasProperty(FM_PROP_READONLY, xSet))
2129 bTouch = !::comphelper::getBOOL(xSet->getPropertyValue(FM_PROP_READONLY));
2131 if (!bTouch)
2132 return;
2134 Reference< XPropertySet > xField;
2135 xSet->getPropertyValue(FM_PROP_BOUNDFIELD) >>= xField;
2136 if (!xField.is())
2137 return;
2139 if (bLocked)
2140 xBound->setLock(bLocked);
2141 else
2145 Any aVal = xField->getPropertyValue(FM_PROP_ISREADONLY);
2146 if (aVal.hasValue() && ::comphelper::getBOOL(aVal))
2147 xBound->setLock(true);
2148 else
2149 xBound->setLock(bLocked);
2151 catch( const Exception& )
2153 DBG_UNHANDLED_EXCEPTION("svx");
2160 void FormController::setLocks()
2162 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2163 // lock/unlock all controls connected to a data source
2164 for (const Reference<XControl>& rControl : m_aControls)
2165 setControlLock( rControl );
2169 namespace
2171 bool lcl_shouldListenForModifications( const Reference< XControl >& _rxControl, const Reference< XPropertyChangeListener >& _rxBoundFieldListener )
2173 bool bShould = false;
2175 Reference< XBoundComponent > xBound( _rxControl, UNO_QUERY );
2176 if ( xBound.is() )
2178 bShould = true;
2180 else if ( _rxControl.is() )
2182 Reference< XPropertySet > xModelProps( _rxControl->getModel(), UNO_QUERY );
2183 if ( xModelProps.is() && ::comphelper::hasProperty( FM_PROP_BOUNDFIELD, xModelProps ) )
2185 Reference< XPropertySet > xField;
2186 xModelProps->getPropertyValue( FM_PROP_BOUNDFIELD ) >>= xField;
2187 bShould = xField.is();
2189 if ( !bShould && _rxBoundFieldListener.is() )
2190 xModelProps->addPropertyChangeListener( FM_PROP_BOUNDFIELD, _rxBoundFieldListener );
2194 return bShould;
2199 void FormController::startControlModifyListening(const Reference< XControl > & xControl)
2201 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2203 bool bModifyListening = lcl_shouldListenForModifications( xControl, this );
2205 // artificial while
2206 while ( bModifyListening )
2208 Reference< XModifyBroadcaster > xMod(xControl, UNO_QUERY);
2209 if (xMod.is())
2211 xMod->addModifyListener(this);
2212 break;
2215 // all the text to prematurely recognize a modified
2216 Reference< XTextComponent > xText(xControl, UNO_QUERY);
2217 if (xText.is())
2219 xText->addTextListener(this);
2220 break;
2223 Reference< XCheckBox > xBox(xControl, UNO_QUERY);
2224 if (xBox.is())
2226 xBox->addItemListener(this);
2227 break;
2230 Reference< XComboBox > xCbBox(xControl, UNO_QUERY);
2231 if (xCbBox.is())
2233 xCbBox->addItemListener(this);
2234 break;
2237 Reference< XListBox > xListBox(xControl, UNO_QUERY);
2238 if (xListBox.is())
2240 xListBox->addItemListener(this);
2241 break;
2243 break;
2248 void FormController::stopControlModifyListening(const Reference< XControl > & xControl)
2250 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2252 bool bModifyListening = lcl_shouldListenForModifications( xControl, nullptr );
2254 // artificial while
2255 while (bModifyListening)
2257 Reference< XModifyBroadcaster > xMod(xControl, UNO_QUERY);
2258 if (xMod.is())
2260 xMod->removeModifyListener(this);
2261 break;
2263 // all the text to prematurely recognize a modified
2264 Reference< XTextComponent > xText(xControl, UNO_QUERY);
2265 if (xText.is())
2267 xText->removeTextListener(this);
2268 break;
2271 Reference< XCheckBox > xBox(xControl, UNO_QUERY);
2272 if (xBox.is())
2274 xBox->removeItemListener(this);
2275 break;
2278 Reference< XComboBox > xCbBox(xControl, UNO_QUERY);
2279 if (xCbBox.is())
2281 xCbBox->removeItemListener(this);
2282 break;
2285 Reference< XListBox > xListBox(xControl, UNO_QUERY);
2286 if (xListBox.is())
2288 xListBox->removeItemListener(this);
2289 break;
2291 break;
2296 void FormController::startListening()
2298 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2299 m_bModified = false;
2301 // now register at bound fields
2302 for (const Reference<XControl>& rControl : m_aControls)
2303 startControlModifyListening( rControl );
2307 void FormController::stopListening()
2309 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2310 m_bModified = false;
2312 // now register at bound fields
2313 for (const Reference<XControl>& rControl : m_aControls)
2314 stopControlModifyListening( rControl );
2318 Reference< XControl > FormController::findControl(Sequence< Reference< XControl > >& _rControls, const Reference< XControlModel > & xCtrlModel ,bool _bRemove,bool _bOverWrite) const
2320 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2321 DBG_ASSERT( xCtrlModel.is(), "findControl - which ?!" );
2323 const Reference< XControl >* pControls = std::find_if(std::cbegin(_rControls), std::cend(_rControls),
2324 [&xCtrlModel](const Reference< XControl >& rControl) {
2325 return rControl.is() && rControl->getModel().get() == xCtrlModel.get(); });
2326 if (pControls != std::cend(_rControls))
2328 Reference< XControl > xControl( *pControls );
2329 auto i = static_cast<sal_Int32>(std::distance(std::cbegin(_rControls), pControls));
2330 if ( _bRemove )
2331 ::comphelper::removeElementAt( _rControls, i );
2332 else if ( _bOverWrite )
2333 _rControls.getArray()[i].clear();
2334 return xControl;
2336 return Reference< XControl > ();
2340 void FormController::implControlInserted( const Reference< XControl>& _rxControl, bool _bAddToEventAttacher )
2342 Reference< XWindow > xWindow( _rxControl, UNO_QUERY );
2343 if ( xWindow.is() )
2345 xWindow->addFocusListener( this );
2346 xWindow->addMouseListener( this );
2348 if ( _bAddToEventAttacher )
2349 addToEventAttacher( _rxControl );
2352 // add a dispatch interceptor to the control (if supported)
2353 Reference< XDispatchProviderInterception > xInterception( _rxControl, UNO_QUERY );
2354 if ( xInterception.is() )
2355 createInterceptor( xInterception );
2357 if ( !_rxControl.is() )
2358 return;
2360 Reference< XControlModel > xModel( _rxControl->getModel() );
2362 // we want to know about the reset of the model of our controls
2363 // (for correctly resetting m_bModified)
2364 Reference< XReset > xReset( xModel, UNO_QUERY );
2365 if ( xReset.is() )
2366 xReset->addResetListener( this );
2368 // and we want to know about the validity, to visually indicate it
2369 Reference< XValidatableFormComponent > xValidatable( xModel, UNO_QUERY );
2370 if ( xValidatable.is() )
2372 xValidatable->addFormComponentValidityListener( this );
2373 m_aControlBorderManager.validityChanged( _rxControl, xValidatable );
2379 void FormController::implControlRemoved( const Reference< XControl>& _rxControl, bool _bRemoveFromEventAttacher )
2381 Reference< XWindow > xWindow( _rxControl, UNO_QUERY );
2382 if ( xWindow.is() )
2384 xWindow->removeFocusListener( this );
2385 xWindow->removeMouseListener( this );
2387 if ( _bRemoveFromEventAttacher )
2388 removeFromEventAttacher( _rxControl );
2391 Reference< XDispatchProviderInterception > xInterception( _rxControl, UNO_QUERY);
2392 if ( xInterception.is() )
2393 deleteInterceptor( xInterception );
2395 if ( _rxControl.is() )
2397 Reference< XControlModel > xModel( _rxControl->getModel() );
2399 Reference< XReset > xReset( xModel, UNO_QUERY );
2400 if ( xReset.is() )
2401 xReset->removeResetListener( this );
2403 Reference< XValidatableFormComponent > xValidatable( xModel, UNO_QUERY );
2404 if ( xValidatable.is() )
2405 xValidatable->removeFormComponentValidityListener( this );
2410 void FormController::implSetCurrentControl( const Reference< XControl >& _rxControl )
2412 if ( m_xCurrentControl.get() == _rxControl.get() )
2413 return;
2415 Reference< XGridControl > xGridControl( m_xCurrentControl, UNO_QUERY );
2416 if ( xGridControl.is() )
2417 xGridControl->removeGridControlListener( this );
2419 m_xCurrentControl = _rxControl;
2421 xGridControl.set( m_xCurrentControl, UNO_QUERY );
2422 if ( xGridControl.is() )
2423 xGridControl->addGridControlListener( this );
2427 void FormController::insertControl(const Reference< XControl > & xControl)
2429 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2430 m_bControlsSorted = false;
2431 m_aControls.realloc(m_aControls.getLength() + 1);
2432 m_aControls.getArray()[m_aControls.getLength() - 1] = xControl;
2434 if (m_pColumnInfoCache)
2435 m_pColumnInfoCache->deinitializeControls();
2437 implControlInserted( xControl, m_bAttachEvents );
2439 if (m_bDBConnection && !m_bFiltering)
2440 setControlLock(xControl);
2442 if (isListeningForChanges() && m_bAttachEvents)
2443 startControlModifyListening( xControl );
2447 void FormController::removeControl(const Reference< XControl > & xControl)
2449 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2450 auto pControl = std::find_if(std::cbegin(m_aControls), std::cend(m_aControls),
2451 [&xControl](const Reference< XControl >& rControl) { return xControl.get() == rControl.get(); });
2452 if (pControl != std::cend(m_aControls))
2454 auto nIndex = static_cast<sal_Int32>(std::distance(std::cbegin(m_aControls), pControl));
2455 ::comphelper::removeElementAt( m_aControls, nIndex );
2458 FilterComponents::iterator componentPos = ::std::find( m_aFilterComponents.begin(), m_aFilterComponents.end(), xControl );
2459 if ( componentPos != m_aFilterComponents.end() )
2460 m_aFilterComponents.erase( componentPos );
2462 implControlRemoved( xControl, m_bDetachEvents );
2464 if ( isListeningForChanges() && m_bDetachEvents )
2465 stopControlModifyListening( xControl );
2468 // XLoadListener
2470 void FormController::loaded(const EventObject& rEvent)
2472 OSL_ENSURE( rEvent.Source == m_xModelAsIndex, "FormController::loaded: where did this come from?" );
2474 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2475 ::osl::MutexGuard aGuard( m_aMutex );
2476 Reference< XRowSet > xForm(rEvent.Source, UNO_QUERY);
2477 // do we have a connected data source
2478 if (xForm.is() && getConnection(xForm).is())
2480 Reference< XPropertySet > xSet(xForm, UNO_QUERY);
2481 if (xSet.is())
2483 Any aVal = xSet->getPropertyValue(FM_PROP_CYCLE);
2484 sal_Int32 aVal2 = 0;
2485 ::cppu::enum2int(aVal2,aVal);
2486 m_bCycle = !aVal.hasValue() || static_cast<form::TabulatorCycle>(aVal2) == TabulatorCycle_RECORDS;
2487 m_bCanUpdate = canUpdate(xSet);
2488 m_bCanInsert = canInsert(xSet);
2489 m_bCurrentRecordModified = ::comphelper::getBOOL(xSet->getPropertyValue(FM_PROP_ISMODIFIED));
2490 m_bCurrentRecordNew = ::comphelper::getBOOL(xSet->getPropertyValue(FM_PROP_ISNEW));
2492 startFormListening( xSet, false );
2494 // set the locks for the current controls
2495 if (getContainer().is())
2497 m_aLoadEvent.Call();
2500 else
2502 m_bCanInsert = m_bCanUpdate = m_bCycle = false;
2503 m_bCurrentRecordModified = false;
2504 m_bCurrentRecordNew = false;
2505 m_bLocked = false;
2507 m_bDBConnection = true;
2509 else
2511 m_bDBConnection = false;
2512 m_bCanInsert = m_bCanUpdate = m_bCycle = false;
2513 m_bCurrentRecordModified = false;
2514 m_bCurrentRecordNew = false;
2515 m_bLocked = false;
2518 Reference< XColumnsSupplier > xFormColumns( xForm, UNO_QUERY );
2519 m_pColumnInfoCache.reset( xFormColumns.is() ? new ColumnInfoCache( xFormColumns ) : nullptr );
2521 updateAllDispatchers();
2525 void FormController::updateAllDispatchers() const
2527 ::std::for_each(
2528 m_aFeatureDispatchers.begin(),
2529 m_aFeatureDispatchers.end(),
2530 [] (const DispatcherContainer::value_type& dispatcher) {
2531 UpdateAllListeners()(dispatcher.second);
2536 IMPL_LINK_NOARG(FormController, OnLoad, void*, void)
2538 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2539 m_bLocked = determineLockState();
2541 setLocks();
2543 if (!m_bLocked)
2544 startListening();
2546 // just one exception toggle the auto values
2547 if (m_bCurrentRecordNew)
2548 toggleAutoFields(true);
2552 void FormController::unloaded(const EventObject& /*rEvent*/)
2554 ::osl::MutexGuard aGuard( m_aMutex );
2555 impl_checkDisposed_throw();
2557 updateAllDispatchers();
2561 void FormController::reloading(const EventObject& /*aEvent*/)
2563 ::osl::MutexGuard aGuard( m_aMutex );
2564 impl_checkDisposed_throw();
2566 // do the same like in unloading
2567 // just one exception toggle the auto values
2568 m_aToggleEvent.CancelPendingCall();
2569 unload();
2573 void FormController::reloaded(const EventObject& aEvent)
2575 ::osl::MutexGuard aGuard( m_aMutex );
2576 impl_checkDisposed_throw();
2578 loaded(aEvent);
2582 void FormController::unloading(const EventObject& /*aEvent*/)
2584 ::osl::MutexGuard aGuard( m_aMutex );
2585 impl_checkDisposed_throw();
2587 unload();
2591 void FormController::unload()
2593 ::osl::MutexGuard aGuard( m_aMutex );
2594 impl_checkDisposed_throw();
2596 m_aLoadEvent.CancelPendingCall();
2598 // be sure not to have autofields
2599 if (m_bCurrentRecordNew)
2600 toggleAutoFields(false);
2602 // remove bound field listing again
2603 removeBoundFieldListener();
2605 if (m_bDBConnection && isListeningForChanges())
2606 stopListening();
2608 Reference< XPropertySet > xSet( m_xModelAsIndex, UNO_QUERY );
2609 if ( m_bDBConnection && xSet.is() )
2610 stopFormListening( xSet, false );
2612 m_bDBConnection = false;
2613 m_bCanInsert = m_bCanUpdate = m_bCycle = false;
2614 m_bCurrentRecordModified = m_bCurrentRecordNew = m_bLocked = false;
2616 m_pColumnInfoCache.reset();
2620 void FormController::removeBoundFieldListener()
2622 for (const Reference<XControl>& rControl : m_aControls)
2624 Reference< XPropertySet > xProp( rControl, UNO_QUERY );
2625 if ( xProp.is() )
2626 xProp->removePropertyChangeListener( FM_PROP_BOUNDFIELD, this );
2631 void FormController::startFormListening( const Reference< XPropertySet >& _rxForm, bool _bPropertiesOnly )
2635 if ( m_bCanInsert || m_bCanUpdate ) // form can be modified
2637 _rxForm->addPropertyChangeListener( FM_PROP_ISNEW, this );
2638 _rxForm->addPropertyChangeListener( FM_PROP_ISMODIFIED, this );
2640 if ( !_bPropertiesOnly )
2642 // set the Listener for UI interaction
2643 Reference< XRowSetApproveBroadcaster > xApprove( _rxForm, UNO_QUERY );
2644 if ( xApprove.is() )
2645 xApprove->addRowSetApproveListener( this );
2647 // listener for row set changes
2648 Reference< XRowSet > xRowSet( _rxForm, UNO_QUERY );
2649 if ( xRowSet.is() )
2650 xRowSet->addRowSetListener( this );
2654 Reference< XPropertySetInfo > xInfo = _rxForm->getPropertySetInfo();
2655 if ( xInfo.is() && xInfo->hasPropertyByName( FM_PROP_DYNAMIC_CONTROL_BORDER ) )
2656 _rxForm->addPropertyChangeListener( FM_PROP_DYNAMIC_CONTROL_BORDER, this );
2658 catch( const Exception& )
2660 DBG_UNHANDLED_EXCEPTION("svx");
2665 void FormController::stopFormListening( const Reference< XPropertySet >& _rxForm, bool _bPropertiesOnly )
2669 if ( m_bCanInsert || m_bCanUpdate )
2671 _rxForm->removePropertyChangeListener( FM_PROP_ISNEW, this );
2672 _rxForm->removePropertyChangeListener( FM_PROP_ISMODIFIED, this );
2674 if ( !_bPropertiesOnly )
2676 Reference< XRowSetApproveBroadcaster > xApprove( _rxForm, UNO_QUERY );
2677 if (xApprove.is())
2678 xApprove->removeRowSetApproveListener(this);
2680 Reference< XRowSet > xRowSet( _rxForm, UNO_QUERY );
2681 if ( xRowSet.is() )
2682 xRowSet->removeRowSetListener( this );
2686 Reference< XPropertySetInfo > xInfo = _rxForm->getPropertySetInfo();
2687 if ( xInfo.is() && xInfo->hasPropertyByName( FM_PROP_DYNAMIC_CONTROL_BORDER ) )
2688 _rxForm->removePropertyChangeListener( FM_PROP_DYNAMIC_CONTROL_BORDER, this );
2690 catch( const Exception& )
2692 DBG_UNHANDLED_EXCEPTION("svx");
2696 // css::sdbc::XRowSetListener
2698 void FormController::cursorMoved(const EventObject& /*event*/)
2700 ::osl::MutexGuard aGuard( m_aMutex );
2701 impl_checkDisposed_throw();
2703 // toggle the locking ?
2704 if (m_bLocked != determineLockState())
2706 m_bLocked = !m_bLocked;
2707 setLocks();
2708 if (isListeningForChanges())
2709 startListening();
2710 else
2711 stopListening();
2714 // neither the current control nor the current record are modified anymore
2715 m_bCurrentRecordModified = m_bModified = false;
2719 void FormController::rowChanged(const EventObject& /*event*/)
2721 // not interested in ...
2724 void FormController::rowSetChanged(const EventObject& /*event*/)
2726 // not interested in ...
2730 // XContainerListener
2732 void SAL_CALL FormController::elementInserted(const ContainerEvent& evt)
2734 ::osl::MutexGuard aGuard( m_aMutex );
2735 impl_checkDisposed_throw();
2737 Reference< XControl > xControl( evt.Element, UNO_QUERY );
2738 if ( !xControl.is() )
2739 return;
2741 Reference< XFormComponent > xModel(xControl->getModel(), UNO_QUERY);
2742 if (xModel.is() && m_xModelAsIndex == xModel->getParent())
2744 insertControl(xControl);
2746 if ( m_aTabActivationIdle.IsActive() )
2747 m_aTabActivationIdle.Stop();
2749 m_aTabActivationIdle.Start();
2751 // are we in filtermode and a XModeSelector has inserted an element
2752 else if (m_bFiltering && Reference< XModeSelector > (evt.Source, UNO_QUERY).is())
2754 xModel.set(evt.Source, UNO_QUERY);
2755 if (xModel.is() && m_xModelAsIndex == xModel->getParent())
2757 Reference< XPropertySet > xSet(xControl->getModel(), UNO_QUERY);
2758 if (xSet.is() && ::comphelper::hasProperty(FM_PROP_BOUNDFIELD, xSet))
2760 // does the model use a bound field ?
2761 Reference< XPropertySet > xField;
2762 xSet->getPropertyValue(FM_PROP_BOUNDFIELD) >>= xField;
2764 Reference< XTextComponent > xText(xControl, UNO_QUERY);
2765 // may we filter the field?
2766 if (xText.is() && xField.is() && ::comphelper::hasProperty(FM_PROP_SEARCHABLE, xField) &&
2767 ::comphelper::getBOOL(xField->getPropertyValue(FM_PROP_SEARCHABLE)))
2769 m_aFilterComponents.push_back( xText );
2770 xText->addTextListener( this );
2778 void SAL_CALL FormController::elementReplaced(const ContainerEvent& evt)
2780 // simulate an elementRemoved
2781 ContainerEvent aRemoveEvent( evt );
2782 aRemoveEvent.Element = evt.ReplacedElement;
2783 aRemoveEvent.ReplacedElement = Any();
2784 elementRemoved( aRemoveEvent );
2786 // simulate an elementInserted
2787 ContainerEvent aInsertEvent( evt );
2788 aInsertEvent.ReplacedElement = Any();
2789 elementInserted( aInsertEvent );
2793 void SAL_CALL FormController::elementRemoved(const ContainerEvent& evt)
2795 ::osl::MutexGuard aGuard( m_aMutex );
2796 impl_checkDisposed_throw();
2798 Reference< XControl > xControl;
2799 evt.Element >>= xControl;
2800 if (!xControl.is())
2801 return;
2803 Reference< XFormComponent > xModel(xControl->getModel(), UNO_QUERY);
2804 if (xModel.is() && m_xModelAsIndex == xModel->getParent())
2806 removeControl(xControl);
2807 // Do not recalculate TabOrder, because it must already work internally!
2809 // are we in filtermode and a XModeSelector has inserted an element
2810 else if (m_bFiltering && Reference< XModeSelector > (evt.Source, UNO_QUERY).is())
2812 FilterComponents::iterator componentPos = ::std::find(
2813 m_aFilterComponents.begin(), m_aFilterComponents.end(), xControl );
2814 if ( componentPos != m_aFilterComponents.end() )
2815 m_aFilterComponents.erase( componentPos );
2820 Reference< XControl > FormController::isInList(const Reference< XWindowPeer > & xPeer) const
2822 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2823 const Reference< XControl >* pControls = m_aControls.getConstArray();
2825 sal_uInt32 nCtrls = m_aControls.getLength();
2826 for ( sal_uInt32 n = 0; n < nCtrls && xPeer.is(); ++n, ++pControls )
2828 if ( pControls->is() )
2830 Reference< XVclWindowPeer > xCtrlPeer( (*pControls)->getPeer(), UNO_QUERY);
2831 if ( ( xCtrlPeer.get() == xPeer.get() ) || xCtrlPeer->isChild( xPeer ) )
2832 return *pControls;
2835 return Reference< XControl > ();
2839 void FormController::activateFirst()
2841 ::osl::MutexGuard aGuard( m_aMutex );
2842 impl_checkDisposed_throw();
2844 DBG_ASSERT(m_xTabController.is(), "FormController::activateFirst : invalid aggregate !");
2845 if (m_xTabController.is())
2846 m_xTabController->activateFirst();
2850 void FormController::activateLast()
2852 ::osl::MutexGuard aGuard( m_aMutex );
2853 impl_checkDisposed_throw();
2855 DBG_ASSERT(m_xTabController.is(), "FormController::activateLast : invalid aggregate !");
2856 if (m_xTabController.is())
2857 m_xTabController->activateLast();
2860 // XFormController
2862 Reference< XFormOperations > SAL_CALL FormController::getFormOperations()
2864 ::osl::MutexGuard aGuard( m_aMutex );
2865 impl_checkDisposed_throw();
2867 return m_xFormOperations;
2871 Reference< XControl> SAL_CALL FormController::getCurrentControl()
2873 ::osl::MutexGuard aGuard( m_aMutex );
2874 impl_checkDisposed_throw();
2875 return m_xCurrentControl;
2879 void SAL_CALL FormController::addActivateListener(const Reference< XFormControllerListener > & l)
2881 ::osl::MutexGuard aGuard( m_aMutex );
2882 impl_checkDisposed_throw();
2883 m_aActivateListeners.addInterface(l);
2886 void SAL_CALL FormController::removeActivateListener(const Reference< XFormControllerListener > & l)
2888 ::osl::MutexGuard aGuard( m_aMutex );
2889 impl_checkDisposed_throw();
2890 m_aActivateListeners.removeInterface(l);
2894 void SAL_CALL FormController::addChildController( const Reference< XFormController >& ChildController )
2896 ::osl::MutexGuard aGuard( m_aMutex );
2897 impl_checkDisposed_throw();
2899 if ( !ChildController.is() )
2900 throw IllegalArgumentException( OUString(), *this, 1 );
2901 // TODO: (localized) error message
2903 // the parent of our (to-be-)child must be our own model
2904 Reference< XFormComponent > xFormOfChild( ChildController->getModel(), UNO_QUERY );
2905 if ( !xFormOfChild.is() )
2906 throw IllegalArgumentException( OUString(), *this, 1 );
2907 // TODO: (localized) error message
2909 if ( xFormOfChild->getParent() != m_xModelAsIndex )
2910 throw IllegalArgumentException( OUString(), *this, 1 );
2911 // TODO: (localized) error message
2913 m_aChildren.push_back( ChildController );
2914 ChildController->setParent( *this );
2916 // search the position of the model within the form
2917 sal_uInt32 nPos = m_xModelAsIndex->getCount();
2918 Reference< XFormComponent > xTemp;
2919 for( ; nPos; )
2921 m_xModelAsIndex->getByIndex(--nPos) >>= xTemp;
2922 if ( xFormOfChild == xTemp )
2924 m_xModelAsManager->attach( nPos, Reference<XInterface>( ChildController, UNO_QUERY ), Any( ChildController) );
2925 break;
2931 Reference< XFormControllerContext > SAL_CALL FormController::getContext()
2933 ::osl::MutexGuard aGuard( m_aMutex );
2934 impl_checkDisposed_throw();
2935 return m_xFormControllerContext;
2939 void SAL_CALL FormController::setContext( const Reference< XFormControllerContext >& _context )
2941 ::osl::MutexGuard aGuard( m_aMutex );
2942 impl_checkDisposed_throw();
2943 m_xFormControllerContext = _context;
2947 Reference< XInteractionHandler > SAL_CALL FormController::getInteractionHandler()
2949 ::osl::MutexGuard aGuard( m_aMutex );
2950 impl_checkDisposed_throw();
2951 return m_xInteractionHandler;
2955 void SAL_CALL FormController::setInteractionHandler( const Reference< XInteractionHandler >& _interactionHandler )
2957 ::osl::MutexGuard aGuard( m_aMutex );
2958 impl_checkDisposed_throw();
2959 m_xInteractionHandler = _interactionHandler;
2963 void FormController::setFilter(::std::vector<FmFieldInfo>& rFieldInfos)
2965 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
2966 // create the composer
2967 Reference< XRowSet > xForm(m_xModelAsIndex, UNO_QUERY);
2968 Reference< XConnection > xConnection(getConnection(xForm));
2969 if (xForm.is())
2973 Reference< XMultiServiceFactory > xFactory( xConnection, UNO_QUERY_THROW );
2974 m_xComposer.set(
2975 xFactory->createInstance(u"com.sun.star.sdb.SingleSelectQueryComposer"_ustr),
2976 UNO_QUERY_THROW );
2978 Reference< XPropertySet > xSet( xForm, UNO_QUERY );
2979 OUString sStatement = ::comphelper::getString( xSet->getPropertyValue( FM_PROP_ACTIVECOMMAND ) );
2980 OUString sFilter = ::comphelper::getString( xSet->getPropertyValue( FM_PROP_FILTER ) );
2981 m_xComposer->setElementaryQuery( sStatement );
2982 m_xComposer->setFilter( sFilter );
2984 catch( const Exception& )
2986 DBG_UNHANDLED_EXCEPTION("svx");
2990 if (m_xComposer.is())
2992 const Sequence< Sequence < PropertyValue > > aFilterRows = m_xComposer->getStructuredFilter();
2994 // ok, we receive the list of filters as sequence of fieldnames, value
2995 // now we have to transform the fieldname into UI names, that could be a label of the field or
2996 // an aliasname or the fieldname itself
2998 // first adjust the field names if necessary
2999 Reference< XNameAccess > xQueryColumns =
3000 Reference< XColumnsSupplier >( m_xComposer, UNO_QUERY_THROW )->getColumns();
3002 for (auto& rFieldInfo : rFieldInfos)
3004 if ( xQueryColumns->hasByName(rFieldInfo.aFieldName) )
3006 if ( (xQueryColumns->getByName(rFieldInfo.aFieldName) >>= rFieldInfo.xField) && rFieldInfo.xField.is() )
3007 rFieldInfo.xField->getPropertyValue(FM_PROP_REALNAME) >>= rFieldInfo.aFieldName;
3011 Reference< XDatabaseMetaData> xMetaData(xConnection->getMetaData());
3012 // now transfer the filters into Value/TextComponent pairs
3013 ::comphelper::UStringMixEqual aCompare(xMetaData->storesMixedCaseQuotedIdentifiers());
3015 // need to parse criteria localized
3016 Reference< XNumberFormatsSupplier> xFormatSupplier( getNumberFormats(xConnection, true));
3017 Reference< XNumberFormatter> xFormatter = NumberFormatter::create(m_xComponentContext);
3018 xFormatter->attachNumberFormatsSupplier(xFormatSupplier);
3019 Locale aAppLocale = Application::GetSettings().GetUILanguageTag().getLocale();
3020 const LocaleDataWrapper& rLocaleWrapper( Application::GetSettings().GetUILocaleDataWrapper() );
3021 OUString strDecimalSeparator = rLocaleWrapper.getNumDecimalSep();
3023 // retrieving the filter
3024 for (const Sequence < PropertyValue >& rRow : aFilterRows)
3026 FmFilterRow aRow;
3028 // search a field for the given name
3029 for (const PropertyValue& rRefValue : rRow)
3031 // look for the text component
3032 Reference< XPropertySet > xField;
3035 Reference< XPropertySet > xSet;
3036 OUString aRealName;
3038 // first look with the given name
3039 if (xQueryColumns->hasByName(rRefValue.Name))
3041 xQueryColumns->getByName(rRefValue.Name) >>= xSet;
3043 // get the RealName
3044 xSet->getPropertyValue(u"RealName"_ustr) >>= aRealName;
3046 // compare the condition field name and the RealName
3047 if (aCompare(aRealName, rRefValue.Name))
3048 xField = xSet;
3050 if (!xField.is())
3052 // no we have to check every column to find the realname
3053 Reference< XIndexAccess > xColumnsByIndex(xQueryColumns, UNO_QUERY);
3054 for (sal_Int32 n = 0, nCount = xColumnsByIndex->getCount(); n < nCount; n++)
3056 xColumnsByIndex->getByIndex(n) >>= xSet;
3057 xSet->getPropertyValue(u"RealName"_ustr) >>= aRealName;
3058 if (aCompare(aRealName, rRefValue.Name))
3060 // get the column by its alias
3061 xField = xSet;
3062 break;
3066 if (!xField.is())
3067 continue;
3069 catch (const Exception&)
3071 continue;
3074 // find the text component
3075 for (const auto& rFieldInfo : rFieldInfos)
3077 // we found the field so insert a new entry to the filter row
3078 if (rFieldInfo.xField == xField)
3080 // do we already have the control ?
3081 if (aRow.find(rFieldInfo.xText) != aRow.end())
3083 OString aVal = m_pParser->getContext().getIntlKeywordAscii(IParseContext::InternationalKeyCode::And);
3084 aRow[rFieldInfo.xText] = aRow[rFieldInfo.xText] + " " +
3085 OStringToOUString(aVal, RTL_TEXTENCODING_ASCII_US) + " " +
3086 ::comphelper::getString(rRefValue.Value);
3088 else
3090 OUString sPredicate,sErrorMsg;
3091 rRefValue.Value >>= sPredicate;
3092 std::unique_ptr< OSQLParseNode > pParseNode = predicateTree(sErrorMsg, sPredicate, xFormatter, xField);
3093 if ( pParseNode != nullptr )
3095 OUString sCriteria;
3096 switch (rRefValue.Handle)
3098 case css::sdb::SQLFilterOperator::EQUAL:
3099 sCriteria += "=";
3100 break;
3101 case css::sdb::SQLFilterOperator::NOT_EQUAL:
3102 sCriteria += "!=";
3103 break;
3104 case css::sdb::SQLFilterOperator::LESS:
3105 sCriteria += "<";
3106 break;
3107 case css::sdb::SQLFilterOperator::GREATER:
3108 sCriteria += ">";
3109 break;
3110 case css::sdb::SQLFilterOperator::LESS_EQUAL:
3111 sCriteria += "<=";
3112 break;
3113 case css::sdb::SQLFilterOperator::GREATER_EQUAL:
3114 sCriteria += ">=";
3115 break;
3116 case css::sdb::SQLFilterOperator::LIKE:
3117 sCriteria += "LIKE ";
3118 break;
3119 case css::sdb::SQLFilterOperator::NOT_LIKE:
3120 sCriteria += "NOT LIKE ";
3121 break;
3122 case css::sdb::SQLFilterOperator::SQLNULL:
3123 sCriteria += "IS NULL";
3124 break;
3125 case css::sdb::SQLFilterOperator::NOT_SQLNULL:
3126 sCriteria += "IS NOT NULL";
3127 break;
3129 pParseNode->parseNodeToPredicateStr( sCriteria
3130 ,xConnection
3131 ,xFormatter
3132 ,xField
3133 ,OUString()
3134 ,aAppLocale
3135 ,strDecimalSeparator
3136 ,getParseContext());
3137 aRow[rFieldInfo.xText] = sCriteria;
3144 if (aRow.empty())
3145 continue;
3147 impl_addFilterRow( aRow );
3151 // now set the filter controls
3152 for (const auto& rFieldInfo : rFieldInfos)
3154 m_aFilterComponents.push_back( rFieldInfo.xText );
3159 void FormController::startFiltering()
3161 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
3163 Reference< XConnection > xConnection( getConnection( Reference< XRowSet >( m_xModelAsIndex, UNO_QUERY ) ) );
3164 if ( !xConnection.is() )
3165 // nothing to do - can't filter a form which is not connected
3166 return;
3168 // stop listening for controls
3169 if (isListeningForChanges())
3170 stopListening();
3172 m_bFiltering = true;
3174 // as we don't want new controls to be attached to the scripting environment
3175 // we change attach flags
3176 m_bAttachEvents = false;
3178 // exchanging the controls for the current form
3179 Sequence< Reference< XControl > > aControlsCopy( m_aControls );
3180 const Reference< XControl >* pControls = aControlsCopy.getConstArray();
3181 sal_Int32 nControlCount = aControlsCopy.getLength();
3183 // the control we have to activate after replacement
3184 Reference< XNumberFormatsSupplier > xFormatSupplier = getNumberFormats(xConnection, true);
3185 Reference< XNumberFormatter > xFormatter = NumberFormatter::create(m_xComponentContext);
3186 xFormatter->attachNumberFormatsSupplier(xFormatSupplier);
3188 // structure for storing the field info
3189 ::std::vector<FmFieldInfo> aFieldInfos;
3191 for (sal_Int32 i = nControlCount; i > 0;)
3193 Reference< XControl > xControl = pControls[--i];
3194 if (xControl.is())
3196 // no events for the control anymore
3197 removeFromEventAttacher(xControl);
3199 // do we have a mode selector
3200 Reference< XModeSelector > xSelector(xControl, UNO_QUERY);
3201 if (xSelector.is())
3203 xSelector->setMode( u"FilterMode"_ustr );
3205 // listening for new controls of the selector
3206 Reference< XContainer > xContainer(xSelector, UNO_QUERY);
3207 if (xContainer.is())
3208 xContainer->addContainerListener(this);
3210 Reference< XEnumerationAccess > xElementAccess(xSelector, UNO_QUERY);
3211 if (xElementAccess.is())
3213 Reference< XEnumeration > xEnumeration(xElementAccess->createEnumeration());
3214 Reference< XControl > xSubControl;
3215 while (xEnumeration->hasMoreElements())
3217 xEnumeration->nextElement() >>= xSubControl;
3218 if (xSubControl.is())
3220 Reference< XPropertySet > xSet(xSubControl->getModel(), UNO_QUERY);
3221 if (xSet.is() && ::comphelper::hasProperty(FM_PROP_BOUNDFIELD, xSet))
3223 // does the model use a bound field ?
3224 Reference< XPropertySet > xField;
3225 xSet->getPropertyValue(FM_PROP_BOUNDFIELD) >>= xField;
3227 Reference< XTextComponent > xText(xSubControl, UNO_QUERY);
3228 // may we filter the field?
3229 if (xText.is() && xField.is() && ::comphelper::hasProperty(FM_PROP_SEARCHABLE, xField) &&
3230 ::comphelper::getBOOL(xField->getPropertyValue(FM_PROP_SEARCHABLE)))
3232 aFieldInfos.emplace_back(xField, xText);
3233 xText->addTextListener(this);
3239 continue;
3242 Reference< XPropertySet > xModel( xControl->getModel(), UNO_QUERY );
3243 if (xModel.is() && ::comphelper::hasProperty(FM_PROP_BOUNDFIELD, xModel))
3245 // does the model use a bound field ?
3246 Any aVal = xModel->getPropertyValue(FM_PROP_BOUNDFIELD);
3247 Reference< XPropertySet > xField;
3248 aVal >>= xField;
3250 // may we filter the field?
3252 if ( xField.is()
3253 && ::comphelper::hasProperty( FM_PROP_SEARCHABLE, xField )
3254 && ::comphelper::getBOOL( xField->getPropertyValue( FM_PROP_SEARCHABLE ) )
3257 // create a filter control
3258 Reference< XControl > xFilterControl = form::control::FilterControl::createWithFormat(
3259 m_xComponentContext,
3260 getDialogParentWindow(this),
3261 xFormatter,
3262 xModel);
3264 if ( replaceControl( xControl, xFilterControl ) )
3266 Reference< XTextComponent > xFilterText( xFilterControl, UNO_QUERY );
3267 aFieldInfos.emplace_back( xField, xFilterText );
3268 xFilterText->addTextListener(this);
3272 else
3274 // unsubscribe from EventManager
3279 // we have all filter controls now, so the next step is to read the filters from the form
3280 // resolve all aliases and set the current filter to the according structure
3281 setFilter(aFieldInfos);
3283 Reference< XPropertySet > xSet( m_xModelAsIndex, UNO_QUERY );
3284 if ( xSet.is() )
3285 stopFormListening( xSet, true );
3287 impl_setTextOnAllFilter_throw();
3289 // lock all controls which are not used for filtering
3290 m_bLocked = determineLockState();
3291 setLocks();
3292 m_bAttachEvents = true;
3296 void FormController::stopFiltering()
3298 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
3299 if ( !m_bFiltering ) // #104693# OJ
3300 { // nothing to do
3301 return;
3304 m_bFiltering = false;
3305 m_bDetachEvents = false;
3307 ::comphelper::disposeComponent(m_xComposer);
3309 // exchanging the controls for the current form
3310 Sequence< Reference< XControl > > aControlsCopy( m_aControls );
3311 const Reference< XControl > * pControls = aControlsCopy.getConstArray();
3312 sal_Int32 nControlCount = aControlsCopy.getLength();
3314 // clear the filter control map
3315 ::std::for_each( m_aFilterComponents.begin(), m_aFilterComponents.end(), RemoveComponentTextListener( this ) );
3316 m_aFilterComponents.clear();
3318 for ( sal_Int32 i = nControlCount; i > 0; )
3320 Reference< XControl > xControl = pControls[--i];
3321 if (xControl.is())
3323 // now enable event handling again
3324 addToEventAttacher(xControl);
3326 Reference< XModeSelector > xSelector(xControl, UNO_QUERY);
3327 if (xSelector.is())
3329 xSelector->setMode( u"DataMode"_ustr );
3331 // listening for new controls of the selector
3332 Reference< XContainer > xContainer(xSelector, UNO_QUERY);
3333 if (xContainer.is())
3334 xContainer->removeContainerListener(this);
3335 continue;
3338 Reference< XPropertySet > xSet(xControl->getModel(), UNO_QUERY);
3339 if (xSet.is() && ::comphelper::hasProperty(FM_PROP_BOUNDFIELD, xSet))
3341 // does the model use a bound field ?
3342 Reference< XPropertySet > xField;
3343 xSet->getPropertyValue(FM_PROP_BOUNDFIELD) >>= xField;
3345 // may we filter the field?
3346 if ( xField.is()
3347 && ::comphelper::hasProperty( FM_PROP_SEARCHABLE, xField )
3348 && ::comphelper::getBOOL( xField->getPropertyValue( FM_PROP_SEARCHABLE ) )
3351 OUString sServiceName;
3352 OSL_VERIFY( xSet->getPropertyValue( FM_PROP_DEFAULTCONTROL ) >>= sServiceName );
3353 Reference< XControl > xNewControl( m_xComponentContext->getServiceManager()->createInstanceWithContext( sServiceName, m_xComponentContext ), UNO_QUERY );
3354 replaceControl( xControl, xNewControl );
3360 Reference< XPropertySet > xSet( m_xModelAsIndex, UNO_QUERY );
3361 if ( xSet.is() )
3362 startFormListening( xSet, true );
3364 m_bDetachEvents = true;
3366 m_aFilterRows.clear();
3367 m_nCurrentFilterPosition = -1;
3369 // release the locks if possible
3370 // lock all controls which are not used for filtering
3371 m_bLocked = determineLockState();
3372 setLocks();
3374 // restart listening for control modifications
3375 if (isListeningForChanges())
3376 startListening();
3379 // XModeSelector
3381 void FormController::setMode(const OUString& Mode)
3383 ::osl::MutexGuard aGuard( m_aMutex );
3384 impl_checkDisposed_throw();
3386 if (!supportsMode(Mode))
3387 throw NoSupportException();
3389 if (Mode == m_aMode)
3390 return;
3392 m_aMode = Mode;
3394 if ( Mode == "FilterMode" )
3395 startFiltering();
3396 else
3397 stopFiltering();
3399 for (const auto& rChild : m_aChildren)
3401 Reference< XModeSelector > xMode(rChild, UNO_QUERY);
3402 if ( xMode.is() )
3403 xMode->setMode(Mode);
3408 OUString SAL_CALL FormController::getMode()
3410 ::osl::MutexGuard aGuard( m_aMutex );
3411 impl_checkDisposed_throw();
3413 return m_aMode;
3417 Sequence< OUString > SAL_CALL FormController::getSupportedModes()
3419 ::osl::MutexGuard aGuard( m_aMutex );
3420 impl_checkDisposed_throw();
3422 static Sequence< OUString > const aModes
3424 u"DataMode"_ustr,
3425 u"FilterMode"_ustr
3427 return aModes;
3430 sal_Bool SAL_CALL FormController::supportsMode(const OUString& Mode)
3432 ::osl::MutexGuard aGuard( m_aMutex );
3433 impl_checkDisposed_throw();
3435 Sequence< OUString > aModes(getSupportedModes());
3436 return comphelper::findValue(aModes, Mode) != -1;
3439 css::uno::Reference<css::awt::XWindow> FormController::getDialogParentWindow(css::uno::Reference<css::form::runtime::XFormController> xFormController)
3443 Reference< XControl > xContainerControl( xFormController->getContainer(), UNO_QUERY_THROW );
3444 Reference<XWindow> xContainerWindow(xContainerControl->getPeer(), UNO_QUERY_THROW);
3445 return xContainerWindow;
3447 catch( const Exception& )
3449 DBG_UNHANDLED_EXCEPTION("svx");
3451 return nullptr;
3454 bool FormController::checkFormComponentValidity( OUString& /* [out] */ _rFirstInvalidityExplanation, Reference< XControlModel >& /* [out] */ _rxFirstInvalidModel )
3458 Reference< XEnumerationAccess > xControlEnumAcc( getModel(), UNO_QUERY );
3459 Reference< XEnumeration > xControlEnumeration;
3460 if ( xControlEnumAcc.is() )
3461 xControlEnumeration = xControlEnumAcc->createEnumeration();
3462 OSL_ENSURE( xControlEnumeration.is(), "FormController::checkFormComponentValidity: cannot enumerate the controls!" );
3463 if ( !xControlEnumeration.is() )
3464 // assume all valid
3465 return true;
3467 Reference< XValidatableFormComponent > xValidatable;
3468 while ( xControlEnumeration->hasMoreElements() )
3470 if ( !( xControlEnumeration->nextElement() >>= xValidatable ) )
3471 // control does not support validation
3472 continue;
3474 if ( xValidatable->isValid() )
3475 continue;
3477 Reference< XValidator > xValidator( xValidatable->getValidator() );
3478 OSL_ENSURE( xValidator.is(), "FormController::checkFormComponentValidity: invalid, but no validator?" );
3479 if ( !xValidator.is() )
3480 // this violates the interface definition of css.form.validation.XValidatableFormComponent ...
3481 continue;
3483 _rFirstInvalidityExplanation = xValidator->explainInvalid( xValidatable->getCurrentValue() );
3484 _rxFirstInvalidModel.set(xValidatable, css::uno::UNO_QUERY);
3485 return false;
3488 catch( const Exception& )
3490 DBG_UNHANDLED_EXCEPTION("svx");
3492 return true;
3496 Reference< XControl > FormController::locateControl( const Reference< XControlModel >& _rxModel )
3500 const Sequence< Reference< XControl > > aControls( getControls() );
3502 for ( auto const & control : aControls )
3504 OSL_ENSURE( control.is(), "FormController::locateControl: NULL-control?" );
3505 if ( control.is() )
3507 if ( control->getModel() == _rxModel )
3508 return control;
3511 OSL_FAIL( "FormController::locateControl: did not find a control for this model!" );
3513 catch( const Exception& )
3515 DBG_UNHANDLED_EXCEPTION("svx");
3517 return nullptr;
3521 namespace
3523 void displayErrorSetFocus(const OUString& _rMessage, const Reference<XControl>& _rxFocusControl,
3524 const css::uno::Reference<css::awt::XWindow>& rDialogParent)
3526 SQLContext aError(SvxResId(RID_STR_WRITEERROR), {}, {}, 0, {}, _rMessage);
3527 displayException(aError, rDialogParent);
3529 if ( _rxFocusControl.is() )
3531 Reference< XWindow > xControlWindow( _rxFocusControl, UNO_QUERY );
3532 OSL_ENSURE( xControlWindow.is(), "displayErrorSetFocus: invalid control!" );
3533 if ( xControlWindow.is() )
3534 xControlWindow->setFocus();
3538 bool lcl_shouldValidateRequiredFields_nothrow( const Reference< XInterface >& _rxForm )
3542 static constexpr OUString s_sFormsCheckRequiredFields = u"FormsCheckRequiredFields"_ustr;
3544 // first, check whether the form has a property telling us the answer
3545 // this allows people to use the XPropertyContainer interface of a form to control
3546 // the behaviour on a per-form basis.
3547 Reference< XPropertySet > xFormProps( _rxForm, UNO_QUERY_THROW );
3548 Reference< XPropertySetInfo > xPSI( xFormProps->getPropertySetInfo() );
3549 if ( xPSI->hasPropertyByName( s_sFormsCheckRequiredFields ) )
3551 bool bShouldValidate = true;
3552 OSL_VERIFY( xFormProps->getPropertyValue( s_sFormsCheckRequiredFields ) >>= bShouldValidate );
3553 return bShouldValidate;
3556 // next, check the data source which created the connection
3557 Reference< XChild > xConnectionAsChild( xFormProps->getPropertyValue( FM_PROP_ACTIVE_CONNECTION ), UNO_QUERY_THROW );
3558 Reference< XPropertySet > xDataSource( xConnectionAsChild->getParent(), UNO_QUERY );
3559 if ( !xDataSource.is() )
3560 // seldom (but possible): this is not a connection created by a data source
3561 return true;
3563 Reference< XPropertySet > xDataSourceSettings(
3564 xDataSource->getPropertyValue(u"Settings"_ustr),
3565 UNO_QUERY_THROW );
3567 bool bShouldValidate = true;
3568 OSL_VERIFY( xDataSourceSettings->getPropertyValue( s_sFormsCheckRequiredFields ) >>= bShouldValidate );
3569 return bShouldValidate;
3571 catch( const Exception& )
3573 DBG_UNHANDLED_EXCEPTION("svx");
3576 return true;
3580 // XRowSetApproveListener
3582 sal_Bool SAL_CALL FormController::approveRowChange(const RowChangeEvent& _rEvent)
3584 ::osl::ClearableMutexGuard aGuard( m_aMutex );
3585 impl_checkDisposed_throw();
3587 ::comphelper::OInterfaceIteratorHelper3 aIter(m_aRowSetApproveListeners);
3588 bool bValid = true;
3589 if (aIter.hasMoreElements())
3591 RowChangeEvent aEvt( _rEvent );
3592 aEvt.Source = *this;
3593 bValid = aIter.next()->approveRowChange(aEvt);
3596 if ( !bValid )
3597 return bValid;
3599 if ( ( _rEvent.Action != RowChangeAction::INSERT )
3600 && ( _rEvent.Action != RowChangeAction::UPDATE )
3602 return bValid;
3604 // if some of the control models are bound to validators, check them
3605 OUString sInvalidityExplanation;
3606 Reference< XControlModel > xInvalidModel;
3607 if ( !checkFormComponentValidity( sInvalidityExplanation, xInvalidModel ) )
3609 Reference< XControl > xControl( locateControl( xInvalidModel ) );
3610 aGuard.clear();
3611 displayErrorSetFocus( sInvalidityExplanation, xControl, getDialogParentWindow(this) );
3612 return false;
3615 // check values on NULL and required flag
3616 if ( !lcl_shouldValidateRequiredFields_nothrow( _rEvent.Source ) )
3617 return true;
3619 OSL_ENSURE(m_pColumnInfoCache, "FormController::approveRowChange: no column infos!");
3620 if (!m_pColumnInfoCache)
3621 return true;
3625 if ( !m_pColumnInfoCache->controlsInitialized() )
3626 m_pColumnInfoCache->initializeControls( getControls() );
3628 size_t colCount = m_pColumnInfoCache->getColumnCount();
3629 for ( size_t col = 0; col < colCount; ++col )
3631 const ColumnInfo& rColInfo = m_pColumnInfoCache->getColumnInfo( col );
3633 if ( rColInfo.bAutoIncrement )
3634 continue;
3636 if ( rColInfo.bReadOnly )
3637 continue;
3639 if ( !rColInfo.xFirstControlWithInputRequired.is() && !rColInfo.xFirstGridWithInputRequiredColumn.is() )
3641 continue;
3644 // TODO: in case of binary fields, this "getString" below is extremely expensive
3645 if ( !rColInfo.xColumn->getString().isEmpty() || !rColInfo.xColumn->wasNull() )
3646 continue;
3648 OUString sMessage( SvxResId( RID_ERR_FIELDREQUIRED ) );
3649 sMessage = sMessage.replaceFirst( "#", rColInfo.sName );
3651 // the control to focus
3652 Reference< XControl > xControl( rColInfo.xFirstControlWithInputRequired );
3653 if ( !xControl.is() )
3654 xControl.set( rColInfo.xFirstGridWithInputRequiredColumn, UNO_QUERY );
3656 aGuard.clear();
3657 displayErrorSetFocus( sMessage, rColInfo.xFirstControlWithInputRequired, getDialogParentWindow(this) );
3658 return false;
3661 catch( const Exception& )
3663 DBG_UNHANDLED_EXCEPTION("svx");
3666 return true;
3670 sal_Bool SAL_CALL FormController::approveCursorMove(const EventObject& event)
3672 ::osl::MutexGuard aGuard( m_aMutex );
3673 impl_checkDisposed_throw();
3675 ::comphelper::OInterfaceIteratorHelper3 aIter(m_aRowSetApproveListeners);
3676 if (aIter.hasMoreElements())
3678 EventObject aEvt(event);
3679 aEvt.Source = *this;
3680 return aIter.next()->approveCursorMove(aEvt);
3683 return true;
3687 sal_Bool SAL_CALL FormController::approveRowSetChange(const EventObject& event)
3689 ::osl::MutexGuard aGuard( m_aMutex );
3690 impl_checkDisposed_throw();
3692 ::comphelper::OInterfaceIteratorHelper3 aIter(m_aRowSetApproveListeners);
3693 if (aIter.hasMoreElements())
3695 EventObject aEvt(event);
3696 aEvt.Source = *this;
3697 return aIter.next()->approveRowSetChange(aEvt);
3700 return true;
3703 // XRowSetApproveBroadcaster
3705 void SAL_CALL FormController::addRowSetApproveListener(const Reference< XRowSetApproveListener > & _rxListener)
3707 ::osl::MutexGuard aGuard( m_aMutex );
3708 impl_checkDisposed_throw();
3710 m_aRowSetApproveListeners.addInterface(_rxListener);
3714 void SAL_CALL FormController::removeRowSetApproveListener(const Reference< XRowSetApproveListener > & _rxListener)
3716 ::osl::MutexGuard aGuard( m_aMutex );
3717 impl_checkDisposed_throw();
3719 m_aRowSetApproveListeners.removeInterface(_rxListener);
3722 // XErrorListener
3724 void SAL_CALL FormController::errorOccured(const SQLErrorEvent& aEvent)
3726 ::osl::ClearableMutexGuard aGuard( m_aMutex );
3727 impl_checkDisposed_throw();
3729 ::comphelper::OInterfaceIteratorHelper3 aIter(m_aErrorListeners);
3730 if (aIter.hasMoreElements())
3732 SQLErrorEvent aEvt(aEvent);
3733 aEvt.Source = *this;
3734 aIter.next()->errorOccured(aEvt);
3736 else
3738 aGuard.clear();
3739 displayException(aEvent, getDialogParentWindow(this));
3743 // XErrorBroadcaster
3745 void SAL_CALL FormController::addSQLErrorListener(const Reference< XSQLErrorListener > & aListener)
3747 ::osl::MutexGuard aGuard( m_aMutex );
3748 impl_checkDisposed_throw();
3750 m_aErrorListeners.addInterface(aListener);
3754 void SAL_CALL FormController::removeSQLErrorListener(const Reference< XSQLErrorListener > & aListener)
3756 ::osl::MutexGuard aGuard( m_aMutex );
3757 impl_checkDisposed_throw();
3759 m_aErrorListeners.removeInterface(aListener);
3762 // XDatabaseParameterBroadcaster2
3764 void SAL_CALL FormController::addDatabaseParameterListener(const Reference< XDatabaseParameterListener > & aListener)
3766 ::osl::MutexGuard aGuard( m_aMutex );
3767 impl_checkDisposed_throw();
3769 m_aParameterListeners.addInterface(aListener);
3773 void SAL_CALL FormController::removeDatabaseParameterListener(const Reference< XDatabaseParameterListener > & aListener)
3775 ::osl::MutexGuard aGuard( m_aMutex );
3776 impl_checkDisposed_throw();
3778 m_aParameterListeners.removeInterface(aListener);
3781 // XDatabaseParameterBroadcaster
3783 void SAL_CALL FormController::addParameterListener(const Reference< XDatabaseParameterListener > & aListener)
3785 FormController::addDatabaseParameterListener( aListener );
3789 void SAL_CALL FormController::removeParameterListener(const Reference< XDatabaseParameterListener > & aListener)
3791 FormController::removeDatabaseParameterListener( aListener );
3794 // XDatabaseParameterListener
3796 sal_Bool SAL_CALL FormController::approveParameter(const DatabaseParameterEvent& aEvent)
3798 SolarMutexGuard aSolarGuard;
3799 ::osl::MutexGuard aGuard( m_aMutex );
3800 impl_checkDisposed_throw();
3802 ::comphelper::OInterfaceIteratorHelper3 aIter(m_aParameterListeners);
3803 if (aIter.hasMoreElements())
3805 DatabaseParameterEvent aEvt(aEvent);
3806 aEvt.Source = *this;
3807 return aIter.next()->approveParameter(aEvt);
3809 else
3811 // default handling: instantiate an interaction handler and let it handle the parameter request
3814 if ( !ensureInteractionHandler() )
3815 return false;
3817 // two continuations allowed: OK and Cancel
3818 rtl::Reference<OParameterContinuation> pParamValues = new OParameterContinuation;
3819 rtl::Reference<OInteractionAbort> pAbort = new OInteractionAbort;
3820 // the request
3821 ParametersRequest aRequest;
3822 aRequest.Parameters = aEvent.Parameters;
3823 aRequest.Connection = getConnection(Reference< XRowSet >(aEvent.Source, UNO_QUERY));
3824 rtl::Reference<OInteractionRequest> pParamRequest = new OInteractionRequest(Any(aRequest));
3825 // some knittings
3826 pParamRequest->addContinuation(pParamValues);
3827 pParamRequest->addContinuation(pAbort);
3829 // handle the request
3830 m_xInteractionHandler->handle(pParamRequest);
3832 if (!pParamValues->wasSelected())
3833 // canceled
3834 return false;
3836 // transfer the values into the parameter supplier
3837 Sequence< PropertyValue > aFinalValues = pParamValues->getValues();
3838 if (aFinalValues.getLength() != aRequest.Parameters->getCount())
3840 OSL_FAIL("FormController::approveParameter: the InteractionHandler returned nonsense!");
3841 return false;
3843 const PropertyValue* pFinalValues = aFinalValues.getConstArray();
3844 for (sal_Int32 i=0; i<aFinalValues.getLength(); ++i, ++pFinalValues)
3846 Reference< XPropertySet > xParam(
3847 aRequest.Parameters->getByIndex(i), css::uno::UNO_QUERY);
3848 if (xParam.is())
3850 #ifdef DBG_UTIL
3851 OUString sName;
3852 xParam->getPropertyValue(FM_PROP_NAME) >>= sName;
3853 DBG_ASSERT(sName == pFinalValues->Name, "FormController::approveParameter: suspicious value names!");
3854 #endif
3855 try { xParam->setPropertyValue(FM_PROP_VALUE, pFinalValues->Value); }
3856 catch(Exception&)
3858 OSL_FAIL("FormController::approveParameter: setting one of the properties failed!");
3863 catch(Exception&)
3865 DBG_UNHANDLED_EXCEPTION("svx");
3868 return true;
3871 // XConfirmDeleteBroadcaster
3873 void SAL_CALL FormController::addConfirmDeleteListener(const Reference< XConfirmDeleteListener > & aListener)
3875 ::osl::MutexGuard aGuard( m_aMutex );
3876 impl_checkDisposed_throw();
3878 m_aDeleteListeners.addInterface(aListener);
3882 void SAL_CALL FormController::removeConfirmDeleteListener(const Reference< XConfirmDeleteListener > & aListener)
3884 ::osl::MutexGuard aGuard( m_aMutex );
3885 impl_checkDisposed_throw();
3887 m_aDeleteListeners.removeInterface(aListener);
3890 // XConfirmDeleteListener
3892 sal_Bool SAL_CALL FormController::confirmDelete(const RowChangeEvent& aEvent)
3894 ::osl::MutexGuard aGuard( m_aMutex );
3895 impl_checkDisposed_throw();
3897 ::comphelper::OInterfaceIteratorHelper3 aIter(m_aDeleteListeners);
3898 if (aIter.hasMoreElements())
3900 RowChangeEvent aEvt(aEvent);
3901 aEvt.Source = *this;
3902 return aIter.next()->confirmDelete(aEvt);
3904 // default handling: instantiate an interaction handler and let it handle the request
3906 OUString sTitle;
3907 sal_Int32 nLength = aEvent.Rows;
3908 if ( nLength > 1 )
3910 sTitle = SvxResId( RID_STR_DELETECONFIRM_RECORDS );
3911 sTitle = sTitle.replaceFirst( "#", OUString::number(nLength) );
3913 else
3914 sTitle = SvxResId( RID_STR_DELETECONFIRM_RECORD );
3918 if ( !ensureInteractionHandler() )
3919 return false;
3921 // two continuations allowed: Yes and No
3922 rtl::Reference<OInteractionApprove> pApprove = new OInteractionApprove;
3923 rtl::Reference<OInteractionDisapprove> pDisapprove = new OInteractionDisapprove;
3925 // the request
3926 SQLWarning aDetails(SvxResId(RID_STR_DELETECONFIRM), {}, {}, 0, {});
3927 SQLWarning aWarning(sTitle, {}, {}, 0, css::uno::Any(aDetails));
3929 rtl::Reference<OInteractionRequest> pRequest = new OInteractionRequest( Any( aWarning ) );
3931 // some knittings
3932 pRequest->addContinuation( pApprove );
3933 pRequest->addContinuation( pDisapprove );
3935 // handle the request
3936 m_xInteractionHandler->handle( pRequest );
3938 if ( pApprove->wasSelected() )
3939 return true;
3941 catch( const Exception& )
3943 DBG_UNHANDLED_EXCEPTION("svx");
3946 return false;
3950 void SAL_CALL FormController::invalidateFeatures( const Sequence< ::sal_Int16 >& Features )
3952 ::osl::MutexGuard aGuard( m_aMutex );
3953 // for now, just copy the ids of the features, because...
3954 m_aInvalidFeatures.insert( Features.begin(), Features.end() );
3956 // ... we will do the real invalidation asynchronously
3957 if ( !m_aFeatureInvalidationTimer.IsActive() )
3958 m_aFeatureInvalidationTimer.Start();
3962 void SAL_CALL FormController::invalidateAllFeatures( )
3964 ::osl::ClearableMutexGuard aGuard( m_aMutex );
3966 Sequence< sal_Int16 > aInterceptedFeatures( comphelper::mapKeysToSequence(m_aFeatureDispatchers) );
3968 aGuard.clear();
3969 if ( aInterceptedFeatures.hasElements() )
3970 invalidateFeatures( aInterceptedFeatures );
3974 Reference< XDispatch >
3975 FormController::interceptedQueryDispatch( const URL& aURL,
3976 const OUString& /*aTargetFrameName*/, sal_Int32 /*nSearchFlags*/)
3978 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
3979 Reference< XDispatch > xReturn;
3980 // dispatches handled by ourself
3981 if ( ( aURL.Complete == FMURL_CONFIRM_DELETION )
3982 || ( ( aURL.Complete == "private:/InteractionHandler" )
3983 && ensureInteractionHandler()
3986 xReturn = static_cast< XDispatch* >( this );
3988 // dispatches of FormSlot-URLs we have to translate
3989 if ( !xReturn.is() && m_xFormOperations.is() )
3991 // find the slot id which corresponds to the URL
3992 sal_Int32 nFeatureSlotId = svx::FeatureSlotTranslation::getControllerFeatureSlotIdForURL( aURL.Main );
3993 sal_Int16 nFormFeature = ( nFeatureSlotId != -1 ) ? svx::FeatureSlotTranslation::getFormFeatureForSlotId( nFeatureSlotId ) : -1;
3994 if ( nFormFeature > 0 )
3996 // get the dispatcher for this feature, create if necessary
3997 DispatcherContainer::const_iterator aDispatcherPos = m_aFeatureDispatchers.find( nFormFeature );
3998 if ( aDispatcherPos == m_aFeatureDispatchers.end() )
4000 aDispatcherPos = m_aFeatureDispatchers.emplace(
4001 nFormFeature, new svx::OSingleFeatureDispatcher( aURL, nFormFeature, m_xFormOperations, m_aMutex )
4002 ).first;
4005 OSL_ENSURE( aDispatcherPos->second.is(), "FormController::interceptedQueryDispatch: should have a dispatcher by now!" );
4006 return aDispatcherPos->second;
4010 // no more to offer
4011 return xReturn;
4015 void SAL_CALL FormController::dispatch( const URL& _rURL, const Sequence< PropertyValue >& _rArgs )
4017 if ( _rArgs.getLength() != 1 )
4019 OSL_FAIL( "FormController::dispatch: no arguments -> no dispatch!" );
4020 return;
4023 if ( _rURL.Complete == "private:/InteractionHandler" )
4025 Reference< XInteractionRequest > xRequest;
4026 OSL_VERIFY( _rArgs[0].Value >>= xRequest );
4027 if ( xRequest.is() )
4028 handle( xRequest );
4029 return;
4032 if ( _rURL.Complete == FMURL_CONFIRM_DELETION )
4034 OSL_FAIL( "FormController::dispatch: How do you expect me to return something via this call?" );
4035 // confirmDelete has a return value - dispatch hasn't
4036 return;
4039 OSL_FAIL( "FormController::dispatch: unknown URL!" );
4043 void SAL_CALL FormController::addStatusListener( const Reference< XStatusListener >& _rxListener, const URL& _rURL )
4045 if (_rURL.Complete == FMURL_CONFIRM_DELETION)
4047 if (_rxListener.is())
4048 { // send an initial statusChanged event
4049 FeatureStateEvent aEvent;
4050 aEvent.FeatureURL = _rURL;
4051 aEvent.IsEnabled = true;
4052 _rxListener->statusChanged(aEvent);
4053 // and don't add the listener at all (the status will never change)
4056 else
4057 OSL_FAIL("FormController::addStatusListener: invalid (unsupported) URL!");
4061 Reference< XInterface > SAL_CALL FormController::getParent()
4063 return m_xParent;
4067 void SAL_CALL FormController::setParent( const Reference< XInterface >& Parent)
4069 m_xParent = Parent;
4073 void SAL_CALL FormController::removeStatusListener( const Reference< XStatusListener >& /*_rxListener*/, const URL& _rURL )
4075 OSL_ENSURE(_rURL.Complete == FMURL_CONFIRM_DELETION, "FormController::removeStatusListener: invalid (unsupported) URL!");
4076 // we never really added the listener, so we don't need to remove it
4080 Reference< XDispatchProviderInterceptor > FormController::createInterceptor(const Reference< XDispatchProviderInterception > & _xInterception)
4082 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
4083 #ifdef DBG_UTIL
4084 // check if we already have an interceptor for the given object
4085 for ( const auto & it : m_aControlDispatchInterceptors )
4087 if (it->getIntercepted() == _xInterception)
4088 OSL_FAIL("FormController::createInterceptor : we already do intercept this objects dispatches !");
4090 #endif
4092 rtl::Reference<DispatchInterceptionMultiplexer> pInterceptor(new DispatchInterceptionMultiplexer( _xInterception, this ));
4093 m_aControlDispatchInterceptors.push_back( pInterceptor );
4095 return pInterceptor;
4099 bool FormController::ensureInteractionHandler()
4101 if ( m_xInteractionHandler.is() )
4102 return true;
4103 if ( m_bAttemptedHandlerCreation )
4104 return false;
4105 m_bAttemptedHandlerCreation = true;
4107 m_xInteractionHandler = InteractionHandler::createWithParent(m_xComponentContext,
4108 getDialogParentWindow(this));
4109 return m_xInteractionHandler.is();
4113 void SAL_CALL FormController::handle( const Reference< XInteractionRequest >& _rRequest )
4115 if ( !ensureInteractionHandler() )
4116 return;
4117 m_xInteractionHandler->handle( _rRequest );
4121 void FormController::deleteInterceptor(const Reference< XDispatchProviderInterception > & _xInterception)
4123 OSL_ENSURE( !impl_isDisposed_nofail(), "FormController: already disposed!" );
4124 // search the interceptor responsible for the given object
4125 auto aIter = std::find_if(m_aControlDispatchInterceptors.begin(), m_aControlDispatchInterceptors.end(),
4126 [&_xInterception](const rtl::Reference<DispatchInterceptionMultiplexer>& rpInterceptor) {
4127 return rpInterceptor->getIntercepted() == _xInterception;
4129 if (aIter != m_aControlDispatchInterceptors.end())
4131 // log off the interception from its interception object
4132 (*aIter)->dispose();
4133 // remove the interceptor from our array
4134 m_aControlDispatchInterceptors.erase(aIter);
4139 void FormController::implInvalidateCurrentControlDependentFeatures()
4141 Sequence< sal_Int16 > aCurrentControlDependentFeatures
4143 FormFeature::SortAscending,
4144 FormFeature::SortDescending,
4145 FormFeature::AutoFilter,
4146 FormFeature::RefreshCurrentControl
4149 invalidateFeatures( aCurrentControlDependentFeatures );
4153 void SAL_CALL FormController::columnChanged( const EventObject& /*_event*/ )
4155 implInvalidateCurrentControlDependentFeatures();
4160 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */