xref: /trunk/main/dbaccess/source/ui/browser/unodatbr.cxx (revision 46c69c84579d1f1df536015e7d54c9965db90b69)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_dbui.hxx"
26 
27 #include "browserids.hxx"
28 #include "dbaccess_helpid.hrc"
29 #include "dbexchange.hxx"
30 #include "dbtreelistbox.hxx"
31 #include "dbtreemodel.hxx"
32 #include "dbtreeview.hxx"
33 #include "dbu_brw.hrc"
34 #include "dbu_reghelper.hxx"
35 #include "dbustrings.hrc"
36 #include "dlgsave.hxx"
37 #include "HtmlReader.hxx"
38 #include "imageprovider.hxx"
39 #include "listviewitems.hxx"
40 #include "QEnumTypes.hxx"
41 #include "RtfReader.hxx"
42 #include "sbagrid.hrc"
43 #include "sbagrid.hxx"
44 #include "sqlmessage.hxx"
45 #include "TokenWriter.hxx"
46 #include "UITools.hxx"
47 #include "unodatbr.hxx"
48 #include "WColumnSelect.hxx"
49 #include "WCopyTable.hxx"
50 #include "WCPage.hxx"
51 #include "WExtendPages.hxx"
52 #include "WNameMatch.hxx"
53 
54 /** === begin UNO includes === **/
55 #include <com/sun/star/awt/LineEndFormat.hpp>
56 #include <com/sun/star/awt/LineEndFormat.hpp>
57 #include <com/sun/star/awt/MouseWheelBehavior.hpp>
58 #include <com/sun/star/awt/TextAlign.hpp>
59 #include <com/sun/star/awt/VisualEffect.hpp>
60 #include <com/sun/star/beans/NamedValue.hpp>
61 #include <com/sun/star/beans/PropertyValue.hpp>
62 #include <com/sun/star/container/XNameContainer.hpp>
63 #include <com/sun/star/form/XForm.hpp>
64 #include <com/sun/star/form/XGridColumnFactory.hpp>
65 #include <com/sun/star/form/XLoadable.hpp>
66 #include <com/sun/star/form/XReset.hpp>
67 #include <com/sun/star/frame/FrameSearchFlag.hpp>
68 #include <com/sun/star/frame/XLayoutManager.hpp>
69 #include <com/sun/star/lang/DisposedException.hpp>
70 #include <com/sun/star/sdb/CommandType.hpp>
71 #include <com/sun/star/sdb/SQLContext.hpp>
72 #include <com/sun/star/sdb/XBookmarksSupplier.hpp>
73 #include <com/sun/star/sdb/XCompletedConnection.hpp>
74 #include <com/sun/star/sdb/XDatabaseRegistrations.hpp>
75 #include <com/sun/star/sdb/XDocumentDataSource.hpp>
76 #include <com/sun/star/sdb/XParametersSupplier.hpp>
77 #include <com/sun/star/sdb/XQueriesSupplier.hpp>
78 #include <com/sun/star/sdb/XQueryDefinitionsSupplier.hpp>
79 #include <com/sun/star/sdb/XResultSetAccess.hpp>
80 #include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
81 #include <com/sun/star/sdb/application/NamedDatabaseObject.hpp>
82 #include <com/sun/star/sdbc/ColumnValue.hpp>
83 #include <com/sun/star/sdbc/DataType.hpp>
84 #include <com/sun/star/sdbc/FetchDirection.hpp>
85 #include <com/sun/star/sdbc/SQLWarning.hpp>
86 #include <com/sun/star/sdbc/XDataSource.hpp>
87 #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
88 #include <com/sun/star/sdbc/XWarningsSupplier.hpp>
89 #include <com/sun/star/sdbcx/Privilege.hpp>
90 #include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
91 #include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp>
92 #include <com/sun/star/sdbcx/XDrop.hpp>
93 #include <com/sun/star/sdbcx/XTablesSupplier.hpp>
94 #include <com/sun/star/sdbcx/XViewsSupplier.hpp>
95 #include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
96 #include <com/sun/star/util/XFlushable.hpp>
97 #include <com/sun/star/sdb/XDocumentDataSource.hpp>
98 #include <com/sun/star/document/MacroExecMode.hpp>
99 #include <com/sun/star/frame/XComponentLoader.hpp>
100 #include <com/sun/star/ui/XContextMenuInterceptor.hpp>
101 /** === end UNO includes === **/
102 
103 #include <comphelper/extract.hxx>
104 #include <comphelper/sequence.hxx>
105 #include <comphelper/types.hxx>
106 #include <connectivity/dbexception.hxx>
107 #include <cppuhelper/exc_hlp.hxx>
108 #include <cppuhelper/implbase2.hxx>
109 #include <cppuhelper/typeprovider.hxx>
110 #include <sfx2/app.hxx>
111 #include <sfx2/dispatch.hxx>
112 #include <sot/storage.hxx>
113 #include <svl/filenotation.hxx>
114 #include <svl/intitem.hxx>
115 #include <unotools/moduleoptions.hxx>
116 #include <svtools/svlbitm.hxx>
117 #include <svtools/svtreebx.hxx>
118 #include <svx/algitem.hxx>
119 #include <svx/dataaccessdescriptor.hxx>
120 #include <svx/databaseregistrationui.hxx>
121 #include <svx/gridctrl.hxx>
122 #include <toolkit/helper/vclunohelper.hxx>
123 #include <tools/diagnose_ex.h>
124 #include <tools/multisel.hxx>
125 #include <tools/urlobj.hxx>
126 #include <unotools/confignode.hxx>
127 #include <vcl/msgbox.hxx>
128 #include <vcl/split.hxx>
129 #include <vcl/stdtext.hxx>
130 #include <vcl/svapp.hxx>
131 #include <vcl/toolbox.hxx>
132 #include <vcl/waitobj.hxx>
133 #include <vcl/wrkwin.hxx>
134 #include <rtl/logfile.hxx>
135 
136 #include <memory>
137 #include <functional>
138 
139 using namespace ::com::sun::star::uno;
140 using namespace ::com::sun::star::awt;
141 using namespace ::com::sun::star::sdb;
142 using namespace ::com::sun::star::sdb::application;
143 using namespace ::com::sun::star::sdbc;
144 using namespace ::com::sun::star::sdbcx;
145 using namespace ::com::sun::star::beans;
146 using namespace ::com::sun::star::util;
147 using namespace ::com::sun::star::frame;
148 using namespace ::com::sun::star::container;
149 using namespace ::com::sun::star::lang;
150 using namespace ::com::sun::star::ui::dialogs;
151 using namespace ::com::sun::star::task;
152 using namespace ::com::sun::star::form;
153 using namespace ::com::sun::star::io;
154 using namespace ::com::sun::star::i18n;
155 using namespace ::com::sun::star::view;
156 using namespace ::com::sun::star::datatransfer;
157 using namespace ::com::sun::star::document;
158 using namespace ::com::sun::star::ui;
159 using namespace ::dbtools;
160 using namespace ::comphelper;
161 using namespace ::svx;
162 
163 // .........................................................................
164 namespace dbaui
165 {
166 // .........................................................................
167 
168 namespace DatabaseObject = ::com::sun::star::sdb::application::DatabaseObject;
169 namespace DatabaseObjectContainer = ::com::sun::star::sdb::application::DatabaseObjectContainer;
170 
171 //==================================================================
172 //= SbaTableQueryBrowser
173 //==================================================================
174 // -------------------------------------------------------------------------
createRegistryInfo_OBrowser()175 extern "C" void SAL_CALL createRegistryInfo_OBrowser()
176 {
177     static OMultiInstanceAutoRegistration< SbaTableQueryBrowser > aAutoRegistration;
178 }
179 // -------------------------------------------------------------------------
SafeAddPropertyListener(const Reference<XPropertySet> & xSet,const::rtl::OUString & rPropName,XPropertyChangeListener * pListener)180 void SafeAddPropertyListener(const Reference< XPropertySet > & xSet, const ::rtl::OUString& rPropName, XPropertyChangeListener* pListener)
181 {
182     Reference< XPropertySetInfo >  xInfo = xSet->getPropertySetInfo();
183     if (xInfo->hasPropertyByName(rPropName))
184         xSet->addPropertyChangeListener(rPropName, pListener);
185 }
186 
187 // -------------------------------------------------------------------------
SafeRemovePropertyListener(const Reference<XPropertySet> & xSet,const::rtl::OUString & rPropName,XPropertyChangeListener * pListener)188 void SafeRemovePropertyListener(const Reference< XPropertySet > & xSet, const ::rtl::OUString& rPropName, XPropertyChangeListener* pListener)
189 {
190     Reference< XPropertySetInfo >  xInfo = xSet->getPropertySetInfo();
191     if (xInfo->hasPropertyByName(rPropName))
192         xSet->removePropertyChangeListener(rPropName, pListener);
193 }
194 //-------------------------------------------------------------------------
getImplementationName()195 ::rtl::OUString SAL_CALL SbaTableQueryBrowser::getImplementationName()
196 {
197     return getImplementationName_Static();
198 }
199 //-------------------------------------------------------------------------
getSupportedServiceNames()200 ::comphelper::StringSequence SAL_CALL SbaTableQueryBrowser::getSupportedServiceNames()
201 {
202     return getSupportedServiceNames_Static();
203 }
204 // -------------------------------------------------------------------------
getImplementationName_Static()205 ::rtl::OUString SbaTableQueryBrowser::getImplementationName_Static()
206 {
207     return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.ODatasourceBrowser");
208 }
209 //-------------------------------------------------------------------------
getSupportedServiceNames_Static()210 ::comphelper::StringSequence SbaTableQueryBrowser::getSupportedServiceNames_Static()
211 {
212     ::comphelper::StringSequence aSupported(1);
213     aSupported.getArray()[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdb.DataSourceBrowser");
214     return aSupported;
215 }
216 //-------------------------------------------------------------------------
Create(const Reference<XMultiServiceFactory> & _rxFactory)217 Reference< XInterface > SAL_CALL SbaTableQueryBrowser::Create(const Reference<XMultiServiceFactory >& _rxFactory)
218 {
219     ::vos::OGuard aGuard(Application::GetSolarMutex());
220     return *(new SbaTableQueryBrowser(_rxFactory));
221 }
222 
223 DBG_NAME(SbaTableQueryBrowser);
224 //------------------------------------------------------------------------------
SbaTableQueryBrowser(const Reference<XMultiServiceFactory> & _rM)225 SbaTableQueryBrowser::SbaTableQueryBrowser(const Reference< XMultiServiceFactory >& _rM)
226     :SbaXDataBrowserController(_rM)
227     ,m_aSelectionListeners( getMutex() )
228     ,m_aContextMenuInterceptors( getMutex() )
229     ,m_aTableCopyHelper(this)
230     ,m_pTreeView(NULL)
231     ,m_pSplitter(NULL)
232     ,m_pTreeModel(NULL)
233     ,m_pCurrentlyDisplayed(NULL)
234     ,m_nAsyncDrop(0)
235     ,m_nBorder(1)
236     ,m_bQueryEscapeProcessing( sal_False )
237     ,m_bShowMenu(sal_False)
238     ,m_bInSuspend(sal_False)
239     ,m_bEnableBrowser(sal_True)
240 {
241     DBG_CTOR(SbaTableQueryBrowser,NULL);
242 }
243 
244 //------------------------------------------------------------------------------
~SbaTableQueryBrowser()245 SbaTableQueryBrowser::~SbaTableQueryBrowser()
246 {
247     DBG_DTOR(SbaTableQueryBrowser,NULL);
248     if ( !rBHelper.bDisposed && !rBHelper.bInDispose )
249     {
250         OSL_ENSURE(0,"Please check who doesn't dispose this component!");
251         // increment ref count to prevent double call of Dtor
252         osl_incrementInterlockedCount( &m_refCount );
253         dispose();
254     }
255 }
256 
257 //------------------------------------------------------------------------------
queryInterface(const Type & _rType)258 Any SAL_CALL SbaTableQueryBrowser::queryInterface(const Type& _rType)
259 {
260     if ( _rType.equals( XScriptInvocationContext::static_type() ) )
261     {
262         OSL_PRECOND( !!m_aDocScriptSupport, "SbaTableQueryBrowser::queryInterface: did not initialize this, yet!" );
263         if ( !!m_aDocScriptSupport && *m_aDocScriptSupport )
264             return makeAny( Reference< XScriptInvocationContext >( this ) );
265         return Any();
266     }
267 
268     Any aReturn = SbaXDataBrowserController::queryInterface(_rType);
269     if (!aReturn.hasValue())
270         aReturn = SbaTableQueryBrowser_Base::queryInterface(_rType);
271     return aReturn;
272 }
273 
274 //------------------------------------------------------------------------------
getTypes()275 Sequence< Type > SAL_CALL SbaTableQueryBrowser::getTypes(  )
276 {
277     Sequence< Type > aTypes( ::comphelper::concatSequences(
278         SbaXDataBrowserController::getTypes(),
279         SbaTableQueryBrowser_Base::getTypes()
280     ) );
281 
282     OSL_PRECOND( !!m_aDocScriptSupport, "SbaTableQueryBrowser::getTypes: did not initialize this, yet!" );
283     if ( !m_aDocScriptSupport || !*m_aDocScriptSupport )
284     {
285         Sequence< Type > aStrippedTypes( aTypes.getLength() - 1 );
286         ::std::remove_copy_if(
287             aTypes.getConstArray(),
288             aTypes.getConstArray() + aTypes.getLength(),
289             aStrippedTypes.getArray(),
290             ::std::bind( ::std::equal_to< Type >(), ::std::placeholders::_1, XScriptInvocationContext::static_type() )
291         );
292         aTypes = aStrippedTypes;
293     }
294     return aTypes;
295 }
296 
297 //------------------------------------------------------------------------------
getImplementationId()298 Sequence< sal_Int8 > SAL_CALL SbaTableQueryBrowser::getImplementationId(  )
299 {
300     static ::cppu::OImplementationId * pId = 0;
301     if (! pId)
302     {
303         ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
304         if (! pId)
305         {
306             static ::cppu::OImplementationId aId;
307             pId = &aId;
308         }
309     }
310     return pId->getImplementationId();
311 }
312 
313 //------------------------------------------------------------------------------
disposing()314 void SAL_CALL SbaTableQueryBrowser::disposing()
315 {
316     ::vos::OGuard aGuard(Application::GetSolarMutex());
317         // doing a lot of VCL stuff here -> lock the SolarMutex
318 
319     // kiss our listeners goodbye
320 
321     ::com::sun::star::lang::EventObject aEvt(*this);
322     m_aSelectionListeners.disposeAndClear(aEvt);
323     m_aContextMenuInterceptors.disposeAndClear(aEvt);
324 
325     // reset the content's tree view: it holds a reference to our model which is to be deleted immediately,
326     // and it will live longer than we do.
327     if (getBrowserView())
328         getBrowserView()->setTreeView(NULL);
329 
330     clearTreeModel();
331     // clear the tree model
332     {
333         ::std::unique_ptr<SvLBoxTreeList> aTemp(m_pTreeModel);
334         m_pTreeModel = NULL;
335     }
336 
337     // remove ourself as status listener
338     implRemoveStatusListeners();
339 
340     // remove the container listener from the database context
341     try
342     {
343         Reference< XDatabaseRegistrations > xDatabaseRegistrations( m_xDatabaseContext, UNO_QUERY_THROW );
344         xDatabaseRegistrations->removeDatabaseRegistrationsListener( this );
345     }
346     catch( const Exception& )
347     {
348         DBG_UNHANDLED_EXCEPTION();
349     }
350 
351     // check out from all the objects we are listening
352     // the frame
353     if (m_xCurrentFrameParent.is())
354         m_xCurrentFrameParent->removeFrameActionListener((::com::sun::star::frame::XFrameActionListener*)this);
355     SbaXDataBrowserController::disposing();
356 }
357 
358 //------------------------------------------------------------------------------
Construct(Window * pParent)359 sal_Bool SbaTableQueryBrowser::Construct(Window* pParent)
360 {
361     if ( !SbaXDataBrowserController::Construct( pParent ) )
362         return sal_False;
363 
364     try
365     {
366         Reference< XDatabaseRegistrations > xDatabaseRegistrations( m_xDatabaseContext, UNO_QUERY_THROW );
367         xDatabaseRegistrations->addDatabaseRegistrationsListener( this );
368 
369         // the collator for the string compares
370         m_xCollator = Reference< XCollator >( getORB()->createInstance(::rtl::OUString::createFromAscii( "com.sun.star.i18n.Collator" ) ), UNO_QUERY_THROW );
371         m_xCollator->loadDefaultCollator( Application::GetSettings().GetLocale(), 0 );
372     }
373     catch(Exception&)
374     {
375         DBG_ERROR("SbaTableQueryBrowser::Construct: could not create (or start listening at) the database context!");
376     }
377     // some help ids
378     if (getBrowserView() && getBrowserView()->getVclControl())
379     {
380 
381         // create controls and set sizes
382         const long  nFrameWidth = getBrowserView()->LogicToPixel( ::Size( 3, 0 ), MAP_APPFONT ).Width();
383 
384         m_pSplitter = new Splitter(getBrowserView(),WB_HSCROLL);
385         m_pSplitter->SetPosSizePixel( ::Point(0,0), ::Size(nFrameWidth,0) );
386         m_pSplitter->SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetDialogColor() ) );
387 
388         m_pTreeView = new DBTreeView(getBrowserView(),getORB(), WB_TABSTOP | WB_BORDER);
389         m_pTreeView->SetPreExpandHandler(LINK(this, SbaTableQueryBrowser, OnExpandEntry));
390 
391         m_pTreeView->setCopyHandler(LINK(this, SbaTableQueryBrowser, OnCopyEntry));
392 
393         m_pTreeView->getListBox().setContextMenuProvider( this );
394         m_pTreeView->getListBox().setControlActionListener( this );
395         m_pTreeView->SetHelpId(HID_CTL_TREEVIEW);
396 
397         // a default pos for the splitter, so that the listbox is about 80 (logical) pixels wide
398         m_pSplitter->SetSplitPosPixel( getBrowserView()->LogicToPixel( ::Size( 80, 0 ), MAP_APPFONT ).Width() );
399 
400         getBrowserView()->setSplitter(m_pSplitter);
401         getBrowserView()->setTreeView(m_pTreeView);
402 
403         // fill view with data
404         m_pTreeModel = new SvLBoxTreeList;
405         m_pTreeModel->SetSortMode(SortAscending);
406         m_pTreeModel->SetCompareHdl(LINK(this, SbaTableQueryBrowser, OnTreeEntryCompare));
407         m_pTreeView->setModel(m_pTreeModel);
408         m_pTreeView->setSelChangeHdl( LINK( this, SbaTableQueryBrowser, OnSelectionChange ) );
409 
410         // TODO
411         getBrowserView()->getVclControl()->GetDataWindow().SetUniqueId(UID_DATABROWSE_DATAWINDOW);
412         getBrowserView()->getVclControl()->SetHelpId(HID_CTL_TABBROWSER);
413         getBrowserView()->SetUniqueId(UID_CTL_CONTENT);
414         if (getBrowserView()->getVclControl()->GetHeaderBar())
415             getBrowserView()->getVclControl()->GetHeaderBar()->SetHelpId(HID_DATABROWSE_HEADER);
416         InvalidateFeature(ID_BROWSER_EXPLORER);
417     }
418 
419     return sal_True;
420 }
421 // ---------------------------------------------------------------------------------------------------------------------
422 namespace
423 {
424     // -----------------------------------------------------------------------------------------------------------------
425     struct SelectValueByName
426     {
427         typedef ::rtl::OUString argument_type;
428         typedef Any result_type;
operator ()dbaui::__anon2d6ac27d0111::SelectValueByName429         const Any& operator()( ::rtl::OUString const& i_name ) const
430         {
431             return m_rCollection.get( i_name );
432         }
433 
SelectValueByNamedbaui::__anon2d6ac27d0111::SelectValueByName434         SelectValueByName( ::comphelper::NamedValueCollection const& i_collection )
435             :m_rCollection( i_collection )
436         {
437         }
438 
439         ::comphelper::NamedValueCollection const&   m_rCollection;
440     };
441 }
442 
443 // ---------------------------------------------------------------------------------------------------------------------
impl_sanitizeRowSetClauses_nothrow()444 void SbaTableQueryBrowser::impl_sanitizeRowSetClauses_nothrow()
445 {
446     try
447     {
448         Reference< XPropertySet > xRowSetProps( getRowSet(), UNO_QUERY_THROW );
449         sal_Bool bEscapeProcessing = sal_False;
450         OSL_VERIFY( xRowSetProps->getPropertyValue( PROPERTY_ESCAPE_PROCESSING ) >>= bEscapeProcessing );
451         if ( !bEscapeProcessing )
452             // don't touch or interpret anything if escape processing is disabled
453             return;
454 
455         Reference< XSingleSelectQueryComposer > xComposer( createParser_nothrow() );
456         if ( !xComposer.is() )
457             // can't do anything. Already reported via assertion in createParser_nothrow.
458             return;
459 
460         // the tables participating in the statement
461         const Reference< XTablesSupplier > xSuppTables( xComposer, UNO_QUERY_THROW );
462         const Reference< XNameAccess > xTableNames( xSuppTables->getTables(), UNO_QUERY_THROW );
463 
464         // the columns participating in the statement
465         const Reference< XColumnsSupplier > xSuppColumns( xComposer, UNO_QUERY_THROW );
466         const Reference< XNameAccess > xColumnNames( xSuppColumns->getColumns(), UNO_QUERY_THROW );
467 
468         // .............................................................................................................
469         // check if the order columns apply to tables which really exist in the statement
470         const Reference< XIndexAccess > xOrderColumns( xComposer->getOrderColumns(), UNO_SET_THROW );
471         const sal_Int32 nOrderColumns( xOrderColumns->getCount() );
472         bool invalidColumn = nOrderColumns == 0;
473         for ( sal_Int32 c=0; ( c < nOrderColumns ) && !invalidColumn; ++c )
474         {
475             const Reference< XPropertySet > xOrderColumn( xOrderColumns->getByIndex(c), UNO_QUERY_THROW );
476             ::rtl::OUString sTableName;
477             OSL_VERIFY( xOrderColumn->getPropertyValue( PROPERTY_TABLENAME ) >>= sTableName );
478             ::rtl::OUString sColumnName;
479             OSL_VERIFY( xOrderColumn->getPropertyValue( PROPERTY_NAME ) >>= sColumnName );
480 
481             if ( sTableName.getLength() == 0 )
482             {
483                 if ( !xColumnNames->hasByName( sColumnName ) )
484                 {
485                     invalidColumn = true;
486                     break;
487                 }
488             }
489             else
490             {
491                 if ( !xTableNames->hasByName( sTableName ) )
492                 {
493                     invalidColumn = true;
494                     break;
495                 }
496 
497                 const Reference< XColumnsSupplier > xSuppTableColumns( xTableNames->getByName( sTableName ), UNO_QUERY_THROW );
498                 const Reference< XNameAccess > xTableColumnNames( xSuppTableColumns->getColumns(), UNO_QUERY_THROW );
499                 if ( !xTableColumnNames->hasByName( sColumnName ) )
500                 {
501                     invalidColumn = true;
502                     break;
503                 }
504             }
505         }
506 
507         if ( invalidColumn )
508         {
509             // reset the complete order statement at both the row set and the parser
510             const ::rtl::OUString sEmptyOrder;
511             xRowSetProps->setPropertyValue( PROPERTY_ORDER, makeAny( sEmptyOrder ) );
512             xComposer->setOrder( sEmptyOrder );
513         }
514 
515         // .............................................................................................................
516         // check if the columns participating in the filter refer to existing tables
517         // TODO: there's no API at all for this. The method which comes nearest to what we need is
518         // "getStructuredFilter", but it returns pure column names only. That is, for a statement like
519         // "SELECT * FROM <table> WHERE <other_table>.<column> = <value>", it will return "<column>". But
520         // there's no API at all to retrieve the information about  "<other_table>" - which is what would
521         // be needed here.
522         // That'd be a chance to replace getStructuredFilter with something more reasonable. This method
523         // has at least one other problem: For a clause like "<column> != <value>", it will return "<column>"
524         // as column name, "NOT_EQUAL" as operator, and "!= <value>" as value, effectively duplicating the
525         // information about the operator, and begging all clients to manually remove the "!=" from the value
526         // string.
527         // So, what really would be handy, is some
528         //   XNormalizedFilter getNormalizedFilter();
529         // with
530         //   interface XDisjunctiveFilterExpression
531         //   {
532         //     XConjunctiveFilterTerm getTerm( int index );
533         //   }
534         //   interface XConjunctiveFilterTerm
535         //   {
536         //     ComparisonPredicate getPredicate( int index );
537         //   }
538         //   struct ComparisonPredicate
539         //   {
540         //     XComparisonOperand   Lhs;
541         //     SQLFilterOperator    Operator;
542         //     XComparisonOperand   Rhs;
543         //   }
544         //   interface XComparisonOperand
545         //   {
546         //     SQLFilterOperand Type;
547         //     XPropertySet     getColumn();
548         //     string           getLiteral();
549         //     ...
550         //   }
551         //   enum SQLFilterOperand { Column, Literal, ... }
552         //
553         // ... or something like this ....
554     }
555     catch( const Exception& )
556     {
557         DBG_UNHANDLED_EXCEPTION();
558     }
559 }
560 
561 // ---------------------------------------------------------------------------------------------------------------------
InitializeForm(const Reference<XPropertySet> & i_formProperties)562 sal_Bool SbaTableQueryBrowser::InitializeForm( const Reference< XPropertySet > & i_formProperties )
563 {
564     if(!m_pCurrentlyDisplayed)
565         return sal_True;
566 
567     // this method set all format settings from the original table or query
568     try
569     {
570         DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(m_pCurrentlyDisplayed->GetUserData());
571         ENSURE_OR_RETURN_FALSE( pData, "SbaTableQueryBrowser::InitializeForm: No user data set at the currently displayed entry!" );
572         ENSURE_OR_RETURN_FALSE( pData->xObjectProperties.is(), "SbaTableQueryBrowser::InitializeForm: No table available!" );
573 
574         Reference< XPropertySetInfo > xPSI( pData->xObjectProperties->getPropertySetInfo(), UNO_SET_THROW );
575 
576         ::comphelper::NamedValueCollection aPropertyValues;
577 
578         const ::rtl::OUString aTransferProperties[] =
579         {
580             PROPERTY_APPLYFILTER,
581             PROPERTY_FILTER,
582             PROPERTY_HAVING_CLAUSE,
583             PROPERTY_ORDER
584         };
585         for ( size_t i=0; i < sizeof( aTransferProperties ) / sizeof( aTransferProperties[0] ); ++i )
586         {
587             if ( !xPSI->hasPropertyByName( aTransferProperties[i] ) )
588                 continue;
589             aPropertyValues.put( aTransferProperties[i], pData->xObjectProperties->getPropertyValue( aTransferProperties[i] ) );
590         }
591 
592         const ::std::vector< ::rtl::OUString > aNames( aPropertyValues.getNames() );
593         Sequence< ::rtl::OUString > aPropNames( aNames.size() );
594         ::std::copy( aNames.begin(), aNames.end(), aPropNames.getArray() );
595 
596         Sequence< Any > aPropValues( aNames.size() );
597         ::std::transform( aNames.begin(), aNames.end(), aPropValues.getArray(), SelectValueByName( aPropertyValues ) );
598 
599         Reference< XMultiPropertySet > xFormMultiSet( i_formProperties, UNO_QUERY_THROW );
600         xFormMultiSet->setPropertyValues( aPropNames, aPropValues );
601 
602         impl_sanitizeRowSetClauses_nothrow();
603     }
604     catch ( const Exception& )
605     {
606         DBG_UNHANDLED_EXCEPTION();
607         return sal_False;
608     }
609 
610     return sal_True;
611 }
612 
613 //------------------------------------------------------------------------------
initializePreviewMode()614 void SbaTableQueryBrowser::initializePreviewMode()
615 {
616     if ( getBrowserView() && getBrowserView()->getVclControl() )
617     {
618         getBrowserView()->getVclControl()->AlwaysEnableInput( sal_False );
619         getBrowserView()->getVclControl()->EnableInput( sal_False );
620         getBrowserView()->getVclControl()->ForceHideScrollbars( sal_True );
621     }
622     Reference< XPropertySet >  xDataSourceSet(getRowSet(), UNO_QUERY);
623     if ( xDataSourceSet.is() )
624     {
625         xDataSourceSet->setPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AllowInserts")),makeAny(sal_False));
626         xDataSourceSet->setPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AllowUpdates")),makeAny(sal_False));
627         xDataSourceSet->setPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AllowDeletes")),makeAny(sal_False));
628     }
629 }
630 
631 //------------------------------------------------------------------------------
InitializeGridModel(const Reference<::com::sun::star::form::XFormComponent> & xGrid)632 sal_Bool SbaTableQueryBrowser::InitializeGridModel(const Reference< ::com::sun::star::form::XFormComponent > & xGrid)
633 {
634     try
635     {
636         Reference< ::com::sun::star::form::XGridColumnFactory >  xColFactory(xGrid, UNO_QUERY);
637         Reference< XNameContainer >  xColContainer(xGrid, UNO_QUERY);
638         clearGridColumns( xColContainer );
639 
640         Reference< XChild > xGridAsChild(xGrid, UNO_QUERY);
641         Reference< XLoadable > xFormAsLoadable;
642         if (xGridAsChild.is())
643             xFormAsLoadable = xFormAsLoadable.query(xGridAsChild->getParent());
644         if (xFormAsLoadable.is() && xFormAsLoadable->isLoaded())
645         {
646             // set the formats from the table
647             if(m_pCurrentlyDisplayed)
648             {
649                 Sequence< ::rtl::OUString> aProperties(6 + ( m_bPreview ? 5 : 0 ));
650                 Sequence< Any> aValues(7 + ( m_bPreview ? 5 : 0 ));
651 
652                 DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(m_pCurrentlyDisplayed->GetUserData());
653                 OSL_ENSURE( pData->xObjectProperties.is(), "SbaTableQueryBrowser::InitializeGridModel: No table available!" );
654                 if ( !pData->xObjectProperties.is() )
655                     return sal_False;
656 
657                 ::rtl::OUString* pStringIter = aProperties.getArray();
658                 Any* pValueIter = aValues.getArray();
659                 if ( m_bPreview )
660                 {
661                     *pStringIter++  = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AlwaysShowCursor"));
662                     *pValueIter++   <<= sal_False;
663                     *pStringIter++  = PROPERTY_BORDER;
664                     *pValueIter++   <<= sal_Int16(0);
665                 }
666 
667                 *pStringIter++  = PROPERTY_FONT;
668                 *pValueIter++   = pData->xObjectProperties->getPropertyValue(PROPERTY_FONT);
669                 *pStringIter++  = PROPERTY_TEXTEMPHASIS;
670                 *pValueIter++   = pData->xObjectProperties->getPropertyValue(PROPERTY_TEXTEMPHASIS);
671                 *pStringIter++  = PROPERTY_TEXTRELIEF;
672                 *pValueIter++   = pData->xObjectProperties->getPropertyValue(PROPERTY_TEXTRELIEF);
673                 if ( m_bPreview )
674                 {
675                     *pStringIter++  = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("HasNavigationBar"));
676                     *pValueIter++       <<= sal_False;
677                     *pStringIter++  = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("HasRecordMarker"));
678                     *pValueIter++       <<= sal_False;
679                 }
680                 *pStringIter++  = PROPERTY_ROW_HEIGHT;
681                 *pValueIter++   = pData->xObjectProperties->getPropertyValue(PROPERTY_ROW_HEIGHT);
682                 if ( m_bPreview )
683                 {
684                     *pStringIter++  = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Tabstop"));
685                     *pValueIter++       <<= sal_False;
686                 }
687                 *pStringIter++  = PROPERTY_TEXTCOLOR;
688                 *pValueIter++   = pData->xObjectProperties->getPropertyValue(PROPERTY_TEXTCOLOR);
689                 *pStringIter++  = PROPERTY_TEXTLINECOLOR;
690                 *pValueIter++   = pData->xObjectProperties->getPropertyValue(PROPERTY_TEXTLINECOLOR);
691 
692                 Reference< XMultiPropertySet >  xFormMultiSet(xGrid, UNO_QUERY);
693                 xFormMultiSet->setPropertyValues(aProperties, aValues);
694             }
695 
696 
697             // get the formats supplier of the database we're working with
698             Reference< ::com::sun::star::util::XNumberFormatsSupplier >  xSupplier = getNumberFormatter()->getNumberFormatsSupplier();
699 
700             Reference<XConnection> xConnection;
701             Reference<XPropertySet> xRowSetProps(getRowSet(),UNO_QUERY);
702             xRowSetProps->getPropertyValue( PROPERTY_ACTIVE_CONNECTION ) >>= xConnection;
703             OSL_ENSURE(xConnection.is(),"A ActiveConnection should normally exists!");
704 
705             Reference<XChild> xChild(xConnection,UNO_QUERY);
706             Reference<XPropertySet> xDataSourceProp(xChild->getParent(),UNO_QUERY);
707             sal_Bool bSuppressVersionCol = sal_False;
708             OSL_VERIFY( xDataSourceProp->getPropertyValue( PROPERTY_SUPPRESSVERSIONCL ) >>= bSuppressVersionCol );
709 
710             // insert the column into the gridcontrol so that we see something :-)
711             ::rtl::OUString aCurrentModelType;
712             Reference<XColumnsSupplier> xSupCols(getRowSet(),UNO_QUERY);
713             Reference<XNameAccess> xColumns     = xSupCols->getColumns();
714             Sequence< ::rtl::OUString> aNames   = xColumns->getElementNames();
715             const ::rtl::OUString* pIter        = aNames.getConstArray();
716             const ::rtl::OUString* pEnd         = pIter + aNames.getLength();
717 
718             ::rtl::OUString sDefaultProperty;
719             Reference< XPropertySet > xColumn;
720             Reference< XPropertySetInfo > xColPSI;
721             for (sal_uInt16 i=0; pIter != pEnd; ++i,++pIter)
722             {
723                 xColumn.set( xColumns->getByName( *pIter ), UNO_QUERY_THROW );
724                 xColPSI.set( xColumn->getPropertySetInfo(), UNO_SET_THROW );
725 
726                 // ignore the column when it is a rowversion one
727                 if  (   bSuppressVersionCol
728                     &&  xColPSI->hasPropertyByName( PROPERTY_ISROWVERSION )
729                     &&  ::cppu::any2bool( xColumn->getPropertyValue( PROPERTY_ISROWVERSION ) )
730                     )
731                     continue;
732 
733                 // use the result set column's type to determine the type of grid column to create
734                 sal_Bool bFormattedIsNumeric    = sal_True;
735                 sal_Int32 nType = ::comphelper::getINT32( xColumn->getPropertyValue( PROPERTY_TYPE ) );
736 
737                 ::std::vector< NamedValue > aInitialValues;
738                 ::std::vector< ::rtl::OUString > aCopyProperties;
739                 Any aDefault;
740 
741                 switch(nType)
742                 {
743                     case DataType::BIT:
744                     case DataType::BOOLEAN:
745                     {
746                         aCurrentModelType = ::rtl::OUString::createFromAscii("CheckBox");
747                         aInitialValues.push_back( NamedValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "VisualEffect" ) ), makeAny( VisualEffect::FLAT ) ) );
748                         sDefaultProperty = PROPERTY_DEFAULTSTATE;
749 
750                         sal_Int32 nNullable = ColumnValue::NULLABLE_UNKNOWN;
751                         OSL_VERIFY( xColumn->getPropertyValue( PROPERTY_ISNULLABLE ) >>= nNullable );
752                         aInitialValues.push_back( NamedValue(
753                             ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "TriState" ) ),
754                             makeAny( sal_Bool( ColumnValue::NO_NULLS != nNullable ) )
755                         ) );
756                         if ( ColumnValue::NO_NULLS == nNullable )
757                             aDefault <<= (sal_Int16)STATE_NOCHECK;
758                     }
759                     break;
760 
761                     case DataType::LONGVARCHAR:
762                     case DataType::CLOB:
763                         aInitialValues.push_back( NamedValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "MultiLine" ) ), makeAny( (sal_Bool)sal_True ) ) );
764                         // NO break!
765                     case DataType::BINARY:
766                     case DataType::VARBINARY:
767                     case DataType::LONGVARBINARY:
768                         aCurrentModelType = ::rtl::OUString::createFromAscii("TextField");
769                         sDefaultProperty = PROPERTY_DEFAULTTEXT;
770                         break;
771 
772                     case DataType::VARCHAR:
773                     case DataType::CHAR:
774                         bFormattedIsNumeric = sal_False;
775                         // NO break!
776                     default:
777                         aCurrentModelType = ::rtl::OUString::createFromAscii("FormattedField");
778                         sDefaultProperty = PROPERTY_EFFECTIVEDEFAULT;
779 
780                         if ( xSupplier.is() )
781                             aInitialValues.push_back( NamedValue( ::rtl::OUString::createFromAscii( "FormatsSupplier" ), makeAny( xSupplier ) ) );
782                         aInitialValues.push_back( NamedValue( ::rtl::OUString::createFromAscii( "TreatAsNumber" ), makeAny( (sal_Bool)bFormattedIsNumeric ) ) );
783                         aCopyProperties.push_back( PROPERTY_FORMATKEY );
784                         break;
785                 }
786 
787                 aInitialValues.push_back( NamedValue( PROPERTY_CONTROLSOURCE, makeAny( *pIter ) ) );
788                 ::rtl::OUString sLabel;
789                 xColumn->getPropertyValue(PROPERTY_LABEL) >>= sLabel;
790                 if ( sLabel.getLength() )
791                     aInitialValues.push_back( NamedValue( PROPERTY_LABEL, makeAny( sLabel ) ) );
792                 else
793                     aInitialValues.push_back( NamedValue( PROPERTY_LABEL, makeAny( *pIter ) ) );
794 
795                 Reference< XPropertySet > xGridCol( xColFactory->createColumn( aCurrentModelType ), UNO_SET_THROW );
796                 Reference< XPropertySetInfo > xGridColPSI( xGridCol->getPropertySetInfo(), UNO_SET_THROW );
797 
798                 // calculate the default
799                 if ( xGridColPSI->hasPropertyByName( PROPERTY_CONTROLDEFAULT ) )
800                 {
801                     aDefault = xColumn->getPropertyValue( PROPERTY_CONTROLDEFAULT );
802                     // default value
803                     if ( nType == DataType::BIT || nType == DataType::BOOLEAN )
804                     {
805                         if ( aDefault.hasValue() )
806                             aDefault <<= (comphelper::getString(aDefault).toInt32() == 0) ? (sal_Int16)STATE_NOCHECK : (sal_Int16)STATE_CHECK;
807                         else
808                             aDefault <<= ((sal_Int16)STATE_DONTKNOW);
809                     }
810                 }
811 
812                 if ( aDefault.hasValue() )
813                     aInitialValues.push_back( NamedValue( sDefaultProperty, aDefault ) );
814 
815                 // transfer properties from the definition to the UNO-model :
816                 aCopyProperties.push_back( PROPERTY_HIDDEN );
817                 aCopyProperties.push_back( PROPERTY_WIDTH );
818 
819                 // help text to display for the column
820                 Any aDescription;
821                 if ( xColPSI->hasPropertyByName( PROPERTY_HELPTEXT ) )
822                     aDescription = xColumn->getPropertyValue( PROPERTY_HELPTEXT );
823                 ::rtl::OUString sTemp;
824                 aDescription >>= sTemp;
825                 if ( !sTemp.getLength() )
826                     xColumn->getPropertyValue( PROPERTY_DESCRIPTION ) >>= sTemp;
827 
828                 aDescription <<= sTemp;
829                 aInitialValues.push_back( NamedValue( PROPERTY_HELPTEXT, aDescription ) );
830 
831                 // ... horizontal justify
832                 Any aAlign; aAlign <<= sal_Int16( 0 );
833                 Any aColAlign( xColumn->getPropertyValue( PROPERTY_ALIGN ) );
834                 if ( aColAlign.hasValue() )
835                     aAlign <<= sal_Int16( ::comphelper::getINT32( aColAlign ) );
836                 aInitialValues.push_back( NamedValue( PROPERTY_ALIGN, aAlign ) );
837 
838                 // don't allow the mouse to scroll in the cells
839                 if ( xGridColPSI->hasPropertyByName( PROPERTY_MOUSE_WHEEL_BEHAVIOR ) )
840                     aInitialValues.push_back( NamedValue( PROPERTY_MOUSE_WHEEL_BEHAVIOR, makeAny( MouseWheelBehavior::SCROLL_DISABLED ) ) );
841 
842                 // now set all those values
843                 for ( ::std::vector< NamedValue >::const_iterator property = aInitialValues.begin();
844                       property != aInitialValues.end();
845                       ++property
846                     )
847                 {
848                     xGridCol->setPropertyValue( property->Name, property->Value );
849                 }
850                 for ( ::std::vector< ::rtl::OUString >::const_iterator copyPropertyName = aCopyProperties.begin();
851                       copyPropertyName != aCopyProperties.end();
852                       ++copyPropertyName
853                     )
854                     xGridCol->setPropertyValue( *copyPropertyName, xColumn->getPropertyValue( *copyPropertyName ) );
855 
856                 xColContainer->insertByName(*pIter, makeAny(xGridCol));
857             }
858         }
859     }
860     catch(Exception&)
861     {
862         DBG_UNHANDLED_EXCEPTION();
863         return sal_False;
864     }
865 
866     return sal_True;
867 }
868 // -----------------------------------------------------------------------------
getColumnHelper(SvLBoxEntry * _pCurrentlyDisplayed,const Reference<XPropertySet> & _rxSource)869 Reference<XPropertySet> getColumnHelper(SvLBoxEntry* _pCurrentlyDisplayed,const Reference<XPropertySet>& _rxSource)
870 {
871     Reference<XPropertySet> xRet;
872     if(_pCurrentlyDisplayed)
873     {
874         DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(_pCurrentlyDisplayed->GetUserData());
875         Reference<XColumnsSupplier> xColumnsSup(pData->xObjectProperties,UNO_QUERY);
876         Reference<XNameAccess> xNames = xColumnsSup->getColumns();
877         ::rtl::OUString aName;
878         _rxSource->getPropertyValue(PROPERTY_NAME) >>= aName;
879         if(xNames.is() && xNames->hasByName(aName))
880             xRet.set(xNames->getByName(aName),UNO_QUERY);
881     }
882     return xRet;
883 }
884 
885 // -----------------------------------------------------------------------
transferChangedControlProperty(const::rtl::OUString & _rProperty,const Any & _rNewValue)886 void SbaTableQueryBrowser::transferChangedControlProperty(const ::rtl::OUString& _rProperty, const Any& _rNewValue)
887 {
888     if(m_pCurrentlyDisplayed)
889     {
890         DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(m_pCurrentlyDisplayed->GetUserData());
891         Reference< XPropertySet > xObjectProps(pData->xObjectProperties, UNO_QUERY);
892         OSL_ENSURE(xObjectProps.is(),"SbaTableQueryBrowser::transferChangedControlProperty: no table/query object!");
893         if (xObjectProps.is())
894             xObjectProps->setPropertyValue(_rProperty, _rNewValue);
895     }
896 }
897 
898 // -----------------------------------------------------------------------
propertyChange(const PropertyChangeEvent & evt)899 void SbaTableQueryBrowser::propertyChange(const PropertyChangeEvent& evt)
900 {
901     SbaXDataBrowserController::propertyChange(evt);
902 
903     try
904     {
905         Reference< XPropertySet >  xSource(evt.Source, UNO_QUERY);
906         if (!xSource.is())
907             return;
908 
909         // one of the many properties which require us to update the definition ?
910         // a column's width ?
911         else if (evt.PropertyName.equals(PROPERTY_WIDTH))
912         {   // a column width has changed -> update the model
913             // (the update of the view is done elsewhere)
914             Reference<XPropertySet> xProp = getColumnHelper(m_pCurrentlyDisplayed,xSource);
915             if(xProp.is())
916             {
917                 if(!evt.NewValue.hasValue())
918                     xProp->setPropertyValue(PROPERTY_WIDTH,makeAny((sal_Int32)227));
919                 else
920                     xProp->setPropertyValue(PROPERTY_WIDTH,evt.NewValue);
921             }
922         }
923 
924         // a column's 'visible' state ?
925         else if (evt.PropertyName.equals(PROPERTY_HIDDEN))
926         {
927             Reference<XPropertySet> xProp = getColumnHelper(m_pCurrentlyDisplayed,xSource);
928             if(xProp.is())
929                 xProp->setPropertyValue(PROPERTY_HIDDEN,evt.NewValue);
930         }
931 
932         // a columns alignment ?
933         else if (evt.PropertyName.equals(PROPERTY_ALIGN))
934         {
935             Reference<XPropertySet> xProp = getColumnHelper(m_pCurrentlyDisplayed,xSource);
936             try
937             {
938                 if(xProp.is())
939                 {
940                     if(evt.NewValue.hasValue())
941                     {
942                         sal_Int16 nAlign = 0;
943                         if(evt.NewValue >>= nAlign)
944                             xProp->setPropertyValue(PROPERTY_ALIGN,makeAny(sal_Int32(nAlign)));
945                         else
946                             xProp->setPropertyValue(PROPERTY_ALIGN,evt.NewValue);
947                     }
948                     else
949                         xProp->setPropertyValue(PROPERTY_ALIGN,makeAny(::com::sun::star::awt::TextAlign::LEFT));
950                 }
951             }
952             catch( const Exception& )
953             {
954                 DBG_UNHANDLED_EXCEPTION();
955             }
956         }
957 
958         // a column's format ?
959         else if (   (evt.PropertyName.equals(PROPERTY_FORMATKEY))
960             &&  (TypeClass_LONG == evt.NewValue.getValueTypeClass())
961             )
962         {
963             // update the model (means the definition object)
964             Reference<XPropertySet> xProp = getColumnHelper(m_pCurrentlyDisplayed,xSource);
965             if(xProp.is())
966                 xProp->setPropertyValue(PROPERTY_FORMATKEY,evt.NewValue);
967         }
968 
969         // some table definition properties ?
970         // the height of the rows in the grid ?
971         else if (evt.PropertyName.equals(PROPERTY_ROW_HEIGHT))
972         {
973             if(m_pCurrentlyDisplayed)
974             {
975                 DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(m_pCurrentlyDisplayed->GetUserData());
976                 OSL_ENSURE( pData->xObjectProperties.is(), "No table available!" );
977 
978                 sal_Bool bDefault = !evt.NewValue.hasValue();
979                 if (bDefault)
980                     pData->xObjectProperties->setPropertyValue(PROPERTY_ROW_HEIGHT,makeAny((sal_Int32)45));
981                 else
982                     pData->xObjectProperties->setPropertyValue(PROPERTY_ROW_HEIGHT,evt.NewValue);
983             }
984         }
985 
986         else if (   evt.PropertyName.equals(PROPERTY_FONT)          // the font ?
987                 ||  evt.PropertyName.equals(PROPERTY_TEXTCOLOR)     // the text color ?
988                 ||  evt.PropertyName.equals(PROPERTY_FILTER)        // the filter ?
989                 ||  evt.PropertyName.equals(PROPERTY_HAVING_CLAUSE) // the having clause ?
990                 ||  evt.PropertyName.equals(PROPERTY_ORDER)         // the sort ?
991                 ||  evt.PropertyName.equals(PROPERTY_APPLYFILTER)   // the appliance of the filter ?
992                 ||  evt.PropertyName.equals(PROPERTY_TEXTLINECOLOR) // the text line color ?
993                 ||  evt.PropertyName.equals(PROPERTY_TEXTEMPHASIS)  // the text emphasis ?
994                 ||  evt.PropertyName.equals(PROPERTY_TEXTRELIEF)    // the text relief ?
995                 )
996         {
997             transferChangedControlProperty(evt.PropertyName, evt.NewValue);
998         }
999     }
1000     catch( const Exception& )
1001     {
1002         DBG_UNHANDLED_EXCEPTION();
1003     }
1004 }
1005 
1006 // -----------------------------------------------------------------------
suspend(sal_Bool bSuspend)1007 sal_Bool SbaTableQueryBrowser::suspend(sal_Bool bSuspend)
1008 {
1009     vos::OGuard aSolarGuard( Application::GetSolarMutex() );
1010     ::osl::MutexGuard aGuard( getMutex() );
1011     if ( getView() && getView()->IsInModalMode() )
1012         return sal_False;
1013     sal_Bool bRet = sal_False;
1014     if ( !m_bInSuspend )
1015     {
1016         m_bInSuspend = sal_True;
1017         if ( rBHelper.bDisposed )
1018             throw DisposedException( ::rtl::OUString(), *this );
1019 
1020         bRet = SbaXDataBrowserController::suspend(bSuspend);
1021         if ( bRet && getView() )
1022             getView()->Hide();
1023 
1024         m_bInSuspend = sal_False;
1025     }
1026 
1027     return bRet;
1028 }
1029 
1030 // -------------------------------------------------------------------------
statusChanged(const FeatureStateEvent & _rEvent)1031 void SAL_CALL SbaTableQueryBrowser::statusChanged( const FeatureStateEvent& _rEvent )
1032 {
1033     // search the external dispatcher causing this call
1034     Reference< XDispatch > xSource(_rEvent.Source, UNO_QUERY);
1035     ExternalFeaturesMap::iterator aLoop;
1036     for ( aLoop = m_aExternalFeatures.begin();
1037           aLoop != m_aExternalFeatures.end();
1038           ++aLoop
1039         )
1040     {
1041         if ( _rEvent.FeatureURL.Complete == aLoop->second.aURL.Complete)
1042         {
1043             DBG_ASSERT( xSource.get() == aLoop->second.xDispatcher.get(), "SbaTableQueryBrowser::statusChanged: inconsistent!" );
1044             // update the enabled state
1045             aLoop->second.bEnabled = _rEvent.IsEnabled;
1046 
1047             switch ( aLoop->first )
1048             {
1049                 case ID_BROWSER_DOCUMENT_DATASOURCE:
1050                 {
1051                     // if it's the slot for the document data source, remember the state
1052                     Sequence< PropertyValue > aDescriptor;
1053     #if OSL_DEBUG_LEVEL > 0
1054                     sal_Bool bProperFormat =
1055     #endif
1056                     _rEvent.State >>= aDescriptor;
1057                     OSL_ENSURE(bProperFormat, "SbaTableQueryBrowser::statusChanged: need a data access descriptor here!");
1058                     m_aDocumentDataSource.initializeFrom(aDescriptor);
1059 
1060                     OSL_ENSURE( (   m_aDocumentDataSource.has(daDataSource)
1061                                 ||  m_aDocumentDataSource.has(daDatabaseLocation)
1062                                 )
1063                                 &&  m_aDocumentDataSource.has(daCommand)
1064                                 &&  m_aDocumentDataSource.has(daCommandType),
1065                         "SbaTableQueryBrowser::statusChanged: incomplete descriptor!");
1066 
1067                     // check if we know the object which is set as document data source
1068                     checkDocumentDataSource();
1069                 }
1070                 break;
1071 
1072                 default:
1073                     // update the toolbox
1074                     implCheckExternalSlot( aLoop->first );
1075                     break;
1076             }
1077             break;
1078         }
1079     }
1080 
1081     DBG_ASSERT(aLoop != m_aExternalFeatures.end(), "SbaTableQueryBrowser::statusChanged: don't know who sent this!");
1082 }
1083 
1084 // -------------------------------------------------------------------------
checkDocumentDataSource()1085 void SbaTableQueryBrowser::checkDocumentDataSource()
1086 {
1087     SvLBoxEntry* pDataSourceEntry = NULL;
1088     SvLBoxEntry* pContainerEntry = NULL;
1089     SvLBoxEntry* pObjectEntry = getObjectEntry( m_aDocumentDataSource, &pDataSourceEntry, &pContainerEntry, sal_False );
1090     sal_Bool bKnownDocDataSource = (NULL != pObjectEntry);
1091     if (!bKnownDocDataSource)
1092     {
1093         if (NULL != pDataSourceEntry)
1094         {   // at least the data source is know
1095             if (NULL != pContainerEntry)
1096                 bKnownDocDataSource = sal_True; // assume we know it.
1097                 // TODO: should we expand the object container? This may be too expensive just for checking ....
1098             else
1099             {
1100                 if ((NULL == pObjectEntry) && m_aDocumentDataSource.has(daCommandType) && m_aDocumentDataSource.has(daCommand))
1101                 {   // maybe we have a command to be displayed ?
1102                     sal_Int32 nCommandType = CommandType::TABLE;
1103                     m_aDocumentDataSource[daCommandType] >>= nCommandType;
1104 
1105                     ::rtl::OUString sCommand;
1106                     m_aDocumentDataSource[daCommand] >>= sCommand;
1107 
1108                     bKnownDocDataSource = (CommandType::COMMAND == nCommandType) && (0 != sCommand.getLength());
1109                 }
1110             }
1111         }
1112     }
1113 
1114     if ( !bKnownDocDataSource )
1115         m_aExternalFeatures[ ID_BROWSER_DOCUMENT_DATASOURCE ].bEnabled = sal_False;
1116 
1117     // update the toolbox
1118     implCheckExternalSlot(ID_BROWSER_DOCUMENT_DATASOURCE);
1119 }
1120 
1121 // -------------------------------------------------------------------------
extractDescriptorProps(const::svx::ODataAccessDescriptor & _rDescriptor,::rtl::OUString & _rDataSource,::rtl::OUString & _rCommand,sal_Int32 & _rCommandType,sal_Bool & _rEscapeProcessing)1122 void SbaTableQueryBrowser::extractDescriptorProps(const ::svx::ODataAccessDescriptor& _rDescriptor, ::rtl::OUString& _rDataSource, ::rtl::OUString& _rCommand, sal_Int32& _rCommandType, sal_Bool& _rEscapeProcessing)
1123 {
1124     _rDataSource = _rDescriptor.getDataSource();
1125     if ( _rDescriptor.has(daCommand) )
1126         _rDescriptor[daCommand] >>= _rCommand;
1127     if ( _rDescriptor.has(daCommandType) )
1128         _rDescriptor[daCommandType] >>= _rCommandType;
1129 
1130     // escape processing is the only one allowed not to be present
1131     _rEscapeProcessing = sal_True;
1132     if (_rDescriptor.has(daEscapeProcessing))
1133         _rEscapeProcessing = ::cppu::any2bool(_rDescriptor[daEscapeProcessing]);
1134 }
1135 
1136 // -------------------------------------------------------------------------
1137 namespace
1138 {
getDataSourceDisplayName_isURL(const String & _rDS,String & _rDisplayName,String & _rUniqueId)1139     bool getDataSourceDisplayName_isURL( const String& _rDS, String& _rDisplayName, String& _rUniqueId )
1140     {
1141         INetURLObject aURL( _rDS );
1142         if ( aURL.GetProtocol() != INET_PROT_NOT_VALID )
1143         {
1144             _rDisplayName = aURL.getBase(INetURLObject::LAST_SEGMENT,true,INetURLObject::DECODE_WITH_CHARSET);
1145             //  _rDisplayName = aURL.getName(INetURLObject::LAST_SEGMENT,true,INetURLObject::DECODE_WITH_CHARSET);
1146             _rUniqueId = aURL.GetMainURL( INetURLObject::NO_DECODE );
1147             return true;
1148         }
1149         _rDisplayName = _rDS;
1150         _rUniqueId = String();
1151         return false;
1152     }
1153 
1154     // .....................................................................
1155     struct FilterByEntryDataId : public IEntryFilter
1156     {
1157         String sId;
FilterByEntryDataIddbaui::__anon2d6ac27d0211::FilterByEntryDataId1158         FilterByEntryDataId( const String& _rId ) : sId( _rId ) { }
1159 
~FilterByEntryDataIddbaui::__anon2d6ac27d0211::FilterByEntryDataId1160         virtual ~FilterByEntryDataId() {}
1161 
1162         virtual bool    includeEntry( SvLBoxEntry* _pEntry ) const;
1163     };
1164 
includeEntry(SvLBoxEntry * _pEntry) const1165     bool FilterByEntryDataId::includeEntry( SvLBoxEntry* _pEntry ) const
1166     {
1167         DBTreeListUserData* pData = static_cast< DBTreeListUserData* >( _pEntry->GetUserData() );
1168         return ( !pData || ( pData->sAccessor == sId ) );
1169     }
1170 }
1171 
1172 // -------------------------------------------------------------------------
getDataSourceAcessor(SvLBoxEntry * _pDataSourceEntry) const1173 String SbaTableQueryBrowser::getDataSourceAcessor( SvLBoxEntry* _pDataSourceEntry ) const
1174 {
1175     DBG_ASSERT( _pDataSourceEntry, "SbaTableQueryBrowser::getDataSourceAcessor: invalid entry!" );
1176 
1177     DBTreeListUserData* pData = static_cast< DBTreeListUserData* >( _pDataSourceEntry->GetUserData() );
1178     DBG_ASSERT( pData, "SbaTableQueryBrowser::getDataSourceAcessor: invalid entry data!" );
1179     DBG_ASSERT( pData->eType == etDatasource, "SbaTableQueryBrowser::getDataSourceAcessor: entry does not denote a data source!" );
1180     return pData->sAccessor.Len() ? pData->sAccessor : GetEntryText( _pDataSourceEntry );
1181 }
1182 
1183 // -------------------------------------------------------------------------
getObjectEntry(const::rtl::OUString & _rDataSource,const::rtl::OUString & _rCommand,sal_Int32 _nCommandType,SvLBoxEntry ** _ppDataSourceEntry,SvLBoxEntry ** _ppContainerEntry,sal_Bool _bExpandAncestors,const SharedConnection & _rxConnection)1184 SvLBoxEntry* SbaTableQueryBrowser::getObjectEntry(const ::rtl::OUString& _rDataSource, const ::rtl::OUString& _rCommand, sal_Int32 _nCommandType,
1185         SvLBoxEntry** _ppDataSourceEntry, SvLBoxEntry** _ppContainerEntry, sal_Bool _bExpandAncestors,
1186         const SharedConnection& _rxConnection )
1187 {
1188     if (_ppDataSourceEntry)
1189         *_ppDataSourceEntry = NULL;
1190     if (_ppContainerEntry)
1191         *_ppContainerEntry = NULL;
1192 
1193     SvLBoxEntry* pObject = NULL;
1194     if ( m_pTreeView )
1195     {
1196         // look for the data source entry
1197         String sDisplayName, sDataSourceId;
1198         bool bIsDataSourceURL = getDataSourceDisplayName_isURL( _rDataSource, sDisplayName, sDataSourceId );
1199             // the display name may differ from the URL for readability reasons
1200             // #i33699# - 2004-09-24 - fs@openoffice.org
1201 
1202         FilterByEntryDataId aFilter( sDataSourceId );
1203         SvLBoxEntry* pDataSource = m_pTreeView->getListBox().GetEntryPosByName( sDisplayName, NULL, &aFilter );
1204         if ( !pDataSource ) // check if the data source name is a file location
1205         {
1206             if ( bIsDataSourceURL )
1207             {
1208                 // special case, the data source is a URL
1209                 // add new entries to the list box model
1210                 implAddDatasource( _rDataSource, _rxConnection );
1211                 pDataSource = m_pTreeView->getListBox().GetEntryPosByName( sDisplayName, NULL, &aFilter );
1212                 DBG_ASSERT( pDataSource, "SbaTableQueryBrowser::getObjectEntry: hmm - did not find it again!" );
1213             }
1214         }
1215         if (_ppDataSourceEntry)
1216             // (caller wants to have it ...)
1217             *_ppDataSourceEntry = pDataSource;
1218 
1219         if (pDataSource)
1220         {
1221             // expand if required so
1222             if (_bExpandAncestors)
1223                 m_pTreeView->getListBox().Expand(pDataSource);
1224 
1225             // look for the object container
1226             SvLBoxEntry* pCommandType = NULL;
1227             switch (_nCommandType)
1228             {
1229                 case CommandType::TABLE:
1230                     pCommandType = m_pTreeView->getListBox().GetModel()->GetEntry(pDataSource, CONTAINER_TABLES);
1231                     break;
1232 
1233                 case CommandType::QUERY:
1234                     pCommandType = m_pTreeView->getListBox().GetModel()->GetEntry(pDataSource, CONTAINER_QUERIES);
1235                     break;
1236             }
1237 
1238             if (_ppContainerEntry)
1239                 *_ppContainerEntry = pCommandType;
1240 
1241             if (pCommandType)
1242             {
1243                 // expand if required so
1244                 if (_bExpandAncestors)
1245                 {
1246                     m_pTreeView->getListBox().Expand(pCommandType);
1247                 }
1248 
1249                 // look for the object
1250                 ::rtl::OUString sCommand = _rCommand;
1251                 sal_Int32 nIndex = 0;
1252                 do
1253                 {
1254                     ::rtl::OUString sPath = sCommand.getToken( 0, '/', nIndex );
1255                     pObject = m_pTreeView->getListBox().GetEntryPosByName(sPath, pCommandType);
1256                     pCommandType = pObject;
1257                     if ( nIndex >= 0 )
1258                     {
1259                         if (ensureEntryObject(pObject))
1260                         {
1261                             DBTreeListUserData* pParentData = static_cast< DBTreeListUserData* >( pObject->GetUserData() );
1262                             Reference< XNameAccess > xCollection( pParentData->xContainer, UNO_QUERY );
1263                             sal_Int32 nIndex2 = nIndex;
1264                             sPath = sCommand.getToken( 0, '/', nIndex2 );
1265                             try
1266                             {
1267                                 if ( xCollection->hasByName(sPath) )
1268                                 {
1269                                     if(!m_pTreeView->getListBox().GetEntryPosByName(sPath,pObject))
1270                                     {
1271                                         Reference<XNameAccess> xChild(xCollection->getByName(sPath),UNO_QUERY);
1272                                         DBTreeListUserData* pEntryData = new DBTreeListUserData;
1273                                         pEntryData->eType = etQuery;
1274                                         if ( xChild.is() )
1275                                         {
1276                                             pEntryData->eType = etQueryContainer;
1277                                         }
1278                                         implAppendEntry( pObject, sPath, pEntryData, pEntryData->eType );
1279                                     }
1280                                 }
1281                             }
1282                             catch(Exception&)
1283                             {
1284                                 DBG_ERROR("SbaTableQueryBrowser::populateTree: could not fill the tree");
1285                             }
1286                         }
1287                     }
1288                      //   m_pTreeView->getListBox().Expand(pCommandType);
1289                 }
1290                 while ( nIndex >= 0 );
1291             }
1292         }
1293     }
1294     return pObject;
1295 }
1296 
1297 // -------------------------------------------------------------------------
getObjectEntry(const::svx::ODataAccessDescriptor & _rDescriptor,SvLBoxEntry ** _ppDataSourceEntry,SvLBoxEntry ** _ppContainerEntry,sal_Bool _bExpandAncestors)1298 SvLBoxEntry* SbaTableQueryBrowser::getObjectEntry(const ::svx::ODataAccessDescriptor& _rDescriptor,
1299         SvLBoxEntry** _ppDataSourceEntry, SvLBoxEntry** _ppContainerEntry,
1300         sal_Bool _bExpandAncestors)
1301 {
1302     // extract the props from the descriptor
1303     ::rtl::OUString sDataSource;
1304     ::rtl::OUString sCommand;
1305     sal_Int32 nCommandType = CommandType::COMMAND;
1306     sal_Bool bEscapeProcessing = sal_True;
1307     extractDescriptorProps(_rDescriptor, sDataSource, sCommand, nCommandType, bEscapeProcessing);
1308 
1309     return getObjectEntry( sDataSource, sCommand, nCommandType, _ppDataSourceEntry, _ppContainerEntry, _bExpandAncestors, SharedConnection() );
1310 }
1311 
1312 // -------------------------------------------------------------------------
connectExternalDispatches()1313 void SbaTableQueryBrowser::connectExternalDispatches()
1314 {
1315     Reference< XDispatchProvider >  xProvider( getFrame(), UNO_QUERY );
1316     DBG_ASSERT(xProvider.is(), "SbaTableQueryBrowser::connectExternalDispatches: no DispatchProvider !");
1317     if (xProvider.is())
1318     {
1319         if ( m_aExternalFeatures.empty() )
1320         {
1321             const sal_Char* pURLs[] = {
1322                 ".uno:DataSourceBrowser/DocumentDataSource",
1323                 ".uno:DataSourceBrowser/FormLetter",
1324                 ".uno:DataSourceBrowser/InsertColumns",
1325                 ".uno:DataSourceBrowser/InsertContent",
1326             };
1327             const sal_uInt16 nIds[] = {
1328                 ID_BROWSER_DOCUMENT_DATASOURCE,
1329                 ID_BROWSER_FORMLETTER,
1330                 ID_BROWSER_INSERTCOLUMNS,
1331                 ID_BROWSER_INSERTCONTENT
1332             };
1333 
1334             for ( size_t i=0; i < sizeof( pURLs ) / sizeof( pURLs[0] ); ++i )
1335             {
1336                 URL aURL;
1337                 aURL.Complete = ::rtl::OUString::createFromAscii( pURLs[i] );
1338                 if ( m_xUrlTransformer.is() )
1339                     m_xUrlTransformer->parseStrict( aURL );
1340                 m_aExternalFeatures[ nIds[ i ] ] = ExternalFeature( aURL );
1341             }
1342         }
1343 
1344         for ( ExternalFeaturesMap::iterator feature = m_aExternalFeatures.begin();
1345               feature != m_aExternalFeatures.end();
1346               ++feature
1347             )
1348         {
1349             feature->second.xDispatcher = xProvider->queryDispatch(
1350                 feature->second.aURL, ::rtl::OUString::createFromAscii("_parent"), FrameSearchFlag::PARENT
1351             );
1352 
1353             if ( feature->second.xDispatcher.get() == static_cast< XDispatch* >( this ) )
1354             {
1355                 OSL_ENSURE( sal_False, "SbaTableQueryBrowser::connectExternalDispatches: this should not happen anymore!" );
1356                     // (nowadays, the URLs aren't in our SupportedFeatures list anymore, so we should
1357                     // not supply a dispatcher for this)
1358                 feature->second.xDispatcher.clear();
1359             }
1360 
1361             if ( feature->second.xDispatcher.is() )
1362             {
1363                 try
1364                 {
1365                     feature->second.xDispatcher->addStatusListener( this, feature->second.aURL );
1366                 }
1367                 catch( const Exception& )
1368                 {
1369                     DBG_UNHANDLED_EXCEPTION();
1370                 }
1371             }
1372 
1373             implCheckExternalSlot( feature->first );
1374         }
1375     }
1376 }
1377 
1378 // -------------------------------------------------------------------------
implCheckExternalSlot(sal_uInt16 _nId)1379 void SbaTableQueryBrowser::implCheckExternalSlot( sal_uInt16 _nId )
1380 {
1381     if ( !m_xMainToolbar.is() )
1382         return;
1383 
1384     Window* pToolboxWindow = VCLUnoHelper::GetWindow( m_xMainToolbar );
1385     ToolBox* pToolbox = dynamic_cast< ToolBox* >( pToolboxWindow );
1386     OSL_ENSURE( pToolbox, "SbaTableQueryBrowser::implCheckExternalSlot: cannot obtain the toolbox window!" );
1387 
1388     // check if we have to hide this item from the toolbox
1389     if ( pToolbox )
1390     {
1391         sal_Bool bHaveDispatcher = m_aExternalFeatures[ _nId ].xDispatcher.is();
1392         if ( bHaveDispatcher != pToolbox->IsItemVisible( _nId ) )
1393             bHaveDispatcher ? pToolbox->ShowItem( _nId ) : pToolbox->HideItem( _nId );
1394     }
1395 
1396     // and invalidate this feature in general
1397     InvalidateFeature( _nId );
1398 }
1399 
1400 // -------------------------------------------------------------------------
disposing(const::com::sun::star::lang::EventObject & _rSource)1401 void SAL_CALL SbaTableQueryBrowser::disposing( const ::com::sun::star::lang::EventObject& _rSource )
1402 {
1403     // our frame ?
1404     Reference< ::com::sun::star::frame::XFrame >  xSourceFrame(_rSource.Source, UNO_QUERY);
1405     if (m_xCurrentFrameParent.is() && (xSourceFrame == m_xCurrentFrameParent))
1406         m_xCurrentFrameParent->removeFrameActionListener((::com::sun::star::frame::XFrameActionListener*)this);
1407     else
1408     {
1409         // search the external dispatcher causing this call in our map
1410         Reference< XDispatch > xSource(_rSource.Source, UNO_QUERY);
1411         if(xSource.is())
1412         {
1413             for (  ExternalFeaturesMap::iterator aLoop = m_aExternalFeatures.begin();
1414                   aLoop != m_aExternalFeatures.end();
1415                 )
1416             {
1417                 if ( aLoop->second.xDispatcher.get() != xSource.get() ) {
1418                     ++aLoop;
1419                     continue;
1420                 }
1421 
1422                 // prepare to erase the aLoop iterator
1423                 const sal_uInt16 nSlotId = aLoop->first;
1424                 ExternalFeaturesMap::iterator aNext = aLoop;
1425                 ++aNext;
1426 
1427                 // remove it
1428                 m_aExternalFeatures.erase( aLoop );
1429 
1430                 // maybe update the UI
1431                 implCheckExternalSlot( nSlotId );
1432 
1433                 // continue, the same XDispatch may be responsible for more than one URL
1434                 aLoop = aNext;
1435             }
1436         }
1437         else
1438         {
1439             Reference<XConnection> xCon(_rSource.Source, UNO_QUERY);
1440             if ( xCon.is() && m_pTreeView )
1441             {   // our connection is in dispose so we have to find the entry equal with this connection
1442                 // and close it what means to collapse the entry
1443                 // get the top-level representing the removed data source
1444                 SvLBoxEntry* pDSLoop = m_pTreeView->getListBox().FirstChild(NULL);
1445                 while (pDSLoop)
1446                 {
1447                     DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(pDSLoop->GetUserData());
1448                     if ( pData && pData->xConnection == xCon )
1449                     {
1450                         // we set the connection to null to avoid a second disposing of the connection
1451                         pData->xConnection.clear();
1452                         closeConnection(pDSLoop,sal_False);
1453                         break;
1454                     }
1455 
1456                     pDSLoop = m_pTreeView->getListBox().NextSibling(pDSLoop);
1457                 }
1458             }
1459             else
1460                 SbaXDataBrowserController::disposing(_rSource);
1461         }
1462     }
1463 }
1464 
1465 // -------------------------------------------------------------------------
implRemoveStatusListeners()1466 void SbaTableQueryBrowser::implRemoveStatusListeners()
1467 {
1468     // clear all old dispatches
1469     for ( ExternalFeaturesMap::const_iterator aLoop = m_aExternalFeatures.begin();
1470           aLoop != m_aExternalFeatures.end();
1471           ++aLoop
1472         )
1473     {
1474         if ( aLoop->second.xDispatcher.is() )
1475         {
1476             try
1477             {
1478                 aLoop->second.xDispatcher->removeStatusListener( this, aLoop->second.aURL );
1479             }
1480             catch (Exception&)
1481             {
1482                 DBG_ERROR("SbaTableQueryBrowser::implRemoveStatusListeners: could not remove a status listener!");
1483             }
1484         }
1485     }
1486     m_aExternalFeatures.clear();
1487 }
1488 
1489 // -------------------------------------------------------------------------
select(const Any & _rSelection)1490 sal_Bool SAL_CALL SbaTableQueryBrowser::select( const Any& _rSelection )
1491 {
1492     ::vos::OGuard aGuard(Application::GetSolarMutex());
1493         // doing a lot of VCL stuff here -> lock the SolarMutex
1494 
1495     Sequence< PropertyValue > aDescriptorSequence;
1496     if (!(_rSelection >>= aDescriptorSequence))
1497         throw IllegalArgumentException(::rtl::OUString(), *this, 1);
1498         // TODO: error message
1499 
1500     ODataAccessDescriptor aDescriptor;
1501     try
1502     {
1503         aDescriptor = ODataAccessDescriptor(aDescriptorSequence);
1504     }
1505     catch(const Exception&)
1506     {
1507         OSL_ENSURE(sal_False, "SbaTableQueryBrowser::select: could not extract the descriptor!");
1508     }
1509 
1510     // check the presence of the props we need
1511     if ( !(aDescriptor.has(daDataSource) || aDescriptor.has(daDatabaseLocation)) || !aDescriptor.has(daCommand) || !aDescriptor.has(daCommandType))
1512         throw IllegalArgumentException(::rtl::OUString(), *this, 1);
1513         // TODO: error message
1514 
1515     return implSelect(aDescriptor,sal_True);
1516 }
1517 
1518 // -------------------------------------------------------------------------
getSelection()1519 Any SAL_CALL SbaTableQueryBrowser::getSelection(  )
1520 {
1521     Any aReturn;
1522 
1523     try
1524     {
1525         Reference< XLoadable > xLoadable(getRowSet(), UNO_QUERY);
1526         if (xLoadable.is() && xLoadable->isLoaded())
1527         {
1528             Reference< XPropertySet > aFormProps(getRowSet(), UNO_QUERY);
1529             ODataAccessDescriptor aDescriptor(aFormProps);
1530             // remove properties which are not part of our "selection"
1531             aDescriptor.erase(daConnection);
1532             aDescriptor.erase(daCursor);
1533 
1534             aReturn <<= aDescriptor.createPropertyValueSequence();
1535         }
1536     }
1537     catch( const Exception& )
1538     {
1539         DBG_UNHANDLED_EXCEPTION();
1540     }
1541 
1542     return aReturn;
1543 }
1544 
1545 // -------------------------------------------------------------------------
addSelectionChangeListener(const Reference<XSelectionChangeListener> & _rxListener)1546 void SAL_CALL SbaTableQueryBrowser::addSelectionChangeListener( const Reference< XSelectionChangeListener >& _rxListener )
1547 {
1548     m_aSelectionListeners.addInterface(_rxListener);
1549 }
1550 
1551 // -------------------------------------------------------------------------
removeSelectionChangeListener(const Reference<XSelectionChangeListener> & _rxListener)1552 void SAL_CALL SbaTableQueryBrowser::removeSelectionChangeListener( const Reference< XSelectionChangeListener >& _rxListener )
1553 {
1554     m_aSelectionListeners.removeInterface(_rxListener);
1555 }
1556 
1557 // -------------------------------------------------------------------------
attachFrame(const Reference<::com::sun::star::frame::XFrame> & _xFrame)1558 void SbaTableQueryBrowser::attachFrame(const Reference< ::com::sun::star::frame::XFrame > & _xFrame)
1559 {
1560     implRemoveStatusListeners();
1561 
1562     if (m_xCurrentFrameParent.is())
1563         m_xCurrentFrameParent->removeFrameActionListener((::com::sun::star::frame::XFrameActionListener*)this);
1564 
1565     SbaXDataBrowserController::attachFrame(_xFrame);
1566 
1567     Reference< XFrame > xCurrentFrame( getFrame() );
1568     if ( xCurrentFrame.is() )
1569     {
1570         m_xCurrentFrameParent = xCurrentFrame->findFrame(::rtl::OUString::createFromAscii("_parent"),FrameSearchFlag::PARENT);
1571         if ( m_xCurrentFrameParent.is() )
1572             m_xCurrentFrameParent->addFrameActionListener((::com::sun::star::frame::XFrameActionListener*)this);
1573 
1574         // obtain our toolbox
1575         try
1576         {
1577             Reference< XPropertySet > xFrameProps( m_aCurrentFrame.getFrame(), UNO_QUERY_THROW );
1578             Reference< XLayoutManager > xLayouter(
1579                 xFrameProps->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "LayoutManager" ) ) ),
1580                 UNO_QUERY );
1581 
1582             if ( xLayouter.is() )
1583             {
1584                 Reference< XUIElement > xUI(
1585                     xLayouter->getElement( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/toolbar" ) ) ),
1586                     UNO_SET_THROW );
1587                 m_xMainToolbar = m_xMainToolbar.query( xUI->getRealInterface() );
1588                 OSL_ENSURE( m_xMainToolbar.is(), "SbaTableQueryBrowser::attachFrame: where's my toolbox?" );
1589             }
1590         }
1591         catch( const Exception& )
1592         {
1593             DBG_UNHANDLED_EXCEPTION();
1594         }
1595     }
1596 
1597     // get the dispatchers for the external slots
1598     connectExternalDispatches();
1599 }
1600 
1601 // -------------------------------------------------------------------------
addModelListeners(const Reference<::com::sun::star::awt::XControlModel> & _xGridControlModel)1602 void SbaTableQueryBrowser::addModelListeners(const Reference< ::com::sun::star::awt::XControlModel > & _xGridControlModel)
1603 {
1604     SbaXDataBrowserController::addModelListeners(_xGridControlModel);
1605     Reference< XPropertySet >  xSourceSet(_xGridControlModel, UNO_QUERY);
1606     if (xSourceSet.is())
1607     {
1608         xSourceSet->addPropertyChangeListener(PROPERTY_ROW_HEIGHT, static_cast<XPropertyChangeListener*>(this));
1609         xSourceSet->addPropertyChangeListener(PROPERTY_FONT, static_cast<XPropertyChangeListener*>(this));
1610         xSourceSet->addPropertyChangeListener(PROPERTY_TEXTCOLOR, static_cast<XPropertyChangeListener*>(this));
1611         xSourceSet->addPropertyChangeListener(PROPERTY_TEXTLINECOLOR, static_cast<XPropertyChangeListener*>(this));
1612         xSourceSet->addPropertyChangeListener(PROPERTY_TEXTEMPHASIS, static_cast<XPropertyChangeListener*>(this));
1613         xSourceSet->addPropertyChangeListener(PROPERTY_TEXTRELIEF, static_cast<XPropertyChangeListener*>(this));
1614     }
1615 
1616 }
1617 
1618 // -------------------------------------------------------------------------
removeModelListeners(const Reference<::com::sun::star::awt::XControlModel> & _xGridControlModel)1619 void SbaTableQueryBrowser::removeModelListeners(const Reference< ::com::sun::star::awt::XControlModel > & _xGridControlModel)
1620 {
1621     SbaXDataBrowserController::removeModelListeners(_xGridControlModel);
1622     Reference< XPropertySet >  xSourceSet(_xGridControlModel, UNO_QUERY);
1623     if (xSourceSet.is())
1624     {
1625         xSourceSet->removePropertyChangeListener(PROPERTY_ROW_HEIGHT, static_cast<XPropertyChangeListener*>(this));
1626         xSourceSet->removePropertyChangeListener(PROPERTY_FONT, static_cast<XPropertyChangeListener*>(this));
1627         xSourceSet->removePropertyChangeListener(PROPERTY_TEXTCOLOR, static_cast<XPropertyChangeListener*>(this));
1628         xSourceSet->removePropertyChangeListener(PROPERTY_TEXTLINECOLOR, static_cast<XPropertyChangeListener*>(this));
1629         xSourceSet->removePropertyChangeListener(PROPERTY_TEXTEMPHASIS, static_cast<XPropertyChangeListener*>(this));
1630         xSourceSet->removePropertyChangeListener(PROPERTY_TEXTRELIEF, static_cast<XPropertyChangeListener*>(this));
1631     }
1632 }
1633 // -------------------------------------------------------------------------
RowChanged()1634 void SbaTableQueryBrowser::RowChanged()
1635 {
1636     if(getBrowserView())
1637     {
1638         SbaGridControl* pControl = getBrowserView()->getVclControl();
1639         if (!pControl->IsEditing())
1640             InvalidateFeature(ID_BROWSER_COPY);
1641     }
1642     SbaXDataBrowserController::RowChanged();
1643 }
1644 
1645 // -------------------------------------------------------------------------
ColumnChanged()1646 void SbaTableQueryBrowser::ColumnChanged()
1647 {
1648     if(getBrowserView())
1649     {
1650         SbaGridControl* pControl = getBrowserView()->getVclControl();
1651         if (!pControl->IsEditing())
1652             InvalidateFeature(ID_BROWSER_COPY);
1653     }
1654     SbaXDataBrowserController::ColumnChanged();
1655 }
1656 //------------------------------------------------------------------------------
AddColumnListener(const Reference<XPropertySet> & xCol)1657 void SbaTableQueryBrowser::AddColumnListener(const Reference< XPropertySet > & xCol)
1658 {
1659     SbaXDataBrowserController::AddColumnListener(xCol);
1660     SafeAddPropertyListener(xCol, PROPERTY_WIDTH, static_cast<XPropertyChangeListener*>(this));
1661     SafeAddPropertyListener(xCol, PROPERTY_HIDDEN, static_cast<XPropertyChangeListener*>(this));
1662     SafeAddPropertyListener(xCol, PROPERTY_ALIGN, static_cast<XPropertyChangeListener*>(this));
1663     SafeAddPropertyListener(xCol, PROPERTY_FORMATKEY, static_cast<XPropertyChangeListener*>(this));
1664 }
1665 
1666 //------------------------------------------------------------------------------
RemoveColumnListener(const Reference<XPropertySet> & xCol)1667 void SbaTableQueryBrowser::RemoveColumnListener(const Reference< XPropertySet > & xCol)
1668 {
1669     SbaXDataBrowserController::RemoveColumnListener(xCol);
1670     SafeRemovePropertyListener(xCol, PROPERTY_WIDTH, static_cast<XPropertyChangeListener*>(this));
1671     SafeRemovePropertyListener(xCol, PROPERTY_HIDDEN, static_cast<XPropertyChangeListener*>(this));
1672     SafeRemovePropertyListener(xCol, PROPERTY_ALIGN, static_cast<XPropertyChangeListener*>(this));
1673     SafeRemovePropertyListener(xCol, PROPERTY_FORMATKEY, static_cast<XPropertyChangeListener*>(this));
1674 }
1675 
1676 //------------------------------------------------------------------------------
criticalFail()1677 void SbaTableQueryBrowser::criticalFail()
1678 {
1679     SbaXDataBrowserController::criticalFail();
1680     unloadAndCleanup( sal_False );
1681 }
1682 
1683 //------------------------------------------------------------------------------
LoadFinished(sal_Bool _bWasSynch)1684 void SbaTableQueryBrowser::LoadFinished(sal_Bool _bWasSynch)
1685 {
1686     SbaXDataBrowserController::LoadFinished(_bWasSynch);
1687 
1688     m_sQueryCommand = ::rtl::OUString();
1689     m_bQueryEscapeProcessing = sal_False;
1690 
1691     if (isValid() && !loadingCancelled())
1692     {
1693         // did we load a query?
1694         sal_Bool bTemporary;    // needed because we m_bQueryEscapeProcessing is only one bit wide (and we want to pass it by reference)
1695         if ( implGetQuerySignature( m_sQueryCommand, bTemporary ) )
1696             m_bQueryEscapeProcessing = bTemporary;
1697     }
1698 
1699     // if the form has been loaded, this means that our "selection" has changed
1700     ::com::sun::star::lang::EventObject aEvent( *this );
1701     m_aSelectionListeners.notifyEach( &XSelectionChangeListener::selectionChanged, aEvent );
1702 }
1703 
1704 //------------------------------------------------------------------------------
getExternalSlotState(sal_uInt16 _nId) const1705 sal_Bool SbaTableQueryBrowser::getExternalSlotState( sal_uInt16 _nId ) const
1706 {
1707     sal_Bool bEnabled = sal_False;
1708     ExternalFeaturesMap::const_iterator aPos = m_aExternalFeatures.find( _nId );
1709     if ( ( m_aExternalFeatures.end() != aPos ) && aPos->second.xDispatcher.is() )
1710         bEnabled = aPos->second.bEnabled;
1711     return bEnabled;
1712 }
1713 
1714 //------------------------------------------------------------------------------
GetState(sal_uInt16 nId) const1715 FeatureState SbaTableQueryBrowser::GetState(sal_uInt16 nId) const
1716 {
1717     FeatureState aReturn;
1718         // (disabled automatically)
1719 
1720     // no chance without a view
1721     if (!getBrowserView() || !getBrowserView()->getVclControl())
1722         return aReturn;
1723 
1724     switch ( nId )
1725     {
1726         case ID_TREE_ADMINISTRATE:
1727             aReturn.bEnabled = true;
1728             return aReturn;
1729 
1730         case ID_BROWSER_CLOSE:
1731             // the close button should always be enabled
1732             aReturn.bEnabled = !m_bEnableBrowser;
1733             return aReturn;
1734 
1735             // "toggle explorer" is always enabled (if we have a explorer)
1736         case ID_BROWSER_EXPLORER:
1737             aReturn.bEnabled = m_bEnableBrowser;
1738             aReturn.bChecked = haveExplorer();
1739             return aReturn;
1740 
1741         case ID_BROWSER_REMOVEFILTER:
1742             return SbaXDataBrowserController::GetState( nId );
1743 
1744         case ID_BROWSER_COPY:
1745             if ( !m_pTreeView->HasChildPathFocus() )
1746                 // handled below
1747                 break;
1748             // NO break!
1749         case ID_TREE_CLOSE_CONN:
1750         case ID_TREE_EDIT_DATABASE:
1751         {
1752             SvLBoxEntry* pCurrentEntry( m_pTreeView->getListBox().GetCurEntry() );
1753             EntryType eType = getEntryType( pCurrentEntry );
1754             if ( eType == etUnknown )
1755                 return aReturn;
1756 
1757             SvLBoxEntry* pDataSourceEntry = m_pTreeView->getListBox().GetRootLevelParent( pCurrentEntry );
1758             DBTreeListUserData* pDSData
1759                 =   pDataSourceEntry
1760                 ?   static_cast< DBTreeListUserData* >( pDataSourceEntry->GetUserData() )
1761                 :   NULL;
1762 
1763             if ( nId == ID_TREE_CLOSE_CONN )
1764             {
1765                 aReturn.bEnabled = ( pDSData != NULL ) && pDSData->xConnection.is();
1766             }
1767             else if ( nId == ID_TREE_EDIT_DATABASE )
1768             {
1769                 ::utl::OConfigurationTreeRoot aConfig( ::utl::OConfigurationTreeRoot::createWithServiceFactory( getORB(),
1770                     ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/org.openoffice.Office.DataAccess/Policies/Features/Common" ) ) ) );
1771                 sal_Bool bHaveEditDatabase( sal_True );
1772                 OSL_VERIFY( aConfig.getNodeValue( "EditDatabaseFromDataSourceView" ) >>= bHaveEditDatabase );
1773                 aReturn.bEnabled = getORB().is() && ( pDataSourceEntry != NULL ) && bHaveEditDatabase;
1774             }
1775             else if ( nId == ID_BROWSER_COPY )
1776             {
1777                 aReturn.bEnabled = isEntryCopyAllowed( pCurrentEntry );
1778             }
1779 
1780             return aReturn;
1781         }
1782     }
1783 
1784     // all slots not handled above are not available if no form is loaded
1785     if (!isLoaded())
1786         return aReturn;
1787 
1788     try
1789     {
1790         sal_Bool bHandled = sal_False;
1791         switch (nId)
1792         {
1793             case ID_BROWSER_DOCUMENT_DATASOURCE:
1794                 // the slot is enabled if we have an external dispatcher able to handle it,
1795                 // and the dispatcher must have enabled the slot in general
1796                 aReturn.bEnabled = getExternalSlotState( ID_BROWSER_DOCUMENT_DATASOURCE );
1797                 bHandled = sal_True;
1798                 break;
1799             case ID_BROWSER_REFRESH:
1800                 aReturn.bEnabled = sal_True;
1801                 bHandled = sal_True;
1802                 break;
1803         }
1804 
1805         if (bHandled)
1806             return aReturn;
1807 
1808         // no chance without valid models
1809         if (isValid() && !isValidCursor() && nId != ID_BROWSER_CLOSE)
1810             return aReturn;
1811 
1812         switch (nId)
1813         {
1814             case ID_BROWSER_INSERTCOLUMNS:
1815             case ID_BROWSER_INSERTCONTENT:
1816             case ID_BROWSER_FORMLETTER:
1817             {
1818                 // the slot is enabled if we have an external dispatcher able to handle it,
1819                 // and the dispatcher must have enabled the slot in general
1820                 aReturn.bEnabled = getExternalSlotState( nId );
1821 
1822                 // for the Insert* slots, we need at least one selected row
1823                 if (ID_BROWSER_FORMLETTER != nId)
1824                     aReturn.bEnabled = aReturn.bEnabled && getBrowserView()->getVclControl()->GetSelectRowCount();
1825 
1826                 // disabled for native queries which are not saved within the database
1827                 // 67706 - 23.08.99 - FS
1828                 Reference< XPropertySet >  xDataSource(getRowSet(), UNO_QUERY);
1829                 try
1830                 {
1831                     aReturn.bEnabled = aReturn.bEnabled && xDataSource.is();
1832 
1833                     if (xDataSource.is())
1834                     {
1835                         sal_Int32 nType = ::comphelper::getINT32(xDataSource->getPropertyValue(PROPERTY_COMMAND_TYPE));
1836                         aReturn.bEnabled = aReturn.bEnabled && ((::comphelper::getBOOL(xDataSource->getPropertyValue(PROPERTY_ESCAPE_PROCESSING)) || (nType == ::com::sun::star::sdb::CommandType::QUERY)));
1837                     }
1838                 }
1839                 catch(DisposedException&)
1840                 {
1841                     OSL_ENSURE(sal_False, "SbaTableQueryBrowser::GetState: object already disposed!");
1842                 }
1843                 catch( const Exception& )
1844                 {
1845                     DBG_UNHANDLED_EXCEPTION();
1846                 }
1847             }
1848             break;
1849 
1850             case ID_BROWSER_TITLE:
1851                 {
1852                     Reference<XPropertySet> xProp(getRowSet(),UNO_QUERY);
1853                     sal_Int32 nCommandType = CommandType::TABLE;
1854                     xProp->getPropertyValue(PROPERTY_COMMAND_TYPE) >>= nCommandType;
1855                     String sTitle;
1856                     switch (nCommandType)
1857                     {
1858                         case CommandType::TABLE:
1859                             sTitle = String(ModuleRes(STR_TBL_TITLE)); break;
1860                         case CommandType::QUERY:
1861                         case CommandType::COMMAND:
1862                             sTitle = String(ModuleRes(STR_QRY_TITLE)); break;
1863                         default:
1864                             DBG_ASSERT(sal_False, "SbaTableQueryBrowser::GetState: unknown command type!");
1865                     }
1866                     ::rtl::OUString aName;
1867                     xProp->getPropertyValue(PROPERTY_COMMAND) >>= aName;
1868                     String sObject(aName.getStr());
1869 
1870                     sTitle.SearchAndReplace('#',sObject);
1871                     aReturn.sTitle = sTitle;
1872                     aReturn.bEnabled = sal_True;
1873                 }
1874                 break;
1875             case ID_BROWSER_TABLEATTR:
1876             case ID_BROWSER_ROWHEIGHT:
1877             case ID_BROWSER_COLATTRSET:
1878             case ID_BROWSER_COLWIDTH:
1879                 aReturn.bEnabled = getBrowserView() && getBrowserView()->getVclControl() && isValid() && isValidCursor();
1880                 //  aReturn.bEnabled &= getDefinition() && !getDefinition()->GetDatabase()->IsReadOnly();
1881                 break;
1882 
1883             case ID_BROWSER_COPY:
1884                 OSL_ENSURE( !m_pTreeView->HasChildPathFocus(), "SbaTableQueryBrowser::GetState( ID_BROWSER_COPY ): this should have been handled above!" );
1885                 if (getBrowserView() && getBrowserView()->getVclControl() && !getBrowserView()->getVclControl()->IsEditing())
1886                 {
1887                     SbaGridControl* pControl = getBrowserView()->getVclControl();
1888                     if ( pControl->GetSelectRowCount() )
1889                     {
1890                         aReturn.bEnabled = m_aCurrentFrame.isActive();
1891                         break;
1892                     } // if ( getBrowserView()->getVclControl()->GetSelectRowCount() )
1893                     else
1894                         aReturn.bEnabled = pControl->canCopyCellText(pControl->GetCurRow(), pControl->GetCurColumnId());
1895                     break;
1896                 }
1897                 // NO break here
1898             default:
1899                 return SbaXDataBrowserController::GetState(nId);
1900         }
1901     }
1902     catch(const Exception&)
1903     {
1904         DBG_UNHANDLED_EXCEPTION();
1905     }
1906 
1907     return aReturn;
1908 
1909 }
1910 
1911 //------------------------------------------------------------------------------
Execute(sal_uInt16 nId,const Sequence<PropertyValue> & aArgs)1912 void SbaTableQueryBrowser::Execute(sal_uInt16 nId, const Sequence< PropertyValue >& aArgs)
1913 {
1914     switch (nId)
1915     {
1916         default:
1917             SbaXDataBrowserController::Execute(nId,aArgs);
1918             break;
1919 
1920         case ID_TREE_EDIT_DATABASE:
1921             implAdministrate( m_pTreeView->getListBox().GetCurEntry() );
1922             break;
1923 
1924         case ID_TREE_CLOSE_CONN:
1925             openHelpAgent( HID_DSBROWSER_DISCONNECTING );
1926             closeConnection( m_pTreeView->getListBox().GetRootLevelParent( m_pTreeView->getListBox().GetCurEntry() ) );
1927             break;
1928 
1929         case ID_TREE_ADMINISTRATE:
1930             ::svx::administrateDatabaseRegistration( getView() );
1931             break;
1932 
1933         case ID_BROWSER_REFRESH:
1934         {
1935             if ( !SaveModified( ) )
1936                 // nothing to do
1937                 break;
1938 
1939             sal_Bool bFullReinit = sal_False;
1940             // check if the query signature (if the form is based on a query) has changed
1941             if ( m_sQueryCommand.getLength() )
1942             {
1943                 ::rtl::OUString sNewQueryCommand;
1944                 sal_Bool bNewQueryEP;
1945 
1946 #if OSL_DEBUG_LEVEL > 0
1947                 sal_Bool bIsQuery =
1948 #endif
1949                 implGetQuerySignature( sNewQueryCommand, bNewQueryEP );
1950                 OSL_ENSURE( bIsQuery, "SbaTableQueryBrowser::Execute: was a query before, but is not anymore?" );
1951 
1952                 bFullReinit = ( sNewQueryCommand != m_sQueryCommand ) || ( m_bQueryEscapeProcessing != bNewQueryEP );
1953             }
1954             if ( !bFullReinit )
1955             {
1956                 // let the base class do a simple reload
1957                 SbaXDataBrowserController::Execute(nId,aArgs);
1958                 break;
1959             }
1960             // NO break here!
1961         }
1962 
1963         case ID_BROWSER_REFRESH_REBUILD:
1964         {
1965             if ( !SaveModified() )
1966                 // nothing to do
1967                 break;
1968 
1969             SvLBoxEntry* pSelected = m_pCurrentlyDisplayed;
1970             // unload
1971             unloadAndCleanup( sal_False );
1972 
1973             // reselect the entry
1974             if ( pSelected )
1975             {
1976                 implSelect( pSelected );
1977             }
1978             else
1979             {
1980                 Reference<XPropertySet> xProp(getRowSet(),UNO_QUERY);
1981                 implSelect(::svx::ODataAccessDescriptor(xProp));
1982             }
1983         }
1984         break;
1985 
1986         case ID_BROWSER_EXPLORER:
1987             toggleExplorer();
1988             break;
1989 
1990         case ID_BROWSER_DOCUMENT_DATASOURCE:
1991             implSelect(m_aDocumentDataSource);
1992             break;
1993 
1994         case ID_BROWSER_INSERTCOLUMNS:
1995         case ID_BROWSER_INSERTCONTENT:
1996         case ID_BROWSER_FORMLETTER:
1997             if (getBrowserView() && isValidCursor())
1998             {
1999                 // the URL the slot id is assigned to
2000                 OSL_ENSURE( m_aExternalFeatures.find( nId ) != m_aExternalFeatures.end(),
2001                     "SbaTableQueryBrowser::Execute( ID_BROWSER_?): how could this ever be enabled?" );
2002                 URL aParentUrl = m_aExternalFeatures[ nId ].aURL;
2003 
2004                 // let the dispatcher execute the slot
2005                 Reference< XDispatch > xDispatch( m_aExternalFeatures[ nId ].xDispatcher );
2006                 if (xDispatch.is())
2007                 {
2008                     // set the properties for the dispatch
2009 
2010                     // first fill the selection
2011                     SbaGridControl* pGrid = getBrowserView()->getVclControl();
2012                     MultiSelection* pSelection = (MultiSelection*)pGrid->GetSelection();
2013                     Sequence< Any > aSelection;
2014                     if ( !pGrid->IsAllSelected() )
2015                     {   // transfer the selected rows only if not all rows are selected
2016                         // (all rows means the whole table)
2017                         // i3832 - 03.04.2002 - fs@openoffice.org
2018                         if (pSelection != NULL)
2019                         {
2020                             aSelection.realloc(pSelection->GetSelectCount());
2021                             long nIdx = pSelection->FirstSelected();
2022                             Any* pSelectionNos = aSelection.getArray();
2023                             while (nIdx >= 0)
2024                             {
2025                                 *pSelectionNos++ <<= (sal_Int32)(nIdx + 1);
2026                                 nIdx = pSelection->NextSelected();
2027                             }
2028                         }
2029                     }
2030 
2031                     Reference< XResultSet > xCursorClone;
2032                     try
2033                     {
2034                         Reference< XResultSetAccess > xResultSetAccess(getRowSet(),UNO_QUERY);
2035                         if (xResultSetAccess.is())
2036                             xCursorClone = xResultSetAccess->createResultSet();
2037                     }
2038                     catch(DisposedException&)
2039                     {
2040                         OSL_ENSURE(0,"Object already disposed!");
2041                     }
2042                     catch(Exception&)
2043                     {
2044                         DBG_ERROR("SbaTableQueryBrowser::Execute(ID_BROWSER_?): could not clone the cursor!");
2045                     }
2046 
2047                     Reference<XPropertySet> xProp(getRowSet(),UNO_QUERY);
2048 
2049                     try
2050                     {
2051                         ODataAccessDescriptor aDescriptor;
2052                         ::rtl::OUString sDataSourceName;
2053                         xProp->getPropertyValue(PROPERTY_DATASOURCENAME) >>= sDataSourceName;
2054 
2055                         aDescriptor.setDataSource(sDataSourceName);
2056                         aDescriptor[daCommand]      =   xProp->getPropertyValue(PROPERTY_COMMAND);
2057                         aDescriptor[daCommandType]  =   xProp->getPropertyValue(PROPERTY_COMMAND_TYPE);
2058                         aDescriptor[daConnection]   =   xProp->getPropertyValue(PROPERTY_ACTIVE_CONNECTION);
2059                         aDescriptor[daCursor]       <<= xCursorClone;
2060                         if ( aSelection.getLength() )
2061                         {
2062                             aDescriptor[daSelection]            <<= aSelection;
2063                             aDescriptor[daBookmarkSelection]    <<= sal_False;
2064                                 // these are selection indices
2065                                 // before we change this, all clients have to be adjusted
2066                                 // so that they recognize the new BookmarkSelection property!
2067                         }
2068 
2069                         xDispatch->dispatch(aParentUrl, aDescriptor.createPropertyValueSequence());
2070                     }
2071                     catch( const Exception& )
2072                     {
2073                         DBG_UNHANDLED_EXCEPTION();
2074                     }
2075                 }
2076             }
2077             break;
2078 
2079         case ID_BROWSER_CLOSE:
2080             closeTask();
2081             // if it's not 0, such a async close is already pending
2082             break;
2083 
2084         case ID_BROWSER_COPY:
2085             if(m_pTreeView->HasChildPathFocus())
2086             {
2087                 copyEntry(m_pTreeView->getListBox().GetCurEntry());
2088             }
2089             else if (getBrowserView() && getBrowserView()->getVclControl() && !getBrowserView()->getVclControl()->IsEditing() && getBrowserView()->getVclControl()->GetSelectRowCount() < 1)
2090             {
2091                 SbaGridControl* pControl = getBrowserView()->getVclControl();
2092                 pControl->copyCellText(pControl->GetCurRow(), pControl->GetCurColumnId());
2093             }
2094             else
2095                 SbaXDataBrowserController::Execute(nId,aArgs);
2096             break;
2097     }
2098 }
2099 
2100 // -------------------------------------------------------------------------
implAddDatasource(const String & _rDataSourceName,const SharedConnection & _rxConnection)2101 void SbaTableQueryBrowser::implAddDatasource( const String& _rDataSourceName, const SharedConnection& _rxConnection )
2102 {
2103     Image a, b, c;
2104     String d, e;
2105     implAddDatasource( _rDataSourceName, a, d, b, e, c, _rxConnection );
2106 }
2107 
2108 // -------------------------------------------------------------------------
implAddDatasource(const String & _rDbName,Image & _rDbImage,String & _rQueryName,Image & _rQueryImage,String & _rTableName,Image & _rTableImage,const SharedConnection & _rxConnection)2109 void SbaTableQueryBrowser::implAddDatasource(const String& _rDbName, Image& _rDbImage,
2110         String& _rQueryName, Image& _rQueryImage, String& _rTableName, Image& _rTableImage,
2111         const SharedConnection& _rxConnection)
2112 {
2113     vos::OGuard aGuard( Application::GetSolarMutex() );
2114     // initialize the names/images if necessary
2115     if (!_rQueryName.Len())
2116         _rQueryName = String(ModuleRes(RID_STR_QUERIES_CONTAINER));
2117     if (!_rTableName.Len())
2118         _rTableName = String(ModuleRes(RID_STR_TABLES_CONTAINER));
2119 
2120     ImageProvider aImageProvider;
2121     if (!_rQueryImage)
2122         _rQueryImage = aImageProvider.getFolderImage( DatabaseObject::QUERY, isHiContrast() );
2123     if (!_rTableImage)
2124         _rTableImage = aImageProvider.getFolderImage( DatabaseObject::TABLE, isHiContrast() );
2125 
2126     if (!_rDbImage)
2127         _rDbImage = aImageProvider.getDatabaseImage( isHiContrast() );
2128 
2129     // add the entry for the data source
2130     // special handling for data sources denoted by URLs - we do not want to display this ugly URL, do we?
2131     // #i33699# - 2004-09-24 - fs@openoffice.org
2132     String sDSDisplayName, sDataSourceId;
2133     getDataSourceDisplayName_isURL( _rDbName, sDSDisplayName, sDataSourceId );
2134 
2135     SvLBoxEntry* pDatasourceEntry = m_pTreeView->getListBox().InsertEntry( sDSDisplayName, _rDbImage, _rDbImage, NULL, sal_False );
2136     DBTreeListUserData* pDSData = new DBTreeListUserData;
2137     pDSData->eType = etDatasource;
2138     pDSData->sAccessor = sDataSourceId;
2139     pDSData->xConnection = _rxConnection;
2140     pDatasourceEntry->SetUserData(pDSData);
2141 
2142     // the child for the queries container
2143     {
2144         DBTreeListUserData* pQueriesData = new DBTreeListUserData;
2145         pQueriesData->eType = etQueryContainer;
2146 
2147         m_pTreeView->getListBox().InsertEntry(
2148             _rQueryName, _rQueryImage, _rQueryImage, pDatasourceEntry,
2149             sal_True /*ChildsOnDemand*/, LIST_APPEND, pQueriesData );
2150     }
2151 
2152     // the child for the tables container
2153     {
2154         DBTreeListUserData* pTablesData = new DBTreeListUserData;
2155         pTablesData->eType = etTableContainer;
2156 
2157         m_pTreeView->getListBox().InsertEntry(
2158             _rTableName, _rTableImage, _rTableImage, pDatasourceEntry,
2159             sal_True /*ChildsOnDemand*/, LIST_APPEND, pTablesData );
2160     }
2161 
2162 }
2163 // -------------------------------------------------------------------------
initializeTreeModel()2164 void SbaTableQueryBrowser::initializeTreeModel()
2165 {
2166     if (m_xDatabaseContext.is())
2167     {
2168         Image aDBImage, aQueriesImage, aTablesImage;
2169         String sQueriesName, sTablesName;
2170 
2171         // fill the model with the names of the registered datasources
2172         Sequence< ::rtl::OUString > aDatasources = m_xDatabaseContext->getElementNames();
2173         const ::rtl::OUString* pIter    = aDatasources.getConstArray();
2174         const ::rtl::OUString* pEnd     = pIter + aDatasources.getLength();
2175         for (; pIter != pEnd; ++pIter)
2176             implAddDatasource( *pIter, aDBImage, sQueriesName, aQueriesImage, sTablesName, aTablesImage, SharedConnection() );
2177     }
2178 }
2179 // -------------------------------------------------------------------------
populateTree(const Reference<XNameAccess> & _xNameAccess,SvLBoxEntry * _pParent,EntryType _eEntryType)2180 void SbaTableQueryBrowser::populateTree(const Reference<XNameAccess>& _xNameAccess,
2181                                             SvLBoxEntry* _pParent,
2182                                             EntryType _eEntryType)
2183 {
2184     DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(_pParent->GetUserData());
2185     if(pData) // don't ask if the nameaccess is already set see OnExpandEntry views and tables
2186         pData->xContainer = _xNameAccess;
2187 
2188     try
2189     {
2190         Sequence< ::rtl::OUString > aNames = _xNameAccess->getElementNames();
2191         const ::rtl::OUString* pIter    = aNames.getConstArray();
2192         const ::rtl::OUString* pEnd     = pIter + aNames.getLength();
2193         for (; pIter != pEnd; ++pIter)
2194         {
2195             if( !m_pTreeView->getListBox().GetEntryPosByName(*pIter,_pParent))
2196             {
2197                 DBTreeListUserData* pEntryData = new DBTreeListUserData;
2198                 pEntryData->eType = _eEntryType;
2199                 if ( _eEntryType == etQuery )
2200                 {
2201                     Reference<XNameAccess> xChild(_xNameAccess->getByName(*pIter),UNO_QUERY);
2202                     if ( xChild.is() )
2203                         pEntryData->eType = etQueryContainer;
2204                 }
2205                 implAppendEntry( _pParent, *pIter, pEntryData, pEntryData->eType );
2206             }
2207         }
2208     }
2209     catch(Exception&)
2210     {
2211         DBG_ERROR("SbaTableQueryBrowser::populateTree: could not fill the tree");
2212     }
2213 }
2214 
2215 //------------------------------------------------------------------------------
implAppendEntry(SvLBoxEntry * _pParent,const String & _rName,void * _pUserData,EntryType _eEntryType)2216 SvLBoxEntry* SbaTableQueryBrowser::implAppendEntry( SvLBoxEntry* _pParent, const String& _rName, void* _pUserData, EntryType _eEntryType )
2217 {
2218     ::std::unique_ptr< ImageProvider > pImageProvider( getImageProviderFor( _pParent ) );
2219 
2220     Image aImage, aImageHC;
2221     pImageProvider->getImages( _rName, getDatabaseObjectType( _eEntryType ), aImage, aImageHC );
2222 
2223     SvLBoxEntry* pNewEntry = m_pTreeView->getListBox().InsertEntry( _rName, _pParent, _eEntryType == etQueryContainer , LIST_APPEND, _pUserData );
2224 
2225     m_pTreeView->getListBox().SetExpandedEntryBmp( pNewEntry, aImage, BMP_COLOR_NORMAL );
2226     m_pTreeView->getListBox().SetCollapsedEntryBmp( pNewEntry, aImage, BMP_COLOR_NORMAL );
2227     m_pTreeView->getListBox().SetExpandedEntryBmp( pNewEntry, aImageHC, BMP_COLOR_HIGHCONTRAST );
2228     m_pTreeView->getListBox().SetCollapsedEntryBmp( pNewEntry, aImageHC, BMP_COLOR_HIGHCONTRAST );
2229 
2230     return pNewEntry;
2231 }
2232 
2233 //------------------------------------------------------------------------------
IMPL_LINK(SbaTableQueryBrowser,OnExpandEntry,SvLBoxEntry *,_pParent)2234 IMPL_LINK(SbaTableQueryBrowser, OnExpandEntry, SvLBoxEntry*, _pParent)
2235 {
2236     if (_pParent->HasChilds())
2237         // nothing to to ...
2238         return 1L;
2239 
2240     SvLBoxEntry* pFirstParent = m_pTreeView->getListBox().GetRootLevelParent(_pParent);
2241     OSL_ENSURE(pFirstParent,"SbaTableQueryBrowser::OnExpandEntry: No rootlevelparent!");
2242 
2243     DBTreeListUserData* pData = static_cast< DBTreeListUserData* >(_pParent->GetUserData());
2244     OSL_ENSURE(pData,"SbaTableQueryBrowser::OnExpandEntry: No user data!");
2245 #if OSL_DEBUG_LEVEL > 0
2246     SvLBoxString* pString = static_cast<SvLBoxString*>(pFirstParent->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING));
2247     OSL_ENSURE(pString,"SbaTableQueryBrowser::OnExpandEntry: No string item!");
2248 #endif
2249 
2250     if (etTableContainer == pData->eType)
2251     {
2252         WaitObject aWaitCursor(getBrowserView());
2253 
2254         // it could be that we already have a connection
2255         SharedConnection xConnection;
2256         ensureConnection( pFirstParent, xConnection );
2257 
2258         if ( xConnection.is() )
2259         {
2260             SQLExceptionInfo aInfo;
2261             try
2262             {
2263                 Reference< XWarningsSupplier > xWarnings(xConnection, UNO_QUERY);
2264                 if (xWarnings.is())
2265                     xWarnings->clearWarnings();
2266 
2267                 // first insert the views because the tables can also include
2268                 // views but that time the bitmap is the wrong one
2269                 // the nameaccess will be overwritten in populateTree
2270                 Reference<XViewsSupplier> xViewSup(xConnection,UNO_QUERY);
2271                 if(xViewSup.is())
2272                     populateTree( xViewSup->getViews(), _pParent, etTableOrView );
2273 
2274                 Reference<XTablesSupplier> xTabSup(xConnection,UNO_QUERY);
2275                 if(xTabSup.is())
2276                 {
2277                     populateTree( xTabSup->getTables(), _pParent, etTableOrView );
2278                     Reference<XContainer> xCont(xTabSup->getTables(),UNO_QUERY);
2279                     if(xCont.is())
2280                         // add as listener to know when elements are inserted or removed
2281                         xCont->addContainerListener(this);
2282                 }
2283 
2284                 if (xWarnings.is())
2285                 {
2286                     SQLExceptionInfo aWarnings(xWarnings->getWarnings());
2287                     if (aWarnings.isValid() && sal_False)
2288                     {
2289                         SQLContext aContext;
2290                         aContext.Message = String(ModuleRes(STR_OPENTABLES_WARNINGS));
2291                         aContext.Details = String(ModuleRes(STR_OPENTABLES_WARNINGS_DETAILS));
2292                         aContext.NextException = aWarnings.get();
2293                         aWarnings = aContext;
2294                         showError(aWarnings);
2295                     }
2296                     // TODO: we need a better concept for these warnings:
2297                     // something like "don't show any warnings for this datasource, again" would be nice
2298                     // But this requires an extension of the InteractionHandler and an additional property on the data source
2299                 }
2300             }
2301             catch(const SQLContext& e) { aInfo = e; }
2302             catch(const SQLWarning& e) { aInfo = e; }
2303             catch(const SQLException& e) { aInfo = e; }
2304             catch(const WrappedTargetException& e)
2305             {
2306                 SQLException aSql;
2307                 if(e.TargetException >>= aSql)
2308                     aInfo = aSql;
2309                 else
2310                     OSL_ENSURE(sal_False, "SbaTableQueryBrowser::OnExpandEntry: something strange happened!");
2311             }
2312             catch( const Exception& )
2313             {
2314                 DBG_UNHANDLED_EXCEPTION();
2315             }
2316             if (aInfo.isValid())
2317                 showError(aInfo);
2318         }
2319         else
2320             return 0L;
2321                 // 0 indicates that an error occurred
2322     }
2323     else
2324     {   // we have to expand the queries or bookmarks
2325         if (ensureEntryObject(_pParent))
2326         {
2327             DBTreeListUserData* pParentData = static_cast< DBTreeListUserData* >( _pParent->GetUserData() );
2328             Reference< XNameAccess > xCollection( pParentData->xContainer, UNO_QUERY );
2329             populateTree( xCollection, _pParent, etQuery );
2330         }
2331     }
2332     return 1L;
2333 }
2334 
2335 //------------------------------------------------------------------------------
ensureEntryObject(SvLBoxEntry * _pEntry)2336 sal_Bool SbaTableQueryBrowser::ensureEntryObject( SvLBoxEntry* _pEntry )
2337 {
2338     DBG_ASSERT(_pEntry, "SbaTableQueryBrowser::ensureEntryObject: invalid argument!");
2339     if (!_pEntry)
2340         return sal_False;
2341 
2342     EntryType eType = getEntryType( _pEntry );
2343 
2344     // the user data of the entry
2345     DBTreeListUserData* pEntryData = static_cast<DBTreeListUserData*>(_pEntry->GetUserData());
2346     OSL_ENSURE(pEntryData,"ensureEntryObject: user data should already be set!");
2347 
2348     SvLBoxEntry* pDataSourceEntry = m_pTreeView->getListBox().GetRootLevelParent(_pEntry);
2349 
2350     sal_Bool bSuccess = sal_False;
2351     switch (eType)
2352     {
2353         case etQueryContainer:
2354             if ( pEntryData->xContainer.is() )
2355             {
2356                 // nothing to do
2357                 bSuccess = sal_True;
2358                 break;
2359             }
2360 
2361             {
2362                 SvLBoxEntry* pParent = m_pTreeView->getListBox().GetParent(_pEntry);
2363                 if ( pParent != pDataSourceEntry )
2364                 {
2365                     SvLBoxString* pString = (SvLBoxString*)_pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING);
2366                     OSL_ENSURE(pString,"There must be a string item!");
2367                     ::rtl::OUString aName(pString->GetText());
2368                     DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(pParent->GetUserData());
2369                     try
2370                     {
2371                         Reference< XNameAccess > xNameAccess(pData->xContainer,UNO_QUERY);
2372                         if ( xNameAccess.is() )
2373                             pEntryData->xContainer.set(xNameAccess->getByName(aName),UNO_QUERY);
2374                     }
2375                     catch(const Exception& )
2376                     {
2377                         DBG_UNHANDLED_EXCEPTION();
2378                     }
2379 
2380                     bSuccess = pEntryData->xContainer.is();
2381                 }
2382                 else
2383                 {
2384                     try
2385                     {
2386                         Reference< XQueryDefinitionsSupplier > xQuerySup;
2387                         m_xDatabaseContext->getByName( getDataSourceAcessor( pDataSourceEntry ) ) >>= xQuerySup;
2388                         if (xQuerySup.is())
2389                         {
2390                             Reference< XNameAccess > xQueryDefs = xQuerySup->getQueryDefinitions();
2391                             Reference< XContainer > xCont(xQueryDefs, UNO_QUERY);
2392                             if (xCont.is())
2393                                 // add as listener to get notified if elements are inserted or removed
2394                                 xCont->addContainerListener(this);
2395 
2396                             pEntryData->xContainer = xQueryDefs;
2397                             bSuccess = pEntryData->xContainer.is();
2398                         }
2399                         else {
2400                             DBG_ERROR("SbaTableQueryBrowser::ensureEntryObject: no XQueryDefinitionsSupplier interface!");
2401                         }
2402                     }
2403                     catch( const Exception& )
2404                     {
2405                         DBG_UNHANDLED_EXCEPTION();
2406                     }
2407                 }
2408             }
2409             break;
2410 
2411         default:
2412             DBG_ERROR("SbaTableQueryBrowser::ensureEntryObject: ooops ... missing some implementation here!");
2413             // TODO ...
2414             break;
2415     }
2416 
2417     return bSuccess;
2418 }
2419 //------------------------------------------------------------------------------
implSelect(const::svx::ODataAccessDescriptor & _rDescriptor,sal_Bool _bSelectDirect)2420 sal_Bool SbaTableQueryBrowser::implSelect(const ::svx::ODataAccessDescriptor& _rDescriptor,sal_Bool _bSelectDirect)
2421 {
2422     // extract the props
2423     ::rtl::OUString sDataSource;
2424     ::rtl::OUString sCommand;
2425     sal_Int32 nCommandType = CommandType::COMMAND;
2426     sal_Bool bEscapeProcessing = sal_True;
2427     extractDescriptorProps(_rDescriptor, sDataSource, sCommand, nCommandType, bEscapeProcessing);
2428 
2429     // select it
2430     return implSelect( sDataSource, sCommand, nCommandType, bEscapeProcessing, SharedConnection(), _bSelectDirect );
2431 }
2432 
2433 //------------------------------------------------------------------------------
implLoadAnything(const::rtl::OUString & _rDataSourceName,const::rtl::OUString & _rCommand,const sal_Int32 _nCommandType,const sal_Bool _bEscapeProcessing,const SharedConnection & _rxConnection)2434 sal_Bool SbaTableQueryBrowser::implLoadAnything(const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rCommand,
2435     const sal_Int32 _nCommandType, const sal_Bool _bEscapeProcessing, const SharedConnection& _rxConnection)
2436 {
2437     try
2438     {
2439         Reference<XPropertySet> xProp( getRowSet(), UNO_QUERY_THROW );
2440         Reference< XLoadable >  xLoadable( xProp, UNO_QUERY_THROW );
2441         // the values allowing the RowSet to re-execute
2442         xProp->setPropertyValue(PROPERTY_DATASOURCENAME, makeAny(_rDataSourceName));
2443         if(_rxConnection.is())
2444             xProp->setPropertyValue( PROPERTY_ACTIVE_CONNECTION, makeAny( _rxConnection.getTyped() ) );
2445 
2446             // set this _before_ setting the connection, else the rowset would rebuild it ...
2447         xProp->setPropertyValue(PROPERTY_COMMAND_TYPE, makeAny(_nCommandType));
2448         xProp->setPropertyValue(PROPERTY_COMMAND, makeAny(_rCommand));
2449         xProp->setPropertyValue(PROPERTY_ESCAPE_PROCESSING, ::cppu::bool2any(_bEscapeProcessing));
2450         if ( m_bPreview )
2451         {
2452             xProp->setPropertyValue(PROPERTY_FETCHDIRECTION, makeAny(FetchDirection::FORWARD));
2453         }
2454 
2455         // the formatter depends on the data source we're working on, so rebuild it here ...
2456         initFormatter();
2457 
2458         // switch the grid to design mode while loading
2459         getBrowserView()->getGridControl()->setDesignMode(sal_True);
2460         InitializeForm( xProp );
2461 
2462         sal_Bool bSuccess = sal_True;
2463 
2464         {
2465             {
2466                 Reference< XNameContainer >  xColContainer(getFormComponent(), UNO_QUERY);
2467                 // first we have to clear the grid
2468                 clearGridColumns(xColContainer);
2469             }
2470             FormErrorHelper aHelper(this);
2471             // load the form
2472             bSuccess = reloadForm(xLoadable);
2473 
2474             // initialize the model
2475             InitializeGridModel(getFormComponent());
2476 
2477             Any aVal = xProp->getPropertyValue(PROPERTY_ISNEW);
2478             if (aVal.hasValue() && ::comphelper::getBOOL(aVal))
2479             {
2480                 // then set the default values and the parameters given from the parent
2481                 Reference< XReset> xReset(xProp, UNO_QUERY);
2482                 xReset->reset();
2483             }
2484 
2485             if ( m_bPreview )
2486                 initializePreviewMode();
2487 
2488             LoadFinished(sal_True);
2489         }
2490 
2491         InvalidateAll();
2492         return bSuccess;
2493     }
2494     catch( const SQLException& e )
2495     {
2496         Any aException( ::cppu::getCaughtException() );
2497         showError( SQLExceptionInfo( aException ) );
2498     }
2499     catch( const WrappedTargetException& e )
2500     {
2501         SQLException aSql;
2502         if  ( e.TargetException.isExtractableTo( ::cppu::UnoType< SQLException >::get() ) )
2503             showError( SQLExceptionInfo( e.TargetException ) );
2504         else
2505         {
2506             DBG_UNHANDLED_EXCEPTION();
2507         }
2508     }
2509     catch(Exception&)
2510     {
2511         DBG_UNHANDLED_EXCEPTION();
2512     }
2513 
2514     InvalidateAll();
2515     return sal_False;
2516 }
2517 
2518 //------------------------------------------------------------------------------
implSelect(const::rtl::OUString & _rDataSourceName,const::rtl::OUString & _rCommand,const sal_Int32 _nCommandType,const sal_Bool _bEscapeProcessing,const SharedConnection & _rxConnection,sal_Bool _bSelectDirect)2519 sal_Bool SbaTableQueryBrowser::implSelect(const ::rtl::OUString& _rDataSourceName, const ::rtl::OUString& _rCommand,
2520                                       const sal_Int32 _nCommandType, const sal_Bool _bEscapeProcessing,
2521                                       const SharedConnection& _rxConnection
2522                                       ,sal_Bool _bSelectDirect)
2523 {
2524     if (_rDataSourceName.getLength() && _rCommand.getLength() && (-1 != _nCommandType))
2525     {
2526         SvLBoxEntry* pDataSource = NULL;
2527         SvLBoxEntry* pCommandType = NULL;
2528         SvLBoxEntry* pCommand = getObjectEntry( _rDataSourceName, _rCommand, _nCommandType, &pDataSource, &pCommandType, sal_True, _rxConnection );
2529 
2530         if (pCommand)
2531         {
2532             bool bSuccess = true;
2533             if ( _bSelectDirect )
2534             {
2535                 bSuccess = implSelect( pCommand );
2536             }
2537             else
2538             {
2539                 m_pTreeView->getListBox().Select( pCommand );
2540             }
2541 
2542             if ( bSuccess )
2543             {
2544                 m_pTreeView->getListBox().MakeVisible(pCommand);
2545                 m_pTreeView->getListBox().SetCursor(pCommand);
2546             }
2547         }
2548         else if (!pCommandType)
2549         {
2550             if ( m_pCurrentlyDisplayed )
2551             {   // tell the old entry (if any) it has been deselected
2552                 selectPath(m_pCurrentlyDisplayed, sal_False);
2553                 m_pCurrentlyDisplayed = NULL;
2554             }
2555 
2556             // we have a command and need to display this in the rowset
2557             return implLoadAnything(_rDataSourceName, _rCommand, _nCommandType, _bEscapeProcessing, _rxConnection);
2558         }
2559     }
2560     return sal_False;
2561 }
2562 
2563 //------------------------------------------------------------------------------
2564 IMPL_LINK(SbaTableQueryBrowser, OnSelectionChange, void*, /*NOINTERESTEDIN*/)
2565 {
2566     return implSelect( m_pTreeView->getListBox().FirstSelected() ) ? 1L : 0L;
2567 }
2568 //------------------------------------------------------------------------------
implGetConnectionEntry(SvLBoxEntry * _pEntry) const2569 SvLBoxEntry* SbaTableQueryBrowser::implGetConnectionEntry(SvLBoxEntry* _pEntry) const
2570 {
2571     SvLBoxEntry* pCurrentEntry = _pEntry;
2572     DBTreeListUserData* pEntryData = static_cast< DBTreeListUserData* >( pCurrentEntry->GetUserData() );
2573     while(pEntryData->eType != etDatasource )
2574     {
2575         pCurrentEntry = m_pTreeModel->GetParent(pCurrentEntry);
2576         pEntryData = static_cast< DBTreeListUserData* >( pCurrentEntry->GetUserData() );
2577     }
2578     return pCurrentEntry;
2579 }
2580 //------------------------------------------------------------------------------
implSelect(SvLBoxEntry * _pEntry)2581 bool SbaTableQueryBrowser::implSelect( SvLBoxEntry* _pEntry )
2582 {
2583     if ( !_pEntry )
2584         return false;
2585 
2586     DBTreeListUserData* pEntryData = static_cast< DBTreeListUserData* >( _pEntry->GetUserData() );
2587     switch (pEntryData->eType)
2588     {
2589         case etTableOrView:
2590         case etQuery:
2591             break;
2592         default:
2593             // nothing to do
2594             return false;
2595     }
2596 
2597     OSL_ENSURE(m_pTreeModel->HasParent(_pEntry), "SbaTableQueryBrowser::implSelect: invalid entry (1)!");
2598     OSL_ENSURE(m_pTreeModel->HasParent(m_pTreeModel->GetParent(_pEntry)), "SbaTableQueryBrowser::implSelect: invalid entry (2)!");
2599 
2600     // get the entry for the tables or queries
2601     SvLBoxEntry* pContainer = m_pTreeModel->GetParent(_pEntry);
2602     DBTreeListUserData* pContainerData = static_cast<DBTreeListUserData*>(pContainer->GetUserData());
2603 
2604     // get the entry for the datasource
2605     SvLBoxEntry* pConnection = implGetConnectionEntry(pContainer);
2606     DBTreeListUserData* pConData = static_cast<DBTreeListUserData*>(pConnection->GetUserData());
2607 
2608     // reinitialize the rowset
2609     // but first check if it is necessary
2610     // get all old properties
2611     Reference<XPropertySet> xRowSetProps(getRowSet(),UNO_QUERY);
2612     ::rtl::OUString aOldName;
2613     xRowSetProps->getPropertyValue(PROPERTY_COMMAND) >>= aOldName;
2614     sal_Int32 nOldType = 0;
2615     xRowSetProps->getPropertyValue(PROPERTY_COMMAND_TYPE) >>= nOldType;
2616     Reference<XConnection> xOldConnection(xRowSetProps->getPropertyValue(PROPERTY_ACTIVE_CONNECTION),UNO_QUERY);
2617 
2618     // the name of the table or query
2619     SvLBoxString* pString = (SvLBoxString*)_pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING);
2620     OSL_ENSURE(pString,"There must be a string item!");
2621     const ::rtl::OUString sSimpleName = pString->GetText();
2622     ::rtl::OUStringBuffer sNameBuffer(sSimpleName);
2623     if ( etQueryContainer == pContainerData->eType )
2624     {
2625         SvLBoxEntry* pTemp = pContainer;
2626         while( m_pTreeModel->GetParent(pTemp) != pConnection )
2627         {
2628             sNameBuffer.insert(0,sal_Unicode('/'));
2629             pString = (SvLBoxString*)pTemp->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING);
2630             OSL_ENSURE(pString,"There must be a string item!");
2631             sNameBuffer.insert(0,pString->GetText());
2632             pTemp = m_pTreeModel->GetParent(pTemp);
2633         }
2634     }
2635     ::rtl::OUString aName = sNameBuffer.makeStringAndClear();
2636 
2637     sal_Int32 nCommandType =    ( etTableContainer == pContainerData->eType)
2638                             ?   CommandType::TABLE
2639                             :   CommandType::QUERY;
2640 
2641     // check if need to rebuild the rowset
2642     sal_Bool bRebuild = ( xOldConnection != pConData->xConnection )
2643                      || ( nOldType != nCommandType )
2644                      || ( aName != aOldName );
2645 
2646     Reference< ::com::sun::star::form::XLoadable >  xLoadable = getLoadable();
2647     bRebuild |= !xLoadable->isLoaded();
2648     bool bSuccess = true;
2649     if ( bRebuild )
2650     {
2651         try
2652         {
2653             WaitObject aWaitCursor(getBrowserView());
2654 
2655             // tell the old entry it has been deselected
2656             selectPath(m_pCurrentlyDisplayed, sal_False);
2657             m_pCurrentlyDisplayed = NULL;
2658 
2659             // not really loaded
2660             m_pCurrentlyDisplayed = _pEntry;
2661             // tell the new entry it has been selected
2662             selectPath(m_pCurrentlyDisplayed, sal_True);
2663 
2664             // get the name of the data source currently selected
2665             ensureConnection( m_pCurrentlyDisplayed, pConData->xConnection );
2666 
2667             if ( !pConData->xConnection.is() )
2668             {
2669                 unloadAndCleanup( sal_False );
2670                 return false;
2671             }
2672 
2673             Reference<XNameAccess> xNameAccess;
2674             switch(nCommandType)
2675             {
2676                 case CommandType::TABLE:
2677                     {
2678                         // only for tables
2679                         if ( !pContainerData->xContainer.is() )
2680                         {
2681                             Reference<XTablesSupplier> xSup( pConData->xConnection, UNO_QUERY );
2682                             if(xSup.is())
2683                                 xNameAccess = xSup->getTables();
2684 
2685                             pContainerData->xContainer = xNameAccess;
2686                         }
2687                         else
2688                             xNameAccess.set( pContainerData->xContainer, UNO_QUERY );
2689                     }
2690                     break;
2691                 case CommandType::QUERY:
2692                     {
2693                         if ( pContainerData->xContainer.is() )
2694                             xNameAccess.set( pContainerData->xContainer, UNO_QUERY );
2695                         else
2696                         {
2697                             Reference<XQueriesSupplier> xSup( pConData->xConnection, UNO_QUERY );
2698                             if(xSup.is())
2699                                 xNameAccess = xSup->getQueries();
2700                         }
2701                     }
2702                     break;
2703             }
2704             String sStatus(ModuleRes( CommandType::TABLE == nCommandType ? STR_LOADING_TABLE : STR_LOADING_QUERY ));
2705             sStatus.SearchAndReplaceAscii("$name$", aName);
2706             BrowserViewStatusDisplay aShowStatus(static_cast<UnoDataBrowserView*>(getView()), sStatus);
2707 
2708 
2709             sal_Bool bEscapeProcessing = sal_True;
2710             if(xNameAccess.is() && xNameAccess->hasByName(sSimpleName))
2711             {
2712                 DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(_pEntry->GetUserData());
2713                 if ( !pData->xObjectProperties.is() )
2714                 {
2715                     Reference<XInterface> xObject;
2716                     if(xNameAccess->getByName(sSimpleName) >>= xObject) // remember the table or query object
2717                     {
2718                         pData->xObjectProperties = pData->xObjectProperties.query( xObject );
2719                         // if the query contains a parameterized statement and preview is enabled we won't get any data.
2720                         if ( nCommandType == CommandType::QUERY && xObject.is() )
2721                         {
2722                             Reference<XPropertySet> xObjectProps(xObject,UNO_QUERY);
2723                             xObjectProps->getPropertyValue(PROPERTY_ESCAPE_PROCESSING) >>= bEscapeProcessing;
2724                             if ( m_bPreview )
2725                             {
2726                                 ::rtl::OUString sSql;
2727                                 xObjectProps->getPropertyValue(PROPERTY_COMMAND) >>= sSql;
2728                                 Reference< XMultiServiceFactory >  xFactory( pConData->xConnection, UNO_QUERY );
2729                                 if (xFactory.is())
2730                                 {
2731                                     try
2732                                     {
2733                                         Reference<XSingleSelectQueryAnalyzer> xAnalyzer(xFactory->createInstance(SERVICE_NAME_SINGLESELECTQUERYCOMPOSER),UNO_QUERY);
2734                                         if ( xAnalyzer.is() )
2735                                         {
2736                                             xAnalyzer->setQuery(sSql);
2737                                             Reference<XParametersSupplier> xParSup(xAnalyzer,UNO_QUERY);
2738                                             if ( xParSup->getParameters()->getCount() > 0 )
2739                                             {
2740                                                 String sFilter = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" WHERE "));
2741                                                 sFilter = sFilter + xAnalyzer->getFilter();
2742                                                 String sReplace(sSql);
2743                                                 sReplace.SearchAndReplace(sFilter,String());
2744                                                 xAnalyzer->setQuery(sReplace);
2745                                                 Reference<XSingleSelectQueryComposer> xComposer(xAnalyzer,UNO_QUERY);
2746                                                 xComposer->setFilter(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0=1")));
2747                                                 aName = xAnalyzer->getQuery();
2748                                                 nCommandType = CommandType::COMMAND;
2749                                             }
2750                                         }
2751                                     }
2752                                     catch (Exception&)
2753                                     {
2754                                         DBG_UNHANDLED_EXCEPTION();
2755                                     }
2756                                 }
2757                             }
2758                         }
2759                     }
2760                 }
2761             }
2762 
2763             String sDataSourceName( getDataSourceAcessor( pConnection ) );
2764             bSuccess = implLoadAnything( sDataSourceName, aName, nCommandType, bEscapeProcessing, pConData->xConnection );
2765             if ( !bSuccess )
2766             {   // clean up
2767                 criticalFail();
2768             }
2769         }
2770         catch(const SQLException& e)
2771         {
2772             showError(SQLExceptionInfo(e));
2773             // reset the values
2774             xRowSetProps->setPropertyValue(PROPERTY_DATASOURCENAME,Any());
2775             xRowSetProps->setPropertyValue(PROPERTY_ACTIVE_CONNECTION,Any());
2776         }
2777         catch(WrappedTargetException& e)
2778         {
2779             SQLException aSql;
2780             if(e.TargetException >>= aSql)
2781                 showError(SQLExceptionInfo(aSql));
2782             else
2783                 OSL_ENSURE(sal_False, "SbaTableQueryBrowser::implSelect: something strange happened!");
2784             // reset the values
2785             xRowSetProps->setPropertyValue(PROPERTY_DATASOURCENAME,Any());
2786             xRowSetProps->setPropertyValue(PROPERTY_ACTIVE_CONNECTION,Any());
2787         }
2788         catch(Exception&)
2789         {
2790             // reset the values
2791             xRowSetProps->setPropertyValue(PROPERTY_DATASOURCENAME,Any());
2792             xRowSetProps->setPropertyValue(PROPERTY_ACTIVE_CONNECTION,Any());
2793         }
2794     }
2795     return bSuccess;
2796 }
2797 
2798 // -----------------------------------------------------------------------------
getEntryFromContainer(const Reference<XNameAccess> & _rxNameAccess)2799 SvLBoxEntry* SbaTableQueryBrowser::getEntryFromContainer(const Reference<XNameAccess>& _rxNameAccess)
2800 {
2801     DBTreeListBox& rListBox = m_pTreeView->getListBox();
2802     SvLBoxEntry* pContainer = NULL;
2803     SvLBoxEntry* pDSLoop = rListBox.FirstChild(NULL);
2804     while (pDSLoop)
2805     {
2806         pContainer  = rListBox.GetEntry(pDSLoop, CONTAINER_QUERIES);
2807         DBTreeListUserData* pQueriesData = static_cast<DBTreeListUserData*>(pContainer->GetUserData());
2808         if ( pQueriesData && pQueriesData->xContainer == _rxNameAccess )
2809             break;
2810 
2811         pContainer  = rListBox.GetEntry(pDSLoop, CONTAINER_TABLES);
2812         DBTreeListUserData* pTablesData = static_cast<DBTreeListUserData*>(pContainer->GetUserData());
2813         if ( pTablesData && pTablesData->xContainer == _rxNameAccess )
2814             break;
2815 
2816         pDSLoop     = rListBox.NextSibling(pDSLoop);
2817         pContainer  = NULL;
2818     }
2819     return pContainer;
2820 }
2821 
2822 // -------------------------------------------------------------------------
elementInserted(const ContainerEvent & _rEvent)2823 void SAL_CALL SbaTableQueryBrowser::elementInserted( const ContainerEvent& _rEvent )
2824 {
2825     vos::OGuard aSolarGuard( Application::GetSolarMutex() );
2826 
2827     Reference< XNameAccess > xNames(_rEvent.Source, UNO_QUERY);
2828     // first search for a definition container where we can insert this element
2829 
2830     SvLBoxEntry* pEntry = getEntryFromContainer(xNames);
2831     if(pEntry)  // found one
2832     {
2833         // insert the new entry into the tree
2834         DBTreeListUserData* pContainerData = static_cast<DBTreeListUserData*>(pEntry->GetUserData());
2835         OSL_ENSURE(pContainerData, "elementInserted: There must be user data for this type!");
2836 
2837         DBTreeListUserData* pNewData = new DBTreeListUserData;
2838         sal_Bool bIsTable = etTableContainer == pContainerData->eType;
2839         if ( bIsTable )
2840         {
2841             _rEvent.Element >>= pNewData->xObjectProperties;// remember the new element
2842             pNewData->eType = etTableOrView;
2843         }
2844         else
2845         {
2846             if ((sal_Int32)m_pTreeView->getListBox().GetChildCount(pEntry) < ( xNames->getElementNames().getLength() - 1 ) )
2847             {
2848                 // the item inserts its children on demand, but it has not been expanded yet. So ensure here and
2849                 // now that it has all items
2850                 populateTree(xNames, pEntry, etQuery );
2851             }
2852             pNewData->eType = etQuery;
2853         }
2854         implAppendEntry( pEntry, ::comphelper::getString( _rEvent.Accessor ), pNewData, pNewData->eType );
2855     }
2856     else
2857         SbaXDataBrowserController::elementInserted(_rEvent);
2858 }
2859 // -------------------------------------------------------------------------
isCurrentlyDisplayedChanged(const String & _sName,SvLBoxEntry * _pContainer)2860 sal_Bool SbaTableQueryBrowser::isCurrentlyDisplayedChanged(const String& _sName,SvLBoxEntry* _pContainer)
2861 {
2862     return m_pCurrentlyDisplayed
2863             &&  getEntryType(m_pCurrentlyDisplayed) == getChildType(_pContainer)
2864             &&  m_pTreeView->getListBox().GetParent(m_pCurrentlyDisplayed) == _pContainer
2865             &&  m_pTreeView->getListBox().GetEntryText(m_pCurrentlyDisplayed) == _sName;
2866 }
2867 // -------------------------------------------------------------------------
elementRemoved(const ContainerEvent & _rEvent)2868 void SAL_CALL SbaTableQueryBrowser::elementRemoved( const ContainerEvent& _rEvent )
2869 {
2870     ::vos::OGuard aSolarGuard(Application::GetSolarMutex());
2871 
2872     Reference< XNameAccess > xNames(_rEvent.Source, UNO_QUERY);
2873     // get the top-level representing the removed data source
2874     // and search for the queries and tables
2875     SvLBoxEntry* pContainer = getEntryFromContainer(xNames);
2876     if ( pContainer )
2877     { // a query or table has been removed
2878         String aName = ::comphelper::getString(_rEvent.Accessor).getStr();
2879 
2880         if ( isCurrentlyDisplayedChanged( aName, pContainer) )
2881         {   // the element displayed currently has been replaced
2882 
2883             // we need to remember the old value
2884             SvLBoxEntry* pTemp = m_pCurrentlyDisplayed;
2885 
2886             // unload
2887             unloadAndCleanup( sal_False ); // don't dispose the connection
2888 
2889             DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(pTemp->GetUserData());
2890             pTemp->SetUserData(NULL);
2891             delete pData;
2892                 // the data could be null because we have a table which isn't correct
2893             m_pTreeModel->Remove(pTemp);
2894         }
2895         else
2896         {
2897             // remove the entry from the model
2898             SvLBoxEntry* pChild = m_pTreeModel->FirstChild(pContainer);
2899             while(pChild)
2900             {
2901                 if (m_pTreeView->getListBox().GetEntryText(pChild) == aName)
2902                 {
2903                     DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(pChild->GetUserData());
2904                     pChild->SetUserData(NULL);
2905                     delete pData;
2906                     m_pTreeModel->Remove(pChild);
2907                     break;
2908                 }
2909                 pChild = m_pTreeModel->NextSibling(pChild);
2910             }
2911         }
2912 
2913         // maybe the object which is part of the document data source has been removed
2914         checkDocumentDataSource();
2915     }
2916     else
2917         SbaXDataBrowserController::elementRemoved(_rEvent);
2918 }
2919 
2920 // -------------------------------------------------------------------------
elementReplaced(const ContainerEvent & _rEvent)2921 void SAL_CALL SbaTableQueryBrowser::elementReplaced( const ContainerEvent& _rEvent )
2922 {
2923     ::vos::OGuard aSolarGuard(Application::GetSolarMutex());
2924 
2925     Reference< XNameAccess > xNames(_rEvent.Source, UNO_QUERY);
2926     SvLBoxEntry* pContainer = getEntryFromContainer(xNames);
2927     if ( pContainer )
2928     {    // a table or query as been replaced
2929         String aName = ::comphelper::getString(_rEvent.Accessor).getStr();
2930 
2931         if ( isCurrentlyDisplayedChanged( aName, pContainer) )
2932         {   // the element displayed currently has been replaced
2933 
2934             // we need to remember the old value
2935             SvLBoxEntry* pTemp = m_pCurrentlyDisplayed;
2936             unloadAndCleanup( sal_False ); // don't dispose the connection
2937 
2938             DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(pTemp->GetUserData());
2939             if (pData)
2940             {
2941                 if ( etTableOrView == pData->eType )
2942                 { // only insert userdata when we have a table because the query is only a commanddefinition object and not a query
2943                      _rEvent.Element >>= pData->xObjectProperties;  // remember the new element
2944                 }
2945                 else
2946                 {
2947                     pTemp->SetUserData(NULL);
2948                     delete pData;
2949                 }
2950             }
2951         }
2952         else
2953         {
2954             // find the entry for this name
2955             SvLBoxEntry* pChild = m_pTreeModel->FirstChild(pContainer);
2956             while(pChild)
2957             {
2958                 if (m_pTreeView->getListBox().GetEntryText(pChild) == aName)
2959                 {
2960                     DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(pChild->GetUserData());
2961                     if (pData)
2962                     {
2963                         if ( etTableOrView == pData->eType )
2964                         { // only insert userdata when we have a table because the query is only a commanddefinition object and not a query
2965                             _rEvent.Element >>= pData->xObjectProperties;   // remember the new element
2966                         }
2967                         else
2968                         {
2969                             pChild->SetUserData(NULL);
2970                             delete pData;
2971                         }
2972                     }
2973                     break;
2974                 }
2975                 pChild = m_pTreeModel->NextSibling(pChild);
2976             }
2977         }
2978 
2979         // maybe the object which is part of the document data source has been removed
2980         checkDocumentDataSource();
2981     }
2982     else if (xNames.get() == m_xDatabaseContext.get())
2983     {   // a datasource has been replaced in the context
2984         DBG_ERROR("SbaTableQueryBrowser::elementReplaced: no support for replaced data sources!");
2985             // very suspicious: the database context should not allow to replace data source, only to register
2986             // and revoke them
2987     }
2988     else
2989         SbaXDataBrowserController::elementReplaced(_rEvent);
2990 }
2991 
2992 // -------------------------------------------------------------------------
impl_releaseConnection(SharedConnection & _rxConnection)2993 void SbaTableQueryBrowser::impl_releaseConnection( SharedConnection& _rxConnection )
2994 {
2995     // remove as event listener
2996     Reference< XComponent > xComponent( _rxConnection, UNO_QUERY );
2997     if ( xComponent.is() )
2998     {
2999         Reference< XEventListener > xListener( static_cast< ::cppu::OWeakObject* >( this ), UNO_QUERY );
3000         xComponent->removeEventListener( xListener );
3001     }
3002 
3003     try
3004     {
3005         // temporary (hopefully!) hack for #i55274#
3006         Reference< XFlushable > xFlush( _rxConnection, UNO_QUERY );
3007         if ( xFlush.is() )
3008             xFlush->flush();
3009     }
3010     catch( const Exception& )
3011     {
3012         DBG_UNHANDLED_EXCEPTION();
3013     }
3014 
3015     // clear
3016     _rxConnection.clear();
3017         // will implicitly dispose if we have the ownership, since xConnection is a SharedConnection
3018 }
3019 
3020 // -------------------------------------------------------------------------
disposeConnection(SvLBoxEntry * _pDSEntry)3021 void SbaTableQueryBrowser::disposeConnection( SvLBoxEntry* _pDSEntry )
3022 {
3023     DBG_ASSERT( _pDSEntry, "SbaTableQueryBrowser::disposeConnection: invalid entry (NULL)!" );
3024     DBG_ASSERT( impl_isDataSourceEntry( _pDSEntry ), "SbaTableQueryBrowser::disposeConnection: invalid entry (not top-level)!" );
3025 
3026     if ( _pDSEntry )
3027     {
3028         DBTreeListUserData* pTreeListData = static_cast< DBTreeListUserData* >( _pDSEntry->GetUserData() );
3029         if ( pTreeListData )
3030             impl_releaseConnection( pTreeListData->xConnection );
3031     }
3032 }
3033 
3034 // -------------------------------------------------------------------------
closeConnection(SvLBoxEntry * _pDSEntry,sal_Bool _bDisposeConnection)3035 void SbaTableQueryBrowser::closeConnection(SvLBoxEntry* _pDSEntry,sal_Bool _bDisposeConnection)
3036 {
3037     DBG_ASSERT(_pDSEntry, "SbaTableQueryBrowser::closeConnection: invalid entry (NULL)!");
3038     DBG_ASSERT( impl_isDataSourceEntry( _pDSEntry ), "SbaTableQueryBrowser::closeConnection: invalid entry (not top-level)!");
3039 
3040     // if one of the entries of the given DS is displayed currently, unload the form
3041     if (m_pCurrentlyDisplayed && (m_pTreeView->getListBox().GetRootLevelParent(m_pCurrentlyDisplayed) == _pDSEntry))
3042         unloadAndCleanup(_bDisposeConnection);
3043 
3044     // collapse the query/table container
3045     for (SvLBoxEntry* pContainers = m_pTreeModel->FirstChild(_pDSEntry); pContainers; pContainers= m_pTreeModel->NextSibling(pContainers))
3046     {
3047         SvLBoxEntry* pElements = m_pTreeModel->FirstChild(pContainers);
3048         if ( pElements )
3049             m_pTreeView->getListBox().Collapse(pContainers);
3050         m_pTreeView->getListBox().EnableExpandHandler(pContainers);
3051         // and delete their children (they are connection-relative)
3052         for (; pElements; )
3053         {
3054             SvLBoxEntry* pRemove = pElements;
3055             pElements= m_pTreeModel->NextSibling(pElements);
3056             DBTreeListUserData* pData = static_cast<DBTreeListUserData*>(pRemove->GetUserData());
3057             pRemove->SetUserData(NULL);
3058             delete pData;
3059             m_pTreeModel->Remove(pRemove);
3060         }
3061     }
3062     // collapse the entry itself
3063     m_pTreeView->getListBox().Collapse(_pDSEntry);
3064 
3065     // dispose/reset the connection
3066     if ( _bDisposeConnection )
3067         disposeConnection( _pDSEntry );
3068 }
3069 
3070 // -------------------------------------------------------------------------
unloadAndCleanup(sal_Bool _bDisposeConnection)3071 void SbaTableQueryBrowser::unloadAndCleanup( sal_Bool _bDisposeConnection )
3072 {
3073     if (!m_pCurrentlyDisplayed)
3074         // nothing to do
3075         return;
3076 
3077     SvLBoxEntry* pDSEntry = m_pTreeView->getListBox().GetRootLevelParent(m_pCurrentlyDisplayed);
3078 
3079     // de-select the path for the currently displayed table/query
3080     if (m_pCurrentlyDisplayed)
3081     {
3082         selectPath(m_pCurrentlyDisplayed, sal_False);
3083     }
3084     m_pCurrentlyDisplayed = NULL;
3085 
3086     try
3087     {
3088         // get the active connection. We need to dispose it.
3089         Reference< XPropertySet > xRowSetProps(getRowSet(),UNO_QUERY);
3090         Reference< XConnection > xConn;
3091         xRowSetProps->getPropertyValue(PROPERTY_ACTIVE_CONNECTION) >>= xConn;
3092 #if OSL_DEBUG_LEVEL > 1
3093         {
3094             Reference< XComponent > xComp;
3095             ::cppu::extractInterface(xComp, xRowSetProps->getPropertyValue(PROPERTY_ACTIVE_CONNECTION));
3096         }
3097 #endif
3098 
3099         // unload the form
3100         Reference< XLoadable > xLoadable = getLoadable();
3101         if (xLoadable->isLoaded())
3102             xLoadable->unload();
3103 
3104         // clear the grid control
3105         Reference< XNameContainer > xConta(getControlModel(),UNO_QUERY);
3106         clearGridColumns(xConta);
3107 
3108         // dispose the connection
3109         if(_bDisposeConnection)
3110             disposeConnection( pDSEntry );
3111     }
3112     catch(SQLException& e)
3113     {
3114         showError(SQLExceptionInfo(e));
3115     }
3116     catch(WrappedTargetException& e)
3117     {
3118         SQLException aSql;
3119         if(e.TargetException >>= aSql)
3120             showError(SQLExceptionInfo(aSql));
3121         else
3122             OSL_ENSURE(sal_False, "SbaTableQueryBrowser::unloadAndCleanup: something strange happened!");
3123     }
3124     catch(Exception&)
3125     {
3126         OSL_ENSURE(sal_False, "SbaTableQueryBrowser::unloadAndCleanup: could not reset the form");
3127     }
3128 }
3129 
3130 // -------------------------------------------------------------------------
3131 namespace
3132 {
lcl_getDataSource(const Reference<XNameAccess> & _rxDatabaseContext,const::rtl::OUString & _rDataSourceName,const Reference<XConnection> & _rxConnection)3133     Reference< XInterface > lcl_getDataSource( const Reference< XNameAccess >& _rxDatabaseContext,
3134         const ::rtl::OUString& _rDataSourceName, const Reference< XConnection >& _rxConnection )
3135     {
3136         Reference< XDataSource > xDataSource;
3137         try
3138         {
3139             if ( _rDataSourceName.getLength() && _rxDatabaseContext->hasByName( _rDataSourceName ) )
3140                 xDataSource.set( _rxDatabaseContext->getByName( _rDataSourceName ), UNO_QUERY_THROW );
3141 
3142             if ( !xDataSource.is() )
3143             {
3144                 Reference< XChild > xConnAsChild( _rxConnection, UNO_QUERY );
3145                 if ( xConnAsChild.is() )
3146                     xDataSource.set( xConnAsChild->getParent(), UNO_QUERY_THROW );
3147             }
3148         }
3149         catch( const Exception& )
3150         {
3151             DBG_UNHANDLED_EXCEPTION();
3152         }
3153         return xDataSource.get();
3154     }
3155 }
3156 
3157 // -------------------------------------------------------------------------
impl_initialize()3158 void SbaTableQueryBrowser::impl_initialize()
3159 {
3160     ::vos::OGuard aGuard(Application::GetSolarMutex());
3161         // doing a lot of VCL stuff here -> lock the SolarMutex
3162 
3163     // first initialize the parent
3164     SbaXDataBrowserController::impl_initialize();
3165 
3166     Reference<XConnection> xForeignConnection;
3167     Reference< XFrame > xFrame;
3168 
3169     ::rtl::OUString aTableName, aCatalogName, aSchemaName;
3170 
3171     sal_Bool bEsacpeProcessing = sal_True;
3172     sal_Int32 nInitialDisplayCommandType = CommandType::COMMAND;
3173     ::rtl::OUString sInitialDataSourceName;
3174     ::rtl::OUString sInitialCommand;
3175 
3176     const NamedValueCollection& rArguments( getInitParams() );
3177 
3178     rArguments.get_ensureType( (::rtl::OUString)PROPERTY_DATASOURCENAME, sInitialDataSourceName );
3179     rArguments.get_ensureType( (::rtl::OUString)PROPERTY_COMMAND_TYPE, nInitialDisplayCommandType );
3180     rArguments.get_ensureType( (::rtl::OUString)PROPERTY_COMMAND, sInitialCommand );
3181     rArguments.get_ensureType( (::rtl::OUString)PROPERTY_ACTIVE_CONNECTION, xForeignConnection );
3182     rArguments.get_ensureType( (::rtl::OUString)PROPERTY_UPDATE_CATALOGNAME, aCatalogName );
3183     rArguments.get_ensureType( (::rtl::OUString)PROPERTY_UPDATE_SCHEMANAME, aSchemaName );
3184     rArguments.get_ensureType( (::rtl::OUString)PROPERTY_UPDATE_TABLENAME, aTableName );
3185     rArguments.get_ensureType( (::rtl::OUString)PROPERTY_ESCAPE_PROCESSING, bEsacpeProcessing );
3186     rArguments.get_ensureType( "Frame", xFrame );
3187     rArguments.get_ensureType( (::rtl::OUString)PROPERTY_SHOWMENU, m_bShowMenu );
3188 
3189     // disable the browser if either of ShowTreeViewButton (compatibility name) or EnableBrowser
3190     // is present and set to FALSE
3191     sal_Bool bDisableBrowser =  ( sal_False == rArguments.getOrDefault( "ShowTreeViewButton", sal_True ) )   // compatibility name
3192                             ||  ( sal_False == rArguments.getOrDefault( (::rtl::OUString)PROPERTY_ENABLE_BROWSER, sal_True ) );
3193     OSL_ENSURE( !rArguments.has( "ShowTreeViewButton" ),
3194         "SbaTableQueryBrowser::impl_initialize: ShowTreeViewButton is superseded by EnableBrowser!" );
3195     m_bEnableBrowser = !bDisableBrowser;
3196 
3197     // hide the tree view it is disabled in general, or if the settings tell to hide it initially
3198     sal_Bool bHideTreeView =    ( !m_bEnableBrowser )
3199                             ||  ( sal_False == rArguments.getOrDefault( "ShowTreeView", sal_True ) )  // compatibility name
3200                             ||  ( sal_False == rArguments.getOrDefault( (::rtl::OUString)PROPERTY_SHOW_BROWSER, sal_True ) );
3201     OSL_ENSURE( !rArguments.has( "ShowTreeView" ),
3202         "SbaTableQueryBrowser::impl_initialize: ShowTreeView is superseded by ShowBrowser!" );
3203 
3204     if ( bHideTreeView )
3205         hideExplorer();
3206     else
3207         showExplorer();
3208 
3209     if ( m_bPreview )
3210     {
3211         try
3212         {
3213             Sequence< ::rtl::OUString> aProperties(5);
3214             Sequence< Any> aValues(5);
3215 
3216             ::rtl::OUString* pStringIter = aProperties.getArray();
3217             Any* pValueIter = aValues.getArray();
3218             *pStringIter++  = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AlwaysShowCursor"));
3219             *pValueIter++   <<= sal_False;
3220             *pStringIter++  = PROPERTY_BORDER;
3221             *pValueIter++   <<= sal_Int16(0);
3222 
3223             *pStringIter++  = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("HasNavigationBar"));
3224             *pValueIter++       <<= sal_False;
3225             *pStringIter++  = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("HasRecordMarker"));
3226             *pValueIter++       <<= sal_False;
3227 
3228             *pStringIter++  = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Tabstop"));
3229             *pValueIter++       <<= sal_False;
3230 
3231             Reference< XMultiPropertySet >  xFormMultiSet(getFormComponent(), UNO_QUERY);
3232             if ( xFormMultiSet.is() )
3233                 xFormMultiSet->setPropertyValues(aProperties, aValues);
3234         }
3235         catch(Exception)
3236         {
3237             DBG_UNHANDLED_EXCEPTION();
3238         }
3239     }
3240 
3241     // are we loaded into a (sub)frame of an embedded document (i.e. a form belonging to a database
3242     // document)?
3243     sal_Bool bSubFrameOfEmbeddedDocument = sal_False;
3244     if ( xFrame.is() )
3245     {
3246         Reference<XFramesSupplier> xSup = xFrame->getCreator();
3247         Reference<XController> xCont = xSup.is() ? xSup->getController() : Reference<XController>();
3248 
3249         bSubFrameOfEmbeddedDocument = xCont.is() && ::dbtools::isEmbeddedInDatabase( xCont->getModel(), xForeignConnection );
3250     }
3251 
3252     // if we have a connection at this point, it was either passed from outside, our
3253     // determined from a outer DB document. In both cases, do not dispose it later on.
3254     SharedConnection xConnection( xForeignConnection, SharedConnection::NoTakeOwnership );
3255 
3256     // should we display all registered databases in the left hand side tree?
3257     // or only *one* special?
3258     sal_Bool bLimitedTreeEntries = sal_False;
3259     // if we're part of a frame which is a secondary frame of a database document, then only
3260     // display the database for this document, not all registered ones
3261     bLimitedTreeEntries |= bSubFrameOfEmbeddedDocument;
3262     // if the tree view is not to be displayed at all, then only display the data source
3263     // which was given as initial selection
3264     bLimitedTreeEntries |= ( m_bEnableBrowser != sal_True );
3265 
3266     if ( bLimitedTreeEntries )
3267     {
3268         if ( xConnection.is() )
3269         {
3270             startConnectionListening( xConnection );
3271 
3272             // if no initial name was given, try to obtain one from the data source
3273             if ( !sInitialDataSourceName.getLength() )
3274             {
3275                 Reference< XChild > xChild( xConnection, UNO_QUERY );
3276                 Reference< XPropertySet > xDataSourceProperties;
3277                 if ( xChild.is() )
3278                     xDataSourceProperties = xDataSourceProperties.query( xChild->getParent() );
3279                 if ( xDataSourceProperties.is() )
3280                 {
3281                     try
3282                     {
3283                         OSL_VERIFY( xDataSourceProperties->getPropertyValue( PROPERTY_NAME ) >>= sInitialDataSourceName );
3284                     }
3285                     catch( const Exception& )
3286                     {
3287                         OSL_ENSURE( sal_False, "SbaTableQueryBrowser::impl_initialize: a connection parent which does not have a 'Name'!??" );
3288                     }
3289                 }
3290             }
3291         }
3292 
3293         implAddDatasource( sInitialDataSourceName, xConnection );
3294         m_pTreeView->getListBox().Expand( m_pTreeView->getListBox().First() );
3295     }
3296     else
3297         initializeTreeModel();
3298 
3299     if ( m_bEnableBrowser )
3300     {
3301         m_aDocScriptSupport = ::boost::optional< bool >( false );
3302     }
3303     else
3304     {
3305         // we are not used as "browser", but as mere view for a single table/query/command. In particular,
3306         // there is a specific database document which we belong to.
3307         Reference< XOfficeDatabaseDocument > xDocument( getDataSourceOrModel(
3308             lcl_getDataSource( m_xDatabaseContext, sInitialDataSourceName, xConnection ) ), UNO_QUERY );
3309         m_aDocScriptSupport = ::boost::optional< bool >( Reference< XEmbeddedScripts >( xDocument, UNO_QUERY ).is() );
3310     }
3311 
3312     if ( implSelect( sInitialDataSourceName, sInitialCommand, nInitialDisplayCommandType, bEsacpeProcessing, xConnection, sal_True ) )
3313     {
3314         try
3315         {
3316             Reference< XPropertySet > xRowSetProps(getRowSet(), UNO_QUERY);
3317             xRowSetProps->setPropertyValue(PROPERTY_UPDATE_CATALOGNAME,makeAny(aCatalogName));
3318             xRowSetProps->setPropertyValue(PROPERTY_UPDATE_SCHEMANAME,makeAny(aSchemaName));
3319             xRowSetProps->setPropertyValue(PROPERTY_UPDATE_TABLENAME,makeAny(aTableName));
3320 
3321         }
3322         catch(const Exception&)
3323         {
3324             OSL_ENSURE(sal_False, "SbaTableQueryBrowser::impl_initialize: could not set the update related names!");
3325         }
3326     }
3327 
3328     InvalidateAll();
3329 }
3330 
3331 // -------------------------------------------------------------------------
haveExplorer() const3332 sal_Bool SbaTableQueryBrowser::haveExplorer() const
3333 {
3334     return m_pTreeView && m_pTreeView->IsVisible();
3335 }
3336 
3337 // -------------------------------------------------------------------------
hideExplorer()3338 void SbaTableQueryBrowser::hideExplorer()
3339 {
3340     if (!haveExplorer())
3341         return;
3342     if (!getBrowserView())
3343         return;
3344 
3345     m_pTreeView->Hide();
3346     m_pSplitter->Hide();
3347     getBrowserView()->Resize();
3348 
3349     InvalidateFeature(ID_BROWSER_EXPLORER);
3350 }
3351 
3352 // -------------------------------------------------------------------------
showExplorer()3353 void SbaTableQueryBrowser::showExplorer()
3354 {
3355     if (haveExplorer())
3356         return;
3357 
3358     if (!getBrowserView())
3359         return;
3360 
3361     m_pTreeView->Show();
3362     m_pSplitter->Show();
3363     getBrowserView()->Resize();
3364 
3365     InvalidateFeature(ID_BROWSER_EXPLORER);
3366 }
3367 
3368 // -----------------------------------------------------------------------------
ensureConnection(SvLBoxEntry * _pAnyEntry,SharedConnection & _rConnection)3369 sal_Bool SbaTableQueryBrowser::ensureConnection(SvLBoxEntry* _pAnyEntry, SharedConnection& _rConnection)
3370 {
3371     SvLBoxEntry* pDSEntry = m_pTreeView->getListBox().GetRootLevelParent(_pAnyEntry);
3372     DBTreeListUserData* pDSData =
3373                 pDSEntry
3374             ?   static_cast<DBTreeListUserData*>(pDSEntry->GetUserData())
3375             :   NULL;
3376 
3377     return ensureConnection( pDSEntry, pDSData, _rConnection );
3378 }
3379 
3380 // -----------------------------------------------------------------------------
getImageProviderFor(SvLBoxEntry * _pAnyEntry)3381 ::std::unique_ptr< ImageProvider > SbaTableQueryBrowser::getImageProviderFor( SvLBoxEntry* _pAnyEntry )
3382 {
3383     ::std::unique_ptr< ImageProvider > pImageProvider( new ImageProvider );
3384     SharedConnection xConnection;
3385     if ( getExistentConnectionFor( _pAnyEntry, xConnection ) )
3386         pImageProvider.reset( new ImageProvider( xConnection ) );
3387     return pImageProvider;
3388 }
3389 
3390 // -----------------------------------------------------------------------------
getExistentConnectionFor(SvLBoxEntry * _pAnyEntry,SharedConnection & _rConnection)3391 sal_Bool SbaTableQueryBrowser::getExistentConnectionFor( SvLBoxEntry* _pAnyEntry, SharedConnection& _rConnection )
3392 {
3393     SvLBoxEntry* pDSEntry = m_pTreeView->getListBox().GetRootLevelParent( _pAnyEntry );
3394     DBTreeListUserData* pDSData =
3395                 pDSEntry
3396             ?   static_cast< DBTreeListUserData* >( pDSEntry->GetUserData() )
3397             :   NULL;
3398     if ( pDSData )
3399         _rConnection = pDSData->xConnection;
3400     return _rConnection.is();
3401 }
3402 
3403 #ifdef DBG_UTIL
3404 // -----------------------------------------------------------------------------
impl_isDataSourceEntry(SvLBoxEntry * _pEntry) const3405 bool SbaTableQueryBrowser::impl_isDataSourceEntry( SvLBoxEntry* _pEntry ) const
3406 {
3407     return m_pTreeModel->GetRootLevelParent( _pEntry ) == _pEntry;
3408 }
3409 #endif
3410 
3411 // -----------------------------------------------------------------------------
ensureConnection(SvLBoxEntry * _pDSEntry,void * pDSData,SharedConnection & _rConnection)3412 sal_Bool SbaTableQueryBrowser::ensureConnection( SvLBoxEntry* _pDSEntry, void* pDSData, SharedConnection& _rConnection )
3413 {
3414     DBG_ASSERT( impl_isDataSourceEntry( _pDSEntry ), "SbaTableQueryBrowser::ensureConnection: this entry does not denote a data source!" );
3415     if(_pDSEntry)
3416     {
3417         DBTreeListUserData* pTreeListData = static_cast<DBTreeListUserData*>(pDSData);
3418         ::rtl::OUString aDSName = GetEntryText(_pDSEntry);
3419 
3420         if ( pTreeListData )
3421             _rConnection = pTreeListData->xConnection;
3422 
3423         if ( !_rConnection.is() && pTreeListData )
3424         {
3425             // show the "connecting to ..." status
3426             String sConnecting(ModuleRes(STR_CONNECTING_DATASOURCE));
3427             sConnecting.SearchAndReplaceAscii("$name$", aDSName);
3428             BrowserViewStatusDisplay aShowStatus(static_cast<UnoDataBrowserView*>(getView()), sConnecting);
3429 
3430             // build a string showing context information in case of error
3431             String sConnectingContext( ModuleRes( STR_COULDNOTCONNECT_DATASOURCE ) );
3432             sConnectingContext.SearchAndReplaceAscii("$name$", aDSName);
3433 
3434             // connect
3435             _rConnection.reset(
3436                 connect( getDataSourceAcessor( _pDSEntry ), sConnectingContext, NULL ),
3437                 SharedConnection::TakeOwnership
3438             );
3439 
3440             // remember the connection
3441             pTreeListData->xConnection = _rConnection;
3442         }
3443     }
3444 
3445     return _rConnection.is();
3446 }
3447 
3448 // -----------------------------------------------------------------------------
IMPL_LINK(SbaTableQueryBrowser,OnTreeEntryCompare,const SvSortData *,_pSortData)3449 IMPL_LINK( SbaTableQueryBrowser, OnTreeEntryCompare, const SvSortData*, _pSortData )
3450 {
3451     SvLBoxEntry* pLHS = static_cast<SvLBoxEntry*>(_pSortData->pLeft);
3452     SvLBoxEntry* pRHS = static_cast<SvLBoxEntry*>(_pSortData->pRight);
3453     DBG_ASSERT(pLHS && pRHS, "SbaTableQueryBrowser::OnTreeEntryCompare: invalid tree entries!");
3454     // we want the table entry and the end so we have to do a check
3455 
3456     if (isContainer(pRHS))
3457     {
3458         // don't use getEntryType (directly or indirectly) for the LHS:
3459         // LHS is currently being inserted, so it is not "completely valid" at the moment
3460 
3461         const EntryType eRight = getEntryType(pRHS);
3462         if (etTableContainer == eRight)
3463             // every other container should be placed _before_ the bookmark container
3464             return -1;
3465 
3466         const String sLeft = m_pTreeView->getListBox().GetEntryText(pLHS);
3467 
3468         EntryType eLeft = etTableContainer;
3469         if (String(ModuleRes(RID_STR_TABLES_CONTAINER)) == sLeft)
3470             eLeft = etTableContainer;
3471         else if (String(ModuleRes(RID_STR_QUERIES_CONTAINER)) == sLeft)
3472             eLeft = etQueryContainer;
3473 
3474         if ( eLeft == eRight )
3475             return COMPARE_EQUAL;
3476 
3477         if ( ( eLeft == etTableContainer ) && ( eRight == etQueryContainer ) )
3478             return COMPARE_GREATER;
3479 
3480         if ( ( eLeft == etQueryContainer ) && ( eRight == etTableContainer ) )
3481             return COMPARE_LESS;
3482 
3483         OSL_ENSURE( false, "SbaTableQueryBrowser::OnTreeEntryCompare: unexpected case!" );
3484         return COMPARE_EQUAL;
3485     }
3486 
3487     SvLBoxString* pLeftTextItem = static_cast<SvLBoxString*>(pLHS->GetFirstItem(SV_ITEM_ID_LBOXSTRING));
3488     SvLBoxString* pRightTextItem = static_cast<SvLBoxString*>(pRHS->GetFirstItem(SV_ITEM_ID_LBOXSTRING));
3489     DBG_ASSERT(pLeftTextItem && pRightTextItem, "SbaTableQueryBrowser::OnTreeEntryCompare: invalid text items!");
3490 
3491     String sLeftText = pLeftTextItem->GetText();
3492     String sRightText = pRightTextItem->GetText();
3493 
3494     sal_Int32 nCompareResult = 0;   // equal by default
3495 
3496     if (m_xCollator.is())
3497     {
3498         try
3499         {
3500             nCompareResult = m_xCollator->compareString(sLeftText, sRightText);
3501         }
3502         catch(Exception&)
3503         {
3504         }
3505     }
3506     else
3507         // default behavior if we do not have a collator -> do the simple string compare
3508         nCompareResult = sLeftText.CompareTo(sRightText);
3509 
3510     return nCompareResult;
3511 }
3512 
3513 // -----------------------------------------------------------------------------
implAdministrate(SvLBoxEntry * _pApplyTo)3514 void SbaTableQueryBrowser::implAdministrate( SvLBoxEntry* _pApplyTo )
3515 {
3516     OSL_PRECOND( _pApplyTo, "SbaTableQueryBrowser::implAdministrate: illegal entry!" );
3517     if ( !_pApplyTo )
3518         return;
3519 
3520     try
3521     {
3522         // get the desktop object
3523         sal_Int32 nFrameSearchFlag = FrameSearchFlag::ALL | FrameSearchFlag::GLOBAL ;
3524         Reference< XComponentLoader > xFrameLoader(getORB()->createInstance(SERVICE_FRAME_DESKTOP),UNO_QUERY);
3525 
3526         if ( xFrameLoader.is() )
3527         {
3528             // the initial selection
3529             SvLBoxEntry* pTopLevelSelected = _pApplyTo;
3530             while (pTopLevelSelected && m_pTreeView->getListBox().GetParent(pTopLevelSelected))
3531                 pTopLevelSelected = m_pTreeView->getListBox().GetParent(pTopLevelSelected);
3532             ::rtl::OUString sInitialSelection;
3533             if (pTopLevelSelected)
3534                 sInitialSelection = getDataSourceAcessor( pTopLevelSelected );
3535 
3536             Reference< XDataSource > xDataSource( getDataSourceByName( sInitialSelection, getView(), getORB(), NULL ) );
3537             Reference< XModel > xDocumentModel( getDataSourceOrModel( xDataSource ), UNO_QUERY );
3538 
3539             if ( xDocumentModel.is() )
3540             {
3541                 Reference< XInteractionHandler > xInteractionHandler(
3542                     getORB()->createInstance(
3543                         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.task.InteractionHandler" ) ) ),
3544                         UNO_QUERY );
3545                 OSL_ENSURE( xInteractionHandler.is(), "SbaTableQueryBrowser::implAdministrate: no interaction handler available!" );
3546 
3547                 ::comphelper::NamedValueCollection aLoadArgs;
3548                 aLoadArgs.put( "Model", xDocumentModel );
3549                 aLoadArgs.put( "InteractionHandler", xInteractionHandler );
3550                 aLoadArgs.put( "MacroExecutionMode", MacroExecMode::USE_CONFIG );
3551 
3552                 Sequence< PropertyValue > aLoadArgPV;
3553                 aLoadArgs >>= aLoadArgPV;
3554 
3555                 xFrameLoader->loadComponentFromURL(
3556                     xDocumentModel->getURL(),
3557                     ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("_default")),
3558                     nFrameSearchFlag,
3559                     aLoadArgPV
3560                 );
3561             }
3562         }
3563     }
3564     catch( const Exception& )
3565     {
3566         DBG_UNHANDLED_EXCEPTION();
3567     }
3568 }
3569 
3570 // -----------------------------------------------------------------------------
requestQuickHelp(const SvLBoxEntry * _pEntry,String & _rText) const3571 sal_Bool SbaTableQueryBrowser::requestQuickHelp( const SvLBoxEntry* _pEntry, String& _rText ) const
3572 {
3573     const DBTreeListUserData* pData = static_cast< const DBTreeListUserData* >( _pEntry->GetUserData() );
3574     if ( ( pData->eType == etDatasource ) && pData->sAccessor.Len() )
3575     {
3576         _rText = ::svt::OFileNotation( pData->sAccessor ).get( ::svt::OFileNotation::N_SYSTEM );
3577         return sal_True;
3578     }
3579     return sal_False;
3580 }
3581 
3582 // -----------------------------------------------------------------------------
getContextMenu(Control & _rControl) const3583 PopupMenu* SbaTableQueryBrowser::getContextMenu( Control& _rControl ) const
3584 {
3585     OSL_PRECOND( &m_pTreeView->getListBox() == &_rControl,
3586         "SbaTableQueryBrowser::getContextMenu: where does this come from?" );
3587     if ( &m_pTreeView->getListBox() != &_rControl )
3588         return NULL;
3589 
3590     return new PopupMenu( ModuleRes( MENU_BROWSER_DEFAULTCONTEXT ) );
3591 }
3592 
3593 // -----------------------------------------------------------------------------
getCommandController()3594 IController& SbaTableQueryBrowser::getCommandController()
3595 {
3596     return *this;
3597 }
3598 
3599 // -----------------------------------------------------------------------------
getContextMenuInterceptors()3600 ::cppu::OInterfaceContainerHelper* SbaTableQueryBrowser::getContextMenuInterceptors()
3601 {
3602     return &m_aContextMenuInterceptors;
3603 }
3604 
3605 // -----------------------------------------------------------------------------
getCurrentSelection(Control & _rControl) const3606 Any SbaTableQueryBrowser::getCurrentSelection( Control& _rControl ) const
3607 {
3608     OSL_PRECOND( &m_pTreeView->getListBox() == &_rControl,
3609         "SbaTableQueryBrowser::getCurrentSelection: where does this come from?" );
3610 
3611     if ( &m_pTreeView->getListBox() != &_rControl )
3612         return Any();
3613 
3614     SvLBoxEntry* pSelected = m_pTreeView->getListBox().FirstSelected();
3615     if ( !pSelected )
3616         return Any();
3617 
3618     OSL_ENSURE( m_pTreeView->getListBox().NextSelected( pSelected ) == NULL,
3619         "SbaTableQueryBrowser::getCurrentSelection: single-selection is expected here!" );
3620 
3621     NamedDatabaseObject aSelectedObject;
3622     DBTreeListUserData* pData = static_cast< DBTreeListUserData* >( pSelected->GetUserData() );
3623     aSelectedObject.Type = static_cast< sal_Int32 >( pData->eType );
3624 
3625     switch ( aSelectedObject.Type )
3626     {
3627     case DatabaseObject::QUERY:
3628     case DatabaseObject::TABLE:
3629         aSelectedObject.Name = m_pTreeView->getListBox().GetEntryText( pSelected );
3630         break;
3631 
3632     case DatabaseObjectContainer::DATA_SOURCE:
3633     case DatabaseObjectContainer::QUERIES:
3634     case DatabaseObjectContainer::TABLES:
3635         aSelectedObject.Name = getDataSourceAcessor( pSelected );
3636         break;
3637 
3638     default:
3639         OSL_ENSURE( false, "SbaTableQueryBrowser::getCurrentSelection: invalid (unexpected) object type!" );
3640         break;
3641     }
3642 
3643     return makeAny( aSelectedObject );
3644 }
3645 
3646 // -----------------------------------------------------------------------------
implGetQuerySignature(::rtl::OUString & _rCommand,sal_Bool & _bEscapeProcessing)3647 sal_Bool SbaTableQueryBrowser::implGetQuerySignature( ::rtl::OUString& _rCommand, sal_Bool& _bEscapeProcessing )
3648 {
3649     _rCommand = ::rtl::OUString();
3650     _bEscapeProcessing = sal_False;
3651 
3652     try
3653     {
3654         // contain the dss (data source signature) of the form
3655         ::rtl::OUString sDataSourceName;
3656         ::rtl::OUString sCommand;
3657         sal_Int32       nCommandType = CommandType::COMMAND;
3658         Reference< XPropertySet > xRowsetProps( getRowSet(), UNO_QUERY );
3659         ODataAccessDescriptor aDesc( xRowsetProps );
3660         sDataSourceName = aDesc.getDataSource();
3661         aDesc[ daCommand ]      >>= sCommand;
3662         aDesc[ daCommandType ]  >>= nCommandType;
3663 
3664         // do we need to do anything?
3665         if ( CommandType::QUERY != nCommandType )
3666             return sal_False;
3667 
3668         // get the query object
3669         Reference< XQueryDefinitionsSupplier > xSuppQueries;
3670         Reference< XNameAccess > xQueries;
3671         Reference< XPropertySet > xQuery;
3672         m_xDatabaseContext->getByName( sDataSourceName ) >>= xSuppQueries;
3673         if ( xSuppQueries.is() )
3674             xQueries = xSuppQueries->getQueryDefinitions();
3675         if ( xQueries.is() )
3676             xQueries->getByName( sCommand ) >>= xQuery;
3677         OSL_ENSURE( xQuery.is(), "SbaTableQueryBrowser::implGetQuerySignature: could not retrieve the query object!" );
3678 
3679         // get the two properties we need
3680         if ( xQuery.is() )
3681         {
3682             xQuery->getPropertyValue( PROPERTY_COMMAND ) >>= _rCommand;
3683             _bEscapeProcessing = ::cppu::any2bool( xQuery->getPropertyValue( PROPERTY_ESCAPE_PROCESSING ) );
3684             return sal_True;
3685         }
3686     }
3687     catch( const Exception& )
3688     {
3689         DBG_UNHANDLED_EXCEPTION();
3690     }
3691 
3692     return sal_False;
3693 }
3694 //------------------------------------------------------------------------------
frameAction(const::com::sun::star::frame::FrameActionEvent & aEvent)3695 void SbaTableQueryBrowser::frameAction(const ::com::sun::star::frame::FrameActionEvent& aEvent)
3696 {
3697     if (aEvent.Frame == m_xCurrentFrameParent)
3698     {
3699         if(aEvent.Action == FrameAction_COMPONENT_DETACHING)
3700             implRemoveStatusListeners();
3701         else if (aEvent.Action == FrameAction_COMPONENT_REATTACHED)
3702             connectExternalDispatches();
3703     }
3704     else
3705         SbaXDataBrowserController::frameAction(aEvent);
3706 
3707 }
3708 // -----------------------------------------------------------------------------
clearGridColumns(const Reference<XNameContainer> & _xColContainer)3709 void SbaTableQueryBrowser::clearGridColumns(const Reference< XNameContainer >& _xColContainer)
3710 {
3711     // first we have to clear the grid
3712     Sequence< ::rtl::OUString > aNames = _xColContainer->getElementNames();
3713     const ::rtl::OUString* pIter    = aNames.getConstArray();
3714     const ::rtl::OUString* pEnd     = pIter + aNames.getLength();
3715     Reference< XInterface > xColumn;
3716     for (; pIter != pEnd;++pIter)
3717     {
3718         _xColContainer->getByName(*pIter) >>= xColumn;
3719         _xColContainer->removeByName(*pIter);
3720         ::comphelper::disposeComponent(xColumn);
3721     }
3722 }
3723 // -----------------------------------------------------------------------------
isHiContrast() const3724 sal_Bool SbaTableQueryBrowser::isHiContrast() const
3725 {
3726     sal_Bool bRet = sal_False;
3727     if ( m_pTreeView )
3728         bRet = m_pTreeView->getListBox().GetSettings().GetStyleSettings().GetHighContrastMode();
3729     return bRet;
3730 }
3731 // -----------------------------------------------------------------------------
loadMenu(const Reference<XFrame> & _xFrame)3732 void SbaTableQueryBrowser::loadMenu(const Reference< XFrame >& _xFrame)
3733 {
3734     if ( m_bShowMenu )
3735     {
3736         OGenericUnoController::loadMenu(_xFrame);
3737     }
3738     else if ( !m_bPreview )
3739     {
3740         Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager = getLayoutManager(_xFrame);
3741 
3742         if ( xLayoutManager.is() )
3743         {
3744             xLayoutManager->lock();
3745             xLayoutManager->createElement( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/toolbar" )));
3746             xLayoutManager->unlock();
3747             xLayoutManager->doLayout();
3748         }
3749         onLoadedMenu( xLayoutManager );
3750     }
3751 }
3752 // -----------------------------------------------------------------------------
getPrivateTitle() const3753 ::rtl::OUString SbaTableQueryBrowser::getPrivateTitle() const
3754 {
3755     ::rtl::OUString sTitle;
3756     if ( m_pCurrentlyDisplayed )
3757     {
3758         SvLBoxEntry* pContainer = m_pTreeModel->GetParent(m_pCurrentlyDisplayed);
3759         // get the entry for the datasource
3760         SvLBoxEntry* pConnection = implGetConnectionEntry(pContainer);
3761         ::rtl::OUString sName = m_pTreeView->getListBox().GetEntryText(m_pCurrentlyDisplayed);
3762         sTitle = GetEntryText( pConnection );
3763         INetURLObject aURL(sTitle);
3764         if ( aURL.GetProtocol() != INET_PROT_NOT_VALID )
3765             sTitle = aURL.getBase(INetURLObject::LAST_SEGMENT,true,INetURLObject::DECODE_WITH_CHARSET);
3766         if ( sName.getLength() )
3767         {
3768             sName += ::rtl::OUString::createFromAscii(" - ");
3769             sName += sTitle;
3770             sTitle = sName;
3771         }
3772     }
3773 
3774     return sTitle;
3775 }
3776 // -----------------------------------------------------------------------------
preReloadForm()3777 sal_Bool SbaTableQueryBrowser::preReloadForm()
3778 {
3779     sal_Bool bIni = sal_False;
3780     if ( !m_pCurrentlyDisplayed )
3781     {
3782         // switch the grid to design mode while loading
3783         getBrowserView()->getGridControl()->setDesignMode(sal_True);
3784         // we had an invalid statement so we need to connect the column models
3785         Reference<XPropertySet> xRowSetProps(getRowSet(),UNO_QUERY);
3786         ::svx::ODataAccessDescriptor aDesc(xRowSetProps);
3787         // extract the props
3788         ::rtl::OUString sDataSource;
3789         ::rtl::OUString sCommand;
3790         sal_Int32 nCommandType = CommandType::COMMAND;
3791         sal_Bool bEscapeProcessing = sal_True;
3792         extractDescriptorProps(aDesc, sDataSource, sCommand, nCommandType, bEscapeProcessing);
3793         if ( sDataSource.getLength() && sCommand.getLength() && (-1 != nCommandType) )
3794         {
3795             SvLBoxEntry* pDataSource = NULL;
3796             SvLBoxEntry* pCommandType = NULL;
3797             m_pCurrentlyDisplayed = getObjectEntry( sDataSource, sCommand, nCommandType, &pDataSource, &pCommandType, sal_True, SharedConnection() );
3798             bIni = sal_True;
3799         }
3800     }
3801     return bIni;
3802 }
3803 
3804 // -----------------------------------------------------------------------------
postReloadForm()3805 void SbaTableQueryBrowser::postReloadForm()
3806 {
3807     InitializeGridModel(getFormComponent());
3808     LoadFinished(sal_True);
3809     //updateTitle();
3810 }
3811 
3812 //------------------------------------------------------------------------------
getScriptContainer()3813 Reference< XEmbeddedScripts > SAL_CALL SbaTableQueryBrowser::getScriptContainer()
3814 {
3815     // update our database document
3816     Reference< XModel > xDocument;
3817     try
3818     {
3819         Reference< XPropertySet > xCursorProps( getRowSet(), UNO_QUERY_THROW );
3820         Reference< XConnection > xConnection( xCursorProps->getPropertyValue( PROPERTY_ACTIVE_CONNECTION ), UNO_QUERY );
3821         if ( xConnection.is() )
3822         {
3823             Reference< XChild > xChild( xConnection, UNO_QUERY_THROW );
3824             Reference< XDocumentDataSource > xDataSource( xChild->getParent(), UNO_QUERY_THROW );
3825             xDocument.set( xDataSource->getDatabaseDocument(), UNO_QUERY_THROW );
3826         }
3827     }
3828     catch( const Exception& )
3829     {
3830         DBG_UNHANDLED_EXCEPTION();
3831     }
3832     Reference< XEmbeddedScripts > xScripts( xDocument, UNO_QUERY );
3833     OSL_ENSURE( xScripts.is() || !xDocument.is(),
3834         "SbaTableQueryBrowser::getScriptContainer: invalid database document!" );
3835     return xScripts;
3836 }
3837 
3838 //------------------------------------------------------------------------------
registerContextMenuInterceptor(const Reference<XContextMenuInterceptor> & _Interceptor)3839 void SAL_CALL SbaTableQueryBrowser::registerContextMenuInterceptor( const Reference< XContextMenuInterceptor >& _Interceptor )
3840 {
3841     if ( _Interceptor.is() )
3842         m_aContextMenuInterceptors.addInterface( _Interceptor );
3843 }
3844 
3845 //------------------------------------------------------------------------------
releaseContextMenuInterceptor(const Reference<XContextMenuInterceptor> & _Interceptor)3846 void SAL_CALL SbaTableQueryBrowser::releaseContextMenuInterceptor( const Reference< XContextMenuInterceptor >& _Interceptor )
3847 {
3848     if ( _Interceptor.is() )
3849         m_aContextMenuInterceptors.removeInterface( _Interceptor );
3850 }
3851 
3852 //------------------------------------------------------------------------------
registeredDatabaseLocation(const DatabaseRegistrationEvent & _Event)3853 void SAL_CALL SbaTableQueryBrowser::registeredDatabaseLocation( const DatabaseRegistrationEvent& _Event )
3854 {
3855     ::vos::OGuard aGuard( Application::GetSolarMutex() );
3856     implAddDatasource( _Event.Name, SharedConnection() );
3857 }
3858 
3859 //------------------------------------------------------------------------------
impl_cleanupDataSourceEntry(const String & _rDataSourceName)3860 void SbaTableQueryBrowser::impl_cleanupDataSourceEntry( const String& _rDataSourceName )
3861 {
3862     // get the top-level representing the removed data source
3863     SvLBoxEntry* pDataSourceEntry = m_pTreeView->getListBox().FirstChild( NULL );
3864     while ( pDataSourceEntry )
3865     {
3866         if ( m_pTreeView->getListBox().GetEntryText( pDataSourceEntry ) == _rDataSourceName )
3867             break;
3868 
3869         pDataSourceEntry = m_pTreeView->getListBox().NextSibling( pDataSourceEntry );
3870     }
3871 
3872     OSL_ENSURE( pDataSourceEntry, "SbaTableQueryBrowser::impl_cleanupDataSourceEntry: do not know this data source!" );
3873     if ( !pDataSourceEntry )
3874         return;
3875 
3876     if ( isSelected( pDataSourceEntry ) )
3877     {   // a table or query belonging to the deleted data source is currently being displayed.
3878         OSL_ENSURE( m_pTreeView->getListBox().GetRootLevelParent( m_pCurrentlyDisplayed ) == pDataSourceEntry,
3879             "SbaTableQueryBrowser::impl_cleanupDataSourceEntry: inconsistence (1)!" );
3880         unloadAndCleanup( sal_True );
3881     }
3882     else
3883         OSL_ENSURE(
3884                 ( NULL == m_pCurrentlyDisplayed )
3885             ||  ( m_pTreeView->getListBox().GetRootLevelParent( m_pCurrentlyDisplayed ) != pDataSourceEntry ),
3886             "SbaTableQueryBrowser::impl_cleanupDataSourceEntry: inconsistence (2)!");
3887 
3888     // delete any user data of the child entries of the to-be-removed entry
3889     SvTreeEntryList* pList = m_pTreeModel->GetChildList( pDataSourceEntry );
3890     if ( pList )
3891     {
3892         SvLBoxEntry* pEntryLoop = static_cast<SvLBoxEntry*>( pList->First() );
3893         while ( pEntryLoop )
3894         {
3895             DBTreeListUserData* pData = static_cast< DBTreeListUserData* >( pEntryLoop->GetUserData() );
3896             pEntryLoop->SetUserData( NULL );
3897             delete pData;
3898             pEntryLoop = static_cast< SvLBoxEntry* >( pList->Next() );
3899         }
3900     }
3901 
3902     // remove the entry
3903     DBTreeListUserData* pData = static_cast< DBTreeListUserData* >( pDataSourceEntry->GetUserData() );
3904     pDataSourceEntry->SetUserData( NULL );
3905     delete pData;
3906     m_pTreeModel->Remove( pDataSourceEntry );
3907 }
3908 
3909 //------------------------------------------------------------------------------
revokedDatabaseLocation(const DatabaseRegistrationEvent & _Event)3910 void SAL_CALL SbaTableQueryBrowser::revokedDatabaseLocation( const DatabaseRegistrationEvent& _Event )
3911 {
3912     ::vos::OGuard aGuard( Application::GetSolarMutex() );
3913 
3914     impl_cleanupDataSourceEntry( _Event.Name );
3915 
3916     // maybe the object which is part of the document data source has been removed
3917     checkDocumentDataSource();
3918 }
3919 
3920 //------------------------------------------------------------------------------
changedDatabaseLocation(const DatabaseRegistrationEvent & _Event)3921 void SAL_CALL SbaTableQueryBrowser::changedDatabaseLocation( const DatabaseRegistrationEvent& _Event )
3922 {
3923     ::vos::OGuard aGuard( Application::GetSolarMutex() );
3924 
3925     // in case the data source was expanded, and connected, we need to clean it up
3926     // for simplicity, just do as if the data source were completely removed and re-added
3927     impl_cleanupDataSourceEntry( _Event.Name );
3928     implAddDatasource( _Event.Name, SharedConnection() );
3929 }
3930 
3931 
3932 // .........................................................................
3933 }   // namespace dbaui
3934 // .........................................................................
3935 
3936 /* vim: set noet sw=4 ts=4: */
3937